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