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