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