Fix reference to README.devlib in header.
[bertos.git] / kern / proc.c
1 /*!
2  * \file
3  * <!--
4  * Copyright 2001,2004 Develer S.r.l. (http://www.develer.com/)
5  * Copyright 1999,2000,2001 Bernardo Innocenti <bernie@develer.com>
6  * This file is part of DevLib - See README.devlib for information.
7  * -->
8  *
9  * \brief Simple realtime multitasking scheduler.
10  *        Context switching is only done cooperatively.
11  *
12  * \version $Id$
13  *
14  * \author Bernardo Innocenti <bernie@develer.com>
15  * \author Stefano Fedrigo <aleph@develer.com>
16  */
17
18 /*#*
19  *#* $Log$
20  *#* Revision 1.27  2005/11/04 16:20:02  bernie
21  *#* Fix reference to README.devlib in header.
22  *#*
23  *#* Revision 1.26  2005/04/11 19:10:28  bernie
24  *#* Include top-level headers from cfg/ subdir.
25  *#*
26  *#* Revision 1.25  2005/03/15 00:20:54  bernie
27  *#* proc_schedule(): New sanity check.
28  *#*
29  *#* Revision 1.24  2005/01/08 09:20:54  bernie
30  *#* Remove unused variable.
31  *#*
32  *#* Revision 1.23  2004/12/13 12:07:06  bernie
33  *#* DISABLE_IRQSAVE/ENABLE_IRQRESTORE: Convert to IRQ_SAVE_DISABLE/IRQ_RESTORE.
34  *#*
35  *#* Revision 1.22  2004/12/13 11:51:08  bernie
36  *#* DISABLE_INTS/ENABLE_INTS: Convert to IRQ_DISABLE/IRQ_ENABLE.
37  *#*
38  *#* Revision 1.21  2004/11/28 23:20:25  bernie
39  *#* Remove obsolete INITLIST macro.
40  *#*
41  *#* Revision 1.20  2004/11/16 22:37:14  bernie
42  *#* Replace IPTR with iptr_t.
43  *#*
44  *#* Revision 1.19  2004/10/19 11:47:39  bernie
45  *#* Kill warnings when !CONFIG_PROC_MONITOR.
46  *#*
47  *#* Revision 1.18  2004/10/19 08:54:43  bernie
48  *#* Initialize forbid_cnt; Formatting/comments fixes.
49  *#*
50  *#* Revision 1.17  2004/10/19 08:47:13  bernie
51  *#* proc_rename(), proc_forbid(), proc_permit(): New functions.
52  *#*
53  *#* Revision 1.16  2004/10/03 20:39:28  bernie
54  *#* Import changes from sc/firmware.
55  *#*
56  *#* Revision 1.15  2004/09/20 03:29:39  bernie
57  *#* C++ fixes.
58  *#*
59  *#* Revision 1.14  2004/09/14 21:06:44  bernie
60  *#* Use debug.h instead of kdebug.h.
61  *#*
62  *#* Revision 1.13  2004/08/29 21:58:53  bernie
63  *#* Include macros.h explicityl.
64  *#*
65  *#* Revision 1.11  2004/08/24 16:09:08  bernie
66  *#* Add missing header.
67  *#*
68  *#* Revision 1.10  2004/08/24 16:07:01  bernie
69  *#* Use kputs()/kputchar() when possible.
70  *#*
71  *#* Revision 1.9  2004/08/24 14:26:57  bernie
72  *#* monitor_debug_stacks(): Conditionally compile on CONFIG_KERN_MONITOR.
73  *#*
74  *#* Revision 1.8  2004/08/14 19:37:57  rasky
75  *#* Merge da SC: macros.h, pool.h, BIT_CHANGE, nome dei processi, etc.
76  *#*
77  *#* Revision 1.7  2004/08/02 20:20:29  aleph
78  *#* Merge from project_ks
79  *#*
80  *#* Revision 1.6  2004/07/30 14:24:16  rasky
81  *#* Task switching con salvataggio perfetto stato di interrupt (SR)
82  *#* Kernel monitor per dump informazioni su stack dei processi
83  *#*
84  *#* Revision 1.5  2004/07/14 14:18:09  rasky
85  *#* Merge da SC: Rimosso timer dentro il task, che รจ uno spreco di memoria per troppi task
86  *#*
87  *#* Revision 1.4  2004/07/13 19:21:28  aleph
88  *#* Avoid warning for unused arg when compiled without some CONFIG_KERN_xx options
89  *#*
90  *#* Revision 1.3  2004/06/06 18:37:57  bernie
91  *#* Rename event macros to look like regular functions.
92  *#*
93  *#* Revision 1.2  2004/06/03 11:27:09  bernie
94  *#* Add dual-license information.
95  *#*
96  *#* Revision 1.1  2004/05/23 17:27:00  bernie
97  *#* Import kern/ subdirectory.
98  *#*
99  *#*/
100
101 #include "proc_p.h"
102 #include "proc.h"
103 #include <cfg/cpu.h>
104 #include "event.h"
105 #include "hw.h"
106 #include <cfg/debug.h>
107 #include <cfg/arch_config.h>  /* ARCH_EMUL */
108 #include <cfg/macros.h>  /* ABS() */
109
110 #include <string.h> /* memset() */
111
112 /*!
113  * CPU dependent context switching routines.
114  *
115  * \note This function *MUST* preserve also the status of the interrupts.
116  */
117 EXTERN_C void asm_switch_context(cpustack_t **new_sp, cpustack_t **save_sp);
118 EXTERN_C int asm_switch_version(void);
119
120 /*
121  * The scheduer tracks ready and waiting processes
122  * by enqueuing them in these lists. A pointer to the currently
123  * running process is stored in the CurrentProcess pointer.
124  *
125  * NOTE: these variables are protected by DI/EI locking
126  */
127 REGISTER Process *CurrentProcess;
128 REGISTER List     ProcReadyList;
129
130
131 #if CONFIG_KERN_PREEMPTIVE
132 /*
133  * The time sharing scheduler forces a task switch when
134  * the current process has consumed its quantum.
135  */
136 uint16_t Quantum;
137 #endif
138
139
140 /* In Win32 we must emulate stack on the real process stack */
141 #if (ARCH & ARCH_EMUL)
142 extern List StackFreeList;
143 #endif
144
145 /*! The main process (the one that executes main()). */
146 struct Process MainProcess;
147
148
149 static void proc_init_struct(Process *proc)
150 {
151         /* Avoid warning for unused argument. */
152         (void)proc;
153
154 #if CONFIG_KERN_SIGNALS
155         proc->sig_recv = 0;
156 #endif
157
158 #if CONFIG_KERN_PREEMPTIVE
159         proc->forbid_cnt = 0;
160 #endif
161
162 #if CONFIG_KERN_HEAP
163         proc->flags = 0;
164 #endif
165 }
166
167
168 void proc_init(void)
169 {
170         LIST_INIT(&ProcReadyList);
171
172 #if CONFIG_KERN_MONITOR
173         monitor_init();
174 #endif
175
176         /* We "promote" the current context into a real process. The only thing we have
177          * to do is create a PCB and make it current. We don't need to setup the stack
178          * pointer because it will be written the first time we switch to another process.
179          */
180         proc_init_struct(&MainProcess);
181         CurrentProcess = &MainProcess;
182
183         /* Make sure the assembly routine is up-to-date with us */
184         ASSERT(asm_switch_version() == 1);
185 }
186
187
188 /*!
189  * Create a new process, starting at the provided entry point.
190  *
191  * \return Process structure of new created process
192  *         if successful, NULL otherwise.
193  */
194 struct Process *proc_new_with_name(UNUSED(const char*, name), void (*entry)(void), iptr_t data, size_t stacksize, cpustack_t *stack_base)
195 {
196         Process *proc;
197         size_t i;
198         size_t proc_size_words = ROUND2(sizeof(Process), sizeof(cpustack_t)) / sizeof(cpustack_t);
199 #if CONFIG_KERN_HEAP
200         bool free_stack = false;
201 #endif
202
203 #if (ARCH & ARCH_EMUL)
204         /* Ignore stack provided by caller and use the large enough default instead. */
205         stack_base = (cpustack_t *)StackFreeList.head;
206         REMOVE((Node *)stack_base);
207         stacksize = DEF_STACKSIZE;
208 #elif CONFIG_KERN_HEAP
209         /* Did the caller provide a stack for us? */
210         if (!stack_base)
211         {
212                 /* Did the caller specify the desired stack size? */
213                 if (!stacksize)
214                         stacksize = CONFIG_KERN_DEFSTACKSIZE + sizeof(Process);
215
216                 /* Allocate stack dinamically */
217                 if (!(stack_base = heap_alloc(stacksize)))
218                         return NULL;
219
220                 free_stack = true;
221         }
222 #else
223         /* Stack must have been provided by the user */
224         ASSERT(stack_base);
225         ASSERT(stacksize);
226 #endif
227
228 #if CONFIG_KERN_MONITOR
229         /* Fill-in the stack with a special marker to help debugging */
230         memset(stack_base, CONFIG_KERN_STACKFILLCODE, stacksize / sizeof(cpustack_t));
231 #endif
232
233         /* Initialize the process control block */
234         if (CPU_STACK_GROWS_UPWARD)
235         {
236                 proc = (Process*)stack_base;
237                 proc->stack = stack_base + proc_size_words;
238                 if (CPU_SP_ON_EMPTY_SLOT)
239                         proc->stack++;
240         }
241         else
242         {
243                 proc = (Process*)(stack_base + stacksize / sizeof(cpustack_t) - proc_size_words);
244                 proc->stack = (cpustack_t*)proc;
245                 if (CPU_SP_ON_EMPTY_SLOT)
246                         proc->stack--;
247         }
248
249         proc_init_struct(proc);
250         proc->user_data = data;
251
252 #if CONFIG_KERN_HEAP
253         proc->stack_base = stack_base;
254         proc->stack_size = stack_size;
255         if (free_stack)
256                 proc->flags |= PF_FREESTACK;
257 #endif
258
259         /* Initialize process stack frame */
260         CPU_PUSH_CALL_CONTEXT(proc->stack, proc_exit);
261         CPU_PUSH_CALL_CONTEXT(proc->stack, entry);
262
263         /* Push a clean set of CPU registers for asm_switch_context() */
264         for (i = 0; i < CPU_SAVED_REGS_CNT; i++)
265                 CPU_PUSH_WORD(proc->stack, CPU_REG_INIT_VALUE(i));
266
267         /* Add to ready list */
268         ATOMIC(SCHED_ENQUEUE(proc));
269
270 #if CONFIG_KERN_MONITOR
271         monitor_add(proc, name, stack_base, stacksize);
272 #endif
273
274         return proc;
275 }
276
277 /*! Rename a process */
278 void proc_rename(struct Process *proc, const char *name)
279 {
280 #if CONFIG_KERN_MONITOR
281         monitor_rename(proc, name);
282 #else
283         (void)proc; (void)name;
284 #endif
285 }
286
287
288 /*!
289  * System scheduler: pass CPU control to the next process in
290  * the ready queue.
291  *
292  * Saving and restoring the context on the stack is done
293  * by a CPU-dependent support routine which must usually be
294  * written in assembly.
295  */
296 void proc_schedule(void)
297 {
298         /* This function must not have any "auto" variables, otherwise
299          * the compiler might put them on the stack of the process
300          * being switched out.
301          */
302         static struct Process *old_process;
303         static cpuflags_t flags;
304
305         /* Remember old process to save its context later */
306         old_process = CurrentProcess;
307
308         /* Scheduling in interrupts is a nono. */
309         ASSERT(!IRQ_RUNNING());
310
311         /* Poll on the ready queue for the first ready process */
312         IRQ_SAVE_DISABLE(flags);
313         while (!(CurrentProcess = (struct Process *)REMHEAD(&ProcReadyList)))
314         {
315                 /*
316                  * Make sure we physically reenable interrupts here, no matter what
317                  * the current task status is. This is important because if we
318                  * are idle-spinning, we must allow interrupts, otherwise no
319                  * process will ever wake up.
320                  *
321                  * \todo If there was a way to write sig_wait() so that it does not
322                  * disable interrupts while waiting, there would not be any
323                  * reason to do this.
324                  */
325                 IRQ_ENABLE;
326                 SCHEDULER_IDLE;
327                 IRQ_DISABLE;
328         }
329         IRQ_RESTORE(flags);
330
331         /*
332          * Optimization: don't switch contexts when the active
333          * process has not changed.
334          */
335         if (CurrentProcess != old_process)
336         {
337                 static cpustack_t *dummy;
338
339 #if CONFIG_KERN_PREEMPTIVE
340                 /* Reset quantum for this process */
341                 Quantum = CONFIG_KERN_QUANTUM;
342 #endif
343
344                 /* Save context of old process and switch to new process. If there is no
345                  * old process, we save the old stack pointer into a dummy variable that
346                  * we ignore. In fact, this happens only when the old process has just
347                  * exited.
348                  * TODO: Instead of physically clearing the process at exit time, a zombie
349                  * list should be created.
350                  */
351                 asm_switch_context(&CurrentProcess->stack, old_process ? &old_process->stack : &dummy);
352         }
353
354         /* This RET resumes the execution on the new process */
355 }
356
357
358 /*!
359  * Terminate the current process
360  */
361 void proc_exit(void)
362 {
363 #if CONFIG_KERN_HEAP
364         /* The following code is BROKEN.
365          * We are freeing our own stack before entering proc_schedule()
366          * BAJO: A correct fix would be to rearrange the scheduler with
367          *  an additional parameter which frees the old stack/process
368          *  after a context switch.
369          */
370         if (CurrentProcess->flags & PF_FREESTACK)
371                 heap_free(CurrentProcess->stack_base, CurrentProcess->stack_size);
372         heap_free(CurrentProcess);
373 #endif
374
375 #if (ARCH & ARCH_EMUL)
376 #error This is wrong
377         /* Reinsert process stack in free list */
378         ADDHEAD(&StackFreeList, (Node *)(CurrentProcess->stack
379                 - (DEF_STACKSIZE / sizeof(cpustack_t))));
380
381         /* NOTE: At this point the first two words of what used
382          * to be our stack contain a list node. From now on, we
383          * rely on the compiler not reading/writing the stack.
384          */
385 #endif /* ARCH_EMUL */
386
387 #if CONFIG_KERN_MONITOR
388         monitor_remove(CurrentProcess);
389 #endif
390
391         CurrentProcess = NULL;
392         proc_schedule();
393         /* not reached */
394 }
395
396
397 /*!
398  * Co-operative context switch
399  */
400 void proc_switch(void)
401 {
402         /* Just like proc_schedule, this function must not have auto variables. */
403         static cpuflags_t flags;
404
405         IRQ_SAVE_DISABLE(flags);
406         SCHED_ENQUEUE(CurrentProcess);
407         IRQ_RESTORE(flags);
408
409         proc_schedule();
410 }
411
412
413 /*!
414  * Get the pointer to the current process
415  */
416 struct Process *proc_current(void)
417 {
418         return CurrentProcess;
419 }
420
421 /*!
422  * Get the pointer to the user data of the current process
423  */
424 iptr_t proc_current_user_data(void)
425 {
426         return CurrentProcess->user_data;
427 }
428
429
430 #if CONFIG_KERN_PREEMPTIVE
431
432 /*!
433  * Disable preemptive task switching.
434  *
435  * The scheduler maintains a per-process nesting counter.  Task switching is
436  * effectively re-enabled only when the number of calls to proc_permit()
437  * matches the number of calls to proc_forbid().
438  *
439  * Calling functions that could sleep while task switching is disabled
440  * is dangerous, although supported.  Preemptive task switching is
441  * resumed while the process is sleeping and disabled again as soon as
442  * it wakes up again.
443  *
444  * \sa proc_permit()
445  */
446 void proc_forbid(void)
447 {
448         /* No need to protect against interrupts here. */
449         ++CurrentProcess->forbid_cnt;
450 }
451
452 /*!
453  * Re-enable preemptive task switching.
454  *
455  * \sa proc_forbid()
456  */
457 void proc_permit(void)
458 {
459         /* No need to protect against interrupts here. */
460         --CurrentProcess->forbid_cnt;
461 }
462
463 #endif /* CONFIG_KERN_PREEMPTIVE */
464
465
466 #if 0 /* Simple testcase for the scheduler */
467
468 #include <drv/timer.h>
469
470 /*!
471  * Proc scheduling test subthread 1
472  */
473 static void NORETURN proc_test_thread1(void)
474 {
475         for (;;)
476         {
477                 kputs(">task 1\n");
478                 timer_delay(50);
479                 proc_switch();
480         }
481 }
482
483 /*!
484  * Proc scheduling test subthread 2
485  */
486 static void NORETURN proc_test_thread2(void)
487 {
488         for (;;)
489         {
490                 kputs(">task 2\n");
491                 timer_delay(75);
492                 proc_switch();
493         }
494 }
495
496 static cpustack_t proc_test_stack1[CONFIG_KERN_DEFSTACKSIZE/sizeof(cpustack_t)];
497 static cpustack_t proc_test_stack2[CONFIG_KERN_DEFSTACKSIZE/sizeof(cpustack_t)];
498
499 /*!
500  * Proc scheduling test
501  */
502 void NORETURN proc_test(void)
503 {
504         proc_new(proc_test_thread1, NULL, sizeof(proc_test_stack1), proc_test_stack1);
505         proc_new(proc_test_thread2, NULL, sizeof(proc_test_stack2), proc_test_stack2);
506         kputs("Created tasks\n");
507
508         kputs("stack1:\n");
509         kdump(proc_test_stack1+sizeof(proc_test_stack1)-64, 64);
510         kputs("stack2:\n");
511         kdump(proc_test_stack2+sizeof(proc_test_stack1)-64, 64);
512
513         for (;;)
514         {
515                 kputs(">main task\n");
516                 timer_delay(93);
517                 proc_switch();
518         }
519
520         ASSERT(false);
521 }
522 #endif