f121d0260f2bde0c1e5c30f47b765faa55a20193
[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  * \author Bernie Innocenti <bernie@codewiz.org>
36  * \author Stefano Fedrigo <aleph@develer.com>
37  */
38
39 #include "proc_p.h"
40 #include "proc.h"
41
42 #include "cfg/cfg_proc.h"
43 #define LOG_LEVEL KERN_LOG_LEVEL
44 #define LOG_FORMAT KERN_LOG_FORMAT
45 #include <cfg/log.h>
46
47 #include "cfg/cfg_arch.h"  // ARCH_EMUL
48 #include "cfg/cfg_monitor.h"
49 #include <cfg/macros.h>    // ROUND_UP2
50 #include <cfg/module.h>
51 #include <cfg/depend.h>    // CONFIG_DEPEND()
52
53 #include <cpu/irq.h>
54 #include <cpu/types.h>
55 #include <cpu/attr.h>
56 #include <cpu/frame.h>
57
58 #if CONFIG_KERN_HEAP
59         #include <struct/heap.h>
60 #endif
61
62 #include <string.h>           /* memset() */
63
64 /*
65  * The scheduer tracks ready processes by enqueuing them in the
66  * ready list.
67  *
68  * \note Access to the list must occur while interrupts are disabled.
69  */
70 REGISTER List ProcReadyList;
71
72 /*
73  * Holds a pointer to the TCB of the currently running process.
74  *
75  * \note User applications should use proc_current() to retrieve this value.
76  */
77 REGISTER Process *CurrentProcess;
78
79 #if (ARCH & ARCH_EMUL)
80 /*
81  * In some hosted environments, we must emulate the stack on the real
82  * process stack to satisfy consistency checks in system libraries and
83  * because some ABIs place trampolines on the stack.
84  *
85  * Access to this list must be protected by PROC_ATOMIC().
86  */
87 List StackFreeList;
88
89 #define NPROC 10
90 cpu_stack_t proc_stacks[NPROC][(64 * 1024) / sizeof(cpu_stack_t)];
91 #endif
92
93 /** The main process (the one that executes main()). */
94 struct Process MainProcess;
95
96
97 static void proc_init_struct(Process *proc)
98 {
99         /* Avoid warning for unused argument. */
100         (void)proc;
101
102 #if CONFIG_KERN_SIGNALS
103         proc->sig_recv = 0;
104         proc->sig_wait = 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
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  *
153  * \note The function
154  * \code
155  * proc_new(entry, data, stacksize, stack)
156  * \endcode
157  * is a more convenient way to create a process, as you don't have to specify
158  * the name.
159  *
160  * \return Process structure of new created process
161  *         if successful, NULL otherwise.
162  */
163 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)
164 {
165         Process *proc;
166         const size_t PROC_SIZE_WORDS = ROUND_UP2(sizeof(Process), sizeof(cpu_stack_t)) / sizeof(cpu_stack_t);
167 #if CONFIG_KERN_HEAP
168         bool free_stack = false;
169 #endif
170         LOG_INFO("name=%s", name);
171
172 #if (ARCH & ARCH_EMUL)
173         /* Ignore stack provided by caller and use the large enough default instead. */
174         PROC_ATOMIC(stack_base = (cpu_stack_t *)list_remHead(&StackFreeList));
175         ASSERT(stack_base);
176
177         stack_size = KERN_MINSTACKSIZE;
178 #elif CONFIG_KERN_HEAP
179         /* Did the caller provide a stack for us? */
180         if (!stack_base)
181         {
182                 /* Did the caller specify the desired stack size? */
183                 if (!stack_size)
184                         stack_size = KERN_MINSTACKSIZE;
185
186                 /* Allocate stack dinamically */
187                 if (!(stack_base = heap_alloc(stack_size)))
188                         return NULL;
189
190                 free_stack = true;
191         }
192
193 #else // !ARCH_EMUL && !CONFIG_KERN_HEAP
194
195         /* Stack must have been provided by the user */
196         ASSERT_VALID_PTR(stack_base);
197         ASSERT(stack_size);
198
199 #endif // !ARCH_EMUL && !CONFIG_KERN_HEAP
200
201 #if CONFIG_KERN_MONITOR
202         /*
203          * Fill-in the stack with a special marker to help debugging.
204          * On 64bit platforms, CONFIG_KERN_STACKFILLCODE is larger
205          * than an int, so the (int) cast is required to silence the
206          * warning for truncating its size.
207          */
208         memset(stack_base, (int)CONFIG_KERN_STACKFILLCODE, stack_size);
209 #endif
210
211         /* Initialize the process control block */
212         if (CPU_STACK_GROWS_UPWARD)
213         {
214                 proc = (Process *)stack_base;
215                 proc->stack = stack_base + PROC_SIZE_WORDS;
216                 // On some architecture stack should be aligned, so we do it.
217                 proc->stack = (cpu_stack_t *)((uintptr_t)proc->stack + (sizeof(cpu_aligned_stack_t) - ((uintptr_t)proc->stack % sizeof(cpu_aligned_stack_t))));
218                 if (CPU_SP_ON_EMPTY_SLOT)
219                         proc->stack++;
220         }
221         else
222         {
223                 proc = (Process *)(stack_base + stack_size / sizeof(cpu_stack_t) - PROC_SIZE_WORDS);
224                 // On some architecture stack should be aligned, so we do it.
225                 proc->stack = (cpu_stack_t *)((uintptr_t)proc - ((uintptr_t)proc % sizeof(cpu_aligned_stack_t)));
226                 if (CPU_SP_ON_EMPTY_SLOT)
227                         proc->stack--;
228         }
229         /* Ensure stack is aligned */
230         ASSERT((uintptr_t)proc->stack % sizeof(cpu_aligned_stack_t) == 0);
231
232         stack_size -= PROC_SIZE_WORDS * sizeof(cpu_stack_t);
233         proc_init_struct(proc);
234         proc->user_data = data;
235
236 #if CONFIG_KERN_HEAP | CONFIG_KERN_MONITOR | (ARCH & ARCH_EMUL)
237         proc->stack_base = stack_base;
238         proc->stack_size = stack_size;
239         #if CONFIG_KERN_HEAP
240         if (free_stack)
241                 proc->flags |= PF_FREESTACK;
242         #endif
243 #endif
244
245         #if CONFIG_KERN_PREEMPT
246
247                 getcontext(&proc->context);
248                 proc->context.uc_stack.ss_sp = proc->stack;
249                 proc->context.uc_stack.ss_size = stack_size - 1;
250                 proc->context.uc_link = NULL;
251                 makecontext(&proc->context, (void (*)(void))proc_entry, 1, entry);
252
253         #else // !CONFIG_KERN_PREEMPT
254
255                 CPU_CREATE_NEW_STACK(proc->stack, entry, proc_exit);
256
257         #endif // CONFIG_KERN_PREEMPT
258
259         #if CONFIG_KERN_MONITOR
260                 monitor_add(proc, name);
261         #endif
262
263         /* Add to ready list */
264         ATOMIC(SCHED_ENQUEUE(proc));
265
266         return proc;
267 }
268
269 /**
270  * Return the name of the specified process.
271  *
272  * NULL is a legal argument and will return the name "<NULL>".
273  */
274 const char *proc_name(struct Process *proc)
275 {
276         #if CONFIG_KERN_MONITOR
277                 return proc ? proc->monitor.name : "<NULL>";
278         #else
279                 (void)proc;
280                 return "---";
281         #endif
282 }
283
284 /// Return the name of the currently running process
285 const char *proc_currentName(void)
286 {
287         return proc_name(proc_current());
288 }
289
290 /// Rename a process
291 void proc_rename(struct Process *proc, const char *name)
292 {
293 #if CONFIG_KERN_MONITOR
294         monitor_rename(proc, name);
295 #else
296         (void)proc; (void)name;
297 #endif
298 }
299
300
301 #if CONFIG_KERN_PRI
302 /**
303  * Change the scheduling priority of a process.
304  *
305  * Process piorities are signed ints, whereas a larger integer value means
306  * higher scheduling priority.  The default priority for new processes is 0.
307  * The idle process runs with the lowest possible priority: INT_MIN.
308  *
309  * A process with a higher priority always preempts lower priority processes.
310  * Processes of equal priority share the CPU time according to a simple
311  * round-robin policy.
312  *
313  * As a general rule to maximize responsiveness, compute-bound processes
314  * should be assigned negative priorities and tight, interactive processes
315  * should be assigned positive priorities.
316  *
317  * To avoid interfering with system background activities such as input
318  * processing, application processes should remain within the range -10
319  * and +10.
320  */
321 void proc_setPri(struct Process *proc, int pri)
322 {
323                 if (proc->link.pri == pri)
324                         return;
325
326                 proc->link.pri = pri;
327
328                 if (proc != CurrentProcess)
329                 {
330                                 proc_forbid();
331                                 ATOMIC(sched_reenqueue(proc));
332                                 proc_permit();
333                 }
334 }
335 #endif // CONFIG_KERN_PRI
336
337 /**
338  * Terminate the current process
339  */
340 void proc_exit(void)
341 {
342         LOG_INFO("%p:%s", CurrentProcess, proc_currentName());
343
344 #if CONFIG_KERN_MONITOR
345         monitor_remove(CurrentProcess);
346 #endif
347
348 #if CONFIG_KERN_HEAP
349         /*
350          * The following code is BROKEN.
351          * We are freeing our own stack before entering proc_schedule()
352          * BAJO: A correct fix would be to rearrange the scheduler with
353          *  an additional parameter which frees the old stack/process
354          *  after a context switch.
355          */
356         if (CurrentProcess->flags & PF_FREESTACK)
357                 heap_free(CurrentProcess->stack_base, CurrentProcess->stack_size);
358         heap_free(CurrentProcess);
359 #endif
360
361 #if (ARCH & ARCH_EMUL)
362         /* Reinsert process stack in free list */
363         PROC_ATOMIC(ADDHEAD(&StackFreeList, (Node *)CurrentProcess->stack_base));
364
365         /*
366          * NOTE: At this point the first two words of what used
367          * to be our stack contain a list node. From now on, we
368          * rely on the compiler not reading/writing the stack.
369          */
370 #endif /* ARCH_EMUL */
371
372         CurrentProcess = NULL;
373         proc_switch();
374         /* not reached */
375 }
376
377
378 /**
379  * Get the pointer to the user data of the current process
380  */
381 iptr_t proc_currentUserData(void)
382 {
383         return CurrentProcess->user_data;
384 }