2 * Copyright (c) 2001 Jake Burkholder <jake@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
31 #include "opt_sched.h"
33 #ifndef KERN_SWITCH_INCLUDE
34 #include <sys/param.h>
35 #include <sys/systm.h>
37 #include <sys/kernel.h>
40 #include <sys/mutex.h>
42 #include <sys/queue.h>
43 #include <sys/sched.h>
44 #else /* KERN_SWITCH_INCLUDE */
45 #if defined(SMP) && (defined(__i386__) || defined(__amd64__))
48 #if defined(SMP) && defined(SCHED_4BSD)
49 #include <sys/sysctl.h>
52 #include <machine/cpu.h>
54 /* Uncomment this to enable logging of critical_enter/exit. */
56 #define KTR_CRITICAL KTR_SCHED
58 #define KTR_CRITICAL 0
61 #ifdef FULL_PREEMPTION
63 #error "The FULL_PREEMPTION option requires the PREEMPTION option"
67 CTASSERT((RQB_BPW * RQB_LEN) == RQ_NQS);
70 * kern.sched.preemption allows user space to determine if preemption support
71 * is compiled in or not. It is not currently a boot or runtime flag that
75 static int kern_sched_preemption = 1;
77 static int kern_sched_preemption = 0;
79 SYSCTL_INT(_kern_sched, OID_AUTO, preemption, CTLFLAG_RD,
80 &kern_sched_preemption, 0, "Kernel preemption enabled");
84 long switch_owepreempt;
85 long switch_turnstile;
87 long switch_sleepqtimo;
88 long switch_relinquish;
89 long switch_needresched;
90 static SYSCTL_NODE(_kern_sched, OID_AUTO, stats, CTLFLAG_RW, 0, "switch stats");
91 SYSCTL_INT(_kern_sched_stats, OID_AUTO, preempt, CTLFLAG_RD, &switch_preempt, 0, "");
92 SYSCTL_INT(_kern_sched_stats, OID_AUTO, owepreempt, CTLFLAG_RD, &switch_owepreempt, 0, "");
93 SYSCTL_INT(_kern_sched_stats, OID_AUTO, turnstile, CTLFLAG_RD, &switch_turnstile, 0, "");
94 SYSCTL_INT(_kern_sched_stats, OID_AUTO, sleepq, CTLFLAG_RD, &switch_sleepq, 0, "");
95 SYSCTL_INT(_kern_sched_stats, OID_AUTO, sleepqtimo, CTLFLAG_RD, &switch_sleepqtimo, 0, "");
96 SYSCTL_INT(_kern_sched_stats, OID_AUTO, relinquish, CTLFLAG_RD, &switch_relinquish, 0, "");
97 SYSCTL_INT(_kern_sched_stats, OID_AUTO, needresched, CTLFLAG_RD, &switch_needresched, 0, "");
99 sysctl_stats_reset(SYSCTL_HANDLER_ARGS)
105 error = sysctl_handle_int(oidp, &val, 0, req);
106 if (error != 0 || req->newptr == NULL)
111 switch_owepreempt = 0;
112 switch_turnstile = 0;
114 switch_sleepqtimo = 0;
115 switch_relinquish = 0;
116 switch_needresched = 0;
121 SYSCTL_PROC(_kern_sched_stats, OID_AUTO, reset, CTLTYPE_INT | CTLFLAG_WR, NULL,
122 0, sysctl_stats_reset, "I", "Reset scheduler statistics");
125 /************************************************************************
126 * Functions that manipulate runnability from a thread perspective. *
127 ************************************************************************/
129 * Select the thread that will be run next.
140 * If we are in panic, only allow system threads,
141 * plus the one we are running in, to be run.
143 if (panicstr && ((td->td_proc->p_flag & P_SYSTEM) == 0 &&
144 (td->td_flags & TDF_INPANIC) == 0)) {
145 /* note that it is no longer on the run queue */
155 * Kernel thread preemption implementation. Critical sections mark
156 * regions of code in which preemptions are not allowed.
165 CTR4(KTR_CRITICAL, "critical_enter by thread %p (%ld, %s) to %d", td,
166 (long)td->td_proc->p_pid, td->td_proc->p_comm, td->td_critnest);
175 KASSERT(td->td_critnest != 0,
176 ("critical_exit: td_critnest == 0"));
178 if (td->td_critnest == 1) {
180 if (td->td_owepreempt) {
184 SCHED_STAT_INC(switch_owepreempt);
185 mi_switch(SW_INVOL|SW_PREEMPT, NULL);
191 CTR4(KTR_CRITICAL, "critical_exit by thread %p (%ld, %s) to %d", td,
192 (long)td->td_proc->p_pid, td->td_proc->p_comm, td->td_critnest);
196 * This function is called when a thread is about to be put on run queue
197 * because it has been made runnable or its priority has been adjusted. It
198 * determines if the new thread should be immediately preempted to. If so,
199 * it switches to it and eventually returns true. If not, it returns false
200 * so that the caller may place the thread on an appropriate run queue.
203 maybe_preempt(struct thread *td)
212 * The new thread should not preempt the current thread if any of the
213 * following conditions are true:
215 * - The kernel is in the throes of crashing (panicstr).
216 * - The current thread has a higher (numerically lower) or
217 * equivalent priority. Note that this prevents curthread from
218 * trying to preempt to itself.
219 * - It is too early in the boot for context switches (cold is set).
220 * - The current thread has an inhibitor set or is in the process of
221 * exiting. In this case, the current thread is about to switch
222 * out anyways, so there's no point in preempting. If we did,
223 * the current thread would not be properly resumed as well, so
224 * just avoid that whole landmine.
225 * - If the new thread's priority is not a realtime priority and
226 * the current thread's priority is not an idle priority and
227 * FULL_PREEMPTION is disabled.
229 * If all of these conditions are false, but the current thread is in
230 * a nested critical section, then we have to defer the preemption
231 * until we exit the critical section. Otherwise, switch immediately
235 THREAD_LOCK_ASSERT(td, MA_OWNED);
236 KASSERT ((ctd->td_sched != NULL && ctd->td_sched->ts_thread == ctd),
237 ("thread has no (or wrong) sched-private part."));
238 KASSERT((td->td_inhibitors == 0),
239 ("maybe_preempt: trying to run inhibited thread"));
240 pri = td->td_priority;
241 cpri = ctd->td_priority;
242 if (panicstr != NULL || pri >= cpri || cold /* || dumping */ ||
243 TD_IS_INHIBITED(ctd))
245 #ifndef FULL_PREEMPTION
246 if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
250 if (ctd->td_critnest > 1) {
251 CTR1(KTR_PROC, "maybe_preempt: in critical section %d",
253 ctd->td_owepreempt = 1;
257 * Thread is runnable but not yet put on system run queue.
259 MPASS(ctd->td_lock == td->td_lock);
260 MPASS(TD_ON_RUNQ(td));
262 CTR3(KTR_PROC, "preempting to thread %p (pid %d, %s)\n", td,
263 td->td_proc->p_pid, td->td_proc->p_comm);
264 SCHED_STAT_INC(switch_preempt);
265 mi_switch(SW_INVOL|SW_PREEMPT, td);
267 * td's lock pointer may have changed. We have to return with it
282 /* XXX: There should be a non-static version of this. */
284 printf_caddr_t(void *data)
286 printf("%s", (char *)data);
288 static char preempt_warning[] =
289 "WARNING: Kernel preemption is disabled, expect reduced performance.\n";
290 SYSINIT(preempt_warning, SI_SUB_COPYRIGHT, SI_ORDER_ANY, printf_caddr_t,
295 /************************************************************************
296 * SYSTEM RUN QUEUE manipulations and tests *
297 ************************************************************************/
299 * Initialize a run structure.
302 runq_init(struct runq *rq)
306 bzero(rq, sizeof *rq);
307 for (i = 0; i < RQ_NQS; i++)
308 TAILQ_INIT(&rq->rq_queues[i]);
312 * Clear the status bit of the queue corresponding to priority level pri,
313 * indicating that it is empty.
316 runq_clrbit(struct runq *rq, int pri)
320 rqb = &rq->rq_status;
321 CTR4(KTR_RUNQ, "runq_clrbit: bits=%#x %#x bit=%#x word=%d",
322 rqb->rqb_bits[RQB_WORD(pri)],
323 rqb->rqb_bits[RQB_WORD(pri)] & ~RQB_BIT(pri),
324 RQB_BIT(pri), RQB_WORD(pri));
325 rqb->rqb_bits[RQB_WORD(pri)] &= ~RQB_BIT(pri);
329 * Find the index of the first non-empty run queue. This is done by
330 * scanning the status bits, a set bit indicates a non-empty queue.
333 runq_findbit(struct runq *rq)
339 rqb = &rq->rq_status;
340 for (i = 0; i < RQB_LEN; i++)
341 if (rqb->rqb_bits[i]) {
342 pri = RQB_FFS(rqb->rqb_bits[i]) + (i << RQB_L2BPW);
343 CTR3(KTR_RUNQ, "runq_findbit: bits=%#x i=%d pri=%d",
344 rqb->rqb_bits[i], i, pri);
352 runq_findbit_from(struct runq *rq, u_char pri)
359 * Set the mask for the first word so we ignore priorities before 'pri'.
361 mask = (rqb_word_t)-1 << (pri & (RQB_BPW - 1));
362 rqb = &rq->rq_status;
364 for (i = RQB_WORD(pri); i < RQB_LEN; mask = -1, i++) {
365 mask = rqb->rqb_bits[i] & mask;
368 pri = RQB_FFS(mask) + (i << RQB_L2BPW);
369 CTR3(KTR_RUNQ, "runq_findbit_from: bits=%#x i=%d pri=%d",
376 * Wrap back around to the beginning of the list just once so we
377 * scan the whole thing.
384 * Set the status bit of the queue corresponding to priority level pri,
385 * indicating that it is non-empty.
388 runq_setbit(struct runq *rq, int pri)
392 rqb = &rq->rq_status;
393 CTR4(KTR_RUNQ, "runq_setbit: bits=%#x %#x bit=%#x word=%d",
394 rqb->rqb_bits[RQB_WORD(pri)],
395 rqb->rqb_bits[RQB_WORD(pri)] | RQB_BIT(pri),
396 RQB_BIT(pri), RQB_WORD(pri));
397 rqb->rqb_bits[RQB_WORD(pri)] |= RQB_BIT(pri);
401 * Add the thread to the queue specified by its priority, and set the
402 * corresponding status bit.
405 runq_add(struct runq *rq, struct td_sched *ts, int flags)
410 pri = ts->ts_thread->td_priority / RQ_PPQ;
411 ts->ts_rqindex = pri;
412 runq_setbit(rq, pri);
413 rqh = &rq->rq_queues[pri];
414 CTR5(KTR_RUNQ, "runq_add: td=%p ts=%p pri=%d %d rqh=%p",
415 ts->ts_thread, ts, ts->ts_thread->td_priority, pri, rqh);
416 if (flags & SRQ_PREEMPTED) {
417 TAILQ_INSERT_HEAD(rqh, ts, ts_procq);
419 TAILQ_INSERT_TAIL(rqh, ts, ts_procq);
424 runq_add_pri(struct runq *rq, struct td_sched *ts, u_char pri, int flags)
428 KASSERT(pri < RQ_NQS, ("runq_add_pri: %d out of range", pri));
429 ts->ts_rqindex = pri;
430 runq_setbit(rq, pri);
431 rqh = &rq->rq_queues[pri];
432 CTR5(KTR_RUNQ, "runq_add_pri: td=%p ke=%p pri=%d idx=%d rqh=%p",
433 ts->ts_thread, ts, ts->ts_thread->td_priority, pri, rqh);
434 if (flags & SRQ_PREEMPTED) {
435 TAILQ_INSERT_HEAD(rqh, ts, ts_procq);
437 TAILQ_INSERT_TAIL(rqh, ts, ts_procq);
441 * Return true if there are runnable processes of any priority on the run
442 * queue, false otherwise. Has no side effects, does not modify the run
446 runq_check(struct runq *rq)
451 rqb = &rq->rq_status;
452 for (i = 0; i < RQB_LEN; i++)
453 if (rqb->rqb_bits[i]) {
454 CTR2(KTR_RUNQ, "runq_check: bits=%#x i=%d",
455 rqb->rqb_bits[i], i);
458 CTR0(KTR_RUNQ, "runq_check: empty");
463 #if defined(SMP) && defined(SCHED_4BSD)
465 SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
469 * Find the highest priority process on the run queue.
472 runq_choose(struct runq *rq)
478 while ((pri = runq_findbit(rq)) != -1) {
479 rqh = &rq->rq_queues[pri];
480 #if defined(SMP) && defined(SCHED_4BSD)
481 /* fuzz == 1 is normal.. 0 or less are ignored */
484 * In the first couple of entries, check if
485 * there is one for our CPU as a preference.
487 int count = runq_fuzz;
488 int cpu = PCPU_GET(cpuid);
489 struct td_sched *ts2;
490 ts2 = ts = TAILQ_FIRST(rqh);
492 while (count-- && ts2) {
493 if (ts2->ts_thread->td_lastcpu == cpu) {
497 ts2 = TAILQ_NEXT(ts2, ts_procq);
501 ts = TAILQ_FIRST(rqh);
502 KASSERT(ts != NULL, ("runq_choose: no proc on busy queue"));
504 "runq_choose: pri=%d td_sched=%p rqh=%p", pri, ts, rqh);
507 CTR1(KTR_RUNQ, "runq_choose: idleproc pri=%d", pri);
513 runq_choose_from(struct runq *rq, u_char idx)
519 if ((pri = runq_findbit_from(rq, idx)) != -1) {
520 rqh = &rq->rq_queues[pri];
521 ts = TAILQ_FIRST(rqh);
522 KASSERT(ts != NULL, ("runq_choose: no proc on busy queue"));
524 "runq_choose_from: pri=%d kse=%p idx=%d rqh=%p",
525 pri, ts, ts->ts_rqindex, rqh);
528 CTR1(KTR_RUNQ, "runq_choose_from: idleproc pri=%d", pri);
533 * Remove the thread from the queue specified by its priority, and clear the
534 * corresponding status bit if the queue becomes empty.
535 * Caller must set state afterwards.
538 runq_remove(struct runq *rq, struct td_sched *ts)
541 runq_remove_idx(rq, ts, NULL);
545 runq_remove_idx(struct runq *rq, struct td_sched *ts, u_char *idx)
550 KASSERT(ts->ts_thread->td_flags & TDF_INMEM,
551 ("runq_remove_idx: thread swapped out"));
552 pri = ts->ts_rqindex;
553 KASSERT(pri < RQ_NQS, ("runq_remove_idx: Invalid index %d\n", pri));
554 rqh = &rq->rq_queues[pri];
555 CTR5(KTR_RUNQ, "runq_remove_idx: td=%p, ts=%p pri=%d %d rqh=%p",
556 ts->ts_thread, ts, ts->ts_thread->td_priority, pri, rqh);
558 struct td_sched *nts;
560 TAILQ_FOREACH(nts, rqh, ts_procq)
564 panic("runq_remove_idx: ts %p not on rqindex %d",
567 TAILQ_REMOVE(rqh, ts, ts_procq);
568 if (TAILQ_EMPTY(rqh)) {
569 CTR0(KTR_RUNQ, "runq_remove_idx: empty");
570 runq_clrbit(rq, pri);
571 if (idx != NULL && *idx == pri)
572 *idx = (pri + 1) % RQ_NQS;
576 /****** functions that are temporarily here ***********/
580 * Allocate scheduler specific per-process resources.
581 * The thread and proc have already been linked in.
584 * proc_init() (UMA init method)
587 sched_newproc(struct proc *p, struct thread *td)
592 * thread is being either created or recycled.
593 * Fix up the per-scheduler resources associated with it.
595 * sched_fork_thread()
596 * thread_dtor() (*may go away)
597 * thread_init() (*may go away)
600 sched_newthread(struct thread *td)
604 ts = (struct td_sched *) (td + 1);
605 bzero(ts, sizeof(*ts));
610 #endif /* KERN_SWITCH_INCLUDE */