Restored test.
[bertos.git] / kern / proc.c
1 /**
2  * \file
3  * <!--
4  * Copyright 2001,2004 Develer S.r.l. (http://www.develer.com/)
5  * Copyright 1999,2000,2001 Bernardo Innocenti <bernie@develer.com>
6  * This file is part of DevLib - See README.devlib for information.
7  * -->
8  *
9  * \brief Simple realtime multitasking scheduler.
10  *        Context switching is only done cooperatively.
11  *
12  * \version $Id$
13  *
14  * \author Bernardo Innocenti <bernie@develer.com>
15  * \author Stefano Fedrigo <aleph@develer.com>
16  */
17
18 /*#*
19  *#* $Log$
20  *#* Revision 1.32  2006/09/20 14:19:23  marco
21  *#* Restored test.
22  *#*
23  *#* Revision 1.31  2006/07/19 12:56:27  bernie
24  *#* Convert to new Doxygen style.
25  *#*
26  *#* Revision 1.30  2006/03/27 04:49:23  bernie
27  *#* CPU_IDLE(): Fix for new emulator.
28  *#*
29  *#* Revision 1.29  2006/02/24 01:17:05  bernie
30  *#* Update for new emulator.
31  *#*
32  *#* Revision 1.28  2006/02/21 16:06:55  bernie
33  *#* Cleanup/update process scheduling.
34  *#*
35  *#* Revision 1.27  2005/11/04 16:20:02  bernie
36  *#* Fix reference to README.devlib in header.
37  *#*
38  *#* Revision 1.26  2005/04/11 19:10:28  bernie
39  *#* Include top-level headers from cfg/ subdir.
40  *#*
41  *#* Revision 1.25  2005/03/15 00:20:54  bernie
42  *#* proc_schedule(): New sanity check.
43  *#*
44  *#* Revision 1.24  2005/01/08 09:20:54  bernie
45  *#* Remove unused variable.
46  *#*
47  *#* Revision 1.23  2004/12/13 12:07:06  bernie
48  *#* DISABLE_IRQSAVE/ENABLE_IRQRESTORE: Convert to IRQ_SAVE_DISABLE/IRQ_RESTORE.
49  *#*
50  *#* Revision 1.22  2004/12/13 11:51:08  bernie
51  *#* DISABLE_INTS/ENABLE_INTS: Convert to IRQ_DISABLE/IRQ_ENABLE.
52  *#*
53  *#* Revision 1.21  2004/11/28 23:20:25  bernie
54  *#* Remove obsolete INITLIST macro.
55  *#*
56  *#* Revision 1.20  2004/11/16 22:37:14  bernie
57  *#* Replace IPTR with iptr_t.
58  *#*
59  *#* Revision 1.19  2004/10/19 11:47:39  bernie
60  *#* Kill warnings when !CONFIG_PROC_MONITOR.
61  *#*
62  *#* Revision 1.18  2004/10/19 08:54:43  bernie
63  *#* Initialize forbid_cnt; Formatting/comments fixes.
64  *#*
65  *#* Revision 1.17  2004/10/19 08:47:13  bernie
66  *#* proc_rename(), proc_forbid(), proc_permit(): New functions.
67  *#*
68  *#* Revision 1.16  2004/10/03 20:39:28  bernie
69  *#* Import changes from sc/firmware.
70  *#*
71  *#* Revision 1.15  2004/09/20 03:29:39  bernie
72  *#* C++ fixes.
73  *#*
74  *#* Revision 1.14  2004/09/14 21:06:44  bernie
75  *#* Use debug.h instead of kdebug.h.
76  *#*
77  *#* Revision 1.13  2004/08/29 21:58:53  bernie
78  *#* Include macros.h explicityl.
79  *#*
80  *#* Revision 1.11  2004/08/24 16:09:08  bernie
81  *#* Add missing header.
82  *#*
83  *#* Revision 1.10  2004/08/24 16:07:01  bernie
84  *#* Use kputs()/kputchar() when possible.
85  *#*
86  *#* Revision 1.9  2004/08/24 14:26:57  bernie
87  *#* monitor_debug_stacks(): Conditionally compile on CONFIG_KERN_MONITOR.
88  *#*
89  *#* Revision 1.8  2004/08/14 19:37:57  rasky
90  *#* Merge da SC: macros.h, pool.h, BIT_CHANGE, nome dei processi, etc.
91  *#*
92  *#* Revision 1.7  2004/08/02 20:20:29  aleph
93  *#* Merge from project_ks
94  *#*
95  *#* Revision 1.6  2004/07/30 14:24:16  rasky
96  *#* Task switching con salvataggio perfetto stato di interrupt (SR)
97  *#* Kernel monitor per dump informazioni su stack dei processi
98  *#*
99  *#* Revision 1.5  2004/07/14 14:18:09  rasky
100  *#* Merge da SC: Rimosso timer dentro il task, che รจ uno spreco di memoria per troppi task
101  *#*
102  *#* Revision 1.4  2004/07/13 19:21:28  aleph
103  *#* Avoid warning for unused arg when compiled without some CONFIG_KERN_xx options
104  *#*
105  *#* Revision 1.3  2004/06/06 18:37:57  bernie
106  *#* Rename event macros to look like regular functions.
107  *#*
108  *#* Revision 1.2  2004/06/03 11:27:09  bernie
109  *#* Add dual-license information.
110  *#*
111  *#* Revision 1.1  2004/05/23 17:27:00  bernie
112  *#* Import kern/ subdirectory.
113  *#*
114  *#*/
115
116 #include "proc_p.h"
117 #include "proc.h"
118 //#include "hw.h"
119 #include <mware/event.h>
120 #include <cfg/cpu.h>
121 #include <cfg/debug.h>
122 #include <cfg/arch_config.h>  /* ARCH_EMUL */
123 #include <cfg/macros.h>  /* ABS() */
124
125 #include <string.h> /* memset() */
126
127 /**
128  * CPU dependent context switching routines.
129  *
130  * \note This function *MUST* preserve also the status of the interrupts.
131  */
132 EXTERN_C void asm_switch_context(cpustack_t **new_sp, cpustack_t **save_sp);
133 EXTERN_C int asm_switch_version(void);
134
135 /*
136  * The scheduer tracks ready and waiting processes
137  * by enqueuing them in these lists. A pointer to the currently
138  * running process is stored in the CurrentProcess pointer.
139  *
140  * NOTE: these variables are protected by DI/EI locking
141  */
142 REGISTER Process *CurrentProcess;
143 REGISTER List     ProcReadyList;
144
145
146 #if CONFIG_KERN_PREEMPTIVE
147 /*
148  * The time sharing scheduler forces a task switch when
149  * the current process has consumed its quantum.
150  */
151 uint16_t Quantum;
152 #endif
153
154
155 /* In Win32 we must emulate stack on the real process stack */
156 #if (ARCH & ARCH_EMUL)
157 extern List StackFreeList;
158 #endif
159
160 /** The main process (the one that executes main()). */
161 struct Process MainProcess;
162
163
164 static void proc_init_struct(Process *proc)
165 {
166         /* Avoid warning for unused argument. */
167         (void)proc;
168
169 #if CONFIG_KERN_SIGNALS
170         proc->sig_recv = 0;
171 #endif
172
173 #if CONFIG_KERN_PREEMPTIVE
174         proc->forbid_cnt = 0;
175 #endif
176
177 #if CONFIG_KERN_HEAP
178         proc->flags = 0;
179 #endif
180 }
181
182
183 void proc_init(void)
184 {
185         LIST_INIT(&ProcReadyList);
186
187 #if CONFIG_KERN_MONITOR
188         monitor_init();
189 #endif
190
191         /* We "promote" the current context into a real process. The only thing we have
192          * to do is create a PCB and make it current. We don't need to setup the stack
193          * pointer because it will be written the first time we switch to another process.
194          */
195         proc_init_struct(&MainProcess);
196         CurrentProcess = &MainProcess;
197
198         /* Make sure the assembly routine is up-to-date with us */
199         ASSERT(asm_switch_version() == 1);
200 }
201
202
203 /**
204  * Create a new process, starting at the provided entry point.
205  *
206  * \return Process structure of new created process
207  *         if successful, NULL otherwise.
208  */
209 struct Process *proc_new_with_name(UNUSED(const char *, name), void (*entry)(void), iptr_t data, size_t stacksize, cpustack_t *stack_base)
210 {
211         Process *proc;
212         size_t i;
213         size_t proc_size_words = ROUND2(sizeof(Process), sizeof(cpustack_t)) / sizeof(cpustack_t);
214 #if CONFIG_KERN_HEAP
215         bool free_stack = false;
216 #endif
217
218 #if (ARCH & ARCH_EMUL)
219         /* Ignore stack provided by caller and use the large enough default instead. */
220         stack_base = (cpustack_t *)LIST_HEAD(&StackFreeList);
221         REMOVE(LIST_HEAD(&StackFreeList));
222         stacksize = CONFIG_KERN_DEFSTACKSIZE;
223 #elif CONFIG_KERN_HEAP
224         /* Did the caller provide a stack for us? */
225         if (!stack_base)
226         {
227                 /* Did the caller specify the desired stack size? */
228                 if (!stacksize)
229                         stacksize = CONFIG_KERN_DEFSTACKSIZE + sizeof(Process);
230
231                 /* Allocate stack dinamically */
232                 if (!(stack_base = heap_alloc(stacksize)))
233                         return NULL;
234
235                 free_stack = true;
236         }
237 #else
238         /* Stack must have been provided by the user */
239         ASSERT(stack_base);
240         ASSERT(stacksize);
241 #endif
242
243 #if CONFIG_KERN_MONITOR
244         /* Fill-in the stack with a special marker to help debugging */
245         memset(stack_base, CONFIG_KERN_STACKFILLCODE, stacksize / sizeof(cpustack_t));
246 #endif
247
248         /* Initialize the process control block */
249         if (CPU_STACK_GROWS_UPWARD)
250         {
251                 proc = (Process*)stack_base;
252                 proc->stack = stack_base + proc_size_words;
253                 if (CPU_SP_ON_EMPTY_SLOT)
254                         proc->stack++;
255         }
256         else
257         {
258                 proc = (Process*)(stack_base + stacksize / sizeof(cpustack_t) - proc_size_words);
259                 proc->stack = (cpustack_t*)proc;
260                 if (CPU_SP_ON_EMPTY_SLOT)
261                         proc->stack--;
262         }
263
264         proc_init_struct(proc);
265         proc->user_data = data;
266
267 #if CONFIG_KERN_HEAP
268         proc->stack_base = stack_base;
269         proc->stack_size = stack_size;
270         if (free_stack)
271                 proc->flags |= PF_FREESTACK;
272 #endif
273
274         /* Initialize process stack frame */
275         CPU_PUSH_CALL_CONTEXT(proc->stack, proc_exit);
276         CPU_PUSH_CALL_CONTEXT(proc->stack, entry);
277
278         /* Push a clean set of CPU registers for asm_switch_context() */
279         for (i = 0; i < CPU_SAVED_REGS_CNT; i++)
280                 CPU_PUSH_WORD(proc->stack, CPU_REG_INIT_VALUE(i));
281
282         /* Add to ready list */
283         ATOMIC(SCHED_ENQUEUE(proc));
284
285 #if CONFIG_KERN_MONITOR
286         monitor_add(proc, name, stack_base, stacksize);
287 #endif
288
289         return proc;
290 }
291
292 /** Rename a process */
293 void proc_rename(struct Process *proc, const char *name)
294 {
295 #if CONFIG_KERN_MONITOR
296         monitor_rename(proc, name);
297 #else
298         (void)proc; (void)name;
299 #endif
300 }
301
302
303 /**
304  * System scheduler: pass CPU control to the next process in
305  * the ready queue.
306  *
307  * Saving and restoring the context on the stack is done
308  * by a CPU-dependent support routine which must usually be
309  * written in assembly.
310  */
311 void proc_schedule(void)
312 {
313         /* This function must not have any "auto" variables, otherwise
314          * the compiler might put them on the stack of the process
315          * being switched out.
316          */
317         static struct Process *old_process;
318         static cpuflags_t flags;
319
320         /* Remember old process to save its context later */
321         old_process = CurrentProcess;
322
323 #ifdef IRQ_RUNNING
324         /* Scheduling in interrupts is a nono. */
325         ASSERT(!IRQ_RUNNING());
326 #endif
327
328         /* Poll on the ready queue for the first ready process */
329         IRQ_SAVE_DISABLE(flags);
330         while (!(CurrentProcess = (struct Process *)list_remHead(&ProcReadyList)))
331         {
332                 /*
333                  * Make sure we physically reenable interrupts here, no matter what
334                  * the current task status is. This is important because if we
335                  * are idle-spinning, we must allow interrupts, otherwise no
336                  * process will ever wake up.
337                  *
338                  * \todo If there was a way to write sig_wait() so that it does not
339                  * disable interrupts while waiting, there would not be any
340                  * reason to do this.
341                  */
342                 IRQ_ENABLE;
343                 CPU_IDLE;
344                 IRQ_DISABLE;
345         }
346         IRQ_RESTORE(flags);
347
348         /*
349          * Optimization: don't switch contexts when the active
350          * process has not changed.
351          */
352         if (CurrentProcess != old_process)
353         {
354                 static cpustack_t *dummy;
355
356 #if CONFIG_KERN_PREEMPTIVE
357                 /* Reset quantum for this process */
358                 Quantum = CONFIG_KERN_QUANTUM;
359 #endif
360
361                 /* Save context of old process and switch to new process. If there is no
362                  * old process, we save the old stack pointer into a dummy variable that
363                  * we ignore. In fact, this happens only when the old process has just
364                  * exited.
365                  * TODO: Instead of physically clearing the process at exit time, a zombie
366                  * list should be created.
367                  */
368                 asm_switch_context(&CurrentProcess->stack, old_process ? &old_process->stack : &dummy);
369         }
370
371         /* This RET resumes the execution on the new process */
372 }
373
374
375 /**
376  * Terminate the current process
377  */
378 void proc_exit(void)
379 {
380 #if CONFIG_KERN_MONITOR
381         monitor_remove(CurrentProcess);
382 #endif
383
384 #if CONFIG_KERN_HEAP
385         /*
386          * The following code is BROKEN.
387          * We are freeing our own stack before entering proc_schedule()
388          * BAJO: A correct fix would be to rearrange the scheduler with
389          *  an additional parameter which frees the old stack/process
390          *  after a context switch.
391          */
392         if (CurrentProcess->flags & PF_FREESTACK)
393                 heap_free(CurrentProcess->stack_base, CurrentProcess->stack_size);
394         heap_free(CurrentProcess);
395 #endif
396
397 #if (ARCH & ARCH_EMUL)
398 #warning This is wrong
399         /* Reinsert process stack in free list */
400         ADDHEAD(&StackFreeList, (Node *)(CurrentProcess->stack
401                 - (CONFIG_KERN_DEFSTACKSIZE / sizeof(cpustack_t))));
402
403         /*
404          * NOTE: At this point the first two words of what used
405          * to be our stack contain a list node. From now on, we
406          * rely on the compiler not reading/writing the stack.
407          */
408 #endif /* ARCH_EMUL */
409
410         CurrentProcess = NULL;
411         proc_schedule();
412         /* not reached */
413 }
414
415
416 /**
417  * Co-operative context switch
418  */
419 void proc_switch(void)
420 {
421         /* Just like proc_schedule, this function must not have auto variables. */
422         static cpuflags_t flags;
423
424         IRQ_SAVE_DISABLE(flags);
425         SCHED_ENQUEUE(CurrentProcess);
426         IRQ_RESTORE(flags);
427
428         proc_schedule();
429 }
430
431
432 /**
433  * Get the pointer to the current process
434  */
435 struct Process *proc_current(void)
436 {
437         return CurrentProcess;
438 }
439
440 /**
441  * Get the pointer to the user data of the current process
442  */
443 iptr_t proc_current_user_data(void)
444 {
445         return CurrentProcess->user_data;
446 }
447
448
449 #if CONFIG_KERN_PREEMPTIVE
450
451 /**
452  * Disable preemptive task switching.
453  *
454  * The scheduler maintains a per-process nesting counter.  Task switching is
455  * effectively re-enabled only when the number of calls to proc_permit()
456  * matches the number of calls to proc_forbid().
457  *
458  * Calling functions that could sleep while task switching is disabled
459  * is dangerous, although supported.  Preemptive task switching is
460  * resumed while the process is sleeping and disabled again as soon as
461  * it wakes up again.
462  *
463  * \sa proc_permit()
464  */
465 void proc_forbid(void)
466 {
467         /* No need to protect against interrupts here. */
468         ++CurrentProcess->forbid_cnt;
469 }
470
471 /**
472  * Re-enable preemptive task switching.
473  *
474  * \sa proc_forbid()
475  */
476 void proc_permit(void)
477 {
478         /* No need to protect against interrupts here. */
479         --CurrentProcess->forbid_cnt;
480 }
481
482 #endif /* CONFIG_KERN_PREEMPTIVE */