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