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