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