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