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