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