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