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