Fix catastrophic bug in proc_switch. Remove unneeded comments.
[bertos.git] / kern / proc.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2001,2004 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 1999,2000,2001 Bernardo Innocenti <bernie@develer.com>
31  *
32  * -->
33  *
34  * \brief Simple realtime multitasking scheduler.
35  *        Context switching is only done cooperatively.
36  *
37  * \version $Id$
38  *
39  * \author Bernardo Innocenti <bernie@develer.com>
40  * \author Stefano Fedrigo <aleph@develer.com>
41  */
42
43
44 #include "proc_p.h"
45 #include "proc.h"
46 //#include "hw.h"
47 #include <mware/event.h>
48 #include <cpu/irq.h>
49 #include <cpu/types.h>
50 #include <cpu/attr.h>
51 #include <cfg/debug.h>
52 #include <cfg/module.h>
53 #include <cfg/arch_config.h>  /* ARCH_EMUL */
54 #include <cfg/macros.h>  /* ABS() */
55
56 #include <string.h> /* memset() */
57
58 /**
59  * CPU dependent context switching routines.
60  *
61  * \note This function *MUST* preserve also the status of the interrupts.
62  */
63 EXTERN_C void asm_switch_context(cpustack_t **new_sp, cpustack_t **save_sp);
64 EXTERN_C int asm_switch_version(void);
65
66 /*
67  * The scheduer tracks ready and waiting processes
68  * by enqueuing them in these lists. A pointer to the currently
69  * running process is stored in the CurrentProcess pointer.
70  *
71  * NOTE: these variables are protected by DI/EI locking
72  */
73 REGISTER Process *CurrentProcess;
74 REGISTER List     ProcReadyList;
75
76
77 #if CONFIG_KERN_PREEMPTIVE
78 /*
79  * The time sharing scheduler forces a task switch when
80  * the current process has consumed its quantum.
81  */
82 uint16_t Quantum;
83 #endif
84
85
86 /* In Win32 we must emulate stack on the real process stack */
87 #if (ARCH & ARCH_EMUL)
88 extern List StackFreeList;
89 #endif
90
91 /** The main process (the one that executes main()). */
92 struct Process MainProcess;
93
94
95 static void proc_init_struct(Process *proc)
96 {
97         /* Avoid warning for unused argument. */
98         (void)proc;
99
100 #if CONFIG_KERN_SIGNALS
101         proc->sig_recv = 0;
102 #endif
103
104 #if CONFIG_KERN_PREEMPTIVE
105         proc->forbid_cnt = 0;
106 #endif
107
108 #if CONFIG_KERN_HEAP
109         proc->flags = 0;
110 #endif
111 }
112
113 MOD_DEFINE(proc);
114
115 void proc_init(void)
116 {
117         LIST_INIT(&ProcReadyList);
118
119 #if CONFIG_KERN_MONITOR
120         monitor_init();
121 #endif
122
123         /* We "promote" the current context into a real process. The only thing we have
124          * to do is create a PCB and make it current. We don't need to setup the stack
125          * pointer because it will be written the first time we switch to another process.
126          */
127         proc_init_struct(&MainProcess);
128         CurrentProcess = &MainProcess;
129
130         /* Make sure the assembly routine is up-to-date with us */
131         ASSERT(asm_switch_version() == 1);
132         MOD_INIT(proc);
133 }
134
135
136 /**
137  * Create a new process, starting at the provided entry point.
138  *
139  * \return Process structure of new created process
140  *         if successful, NULL otherwise.
141  */
142 struct Process *proc_new_with_name(UNUSED(const char *, name), void (*entry)(void), iptr_t data, size_t stacksize, cpustack_t *stack_base)
143 {
144         Process *proc;
145         size_t i;
146         size_t proc_size_words = ROUND2(sizeof(Process), sizeof(cpustack_t)) / sizeof(cpustack_t);
147 #if CONFIG_KERN_HEAP
148         bool free_stack = false;
149 #endif
150
151 #if (ARCH & ARCH_EMUL)
152         /* Ignore stack provided by caller and use the large enough default instead. */
153         stack_base = (cpustack_t *)LIST_HEAD(&StackFreeList);
154         REMOVE(LIST_HEAD(&StackFreeList));
155         stacksize = CONFIG_PROC_DEFSTACKSIZE;
156 #elif CONFIG_KERN_HEAP
157         /* Did the caller provide a stack for us? */
158         if (!stack_base)
159         {
160                 /* Did the caller specify the desired stack size? */
161                 if (!stacksize)
162                         stacksize = CONFIG_PROC_DEFSTACKSIZE + sizeof(Process);
163
164                 /* Allocate stack dinamically */
165                 if (!(stack_base = heap_alloc(stacksize)))
166                         return NULL;
167
168                 free_stack = true;
169         }
170 #else
171         /* Stack must have been provided by the user */
172         ASSERT(stack_base);
173         ASSERT(stacksize);
174 #endif
175
176 #if CONFIG_KERN_MONITOR
177         /* Fill-in the stack with a special marker to help debugging */
178         memset(stack_base, CONFIG_KERN_STACKFILLCODE, stacksize / sizeof(cpustack_t));
179 #endif
180
181         /* Initialize the process control block */
182         if (CPU_STACK_GROWS_UPWARD)
183         {
184                 proc = (Process*)stack_base;
185                 proc->stack = stack_base + proc_size_words;
186                 if (CPU_SP_ON_EMPTY_SLOT)
187                         proc->stack++;
188         }
189         else
190         {
191                 proc = (Process*)(stack_base + stacksize / sizeof(cpustack_t) - proc_size_words);
192                 proc->stack = (cpustack_t*)proc;
193                 if (CPU_SP_ON_EMPTY_SLOT)
194                         proc->stack--;
195         }
196
197         proc_init_struct(proc);
198         proc->user_data = data;
199
200 #if CONFIG_KERN_HEAP
201         proc->stack_base = stack_base;
202         proc->stack_size = stack_size;
203         if (free_stack)
204                 proc->flags |= PF_FREESTACK;
205 #endif
206
207         /* Initialize process stack frame */
208         CPU_PUSH_CALL_CONTEXT(proc->stack, proc_exit);
209         CPU_PUSH_CALL_CONTEXT(proc->stack, entry);
210
211         /* Push a clean set of CPU registers for asm_switch_context() */
212         for (i = 0; i < CPU_SAVED_REGS_CNT; i++)
213                 CPU_PUSH_WORD(proc->stack, CPU_REG_INIT_VALUE(i));
214
215         /* Add to ready list */
216         ATOMIC(SCHED_ENQUEUE(proc));
217
218 #if CONFIG_KERN_MONITOR
219         monitor_add(proc, name, stack_base, stacksize);
220 #endif
221
222         return proc;
223 }
224
225 /** Rename a process */
226 void proc_rename(struct Process *proc, const char *name)
227 {
228 #if CONFIG_KERN_MONITOR
229         monitor_rename(proc, name);
230 #else
231         (void)proc; (void)name;
232 #endif
233 }
234
235
236 /**
237  * System scheduler: pass CPU control to the next process in
238  * the ready queue.
239  *
240  * Saving and restoring the context on the stack is done
241  * by a CPU-dependent support routine which must usually be
242  * written in assembly.
243  */
244 void proc_schedule(void)
245 {
246         struct Process *old_process;
247         cpuflags_t flags;
248
249         /* Remember old process to save its context later */
250         old_process = CurrentProcess;
251
252 #ifdef IRQ_RUNNING
253         /* Scheduling in interrupts is a nono. */
254         ASSERT(!IRQ_RUNNING());
255 #endif
256
257         /* Poll on the ready queue for the first ready process */
258         IRQ_SAVE_DISABLE(flags);
259         while (!(CurrentProcess = (struct Process *)list_remHead(&ProcReadyList)))
260         {
261                 /*
262                  * Make sure we physically reenable interrupts here, no matter what
263                  * the current task status is. This is important because if we
264                  * are idle-spinning, we must allow interrupts, otherwise no
265                  * process will ever wake up.
266                  *
267                  * \todo If there was a way to write sig_wait() so that it does not
268                  * disable interrupts while waiting, there would not be any
269                  * reason to do this.
270                  */
271                 IRQ_ENABLE;
272                 CPU_IDLE;
273                 IRQ_DISABLE;
274         }
275         IRQ_RESTORE(flags);
276
277         /*
278          * Optimization: don't switch contexts when the active
279          * process has not changed.
280          */
281         if (CurrentProcess != old_process)
282         {
283                 cpustack_t *dummy;
284
285 #if CONFIG_KERN_PREEMPTIVE
286                 /* Reset quantum for this process */
287                 Quantum = CONFIG_KERN_QUANTUM;
288 #endif
289
290                 /* Save context of old process and switch to new process. If there is no
291                  * old process, we save the old stack pointer into a dummy variable that
292                  * we ignore. In fact, this happens only when the old process has just
293                  * exited.
294                  * TODO: Instead of physically clearing the process at exit time, a zombie
295                  * list should be created.
296                  */
297                 asm_switch_context(&CurrentProcess->stack, old_process ? &old_process->stack : &dummy);
298         }
299
300         /* This RET resumes the execution on the new process */
301 }
302
303
304 /**
305  * Terminate the current process
306  */
307 void proc_exit(void)
308 {
309 #if CONFIG_KERN_MONITOR
310         monitor_remove(CurrentProcess);
311 #endif
312
313 #if CONFIG_KERN_HEAP
314         /*
315          * The following code is BROKEN.
316          * We are freeing our own stack before entering proc_schedule()
317          * BAJO: A correct fix would be to rearrange the scheduler with
318          *  an additional parameter which frees the old stack/process
319          *  after a context switch.
320          */
321         if (CurrentProcess->flags & PF_FREESTACK)
322                 heap_free(CurrentProcess->stack_base, CurrentProcess->stack_size);
323         heap_free(CurrentProcess);
324 #endif
325
326 #if (ARCH & ARCH_EMUL)
327 #warning This is wrong
328         /* Reinsert process stack in free list */
329         ADDHEAD(&StackFreeList, (Node *)(CurrentProcess->stack
330                 - (CONFIG_PROC_DEFSTACKSIZE / sizeof(cpustack_t))));
331
332         /*
333          * NOTE: At this point the first two words of what used
334          * to be our stack contain a list node. From now on, we
335          * rely on the compiler not reading/writing the stack.
336          */
337 #endif /* ARCH_EMUL */
338
339         CurrentProcess = NULL;
340         proc_schedule();
341         /* not reached */
342 }
343
344
345 /**
346  * Co-operative context switch
347  */
348 void proc_switch(void)
349 {
350         cpuflags_t flags;
351
352         IRQ_SAVE_DISABLE(flags);
353         SCHED_ENQUEUE(CurrentProcess);
354         IRQ_RESTORE(flags);
355
356         proc_schedule();
357 }
358
359
360 /**
361  * Get the pointer to the current process
362  */
363 struct Process *proc_current(void)
364 {
365         return CurrentProcess;
366 }
367
368 /**
369  * Get the pointer to the user data of the current process
370  */
371 iptr_t proc_current_user_data(void)
372 {
373         return CurrentProcess->user_data;
374 }
375
376
377 #if CONFIG_KERN_PREEMPTIVE
378
379 /**
380  * Disable preemptive task switching.
381  *
382  * The scheduler maintains a per-process nesting counter.  Task switching is
383  * effectively re-enabled only when the number of calls to proc_permit()
384  * matches the number of calls to proc_forbid().
385  *
386  * Calling functions that could sleep while task switching is disabled
387  * is dangerous, although supported.  Preemptive task switching is
388  * resumed while the process is sleeping and disabled again as soon as
389  * it wakes up again.
390  *
391  * \sa proc_permit()
392  */
393 void proc_forbid(void)
394 {
395         /* No need to protect against interrupts here. */
396         ++CurrentProcess->forbid_cnt;
397 }
398
399 /**
400  * Re-enable preemptive task switching.
401  *
402  * \sa proc_forbid()
403  */
404 void proc_permit(void)
405 {
406         /* No need to protect against interrupts here. */
407         --CurrentProcess->forbid_cnt;
408 }
409
410 #endif /* CONFIG_KERN_PREEMPTIVE */