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