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