Add priority inheritance implementation for Semaphores.
[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
197 # if CONFIG_KERN_PRI_INHERIT
198         proc->orig_pri = proc->inh_link.pri = proc->link.pri;
199         proc->inh_blocked_by = NULL;
200         LIST_INIT(&proc->inh_list);
201 # endif
202 #endif
203 }
204
205 MOD_DEFINE(proc);
206
207 void proc_init(void)
208 {
209         LIST_INIT(&proc_ready_list);
210
211 #if CONFIG_KERN_HEAP
212         LIST_INIT(&zombie_list);
213         heap_init(&proc_heap, heap_buf, sizeof(heap_buf));
214 #endif
215         /*
216          * We "promote" the current context into a real process. The only thing we have
217          * to do is create a PCB and make it current. We don't need to setup the stack
218          * pointer because it will be written the first time we switch to another process.
219          */
220         proc_initStruct(&main_process);
221         current_process = &main_process;
222
223 #if CONFIG_KERN_MONITOR
224         monitor_init();
225         monitor_add(current_process, "main");
226 #endif
227         MOD_INIT(proc);
228 }
229
230
231 #if CONFIG_KERN_HEAP
232
233 /**
234  * Free all the resources of all zombie processes previously added to the zombie
235  * list.
236  */
237 static void proc_freeZombies(void)
238 {
239         Process *proc;
240
241         while (1)
242         {
243                 PROC_ATOMIC(proc = (Process *)list_remHead(&zombie_list));
244                 if (proc == NULL)
245                         return;
246
247                 if (proc->flags & PF_FREESTACK)
248                 {
249                         PROC_ATOMIC(heap_freemem(&proc_heap, proc->stack_base,
250                                 proc->stack_size + PROC_SIZE_WORDS * sizeof(cpu_stack_t)));
251                 }
252         }
253 }
254
255 /**
256  * Enqueue a process in the zombie list.
257  */
258 static void proc_addZombie(Process *proc)
259 {
260         Node *node;
261 #if CONFIG_KERN_PREEMPT
262         ASSERT(!proc_preemptAllowed());
263 #endif
264
265 #if CONFIG_KERN_PRI
266         node = &(proc)->link.link;
267 #else
268         node = &(proc)->link;
269 #endif
270         LIST_ASSERT_VALID(&zombie_list);
271         ADDTAIL(&zombie_list, node);
272 }
273
274 #endif /* CONFIG_KERN_HEAP */
275
276 /**
277  * Create a new process, starting at the provided entry point.
278  *
279  *
280  * \note The function
281  * \code
282  * proc_new(entry, data, stacksize, stack)
283  * \endcode
284  * is a more convenient way to create a process, as you don't have to specify
285  * the name.
286  *
287  * \return Process structure of new created process
288  *         if successful, NULL otherwise.
289  */
290 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)
291 {
292         Process *proc;
293         LOG_INFO("name=%s", name);
294 #if CONFIG_KERN_HEAP
295         bool free_stack = false;
296
297         /*
298          * Free up resources of a zombie process.
299          *
300          * We're implementing a kind of lazy garbage collector here for
301          * efficiency reasons: we can avoid to introduce overhead into another
302          * kernel task dedicated to free up resources (e.g., idle) and we're
303          * not introducing any overhead into the scheduler after a context
304          * switch (that would be *very* bad, because the scheduler runs with
305          * IRQ disabled).
306          *
307          * In this way we are able to release the memory of the zombie tasks
308          * without disabling IRQs and without introducing any significant
309          * overhead in any other kernel task.
310          */
311         proc_freeZombies();
312
313         /* Did the caller provide a stack for us? */
314         if (!stack_base)
315         {
316                 /* Did the caller specify the desired stack size? */
317                 if (!stack_size)
318                         stack_size = KERN_MINSTACKSIZE;
319
320                 /* Allocate stack dinamically */
321                 PROC_ATOMIC(stack_base =
322                         (cpu_stack_t *)heap_allocmem(&proc_heap, stack_size));
323                 if (stack_base == NULL)
324                         return NULL;
325
326                 free_stack = true;
327         }
328
329 #else // CONFIG_KERN_HEAP
330
331         /* Stack must have been provided by the user */
332         ASSERT2(IS_VALID_PTR(stack_base), "Invalid stack pointer. Did you forget to \
333                 enable CONFIG_KERN_HEAP?");
334         ASSERT2(stack_size, "Stack size cannot be 0.");
335
336 #endif // CONFIG_KERN_HEAP
337
338 #if CONFIG_KERN_MONITOR
339         /*
340          * Fill-in the stack with a special marker to help debugging.
341          * On 64bit platforms, CONFIG_KERN_STACKFILLCODE is larger
342          * than an int, so the (int) cast is required to silence the
343          * warning for truncating its size.
344          */
345         memset(stack_base, (int)CONFIG_KERN_STACKFILLCODE, stack_size);
346 #endif
347
348         /* Initialize the process control block */
349         if (CPU_STACK_GROWS_UPWARD)
350         {
351                 proc = (Process *)stack_base;
352                 proc->stack = stack_base + PROC_SIZE_WORDS;
353                 // On some architecture stack should be aligned, so we do it.
354                 proc->stack = (cpu_stack_t *)((uintptr_t)proc->stack + (sizeof(cpu_aligned_stack_t) - ((uintptr_t)proc->stack % sizeof(cpu_aligned_stack_t))));
355                 if (CPU_SP_ON_EMPTY_SLOT)
356                         proc->stack++;
357         }
358         else
359         {
360                 proc = (Process *)(stack_base + stack_size / sizeof(cpu_stack_t) - PROC_SIZE_WORDS);
361                 // On some architecture stack should be aligned, so we do it.
362                 proc->stack = (cpu_stack_t *)((uintptr_t)proc - ((uintptr_t)proc % sizeof(cpu_aligned_stack_t)));
363                 if (CPU_SP_ON_EMPTY_SLOT)
364                         proc->stack--;
365         }
366         /* Ensure stack is aligned */
367         ASSERT((uintptr_t)proc->stack % sizeof(cpu_aligned_stack_t) == 0);
368
369         stack_size -= PROC_SIZE_WORDS * sizeof(cpu_stack_t);
370         proc_initStruct(proc);
371         proc->user_data = data;
372
373 #if CONFIG_KERN_HEAP | CONFIG_KERN_MONITOR
374         proc->stack_base = stack_base;
375         proc->stack_size = stack_size;
376         #if CONFIG_KERN_HEAP
377         if (free_stack)
378                 proc->flags |= PF_FREESTACK;
379         #endif
380 #endif
381         proc->user_entry = entry;
382         CPU_CREATE_NEW_STACK(proc->stack);
383
384 #if CONFIG_KERN_MONITOR
385         monitor_add(proc, name);
386 #endif
387
388         /* Add to ready list */
389         ATOMIC(SCHED_ENQUEUE(proc));
390
391         return proc;
392 }
393
394 /**
395  * Return the name of the specified process.
396  *
397  * NULL is a legal argument and will return the name "<NULL>".
398  */
399 const char *proc_name(struct Process *proc)
400 {
401 #if CONFIG_KERN_MONITOR
402         return proc ? proc->monitor.name : "<NULL>";
403 #else
404         (void)proc;
405         return "---";
406 #endif
407 }
408
409 /// Return the name of the currently running process
410 const char *proc_currentName(void)
411 {
412         return proc_name(proc_current());
413 }
414
415 /// Rename a process
416 void proc_rename(struct Process *proc, const char *name)
417 {
418 #if CONFIG_KERN_MONITOR
419         monitor_rename(proc, name);
420 #else
421         (void)proc; (void)name;
422 #endif
423 }
424
425
426 #if CONFIG_KERN_PRI
427 /**
428  * Change the scheduling priority of a process.
429  *
430  * Process piorities are signed ints, whereas a larger integer value means
431  * higher scheduling priority.  The default priority for new processes is 0.
432  * The idle process runs with the lowest possible priority: INT_MIN.
433  *
434  * A process with a higher priority always preempts lower priority processes.
435  * Processes of equal priority share the CPU time according to a simple
436  * round-robin policy.
437  *
438  * As a general rule to maximize responsiveness, compute-bound processes
439  * should be assigned negative priorities and tight, interactive processes
440  * should be assigned positive priorities.
441  *
442  * To avoid interfering with system background activities such as input
443  * processing, application processes should remain within the range -10
444  * and +10.
445  */
446 void proc_setPri(struct Process *proc, int pri)
447 {
448 #if CONFIG_KERN_PRI_INHERIT
449         int new_pri;
450
451         /*
452          * Whatever it will happen below, this is the new
453          * original priority of the process, i.e., the priority
454          * it has without taking inheritance under account.
455          */
456         proc->orig_pri = pri;
457
458         /* If not changing anything we can just leave */
459         if ((new_pri = __prio_proc(proc)) == proc->link.pri)
460                 return;
461
462         /*
463          * Actual process priority is the highest among its
464          * own priority and the one of the top-priority
465          * process that it is blocking (returned by
466          * __prio_proc()).
467          */
468         proc->link.pri = new_pri;
469 #else
470         if (proc->link.pri == pri)
471                 return;
472
473         proc->link.pri = pri;
474 #endif // CONFIG_KERN_PRI_INHERIT
475
476         if (proc != current_process)
477                 ATOMIC(sched_reenqueue(proc));
478 }
479 #endif // CONFIG_KERN_PRI
480
481 INLINE void proc_run(void)
482 {
483         void (*entry)(void) = current_process->user_entry;
484
485         LOG_INFO("New process starting at %p", entry);
486         entry();
487 }
488
489 /**
490  * Entry point for all the processes.
491  */
492 void proc_entry(void)
493 {
494         /*
495          * Return from a context switch assumes interrupts are disabled, so
496          * we need to explicitly re-enable them as soon as possible.
497          */
498         IRQ_ENABLE;
499         /* Call the actual process's entry point */
500         proc_run();
501         proc_exit();
502 }
503
504 /**
505  * Terminate the current process
506  */
507 void proc_exit(void)
508 {
509         LOG_INFO("%p:%s", current_process, proc_currentName());
510
511 #if CONFIG_KERN_MONITOR
512         monitor_remove(current_process);
513 #endif
514
515         proc_forbid();
516 #if CONFIG_KERN_HEAP
517         /*
518          * Set the task as zombie, its resources will be freed in proc_new() in
519          * a lazy way, when another process will be created.
520          */
521         proc_addZombie(current_process);
522 #endif
523         current_process = NULL;
524         proc_permit();
525
526         proc_switch();
527
528         /* never reached */
529         ASSERT(0);
530 }
531
532 /**
533  * Call the scheduler and eventually replace the current running process.
534  */
535 static void proc_schedule(void)
536 {
537         Process *old_process = current_process;
538
539         IRQ_ASSERT_DISABLED();
540
541         /* Poll on the ready queue for the first ready process */
542         LIST_ASSERT_VALID(&proc_ready_list);
543         while (!(current_process = (struct Process *)list_remHead(&proc_ready_list)))
544         {
545                 /*
546                  * Make sure we physically reenable interrupts here, no matter what
547                  * the current task status is. This is important because if we
548                  * are idle-spinning, we must allow interrupts, otherwise no
549                  * process will ever wake up.
550                  *
551                  * During idle-spinning, an interrupt can occur and it may
552                  * modify \p proc_ready_list. To ensure that compiler reload this
553                  * variable every while cycle we call CPU_MEMORY_BARRIER.
554                  * The memory barrier ensure that all variables used in this context
555                  * are reloaded.
556                  * \todo If there was a way to write sig_wait() so that it does not
557                  * disable interrupts while waiting, there would not be any
558                  * reason to do this.
559                  */
560                 IRQ_ENABLE;
561                 CPU_IDLE;
562                 MEMORY_BARRIER;
563                 IRQ_DISABLE;
564         }
565         if (CONTEXT_SWITCH_FROM_ISR())
566                 proc_context_switch(current_process, old_process);
567         /* This RET resumes the execution on the new process */
568         LOG_INFO("resuming %p:%s\n", current_process, proc_currentName());
569 }
570
571 #if CONFIG_KERN_PREEMPT
572 /* Global preemption nesting counter */
573 cpu_atomic_t preempt_count;
574
575 /*
576  * The time sharing interval: when a process is scheduled on a CPU it gets an
577  * amount of CONFIG_KERN_QUANTUM clock ticks. When these ticks expires and
578  * preemption is enabled a new process is selected to run.
579  */
580 int _proc_quantum;
581
582 /**
583  * Check if we need to schedule another task
584  */
585 bool proc_needPreempt(void)
586 {
587         if (UNLIKELY(current_process == NULL))
588                 return false;
589         if (!proc_preemptAllowed())
590                 return false;
591         if (LIST_EMPTY(&proc_ready_list))
592                 return false;
593         return preempt_quantum() ? prio_next() > prio_curr() :
594                         prio_next() >= prio_curr();
595 }
596
597 /**
598  * Preempt the current task.
599  */
600 void proc_preempt(void)
601 {
602         IRQ_ASSERT_DISABLED();
603         ASSERT(current_process);
604
605         /* Perform the kernel preemption */
606         LOG_INFO("preempting %p:%s\n", current_process, proc_currentName());
607         /* We are inside a IRQ context, so ATOMIC is not needed here */
608         SCHED_ENQUEUE(current_process);
609         preempt_reset_quantum();
610         proc_schedule();
611 }
612 #endif /* CONFIG_KERN_PREEMPT */
613
614 /* Immediately switch to a particular process */
615 static void proc_switchTo(Process *proc)
616 {
617         Process *old_process = current_process;
618
619         SCHED_ENQUEUE(current_process);
620         preempt_reset_quantum();
621         current_process = proc;
622         proc_context_switch(current_process, old_process);
623 }
624
625 /**
626  * Give the control of the CPU to another process.
627  *
628  * \note Assume the current process has been already added to a wait queue.
629  *
630  * \warning This should be considered an internal kernel function, even if it
631  * is allowed, usage from application code is strongly discouraged.
632  */
633 void proc_switch(void)
634 {
635         ASSERT(proc_preemptAllowed());
636         ATOMIC(
637                 preempt_reset_quantum();
638                 proc_schedule();
639         );
640 }
641
642 /**
643  * Immediately wakeup a process, dispatching it to the CPU.
644  */
645 void proc_wakeup(Process *proc)
646 {
647         ASSERT(proc_preemptAllowed());
648         ASSERT(current_process);
649         IRQ_ASSERT_DISABLED();
650
651         if (prio_proc(proc) >= prio_curr())
652                 proc_switchTo(proc);
653         else
654                 SCHED_ENQUEUE_HEAD(proc);
655 }
656
657 /**
658  * Voluntarily release the CPU.
659  */
660 void proc_yield(void)
661 {
662         Process *proc;
663
664         /*
665          * Voluntary preemption while preemption is disabled is considered
666          * illegal, as not very useful in practice.
667          *
668          * ASSERT if it happens.
669          */
670         ASSERT(proc_preemptAllowed());
671         IRQ_ASSERT_ENABLED();
672
673         IRQ_DISABLE;
674         proc = (struct Process *)list_remHead(&proc_ready_list);
675         if (proc)
676                 proc_switchTo(proc);
677         IRQ_ENABLE;
678 }