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