Initial (nonworking) draft of preemptive task switching
[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 #if CONFIG_KERN_PREEMPT
56 #include "preempt.h"
57 #endif
58
59 /*
60  * The scheduer tracks ready processes by enqueuing them in the
61  * ready list.
62  *
63  * \note Access to the list must occur while interrupts are disabled.
64  */
65 REGISTER List ProcReadyList;
66
67 /*
68  * Holds a pointer to the TCB of the currently running process.
69  *
70  * \note User applications should use proc_current() to retrieve this value.
71  */
72 REGISTER Process *CurrentProcess;
73
74 #if (ARCH & ARCH_EMUL)
75 /*
76  * In hosted environments, we must emulate the stack on the real process stack.
77  *
78  * Access to this list must be protected by PROC_ATOMIC().
79  */
80 extern List StackFreeList;
81 #endif
82
83 /** The main process (the one that executes main()). */
84 struct Process MainProcess;
85
86
87 static void proc_init_struct(Process *proc)
88 {
89         /* Avoid warning for unused argument. */
90         (void)proc;
91
92 #if CONFIG_KERN_SIGNALS
93         proc->sig_recv = 0;
94 #endif
95
96 #if CONFIG_KERN_PREEMPTIVE
97         proc->forbid_cnt = 0;
98 #endif
99
100 #if CONFIG_KERN_HEAP
101         proc->flags = 0;
102 #endif
103 }
104
105 MOD_DEFINE(proc);
106
107 void proc_init(void)
108 {
109         LIST_INIT(&ProcReadyList);
110
111         /*
112          * We "promote" the current context into a real process. The only thing we have
113          * to do is create a PCB and make it current. We don't need to setup the stack
114          * pointer because it will be written the first time we switch to another process.
115          */
116         proc_init_struct(&MainProcess);
117         CurrentProcess = &MainProcess;
118
119 #if CONFIG_KERN_MONITOR
120         monitor_init();
121         monitor_add(CurrentProcess, "main");
122 #endif
123
124 #if CONFIG_KERN_PREEMPTIVE
125         preempt_init();
126 #endif
127
128         MOD_INIT(proc);
129 }
130
131
132 /**
133  * Create a new process, starting at the provided entry point.
134  *
135  * \return Process structure of new created process
136  *         if successful, NULL otherwise.
137  */
138 struct Process *proc_new_with_name(UNUSED(const char *, name), void (*entry)(void), iptr_t data, size_t stack_size, cpustack_t *stack_base)
139 {
140         Process *proc;
141         size_t i;
142         const size_t PROC_SIZE_WORDS = ROUND2(sizeof(Process), sizeof(cpustack_t)) / sizeof(cpustack_t);
143 #if CONFIG_KERN_HEAP
144         bool free_stack = false;
145 #endif
146         TRACEMSG("name=%s", name);
147
148 #if (ARCH & ARCH_EMUL)
149         /* Ignore stack provided by caller and use the large enough default instead. */
150         PROC_ATOMIC(stack_base = (cpustack_t *)list_remHead(&StackFreeList));
151
152         stack_size = CONFIG_PROC_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 (!stack_size)
159                         stack_size = CONFIG_PROC_DEFSTACKSIZE + sizeof(Process);
160
161                 /* Allocate stack dinamically */
162                 if (!(stack_base = heap_alloc(stack_size)))
163                         return NULL;
164
165                 free_stack = true;
166         }
167 #else
168         /* Stack must have been provided by the user */
169         ASSERT_VALID_PTR(stack_base);
170         ASSERT(stack_size);
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, stack_size);
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 + stack_size / 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 | CONFIG_KERN_MONITOR | (ARCH & ARCH_EMUL)
198         proc->stack_base = stack_base;
199         proc->stack_size = stack_size;
200         #if CONFIG_KERN_HEAP
201         if (free_stack)
202                 proc->flags |= PF_FREESTACK;
203         #endif
204 #endif
205
206         /* Initialize process stack frame */
207         CPU_PUSH_CALL_FRAME(proc->stack, proc_exit);
208         CPU_PUSH_CALL_FRAME(proc->stack, entry);
209
210         /* Push a clean set of CPU registers for asm_switch_context() */
211         for (i = 0; i < CPU_SAVED_REGS_CNT; i++)
212                 CPU_PUSH_WORD(proc->stack, CPU_REG_INIT_VALUE(i));
213
214         /* Add to ready list */
215         ATOMIC(SCHED_ENQUEUE(proc));
216         ATOMIC(LIST_ASSERT_VALID(&ProcReadyList));
217
218 #if CONFIG_KERN_MONITOR
219         monitor_add(proc, name);
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  * Terminate the current process
238  */
239 void proc_exit(void)
240 {
241         TRACE;
242
243 #if CONFIG_KERN_MONITOR
244         monitor_remove(CurrentProcess);
245 #endif
246
247 #if CONFIG_KERN_HEAP
248         /*
249          * The following code is BROKEN.
250          * We are freeing our own stack before entering proc_schedule()
251          * BAJO: A correct fix would be to rearrange the scheduler with
252          *  an additional parameter which frees the old stack/process
253          *  after a context switch.
254          */
255         if (CurrentProcess->flags & PF_FREESTACK)
256                 heap_free(CurrentProcess->stack_base, CurrentProcess->stack_size);
257         heap_free(CurrentProcess);
258 #endif
259
260 #if (ARCH & ARCH_EMUL)
261 #warning This is wrong
262         /* Reinsert process stack in free list */
263         PROC_ATOMIC(ADDHEAD(&StackFreeList, (Node *)(CurrentProcess->stack
264                 - (CONFIG_PROC_DEFSTACKSIZE / sizeof(cpustack_t)))));
265
266         /*
267          * NOTE: At this point the first two words of what used
268          * to be our stack contain a list node. From now on, we
269          * rely on the compiler not reading/writing the stack.
270          */
271 #endif /* ARCH_EMUL */
272
273         CurrentProcess = NULL;
274         proc_schedule();
275         /* not reached */
276 }
277
278
279 /**
280  * Get the pointer to the current process
281  */
282 struct Process *proc_current(void)
283 {
284         return CurrentProcess;
285 }
286
287 /**
288  * Get the pointer to the user data of the current process
289  */
290 iptr_t proc_current_user_data(void)
291 {
292         return CurrentProcess->user_data;
293 }