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