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