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