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