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