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