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