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