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