2f44164b20174382c48355b08842fe2e314b5e51
[bertos.git] / bertos / kern / preempt.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  * Copyright 2008 Bernie Innocenti <bernie@codewiz.org>
30  * Copyright 2009 Andrea Righi <arighi@develer.com>
31  * -->
32  *
33  * \brief Simple preemptive multitasking scheduler.
34  *
35  * Preemption is explicitly regulated at the exit of each interrupt service
36  * routine (ISR). Each task obtains a time quantum as soon as it is scheduled
37  * on the CPU and its quantum is decremented at each clock tick. The frequency
38  * of the timer determines the system tick granularity and CONFIG_KERN_QUANTUM
39  * the time sharing interval.
40  *
41  * When the quantum expires the handler proc_needPreempt() checks if the
42  * preemption is enabled and in this case preempt_schedule() is called, that
43  * possibly replaces the current running thread with a different one.
44  *
45  * The preemption can be disabled or enabled via proc_forbid() and
46  * proc_permit() primitives. This is implemented using a global atomic counter.
47  * When the counter is greater than 0 the task cannot be preempted; only when
48  * the counter reaches 0 the task can be preempted again.
49  *
50  * Preemption-disabled sections may be nested. The preemption will be
51  * re-enabled when the outermost preemption-disabled section completes.
52  *
53  * The voluntary preemption still happens via proc_switch() or proc_yield().
54  * The first one assumes the current process has been already added to a
55  * private wait queue (e.g., on a semaphore or a signal), while the second one
56  * takes care of adding the process into the ready queue.
57  *
58  * Context switch is done by CPU-dependent support routines. In case of a
59  * voluntary preemption the context switch routine must take care of
60  * saving/restoring only the callee-save registers (the voluntary-preemption is
61  * actually a function call). The kernel-preemption always happens inside a
62  * signal/interrupt context and it must take care of saving all registers. For
63  * this, in the entry point of each ISR the caller-save registers must be
64  * saved. In the ISR exit point, if the context switch must happen, we switch
65  * to user-context and call the same voluntary context switch routine that take
66  * care of saving/restoring also the callee-save registers. On resume from the
67  * switch, the interrupt exit point moves back to interrupt-context, resumes
68  * the caller-save registers (saved in the ISR entry point) and return from the
69  * interrupt-context.
70  *
71  * \note Thread priority (if enabled by CONFIG_KERN_PRI) defines the order in
72  * the \p proc_ready_list and the capability to deschedule a running process. A
73  * low-priority thread can't preempt a high-priority thread.
74  *
75  * A high-priority process can preempt a low-priority process immediately (it
76  * will be descheduled and replaced in the interrupt exit point). Processes
77  * running at the same priority can be descheduled when they expire the time
78  * quantum.
79  *
80  * \note Sleeping while preemption is disabled fallbacks to a busy-wait sleep.
81  * Voluntary preemption when preemption is disabled raises a kernel bug.
82  *
83  * \author Bernie Innocenti <bernie@codewiz.org>
84  * \author Andrea Righi <arighi@develer.com>
85  */
86
87 #include "cfg/cfg_proc.h"
88
89 #include "proc_p.h"
90 #include "proc.h"
91
92 #include <kern/irq.h>
93 #include <kern/monitor.h>
94 #include <kern/idle.h> // idle_proc
95 #include <cpu/frame.h> // CPU_IDLE
96 #include <cpu/irq.h>   // IRQ_DISABLE()...
97 #include <cfg/log.h>
98 #include <cfg/module.h>
99 #include <cfg/depend.h>    // CONFIG_DEPEND()
100
101 // Check config dependencies
102 CONFIG_DEPEND(CONFIG_KERN_PREEMPT, CONFIG_KERN);
103
104 MOD_DEFINE(preempt)
105
106 /**
107  * CPU dependent context switching routines.
108  *
109  * Saving and restoring the context on the stack is done by a CPU-dependent
110  * support routine which usually needs to be written in assembly.
111  */
112 EXTERN_C void asm_switch_context(cpu_stack_t **new_sp, cpu_stack_t **save_sp);
113
114 /* Global preemption nesting counter */
115 cpu_atomic_t preempt_count;
116
117 /*
118  * The time sharing interval: when a process is scheduled on a CPU it gets an
119  * amount of CONFIG_KERN_QUANTUM clock ticks. When these ticks expires and
120  * preemption is enabled a new process is selected to run.
121  */
122 int _proc_quantum;
123
124 /**
125  * Define function prototypes exported outside.
126  *
127  * Required to silent gcc "no previous prototype" warnings.
128  */
129 void preempt_yield(void);
130 int preempt_needPreempt(void);
131 void preempt_preempt(void);
132 void preempt_switch(void);
133 void preempt_init(void);
134
135 /**
136  * Call the scheduler and eventually replace the current running process.
137  */
138 static void preempt_schedule(void)
139 {
140         Process *old_process = current_process;
141
142         IRQ_ASSERT_DISABLED();
143
144         /* Poll on the ready queue for the first ready process */
145         LIST_ASSERT_VALID(&proc_ready_list);
146         current_process = (Process *)list_remHead(&proc_ready_list);
147         if (UNLIKELY(!current_process))
148                 current_process = idle_proc;
149         _proc_quantum = CONFIG_KERN_QUANTUM;
150         /*
151          * Optimization: don't switch contexts when the active process has not
152          * changed.
153          */
154         if (LIKELY(old_process != current_process))
155         {
156                 cpu_stack_t *dummy;
157
158                 /*
159                  * Save context of old process and switch to new process. If
160                  * there is no old process, we save the old stack pointer into
161                  * a dummy variable that we ignore. In fact, this happens only
162                  * when the old process has just exited.
163                  *
164                  * \todo Instead of physically clearing the process at exit
165                  * time, a zombie list should be created.
166                  */
167                 asm_switch_context(&current_process->stack,
168                                 old_process ? &old_process->stack : &dummy);
169         }
170
171         /* This RET resumes the execution on the new process */
172         LOG_INFO("resuming %p:%s\n", current_process, proc_currentName());
173 }
174
175 /**
176  * Check if we need to schedule another task
177  */
178 int preempt_needPreempt(void)
179 {
180         if (UNLIKELY(current_process == NULL))
181                 return 0;
182         if (!proc_preemptAllowed())
183                 return 0;
184         return _proc_quantum ? prio_next() > prio_curr() :
185                         prio_next() >= prio_curr();
186 }
187
188 /**
189  * Preempt the current task.
190  */
191 void preempt_preempt(void)
192 {
193         IRQ_ASSERT_DISABLED();
194         ASSERT(current_process);
195
196         /* Perform the kernel preemption */
197         LOG_INFO("preempting %p:%s\n", current_process, proc_currentName());
198         /* We are inside a IRQ context, so ATOMIC is not needed here */
199         if (current_process != idle_proc)
200                 SCHED_ENQUEUE(current_process);
201         preempt_schedule();
202 }
203
204 /**
205  * Give the control of the CPU to another process.
206  *
207  * \note Assume the current process has been already added to a wait queue.
208  *
209  * \warning This should be considered an internal kernel function, even if it
210  * is allowed, usage from application code is strongly discouraged.
211  */
212 void preempt_switch(void)
213 {
214         ASSERT(proc_preemptAllowed());
215         IRQ_ASSERT_ENABLED();
216
217         ATOMIC(preempt_schedule());
218 }
219
220 /**
221  * Voluntarily release the CPU.
222  */
223 void preempt_yield(void)
224 {
225         /*
226          * Voluntary preemption while preemption is disabled is considered
227          * illegal, as not very useful in practice.
228          *
229          * ASSERT if it happens.
230          */
231         ASSERT(proc_preemptAllowed());
232         IRQ_ASSERT_ENABLED();
233
234         ATOMIC(
235                 SCHED_ENQUEUE(current_process);
236                 preempt_schedule();
237         );
238 }
239
240 void preempt_init(void)
241 {
242         idle_init();
243         MOD_INIT(preempt);
244 }