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