preempt: thinko: proc->context.uc_stack.ss_size needs to be reduced by the size of...
[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
56 /*
57  * The scheduer tracks ready processes by enqueuing them in the
58  * ready list.
59  *
60  * \note Access to the list must occur while interrupts are disabled.
61  */
62 REGISTER List ProcReadyList;
63
64 /*
65  * Holds a pointer to the TCB of the currently running process.
66  *
67  * \note User applications should use proc_current() to retrieve this value.
68  */
69 REGISTER Process *CurrentProcess;
70
71 #if (ARCH & ARCH_EMUL)
72 /*
73  * In hosted environments, we must emulate the stack on the real process stack.
74  *
75  * Access to this list must be protected by PROC_ATOMIC().
76  */
77 extern List StackFreeList;
78 #endif
79
80 /** The main process (the one that executes main()). */
81 struct Process MainProcess;
82
83
84 static void proc_init_struct(Process *proc)
85 {
86         /* Avoid warning for unused argument. */
87         (void)proc;
88
89 #if CONFIG_KERN_SIGNALS
90         proc->sig_recv = 0;
91 #endif
92
93 #if CONFIG_KERN_HEAP
94         proc->flags = 0;
95 #endif
96 }
97
98 MOD_DEFINE(proc);
99
100 void proc_init(void)
101 {
102         LIST_INIT(&ProcReadyList);
103
104         /*
105          * We "promote" the current context into a real process. The only thing we have
106          * to do is create a PCB and make it current. We don't need to setup the stack
107          * pointer because it will be written the first time we switch to another process.
108          */
109         proc_init_struct(&MainProcess);
110         CurrentProcess = &MainProcess;
111
112 #if CONFIG_KERN_MONITOR
113         monitor_init();
114         monitor_add(CurrentProcess, "main");
115 #endif
116
117 #if CONFIG_KERN_PREEMPT
118         preempt_init();
119 #endif
120
121         MOD_INIT(proc);
122 }
123
124
125 /**
126  * Create a new process, starting at the provided entry point.
127  *
128  * \return Process structure of new created process
129  *         if successful, NULL otherwise.
130  */
131 struct Process *proc_new_with_name(UNUSED(const char *, name), void (*entry)(void), iptr_t data, size_t stack_size, cpustack_t *stack_base)
132 {
133         Process *proc;
134         const size_t PROC_SIZE_WORDS = ROUND2(sizeof(Process), sizeof(cpustack_t)) / sizeof(cpustack_t);
135 #if CONFIG_KERN_HEAP
136         bool free_stack = false;
137 #endif
138         TRACEMSG("name=%s", name);
139
140 #if (ARCH & ARCH_EMUL)
141         /* Ignore stack provided by caller and use the large enough default instead. */
142         PROC_ATOMIC(stack_base = (cpustack_t *)list_remHead(&StackFreeList));
143
144         stack_size = CONFIG_KERN_MINSTACKSIZE;
145 #elif CONFIG_KERN_HEAP
146         /* Did the caller provide a stack for us? */
147         if (!stack_base)
148         {
149                 /* Did the caller specify the desired stack size? */
150                 if (!stack_size)
151                         stack_size = CONFIG_KERN_MINSTACKSIZE;
152
153                 /* Allocate stack dinamically */
154                 if (!(stack_base = heap_alloc(stack_size)))
155                         return NULL;
156
157                 free_stack = true;
158         }
159
160 #else // !ARCH_EMUL && !CONFIG_KERN_HEAP
161
162         /* Stack must have been provided by the user */
163         ASSERT_VALID_PTR(stack_base);
164         ASSERT(stack_size);
165
166 #endif // !ARCH_EMUL && !CONFIG_KERN_HEAP
167
168 #if CONFIG_KERN_MONITOR
169         /* Fill-in the stack with a special marker to help debugging */
170         memset(stack_base, CONFIG_KERN_STACKFILLCODE, stack_size);
171 #endif
172
173         /* Initialize the process control block */
174         if (CPU_STACK_GROWS_UPWARD)
175         {
176                 proc = (Process *)stack_base;
177                 proc->stack = stack_base + PROC_SIZE_WORDS;
178                 if (CPU_SP_ON_EMPTY_SLOT)
179                         proc->stack++;
180         }
181         else
182         {
183                 proc = (Process *)(stack_base + stack_size / sizeof(cpustack_t) - PROC_SIZE_WORDS);
184                 proc->stack = (cpustack_t *)proc;
185                 if (CPU_SP_ON_EMPTY_SLOT)
186                         proc->stack--;
187         }
188
189         proc_init_struct(proc);
190         proc->user_data = data;
191
192 #if CONFIG_KERN_HEAP | CONFIG_KERN_MONITOR | (ARCH & ARCH_EMUL)
193         proc->stack_base = stack_base;
194         proc->stack_size = stack_size;
195         #if CONFIG_KERN_HEAP
196         if (free_stack)
197                 proc->flags |= PF_FREESTACK;
198         #endif
199 #endif
200
201         #if CONFIG_KERN_PREEMPT
202
203                 getcontext(&proc->context);
204                 proc->context.uc_stack.ss_sp = proc->stack;
205                 proc->context.uc_stack.ss_size = stack_size - PROC_SIZE_WORDS - 1;
206                 proc->context.uc_link = NULL;
207                 makecontext(&proc->context, (void (*)(void))proc_entry, 1, entry);
208
209         #else // !CONFIG_KERN_PREEMPT
210         {
211                 size_t i;
212
213                 /* Initialize process stack frame */
214                 CPU_PUSH_CALL_FRAME(proc->stack, proc_exit);
215                 CPU_PUSH_CALL_FRAME(proc->stack, entry);
216
217                 /* Push a clean set of CPU registers for asm_switch_context() */
218                 for (i = 0; i < CPU_SAVED_REGS_CNT; i++)
219                         CPU_PUSH_WORD(proc->stack, CPU_REG_INIT_VALUE(i));
220         }
221         #endif // CONFIG_KERN_PREEMPT
222
223         #if CONFIG_KERN_MONITOR
224                 monitor_add(proc, name);
225         #endif
226
227         /* Add to ready list */
228         ATOMIC(SCHED_ENQUEUE(proc));
229
230         return proc;
231 }
232
233 /**
234  * Return the name of the specified process.
235  *
236  * NULL is a legal argument and will return the name "<NULL>".
237  */
238 const char *proc_name(struct Process *proc)
239 {
240         #if CONFIG_KERN_MONITOR
241                 return proc ? proc->monitor.name : "<NULL>";
242         #else
243                 (void)proc;
244                 return "---";
245         #endif
246 }
247
248 /// Return the name of the currently running process
249 const char *proc_currentName(void)
250 {
251         return proc_name(proc_current());
252 }
253
254 /// Rename a process
255 void proc_rename(struct Process *proc, const char *name)
256 {
257 #if CONFIG_KERN_MONITOR
258         monitor_rename(proc, name);
259 #else
260         (void)proc; (void)name;
261 #endif
262 }
263
264 /**
265  * Terminate the current process
266  */
267 void proc_exit(void)
268 {
269         TRACEMSG("%p:%s", CurrentProcess, proc_currentName());
270
271 #if CONFIG_KERN_MONITOR
272         monitor_remove(CurrentProcess);
273 #endif
274
275 #if CONFIG_KERN_HEAP
276         /*
277          * The following code is BROKEN.
278          * We are freeing our own stack before entering proc_schedule()
279          * BAJO: A correct fix would be to rearrange the scheduler with
280          *  an additional parameter which frees the old stack/process
281          *  after a context switch.
282          */
283         if (CurrentProcess->flags & PF_FREESTACK)
284                 heap_free(CurrentProcess->stack_base, CurrentProcess->stack_size);
285         heap_free(CurrentProcess);
286 #endif
287
288 #if (ARCH & ARCH_EMUL)
289 #warning This is wrong
290         /* Reinsert process stack in free list */
291         PROC_ATOMIC(ADDHEAD(&StackFreeList, (Node *)(CurrentProcess->stack
292                 - (CONFIG_PROC_DEFSTACKSIZE / sizeof(cpustack_t)))));
293
294         /*
295          * NOTE: At this point the first two words of what used
296          * to be our stack contain a list node. From now on, we
297          * rely on the compiler not reading/writing the stack.
298          */
299 #endif /* ARCH_EMUL */
300
301         CurrentProcess = NULL;
302         proc_schedule();
303         /* not reached */
304 }
305
306
307 /**
308  * Get the pointer to the current process
309  */
310 struct Process *proc_current(void)
311 {
312         return CurrentProcess;
313 }
314
315 /**
316  * Get the pointer to the user data of the current process
317  */
318 iptr_t proc_currentUserData(void)
319 {
320         return CurrentProcess->user_data;
321 }