kernel: preemptive and cooperative scheduler refactoring.
[bertos.git] / bertos / kern / proc.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * \brief Simple preemptive multitasking scheduler.
30  *
31  * Preemption is explicitly regulated at the exit of each interrupt service
32  * routine (ISR). Each task obtains a time quantum as soon as it is scheduled
33  * on the CPU and its quantum is decremented at each clock tick. The frequency
34  * of the timer determines the system tick granularity and CONFIG_KERN_QUANTUM
35  * the time sharing interval.
36  *
37  * When the quantum expires the handler proc_needPreempt() checks if the
38  * preemption is enabled and in this case proc_schedule() is called, that
39  * possibly replaces the current running thread with a different one.
40  *
41  * The preemption can be disabled or enabled via proc_forbid() and
42  * proc_permit() primitives. This is implemented using a global atomic counter.
43  * When the counter is greater than 0 the task cannot be preempted; only when
44  * the counter reaches 0 the task can be preempted again.
45  *
46  * Preemption-disabled sections may be nested. The preemption will be
47  * re-enabled when the outermost preemption-disabled section completes.
48  *
49  * The voluntary preemption still happens via proc_switch() or proc_yield().
50  * The first one assumes the current process has been already added to a
51  * private wait queue (e.g., on a semaphore or a signal), while the second one
52  * takes care of adding the process into the ready queue.
53  *
54  * Context switch is done by CPU-dependent support routines. In case of a
55  * voluntary preemption the context switch routine must take care of
56  * saving/restoring only the callee-save registers (the voluntary-preemption is
57  * actually a function call). The kernel-preemption always happens inside a
58  * signal/interrupt context and it must take care of saving all registers. For
59  * this, in the entry point of each ISR the caller-save registers must be
60  * saved. In the ISR exit point, if the context switch must happen, we switch
61  * to user-context and call the same voluntary context switch routine that take
62  * care of saving/restoring also the callee-save registers. On resume from the
63  * switch, the interrupt exit point moves back to interrupt-context, resumes
64  * the caller-save registers (saved in the ISR entry point) and return from the
65  * interrupt-context.
66  *
67  * \note Thread priority (if enabled by CONFIG_KERN_PRI) defines the order in
68  * the \p proc_ready_list and the capability to deschedule a running process. A
69  * low-priority thread can't preempt a high-priority thread.
70  *
71  * A high-priority process can preempt a low-priority process immediately (it
72  * will be descheduled and replaced in the interrupt exit point). Processes
73  * running at the same priority can be descheduled when they expire the time
74  * quantum.
75  *
76  * \note Sleeping while preemption is disabled fallbacks to a busy-wait sleep.
77  * Voluntary preemption when preemption is disabled raises a kernel bug.
78  *
79  * -->
80  *
81  * \brief Simple cooperative and preemptive multitasking scheduler.
82  *
83  * \author Bernie Innocenti <bernie@codewiz.org>
84  * \author Stefano Fedrigo <aleph@develer.com>
85  * \author Andrea Righi <arighi@develer.com>
86  */
87
88 #include "proc_p.h"
89 #include "proc.h"
90
91 #include "cfg/cfg_proc.h"
92 #define LOG_LEVEL KERN_LOG_LEVEL
93 #define LOG_FORMAT KERN_LOG_FORMAT
94 #include <cfg/log.h>
95
96 #include "cfg/cfg_monitor.h"
97 #include <cfg/macros.h>    // ROUND_UP2
98 #include <cfg/module.h>
99 #include <cfg/depend.h>    // CONFIG_DEPEND()
100
101 #include <cpu/irq.h>
102 #include <cpu/types.h>
103 #include <cpu/attr.h>
104 #include <cpu/frame.h>
105
106 #if CONFIG_KERN_HEAP
107         #include <struct/heap.h>
108 #endif
109
110 #include <string.h>           /* memset() */
111
112 #define PROC_SIZE_WORDS (ROUND_UP2(sizeof(Process), sizeof(cpu_stack_t)) / sizeof(cpu_stack_t))
113
114 /*
115  * The scheduer tracks ready processes by enqueuing them in the
116  * ready list.
117  *
118  * \note Access to the list must occur while interrupts are disabled.
119  */
120 REGISTER List proc_ready_list;
121
122 /*
123  * Holds a pointer to the TCB of the currently running process.
124  *
125  * \note User applications should use proc_current() to retrieve this value.
126  */
127 REGISTER Process *current_process;
128
129 /** The main process (the one that executes main()). */
130 static struct Process main_process;
131
132 #if CONFIG_KERN_HEAP
133
134 /**
135  * Local heap dedicated to allocate the memory used by the processes.
136  */
137 static HEAP_DEFINE_BUF(heap_buf, CONFIG_KERN_HEAP_SIZE);
138 static Heap proc_heap;
139
140 /*
141  * Keep track of zombie processes (processes that are exiting and need to
142  * release some resources).
143  *
144  * \note Access to the list must occur while kernel preemption is disabled.
145  */
146 static List zombie_list;
147
148 #endif /* CONFIG_KERN_HEAP */
149
150 /*
151  * Check if the process context switch can be performed directly by the
152  * architecture-dependent asm_switch_context() or if it must be delayed
153  * because we're in the middle of an ISR.
154  *
155  * Return true if asm_switch_context() can be executed, false
156  * otherwise.
157  *
158  * NOTE: if an architecture does not implement IRQ_RUNNING() this function
159  * always returns true.
160  */
161 #define CONTEXT_SWITCH_FROM_ISR()       (!IRQ_RUNNING())
162
163 /*
164  * Save context of old process and switch to new process.
165   */
166 static void proc_context_switch(Process *next, Process *prev)
167 {
168         cpu_stack_t *dummy;
169
170         if (UNLIKELY(next == prev))
171                 return;
172         /*
173          * If there is no old process, we save the old stack pointer into a
174          * dummy variable that we ignore.  In fact, this happens only when the
175          * old process has just exited.
176          */
177         asm_switch_context(&next->stack, prev ? &prev->stack : &dummy);
178 }
179
180 static void proc_initStruct(Process *proc)
181 {
182         /* Avoid warning for unused argument. */
183         (void)proc;
184
185 #if CONFIG_KERN_SIGNALS
186         proc->sig_recv = 0;
187         proc->sig_wait = 0;
188 #endif
189
190 #if CONFIG_KERN_HEAP
191         proc->flags = 0;
192 #endif
193
194 #if CONFIG_KERN_PRI
195         proc->link.pri = 0;
196 #endif
197 }
198
199 MOD_DEFINE(proc);
200
201 void proc_init(void)
202 {
203         LIST_INIT(&proc_ready_list);
204
205 #if CONFIG_KERN_HEAP
206         LIST_INIT(&zombie_list);
207         heap_init(&proc_heap, heap_buf, sizeof(heap_buf));
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_initStruct(&main_process);
215         current_process = &main_process;
216
217 #if CONFIG_KERN_MONITOR
218         monitor_init();
219         monitor_add(current_process, "main");
220 #endif
221         MOD_INIT(proc);
222 }
223
224
225 #if CONFIG_KERN_HEAP
226
227 /**
228  * Free all the resources of all zombie processes previously added to the zombie
229  * list.
230  */
231 static void proc_freeZombies(void)
232 {
233         Process *proc;
234
235         while (1)
236         {
237                 PROC_ATOMIC(proc = (Process *)list_remHead(&zombie_list));
238                 if (proc == NULL)
239                         return;
240
241                 if (proc->flags & PF_FREESTACK)
242                 {
243                         PROC_ATOMIC(heap_freemem(&proc_heap, proc->stack_base,
244                                 proc->stack_size + PROC_SIZE_WORDS * sizeof(cpu_stack_t)));
245                 }
246         }
247 }
248
249 /**
250  * Enqueue a process in the zombie list.
251  */
252 static void proc_addZombie(Process *proc)
253 {
254         Node *node;
255 #if CONFIG_KERN_PREEMPT
256         ASSERT(!proc_preemptAllowed());
257 #endif
258
259 #if CONFIG_KERN_PRI
260         node = &(proc)->link.link;
261 #else
262         node = &(proc)->link;
263 #endif
264         LIST_ASSERT_VALID(&zombie_list);
265         ADDTAIL(&zombie_list, node);
266 }
267
268 #endif /* CONFIG_KERN_HEAP */
269
270 /**
271  * Create a new process, starting at the provided entry point.
272  *
273  *
274  * \note The function
275  * \code
276  * proc_new(entry, data, stacksize, stack)
277  * \endcode
278  * is a more convenient way to create a process, as you don't have to specify
279  * the name.
280  *
281  * \return Process structure of new created process
282  *         if successful, NULL otherwise.
283  */
284 struct Process *proc_new_with_name(UNUSED_ARG(const char *, name), void (*entry)(void), iptr_t data, size_t stack_size, cpu_stack_t *stack_base)
285 {
286         Process *proc;
287         LOG_INFO("name=%s", name);
288 #if CONFIG_KERN_HEAP
289         bool free_stack = false;
290
291         /*
292          * Free up resources of a zombie process.
293          *
294          * We're implementing a kind of lazy garbage collector here for
295          * efficiency reasons: we can avoid to introduce overhead into another
296          * kernel task dedicated to free up resources (e.g., idle) and we're
297          * not introducing any overhead into the scheduler after a context
298          * switch (that would be *very* bad, because the scheduler runs with
299          * IRQ disabled).
300          *
301          * In this way we are able to release the memory of the zombie tasks
302          * without disabling IRQs and without introducing any significant
303          * overhead in any other kernel task.
304          */
305         proc_freeZombies();
306
307         /* Did the caller provide a stack for us? */
308         if (!stack_base)
309         {
310                 /* Did the caller specify the desired stack size? */
311                 if (!stack_size)
312                         stack_size = KERN_MINSTACKSIZE;
313
314                 /* Allocate stack dinamically */
315                 PROC_ATOMIC(stack_base =
316                         (cpu_stack_t *)heap_allocmem(&proc_heap, stack_size));
317                 if (stack_base == NULL)
318                         return NULL;
319
320                 free_stack = true;
321         }
322
323 #else // CONFIG_KERN_HEAP
324
325         /* Stack must have been provided by the user */
326         ASSERT_VALID_PTR(stack_base);
327         ASSERT(stack_size);
328
329 #endif // CONFIG_KERN_HEAP
330
331 #if CONFIG_KERN_MONITOR
332         /*
333          * Fill-in the stack with a special marker to help debugging.
334          * On 64bit platforms, CONFIG_KERN_STACKFILLCODE is larger
335          * than an int, so the (int) cast is required to silence the
336          * warning for truncating its size.
337          */
338         memset(stack_base, (int)CONFIG_KERN_STACKFILLCODE, stack_size);
339 #endif
340
341         /* Initialize the process control block */
342         if (CPU_STACK_GROWS_UPWARD)
343         {
344                 proc = (Process *)stack_base;
345                 proc->stack = stack_base + PROC_SIZE_WORDS;
346                 // On some architecture stack should be aligned, so we do it.
347                 proc->stack = (cpu_stack_t *)((uintptr_t)proc->stack + (sizeof(cpu_aligned_stack_t) - ((uintptr_t)proc->stack % sizeof(cpu_aligned_stack_t))));
348                 if (CPU_SP_ON_EMPTY_SLOT)
349                         proc->stack++;
350         }
351         else
352         {
353                 proc = (Process *)(stack_base + stack_size / sizeof(cpu_stack_t) - PROC_SIZE_WORDS);
354                 // On some architecture stack should be aligned, so we do it.
355                 proc->stack = (cpu_stack_t *)((uintptr_t)proc - ((uintptr_t)proc % sizeof(cpu_aligned_stack_t)));
356                 if (CPU_SP_ON_EMPTY_SLOT)
357                         proc->stack--;
358         }
359         /* Ensure stack is aligned */
360         ASSERT((uintptr_t)proc->stack % sizeof(cpu_aligned_stack_t) == 0);
361
362         stack_size -= PROC_SIZE_WORDS * sizeof(cpu_stack_t);
363         proc_initStruct(proc);
364         proc->user_data = data;
365
366 #if CONFIG_KERN_HEAP | CONFIG_KERN_MONITOR
367         proc->stack_base = stack_base;
368         proc->stack_size = stack_size;
369         #if CONFIG_KERN_HEAP
370         if (free_stack)
371                 proc->flags |= PF_FREESTACK;
372         #endif
373 #endif
374         proc->user_entry = entry;
375         CPU_CREATE_NEW_STACK(proc->stack);
376
377 #if CONFIG_KERN_MONITOR
378         monitor_add(proc, name);
379 #endif
380
381         /* Add to ready list */
382         ATOMIC(SCHED_ENQUEUE(proc));
383
384         return proc;
385 }
386
387 /**
388  * Return the name of the specified process.
389  *
390  * NULL is a legal argument and will return the name "<NULL>".
391  */
392 const char *proc_name(struct Process *proc)
393 {
394 #if CONFIG_KERN_MONITOR
395         return proc ? proc->monitor.name : "<NULL>";
396 #else
397         (void)proc;
398         return "---";
399 #endif
400 }
401
402 /// Return the name of the currently running process
403 const char *proc_currentName(void)
404 {
405         return proc_name(proc_current());
406 }
407
408 /// Rename a process
409 void proc_rename(struct Process *proc, const char *name)
410 {
411 #if CONFIG_KERN_MONITOR
412         monitor_rename(proc, name);
413 #else
414         (void)proc; (void)name;
415 #endif
416 }
417
418
419 #if CONFIG_KERN_PRI
420 /**
421  * Change the scheduling priority of a process.
422  *
423  * Process piorities are signed ints, whereas a larger integer value means
424  * higher scheduling priority.  The default priority for new processes is 0.
425  * The idle process runs with the lowest possible priority: INT_MIN.
426  *
427  * A process with a higher priority always preempts lower priority processes.
428  * Processes of equal priority share the CPU time according to a simple
429  * round-robin policy.
430  *
431  * As a general rule to maximize responsiveness, compute-bound processes
432  * should be assigned negative priorities and tight, interactive processes
433  * should be assigned positive priorities.
434  *
435  * To avoid interfering with system background activities such as input
436  * processing, application processes should remain within the range -10
437  * and +10.
438  */
439 void proc_setPri(struct Process *proc, int pri)
440 {
441         if (proc->link.pri == pri)
442                 return;
443
444         proc->link.pri = pri;
445
446         if (proc != current_process)
447                 ATOMIC(sched_reenqueue(proc));
448 }
449 #endif // CONFIG_KERN_PRI
450
451 INLINE void proc_run(void)
452 {
453         void (*entry)(void) = current_process->user_entry;
454
455         LOG_INFO("New process starting at %p", entry);
456         entry();
457 }
458
459 /**
460  * Entry point for all the processes.
461  */
462 void proc_entry(void)
463 {
464         /*
465          * Return from a context switch assumes interrupts are disabled, so
466          * we need to explicitly re-enable them as soon as possible.
467          */
468         IRQ_ENABLE;
469         /* Call the actual process's entry point */
470         proc_run();
471         proc_exit();
472 }
473
474 /**
475  * Terminate the current process
476  */
477 void proc_exit(void)
478 {
479         LOG_INFO("%p:%s", current_process, proc_currentName());
480
481 #if CONFIG_KERN_MONITOR
482         monitor_remove(current_process);
483 #endif
484
485         proc_forbid();
486 #if CONFIG_KERN_HEAP
487         /*
488          * Set the task as zombie, its resources will be freed in proc_new() in
489          * a lazy way, when another process will be created.
490          */
491         proc_addZombie(current_process);
492 #endif
493         current_process = NULL;
494         proc_permit();
495
496         proc_switch();
497
498         /* never reached */
499         ASSERT(0);
500 }
501
502 /**
503  * Call the scheduler and eventually replace the current running process.
504  */
505 static void proc_schedule(void)
506 {
507         Process *old_process = current_process;
508
509         IRQ_ASSERT_DISABLED();
510
511         /* Poll on the ready queue for the first ready process */
512         LIST_ASSERT_VALID(&proc_ready_list);
513         while (!(current_process = (struct Process *)list_remHead(&proc_ready_list)))
514         {
515                 /*
516                  * Make sure we physically reenable interrupts here, no matter what
517                  * the current task status is. This is important because if we
518                  * are idle-spinning, we must allow interrupts, otherwise no
519                  * process will ever wake up.
520                  *
521                  * During idle-spinning, an interrupt can occur and it may
522                  * modify \p proc_ready_list. To ensure that compiler reload this
523                  * variable every while cycle we call CPU_MEMORY_BARRIER.
524                  * The memory barrier ensure that all variables used in this context
525                  * are reloaded.
526                  * \todo If there was a way to write sig_wait() so that it does not
527                  * disable interrupts while waiting, there would not be any
528                  * reason to do this.
529                  */
530                 IRQ_ENABLE;
531                 CPU_IDLE;
532                 MEMORY_BARRIER;
533                 IRQ_DISABLE;
534         }
535         if (CONTEXT_SWITCH_FROM_ISR())
536                 proc_context_switch(current_process, old_process);
537         /* This RET resumes the execution on the new process */
538         LOG_INFO("resuming %p:%s\n", current_process, proc_currentName());
539 }
540
541 #if CONFIG_KERN_PREEMPT
542 /* Global preemption nesting counter */
543 cpu_atomic_t preempt_count;
544
545 /*
546  * The time sharing interval: when a process is scheduled on a CPU it gets an
547  * amount of CONFIG_KERN_QUANTUM clock ticks. When these ticks expires and
548  * preemption is enabled a new process is selected to run.
549  */
550 int _proc_quantum;
551
552 /**
553  * Check if we need to schedule another task
554  */
555 bool proc_needPreempt(void)
556 {
557         if (UNLIKELY(current_process == NULL))
558                 return false;
559         if (!proc_preemptAllowed())
560                 return false;
561         if (LIST_EMPTY(&proc_ready_list))
562                 return false;
563         return preempt_quantum() ? prio_next() > prio_curr() :
564                         prio_next() >= prio_curr();
565 }
566
567 /**
568  * Preempt the current task.
569  */
570 void proc_preempt(void)
571 {
572         IRQ_ASSERT_DISABLED();
573         ASSERT(current_process);
574
575         /* Perform the kernel preemption */
576         LOG_INFO("preempting %p:%s\n", current_process, proc_currentName());
577         /* We are inside a IRQ context, so ATOMIC is not needed here */
578         SCHED_ENQUEUE(current_process);
579         preempt_reset_quantum();
580         proc_schedule();
581 }
582 #endif /* CONFIG_KERN_PREEMPT */
583
584 /* Immediately switch to a particular process */
585 static void proc_switchTo(Process *proc)
586 {
587         Process *old_process = current_process;
588
589         SCHED_ENQUEUE(current_process);
590         preempt_reset_quantum();
591         current_process = proc;
592         proc_context_switch(current_process, old_process);
593 }
594
595 /**
596  * Give the control of the CPU to another process.
597  *
598  * \note Assume the current process has been already added to a wait queue.
599  *
600  * \warning This should be considered an internal kernel function, even if it
601  * is allowed, usage from application code is strongly discouraged.
602  */
603 void proc_switch(void)
604 {
605         ASSERT(proc_preemptAllowed());
606         ATOMIC(
607                 preempt_reset_quantum();
608                 proc_schedule();
609         );
610 }
611
612 /**
613  * Immediately wakeup a process, dispatching it to the CPU.
614  */
615 void proc_wakeup(Process *proc)
616 {
617         ASSERT(proc_preemptAllowed());
618         ASSERT(current_process);
619         IRQ_ASSERT_DISABLED();
620
621         if (prio_proc(proc) >= prio_curr())
622                 proc_switchTo(proc);
623         else
624                 SCHED_ENQUEUE_HEAD(proc);
625 }
626
627 /**
628  * Voluntarily release the CPU.
629  */
630 void proc_yield(void)
631 {
632         Process *proc;
633
634         /*
635          * Voluntary preemption while preemption is disabled is considered
636          * illegal, as not very useful in practice.
637          *
638          * ASSERT if it happens.
639          */
640         ASSERT(proc_preemptAllowed());
641         IRQ_ASSERT_ENABLED();
642
643         IRQ_DISABLE;
644         proc = (struct Process *)list_remHead(&proc_ready_list);
645         if (proc)
646                 proc_switchTo(proc);
647         IRQ_ENABLE;
648 }