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