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