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