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