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