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