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