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