Rename event macros to look like regular functions.
[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.3  2004/06/06 18:37:57  bernie
21  * Rename event macros to look like regular functions.
22  *
23  * Revision 1.2  2004/06/03 11:27:09  bernie
24  * Add dual-license information.
25  *
26  * Revision 1.1  2004/05/23 17:27:00  bernie
27  * Import kern/ subdirectory.
28  *
29  */
30
31 #include "cpu.h"
32 #include "proc_p.h"
33 #include "proc.h"
34 #include "event.h"
35 #include "hw.h"
36 #include <drv/kdebug.h>
37
38 #include <string.h> /* memset() */
39
40 /* CPU dependent context switching routines */
41 extern void asm_switch_context(cpustack_t **new_sp, cpustack_t **save_sp);
42
43 /*
44  * The scheduer tracks ready and waiting processes
45  * by enqueuing them in these lists. A pointer to the currently
46  * running process is stored in the CurrentProcess pointer.
47  *
48  * NOTE: these variables are protected by DI/EI locking
49  */
50 REGISTER Process *CurrentProcess;
51 REGISTER List     ProcReadyList;
52
53 #if CONFIG_KERN_PREEMPTIVE
54 /*
55  * The time sharing scheduler forces a task switch when
56  * the current process has consumed its quantum.
57  */
58 uint16_t Quantum;
59 #endif
60
61
62 /* In Win32 we must emulate stack on the real process stack */
63 #if (ARCH & ARCH_EMUL)
64 extern List StackFreeList;
65 #endif
66
67 /* The main process (the one that executes main()) */
68 struct Process MainProcess;
69
70 static void proc_init_struct(Process* proc)
71 {
72 #if CONFIG_KERN_TIMER
73         event_initSignal(&proc->proc_timer.expire, proc, SIG_SINGLE);
74 #endif
75
76 #if CONFIG_KERN_SIGNALS
77         proc->sig_recv = 0;
78 #endif
79
80 #if CONFIG_KERN_HEAP
81         proc->flags = 0;
82 #endif
83 }
84
85 void proc_init(void)
86 {
87         INITLIST(&ProcReadyList);
88
89         /* We "promote" the current context into a real process. The only thing we have
90            to do is create a PCB and make it current. We don't need to setup the stack
91            pointer because it will be written the first time we switch to another process. */
92         proc_init_struct(&MainProcess);
93         CurrentProcess = &MainProcess;
94 }
95
96
97 /*!
98  * Create a new process, starting at the provided entry point.
99  *
100  * \return Process structure of new created process
101  *         if successful, NULL otherwise.
102  */
103 Process *proc_new(void (*entry)(void), size_t stacksize, cpustack_t *stack_base)
104 {
105         Process *proc;
106         size_t i;
107         size_t proc_size_words = ROUND2(sizeof(Process), sizeof(cpustack_t)) / sizeof(cpustack_t);
108 #if CONFIG_KERN_HEAP
109         bool free_stack = false;
110 #endif
111
112 #if (ARCH & ARCH_EMUL)
113         /* Ignore stack provided by caller
114         * and use the large enough default instead
115         */
116         stack_base = (cpustack_t *)StackFreeList.head;
117         REMOVE((Node *)stack_base);
118         stacksize = DEF_STACKSIZE;
119 #elif CONFIG_KERN_HEAP
120         /* Did the caller provide a stack for us? */
121         if (!stack_base)
122         {
123                 /* Did the caller specify the desired stack size? */
124                 if (!stacksize)
125                         stacksize = CONFIG_KERN_DEFSTACKSIZE + sizeof(Process);
126
127                 /* Allocate stack dinamically */
128                 if (!(stack_base = heap_alloc(stacksize)))
129                         return NULL;
130
131                 free_stack = true;
132         }
133 #else
134         /* Stack must have been provided by the user */
135         ASSERT(stack_base);
136         ASSERT(stacksize);
137 #endif
138
139 #ifdef _DEBUG
140         /* Fill-in the stack with a special marker to help debugging */
141         memset(stack_base, CONFIG_KERN_STACKFILLCODE, stacksize / sizeof(cpustack_t));
142 #endif /* _DEBUG */
143
144         /* Initialize the process control block */
145         if (CPU_STACK_GROWS_UPWARD)
146         {
147                 proc = (Process*)stack_base;
148                 proc->stack = stack_base + proc_size_words;
149                 if (CPU_SP_ON_EMPTY_SLOT)
150                         proc->stack++;
151         }
152         else
153         {
154                 proc = (Process*)(stack_base + stacksize / sizeof(cpustack_t) - proc_size_words);
155                 proc->stack = (cpustack_t*)proc;
156                 if (CPU_SP_ON_EMPTY_SLOT)
157                         proc->stack--;
158         }
159
160         proc_init_struct(proc);
161
162 #if CONFIG_KERN_HEAP
163         proc->stack_base = stack_base;
164         proc->stack_size = stack_size;
165         if (free_stack)
166                 proc->flags |= PF_FREESTACK;
167 #endif
168
169         /* Initialize process stack frame */
170         CPU_PUSH_CALL_CONTEXT(proc->stack, proc_exit);
171         CPU_PUSH_CALL_CONTEXT(proc->stack, entry);
172
173         /* Push a clean set of CPU registers for asm_switch_context() */
174         for (i = 0; i < CPU_SAVED_REGS_CNT; i++)
175                 CPU_PUSH_WORD(proc->stack, CPU_REG_INIT_VALUE(i));
176
177         /* Add to ready list */
178         DISABLE_INTS;
179         SCHED_ENQUEUE(proc);
180         ENABLE_INTS;
181
182         return proc;
183 }
184
185
186 /*!
187  * System scheduler: pass CPU control to the next process in
188  * the ready queue.
189  *
190  * Saving and restoring the context on the stack is done
191  * by a CPU-dependent support routine which must usually be
192  * written in assembly.
193  */
194 void proc_schedule(void)
195 {
196         /* This function must not have any "auto" variables, otherwise
197          * the compiler might put them on the stack of the process
198          * being switched out.
199          */
200         static Process *old_process;
201
202         /* Remember old process to save its context later */
203         old_process = CurrentProcess;
204         CurrentProcess = NULL;
205
206         /* Poll on the ready queue for the first ready process
207          */
208         for(;;) /* forever */
209         {
210                 /* Do CPU specific idle processing (ARGH, should be moved to the end of the loop!) */
211                 SCHEDULER_IDLE;
212
213                 DISABLE_INTS;
214                 if (!ISLISTEMPTY(&ProcReadyList))
215                 {
216                         /* Get process from ready list */
217                         CurrentProcess = (Process *)ProcReadyList.head;
218                         REMOVE((Node *)CurrentProcess);
219                         ENABLE_INTS;
220                         break;
221                 }
222                 ENABLE_INTS;
223         }
224
225         /* Optimization: don't switch contexts when the active
226          * process has not changed.
227          */
228         if (CurrentProcess != old_process)
229         {
230                 static cpustack_t* dummy;
231
232 #if CONFIG_KERN_PREEMPTIVE
233                 /* Reset quantum for this process */
234                 Quantum = CONFIG_KERN_QUANTUM;
235 #endif
236
237                 /* Save context of old process and switch to new process. If there is no
238                  * old process, we save the old stack pointer into a dummy variable that
239                  * we ignore. In fact, this happens only when the old process has just
240                  * exited.
241                  * TODO: Instead of physically clearing the process at exit time, a zombie
242                  * list should be created.
243                  */
244                 asm_switch_context(&CurrentProcess->stack, old_process ? &old_process->stack : &dummy);
245         }
246
247         /* This RET resumes the execution on the new process */
248 }
249
250
251 /*!
252  * Terminate the current process
253  */
254 void proc_exit(void)
255 {
256 #if CONFIG_KERN_HEAP
257         /* The following code is BROKEN.
258          * We are freeing our own stack before entering proc_schedule()
259          * BAJO: A correct fix would be to rearrange the scheduler with
260          *  an additional parameter which frees the old stack/process
261          *  after a context switch.
262          */
263         if (CurrentProcess->flags & PF_FREESTACK)
264                 heap_free(CurrentProcess->stack_base, CurrentProcess->stack_size);
265         heap_free(CurrentProcess);
266 #endif
267
268 #if (ARCH & ARCH_EMUL)
269 #error This is wrong
270         /* Reinsert process stack in free list */
271         ADDHEAD(&StackFreeList, (Node *)(CurrentProcess->stack
272                 - (DEF_STACKSIZE / sizeof(cpustack_t))));
273
274         /* NOTE: At this point the first two words of what used
275          * to be our stack contain a list node. From now on, we
276          * rely on the compiler not reading/writing the stack.
277          */
278 #endif /* ARCH_EMUL */
279
280         CurrentProcess = NULL;
281         proc_schedule();
282         /* not reached */
283 }
284
285
286 /*!
287  * Co-operative context switch
288  */
289 void proc_switch(void)
290 {
291         DISABLE_INTS;
292         SCHED_ENQUEUE(CurrentProcess);
293         ENABLE_INTS;
294         proc_schedule();
295 }
296
297
298 /*!
299  * Get the pointer to the current process
300  */
301 struct Process *proc_current(void)
302 {
303         return CurrentProcess;
304 }
305
306
307 #if 0 /* Simple testcase for the scheduler */
308
309 /*!
310  * Proc scheduling test subthread 1
311  */
312 static void NORETURN proc_test_thread1(void)
313 {
314         for (;;)
315         {
316                 kputs(">task 1\n");
317                 timer_delay(50);
318                 proc_switch();
319         }
320 }
321
322 /*!
323  * Proc scheduling test subthread 2
324  */
325 static void NORETURN proc_test_thread2(void)
326 {
327         for (;;)
328         {
329                 kputs(">task 2\n");
330                 timer_delay(75);
331                 proc_switch();
332         }
333 }
334
335 static cpustack_t proc_test_stack1[CONFIG_KERN_DEFSTACKSIZE/sizeof(cpustack_t)];
336 static cpustack_t proc_test_stack2[CONFIG_KERN_DEFSTACKSIZE/sizeof(cpustack_t)];
337
338 /*!
339  * Proc scheduling test
340  */
341 void NORETURN proc_test(void)
342 {
343         proc_new(proc_test_thread1, sizeof(proc_test_stack1), proc_test_stack1);
344         proc_new(proc_test_thread2, sizeof(proc_test_stack2), proc_test_stack2);
345         kputs("Created tasks\n");
346
347         kputs("stack1:\n");
348         kdump(proc_test_stack1+sizeof(proc_test_stack1)-64, 64);
349         kputs("stack2:\n");
350         kdump(proc_test_stack2+sizeof(proc_test_stack1)-64, 64);
351
352         for (;;)
353         {
354                 kputs(">main task\n");
355                 timer_delay(93);
356                 proc_switch();
357         }
358
359         ASSERT(false);
360 }
361 #endif