preempt: Implement scheduling priorities
[bertos.git] / bertos / 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, 2008 Bernie Innocenti <bernie@codewiz.org>
31  * -->
32  *
33  * \brief Simple realtime multitasking scheduler.
34  *        Context switching is only done cooperatively.
35  *
36  * \version $Id$
37  * \author Bernie Innocenti <bernie@codewiz.org>
38  * \author Stefano Fedrigo <aleph@develer.com>
39  */
40
41 #include "proc_p.h"
42 #include "proc.h"
43
44 #include "cfg/cfg_arch.h"  /* ARCH_EMUL */
45 #include "cfg/cfg_kern.h"
46 #include <cfg/module.h>
47
48 #include <cpu/irq.h>
49 #include <cpu/types.h>
50 #include <cpu/attr.h>
51 #include <cpu/frame.h>
52
53 #include <string.h>           /* memset() */
54
55 // FIXME: move somewhere
56 #define CONFIG_DEPEND(FEATURE, DEPS)  STATIC_ASSERT(!(FEATURE) || !!(DEPS))
57
58 CONFIG_DEPEND(CONFIG_KERN_PRI, CONFIG_KERN_PREEMPT);
59
60
61 /*
62  * The scheduer tracks ready processes by enqueuing them in the
63  * ready list.
64  *
65  * \note Access to the list must occur while interrupts are disabled.
66  */
67 REGISTER List ProcReadyList;
68
69 /*
70  * Holds a pointer to the TCB of the currently running process.
71  *
72  * \note User applications should use proc_current() to retrieve this value.
73  */
74 REGISTER Process *CurrentProcess;
75
76 #if (ARCH & ARCH_EMUL)
77 /*
78  * In hosted environments, we must emulate the stack on the real process stack.
79  *
80  * Access to this list must be protected by PROC_ATOMIC().
81  */
82 extern List StackFreeList;
83 #endif
84
85 /** The main process (the one that executes main()). */
86 struct Process MainProcess;
87
88
89 static void proc_init_struct(Process *proc)
90 {
91         /* Avoid warning for unused argument. */
92         (void)proc;
93
94 #if CONFIG_KERN_SIGNALS
95         proc->sig_recv = 0;
96 #endif
97
98 #if CONFIG_KERN_HEAP
99         proc->flags = 0;
100 #endif
101
102 #if CONFIG_KERN_PRI
103         proc->link.pri = 0;
104 #endif
105 }
106
107 MOD_DEFINE(proc);
108
109 void proc_init(void)
110 {
111         LIST_INIT(&ProcReadyList);
112
113         /*
114          * We "promote" the current context into a real process. The only thing we have
115          * to do is create a PCB and make it current. We don't need to setup the stack
116          * pointer because it will be written the first time we switch to another process.
117          */
118         proc_init_struct(&MainProcess);
119         CurrentProcess = &MainProcess;
120
121 #if CONFIG_KERN_MONITOR
122         monitor_init();
123         monitor_add(CurrentProcess, "main");
124 #endif
125
126 #if CONFIG_KERN_PREEMPT
127         preempt_init();
128 #endif
129
130         MOD_INIT(proc);
131 }
132
133
134 /**
135  * Create a new process, starting at the provided entry point.
136  *
137  * \return Process structure of new created process
138  *         if successful, NULL otherwise.
139  */
140 struct Process *proc_new_with_name(UNUSED(const char *, name), void (*entry)(void), iptr_t data, size_t stack_size, cpustack_t *stack_base)
141 {
142         Process *proc;
143         const 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         TRACEMSG("name=%s", name);
148
149 #if (ARCH & ARCH_EMUL)
150         /* Ignore stack provided by caller and use the large enough default instead. */
151         PROC_ATOMIC(stack_base = (cpustack_t *)list_remHead(&StackFreeList));
152
153         stack_size = CONFIG_KERN_MINSTACKSIZE;
154 #elif CONFIG_KERN_HEAP
155         /* Did the caller provide a stack for us? */
156         if (!stack_base)
157         {
158                 /* Did the caller specify the desired stack size? */
159                 if (!stack_size)
160                         stack_size = CONFIG_KERN_MINSTACKSIZE;
161
162                 /* Allocate stack dinamically */
163                 if (!(stack_base = heap_alloc(stack_size)))
164                         return NULL;
165
166                 free_stack = true;
167         }
168
169 #else // !ARCH_EMUL && !CONFIG_KERN_HEAP
170
171         /* Stack must have been provided by the user */
172         ASSERT_VALID_PTR(stack_base);
173         ASSERT(stack_size);
174
175 #endif // !ARCH_EMUL && !CONFIG_KERN_HEAP
176
177 #if CONFIG_KERN_MONITOR
178         /* Fill-in the stack with a special marker to help debugging */
179         memset(stack_base, CONFIG_KERN_STACKFILLCODE, stack_size);
180 #endif
181
182         /* Initialize the process control block */
183         if (CPU_STACK_GROWS_UPWARD)
184         {
185                 proc = (Process *)stack_base;
186                 proc->stack = stack_base + PROC_SIZE_WORDS;
187                 if (CPU_SP_ON_EMPTY_SLOT)
188                         proc->stack++;
189         }
190         else
191         {
192                 proc = (Process *)(stack_base + stack_size / sizeof(cpustack_t) - PROC_SIZE_WORDS);
193                 proc->stack = (cpustack_t *)proc;
194                 if (CPU_SP_ON_EMPTY_SLOT)
195                         proc->stack--;
196         }
197
198         proc_init_struct(proc);
199         proc->user_data = data;
200
201 #if CONFIG_KERN_HEAP | CONFIG_KERN_MONITOR | (ARCH & ARCH_EMUL)
202         proc->stack_base = stack_base;
203         proc->stack_size = stack_size;
204         #if CONFIG_KERN_HEAP
205         if (free_stack)
206                 proc->flags |= PF_FREESTACK;
207         #endif
208 #endif
209
210         #if CONFIG_KERN_PREEMPT
211
212                 getcontext(&proc->context);
213                 proc->context.uc_stack.ss_sp = proc->stack;
214                 proc->context.uc_stack.ss_size = stack_size - PROC_SIZE_WORDS - 1;
215                 proc->context.uc_link = NULL;
216                 makecontext(&proc->context, (void (*)(void))proc_entry, 1, entry);
217
218         #else // !CONFIG_KERN_PREEMPT
219         {
220                 size_t i;
221
222                 /* Initialize process stack frame */
223                 CPU_PUSH_CALL_FRAME(proc->stack, proc_exit);
224                 CPU_PUSH_CALL_FRAME(proc->stack, entry);
225
226                 /* Push a clean set of CPU registers for asm_switch_context() */
227                 for (i = 0; i < CPU_SAVED_REGS_CNT; i++)
228                         CPU_PUSH_WORD(proc->stack, CPU_REG_INIT_VALUE(i));
229         }
230         #endif // CONFIG_KERN_PREEMPT
231
232         #if CONFIG_KERN_MONITOR
233                 monitor_add(proc, name);
234         #endif
235
236         /* Add to ready list */
237         ATOMIC(SCHED_ENQUEUE(proc));
238
239         return proc;
240 }
241
242 /**
243  * Return the name of the specified process.
244  *
245  * NULL is a legal argument and will return the name "<NULL>".
246  */
247 const char *proc_name(struct Process *proc)
248 {
249         #if CONFIG_KERN_MONITOR
250                 return proc ? proc->monitor.name : "<NULL>";
251         #else
252                 (void)proc;
253                 return "---";
254         #endif
255 }
256
257 /// Return the name of the currently running process
258 const char *proc_currentName(void)
259 {
260         return proc_name(proc_current());
261 }
262
263 /// Rename a process
264 void proc_rename(struct Process *proc, const char *name)
265 {
266 #if CONFIG_KERN_MONITOR
267         monitor_rename(proc, name);
268 #else
269         (void)proc; (void)name;
270 #endif
271 }
272
273 /**
274  * Change the scheduling priority of a process.
275  *
276  * Process piorities are signed ints, whereas a larger integer value means
277  * higher scheduling priority.  The default priority for new processes is 0.
278  * The idle process runs with the lowest possible priority: INT_MIN.
279  *
280  * A process with a higher priority always preempts lower priority processes.
281  * Processes of equal priority share the CPU time according to a simple
282  * round-robin policy.
283  *
284  * As a general rule to maximize responsiveness, compute-bound processes
285  * should be assigned negative priorities and tight, interactive processes
286  * should be assigned positive priorities.
287  *
288  * To avoid interfering with system background activities such as input
289  * processing, application processes should remain within the range -10
290  * and +10.
291  */
292 void proc_setPri(struct Process *proc, int pri)
293 {
294                 if (proc->link.pri == pri)
295                         return;
296
297                 proc->link.pri = pri;
298
299                 if (proc != CurrentProcess)
300                 {
301                                 //proc_forbid();
302                                 //TODO: re-enqueue process
303                                 //pric_permit();
304                 }
305 }
306
307 /**
308  * Terminate the current process
309  */
310 void proc_exit(void)
311 {
312         TRACEMSG("%p:%s", CurrentProcess, proc_currentName());
313
314 #if CONFIG_KERN_MONITOR
315         monitor_remove(CurrentProcess);
316 #endif
317
318 #if CONFIG_KERN_HEAP
319         /*
320          * The following code is BROKEN.
321          * We are freeing our own stack before entering proc_schedule()
322          * BAJO: A correct fix would be to rearrange the scheduler with
323          *  an additional parameter which frees the old stack/process
324          *  after a context switch.
325          */
326         if (CurrentProcess->flags & PF_FREESTACK)
327                 heap_free(CurrentProcess->stack_base, CurrentProcess->stack_size);
328         heap_free(CurrentProcess);
329 #endif
330
331 #if (ARCH & ARCH_EMUL)
332         /* Reinsert process stack in free list */
333         PROC_ATOMIC(ADDHEAD(&StackFreeList, (Node *)CurrentProcess->stack_base));
334
335         /*
336          * NOTE: At this point the first two words of what used
337          * to be our stack contain a list node. From now on, we
338          * rely on the compiler not reading/writing the stack.
339          */
340 #endif /* ARCH_EMUL */
341
342         CurrentProcess = NULL;
343         proc_schedule();
344         /* not reached */
345 }
346
347
348 /**
349  * Get the pointer to the current process
350  */
351 struct Process *proc_current(void)
352 {
353         return CurrentProcess;
354 }
355
356 /**
357  * Get the pointer to the user data of the current process
358  */
359 iptr_t proc_currentUserData(void)
360 {
361         return CurrentProcess->user_data;
362 }