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