xref: /freebsd/sys/kern/sched_4bsd.c (revision 785797c341c3f39f8c4e6828e579d0d32489255c)
1b43179fbSJeff Roberson /*-
2b43179fbSJeff Roberson  * Copyright (c) 1982, 1986, 1990, 1991, 1993
3b43179fbSJeff Roberson  *	The Regents of the University of California.  All rights reserved.
4b43179fbSJeff Roberson  * (c) UNIX System Laboratories, Inc.
5b43179fbSJeff Roberson  * All or some portions of this file are derived from material licensed
6b43179fbSJeff Roberson  * to the University of California by American Telephone and Telegraph
7b43179fbSJeff Roberson  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8b43179fbSJeff Roberson  * the permission of UNIX System Laboratories, Inc.
9b43179fbSJeff Roberson  *
10b43179fbSJeff Roberson  * Redistribution and use in source and binary forms, with or without
11b43179fbSJeff Roberson  * modification, are permitted provided that the following conditions
12b43179fbSJeff Roberson  * are met:
13b43179fbSJeff Roberson  * 1. Redistributions of source code must retain the above copyright
14b43179fbSJeff Roberson  *    notice, this list of conditions and the following disclaimer.
15b43179fbSJeff Roberson  * 2. Redistributions in binary form must reproduce the above copyright
16b43179fbSJeff Roberson  *    notice, this list of conditions and the following disclaimer in the
17b43179fbSJeff Roberson  *    documentation and/or other materials provided with the distribution.
18b43179fbSJeff Roberson  * 4. Neither the name of the University nor the names of its contributors
19b43179fbSJeff Roberson  *    may be used to endorse or promote products derived from this software
20b43179fbSJeff Roberson  *    without specific prior written permission.
21b43179fbSJeff Roberson  *
22b43179fbSJeff Roberson  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23b43179fbSJeff Roberson  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24b43179fbSJeff Roberson  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25b43179fbSJeff Roberson  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26b43179fbSJeff Roberson  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27b43179fbSJeff Roberson  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28b43179fbSJeff Roberson  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29b43179fbSJeff Roberson  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30b43179fbSJeff Roberson  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31b43179fbSJeff Roberson  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32b43179fbSJeff Roberson  * SUCH DAMAGE.
33b43179fbSJeff Roberson  */
34b43179fbSJeff Roberson 
35677b542eSDavid E. O'Brien #include <sys/cdefs.h>
36677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
37677b542eSDavid E. O'Brien 
384da0d332SPeter Wemm #include "opt_hwpmc_hooks.h"
39a564bfc7SJeff Roberson #include "opt_sched.h"
406f5f25e5SJohn Birrell #include "opt_kdtrace.h"
414da0d332SPeter Wemm 
42b43179fbSJeff Roberson #include <sys/param.h>
43b43179fbSJeff Roberson #include <sys/systm.h>
44f5a3ef99SMarcel Moolenaar #include <sys/cpuset.h>
45b43179fbSJeff Roberson #include <sys/kernel.h>
46b43179fbSJeff Roberson #include <sys/ktr.h>
47b43179fbSJeff Roberson #include <sys/lock.h>
48c55bbb6cSJohn Baldwin #include <sys/kthread.h>
49b43179fbSJeff Roberson #include <sys/mutex.h>
50b43179fbSJeff Roberson #include <sys/proc.h>
51b43179fbSJeff Roberson #include <sys/resourcevar.h>
52b43179fbSJeff Roberson #include <sys/sched.h>
53b3e9e682SRyan Stone #include <sys/sdt.h>
54b43179fbSJeff Roberson #include <sys/smp.h>
55b43179fbSJeff Roberson #include <sys/sysctl.h>
56b43179fbSJeff Roberson #include <sys/sx.h>
57f5c157d9SJohn Baldwin #include <sys/turnstile.h>
583db720fdSDavid Xu #include <sys/umtx.h>
592e4db89cSDavid E. O'Brien #include <machine/pcb.h>
60293968d8SJulian Elischer #include <machine/smp.h>
61b43179fbSJeff Roberson 
62ebccf1e3SJoseph Koshy #ifdef HWPMC_HOOKS
63ebccf1e3SJoseph Koshy #include <sys/pmckern.h>
64ebccf1e3SJoseph Koshy #endif
65ebccf1e3SJoseph Koshy 
666f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
676f5f25e5SJohn Birrell #include <sys/dtrace_bsd.h>
686f5f25e5SJohn Birrell int				dtrace_vtime_active;
696f5f25e5SJohn Birrell dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
706f5f25e5SJohn Birrell #endif
716f5f25e5SJohn Birrell 
7206439a04SJeff Roberson /*
7306439a04SJeff Roberson  * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
7406439a04SJeff Roberson  * the range 100-256 Hz (approximately).
7506439a04SJeff Roberson  */
7606439a04SJeff Roberson #define	ESTCPULIM(e) \
7706439a04SJeff Roberson     min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
7806439a04SJeff Roberson     RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
79b698380fSBruce Evans #ifdef SMP
80b698380fSBruce Evans #define	INVERSE_ESTCPU_WEIGHT	(8 * smp_cpus)
81b698380fSBruce Evans #else
8206439a04SJeff Roberson #define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
83b698380fSBruce Evans #endif
8406439a04SJeff Roberson #define	NICE_WEIGHT		1	/* Priorities per nice level. */
8506439a04SJeff Roberson 
860d2cf837SJeff Roberson #define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
878f51ad55SJeff Roberson 
888460a577SJohn Birrell /*
898460a577SJohn Birrell  * The schedulable entity that runs a context.
90ad1e7d28SJulian Elischer  * This is  an extension to the thread structure and is tailored to
91ad1e7d28SJulian Elischer  * the requirements of this scheduler
928460a577SJohn Birrell  */
93ad1e7d28SJulian Elischer struct td_sched {
94ad1e7d28SJulian Elischer 	fixpt_t		ts_pctcpu;	/* (j) %cpu during p_swtime. */
95ad1e7d28SJulian Elischer 	int		ts_cpticks;	/* (j) Ticks of cpu time. */
9654b0e65fSJeff Roberson 	int		ts_slptime;	/* (j) Seconds !RUNNING. */
9748317e9eSAlexander Motin 	int		ts_slice;	/* Remaining part of time slice. */
98f200843bSJohn Baldwin 	int		ts_flags;
99ad1e7d28SJulian Elischer 	struct runq	*ts_runq;	/* runq the thread is currently on */
1008f51ad55SJeff Roberson #ifdef KTR
1018f51ad55SJeff Roberson 	char		ts_name[TS_NAME_LEN];
1028f51ad55SJeff Roberson #endif
103bcb06d59SJeff Roberson };
104ed062c8dSJulian Elischer 
105ed062c8dSJulian Elischer /* flags kept in td_flags */
106ad1e7d28SJulian Elischer #define TDF_DIDRUN	TDF_SCHED0	/* thread actually ran. */
1079727e637SJeff Roberson #define TDF_BOUND	TDF_SCHED1	/* Bound to one CPU. */
1083d7f4117SAlexander Motin #define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
109bcb06d59SJeff Roberson 
110f200843bSJohn Baldwin /* flags kept in ts_flags */
111f200843bSJohn Baldwin #define	TSF_AFFINITY	0x0001		/* Has a non-"full" CPU set. */
112f200843bSJohn Baldwin 
113ad1e7d28SJulian Elischer #define SKE_RUNQ_PCPU(ts)						\
114ad1e7d28SJulian Elischer     ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
115e17c57b1SJeff Roberson 
116f200843bSJohn Baldwin #define	THREAD_CAN_SCHED(td, cpu)	\
117f200843bSJohn Baldwin     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
118f200843bSJohn Baldwin 
119ad1e7d28SJulian Elischer static struct td_sched td_sched0;
1206ea38de8SJeff Roberson struct mtx sched_lock;
121b43179fbSJeff Roberson 
122579895dfSAlexander Motin static int	realstathz = 127; /* stathz is sometimes 0 and run off of hz. */
123ca59f152SJeff Roberson static int	sched_tdcnt;	/* Total runnable threads in the system. */
124579895dfSAlexander Motin static int	sched_slice = 12; /* Thread run time before rescheduling. */
125b43179fbSJeff Roberson 
126e17c57b1SJeff Roberson static void	setup_runqs(void);
127c55bbb6cSJohn Baldwin static void	schedcpu(void);
128e17c57b1SJeff Roberson static void	schedcpu_thread(void);
129f5c157d9SJohn Baldwin static void	sched_priority(struct thread *td, u_char prio);
130b43179fbSJeff Roberson static void	sched_setup(void *dummy);
131b43179fbSJeff Roberson static void	maybe_resched(struct thread *td);
1328460a577SJohn Birrell static void	updatepri(struct thread *td);
1338460a577SJohn Birrell static void	resetpriority(struct thread *td);
1348460a577SJohn Birrell static void	resetpriority_thread(struct thread *td);
13500b0483dSJulian Elischer #ifdef SMP
136f200843bSJohn Baldwin static int	sched_pickcpu(struct thread *td);
13782a1dfc1SJulian Elischer static int	forward_wakeup(int cpunum);
1388aa3d7ffSJohn Baldwin static void	kick_other_cpu(int pri, int cpuid);
13900b0483dSJulian Elischer #endif
140b43179fbSJeff Roberson 
141e17c57b1SJeff Roberson static struct kproc_desc sched_kp = {
142e17c57b1SJeff Roberson         "schedcpu",
143e17c57b1SJeff Roberson         schedcpu_thread,
144e17c57b1SJeff Roberson         NULL
145e17c57b1SJeff Roberson };
146*785797c3SAndriy Gapon SYSINIT(schedcpu, SI_SUB_LAST, SI_ORDER_FIRST, kproc_start,
147237fdd78SRobert Watson     &sched_kp);
148237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
149b43179fbSJeff Roberson 
15048317e9eSAlexander Motin static void sched_initticks(void *dummy);
15148317e9eSAlexander Motin SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
15248317e9eSAlexander Motin     NULL);
15348317e9eSAlexander Motin 
154b43179fbSJeff Roberson /*
155b43179fbSJeff Roberson  * Global run queue.
156b43179fbSJeff Roberson  */
157b43179fbSJeff Roberson static struct runq runq;
158e17c57b1SJeff Roberson 
159e17c57b1SJeff Roberson #ifdef SMP
160e17c57b1SJeff Roberson /*
161e17c57b1SJeff Roberson  * Per-CPU run queues
162e17c57b1SJeff Roberson  */
163e17c57b1SJeff Roberson static struct runq runq_pcpu[MAXCPU];
164f200843bSJohn Baldwin long runq_length[MAXCPU];
1653121f534SAttilio Rao 
16671a19bdcSAttilio Rao static cpuset_t idle_cpus_mask;
167e17c57b1SJeff Roberson #endif
168e17c57b1SJeff Roberson 
169b722ad00SAlexander Motin struct pcpuidlestat {
170b722ad00SAlexander Motin 	u_int idlecalls;
171b722ad00SAlexander Motin 	u_int oldidlecalls;
172b722ad00SAlexander Motin };
1733e288e62SDimitry Andric static DPCPU_DEFINE(struct pcpuidlestat, idlestat);
174b722ad00SAlexander Motin 
175e17c57b1SJeff Roberson static void
176e17c57b1SJeff Roberson setup_runqs(void)
177e17c57b1SJeff Roberson {
178e17c57b1SJeff Roberson #ifdef SMP
179e17c57b1SJeff Roberson 	int i;
180e17c57b1SJeff Roberson 
181e17c57b1SJeff Roberson 	for (i = 0; i < MAXCPU; ++i)
182e17c57b1SJeff Roberson 		runq_init(&runq_pcpu[i]);
183e17c57b1SJeff Roberson #endif
184e17c57b1SJeff Roberson 
185e17c57b1SJeff Roberson 	runq_init(&runq);
186e17c57b1SJeff Roberson }
187b43179fbSJeff Roberson 
188579895dfSAlexander Motin static int
189579895dfSAlexander Motin sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
190579895dfSAlexander Motin {
191579895dfSAlexander Motin 	int error, new_val, period;
192579895dfSAlexander Motin 
193579895dfSAlexander Motin 	period = 1000000 / realstathz;
194579895dfSAlexander Motin 	new_val = period * sched_slice;
195579895dfSAlexander Motin 	error = sysctl_handle_int(oidp, &new_val, 0, req);
196579895dfSAlexander Motin 	if (error != 0 || req->newptr == NULL)
197579895dfSAlexander Motin 		return (error);
198579895dfSAlexander Motin 	if (new_val <= 0)
199579895dfSAlexander Motin 		return (EINVAL);
20037f4e025SAlexander Motin 	sched_slice = imax(1, (new_val + period / 2) / period);
20137f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
20237f4e025SAlexander Motin 	    realstathz);
203579895dfSAlexander Motin 	return (0);
204579895dfSAlexander Motin }
205579895dfSAlexander Motin 
206e038d354SScott Long SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
207dc095794SScott Long 
208e038d354SScott Long SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
209e038d354SScott Long     "Scheduler name");
210579895dfSAlexander Motin SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
211579895dfSAlexander Motin     NULL, 0, sysctl_kern_quantum, "I",
21237f4e025SAlexander Motin     "Quantum for timeshare threads in microseconds");
21348317e9eSAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
21437f4e025SAlexander Motin     "Quantum for timeshare threads in stathz ticks");
21537c28a02SJulian Elischer #ifdef SMP
21682a1dfc1SJulian Elischer /* Enable forwarding of wakeups to all other cpus */
2176472ac3dSEd Schouten static SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL,
2186472ac3dSEd Schouten     "Kernel SMP");
21982a1dfc1SJulian Elischer 
220a90f3f25SJeff Roberson static int runq_fuzz = 1;
221a90f3f25SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
222a90f3f25SJeff Roberson 
223bce73aedSJulian Elischer static int forward_wakeup_enabled = 1;
22482a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
22582a1dfc1SJulian Elischer 	   &forward_wakeup_enabled, 0,
22682a1dfc1SJulian Elischer 	   "Forwarding of wakeup to idle CPUs");
22782a1dfc1SJulian Elischer 
22882a1dfc1SJulian Elischer static int forward_wakeups_requested = 0;
22982a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
23082a1dfc1SJulian Elischer 	   &forward_wakeups_requested, 0,
23182a1dfc1SJulian Elischer 	   "Requests for Forwarding of wakeup to idle CPUs");
23282a1dfc1SJulian Elischer 
23382a1dfc1SJulian Elischer static int forward_wakeups_delivered = 0;
23482a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
23582a1dfc1SJulian Elischer 	   &forward_wakeups_delivered, 0,
23682a1dfc1SJulian Elischer 	   "Completed Forwarding of wakeup to idle CPUs");
23782a1dfc1SJulian Elischer 
238bce73aedSJulian Elischer static int forward_wakeup_use_mask = 1;
23982a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
24082a1dfc1SJulian Elischer 	   &forward_wakeup_use_mask, 0,
24182a1dfc1SJulian Elischer 	   "Use the mask of idle cpus");
24282a1dfc1SJulian Elischer 
24382a1dfc1SJulian Elischer static int forward_wakeup_use_loop = 0;
24482a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
24582a1dfc1SJulian Elischer 	   &forward_wakeup_use_loop, 0,
24682a1dfc1SJulian Elischer 	   "Use a loop to find idle cpus");
24782a1dfc1SJulian Elischer 
24837c28a02SJulian Elischer #endif
249ad1e7d28SJulian Elischer #if 0
2503389af30SJulian Elischer static int sched_followon = 0;
2513389af30SJulian Elischer SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
2523389af30SJulian Elischer 	   &sched_followon, 0,
2533389af30SJulian Elischer 	   "allow threads to share a quantum");
2548460a577SJohn Birrell #endif
25582a1dfc1SJulian Elischer 
256b3e9e682SRyan Stone SDT_PROVIDER_DEFINE(sched);
257b3e9e682SRyan Stone 
258b3e9e682SRyan Stone SDT_PROBE_DEFINE3(sched, , , change_pri, change-pri, "struct thread *",
259b3e9e682SRyan Stone     "struct proc *", "uint8_t");
260b3e9e682SRyan Stone SDT_PROBE_DEFINE3(sched, , , dequeue, dequeue, "struct thread *",
261b3e9e682SRyan Stone     "struct proc *", "void *");
262b3e9e682SRyan Stone SDT_PROBE_DEFINE4(sched, , , enqueue, enqueue, "struct thread *",
263b3e9e682SRyan Stone     "struct proc *", "void *", "int");
264b3e9e682SRyan Stone SDT_PROBE_DEFINE4(sched, , , lend_pri, lend-pri, "struct thread *",
265b3e9e682SRyan Stone     "struct proc *", "uint8_t", "struct thread *");
266b3e9e682SRyan Stone SDT_PROBE_DEFINE2(sched, , , load_change, load-change, "int", "int");
267b3e9e682SRyan Stone SDT_PROBE_DEFINE2(sched, , , off_cpu, off-cpu, "struct thread *",
268b3e9e682SRyan Stone     "struct proc *");
269b3e9e682SRyan Stone SDT_PROBE_DEFINE(sched, , , on_cpu, on-cpu);
270b3e9e682SRyan Stone SDT_PROBE_DEFINE(sched, , , remain_cpu, remain-cpu);
271b3e9e682SRyan Stone SDT_PROBE_DEFINE2(sched, , , surrender, surrender, "struct thread *",
272b3e9e682SRyan Stone     "struct proc *");
273b3e9e682SRyan Stone 
274907bdbc2SJeff Roberson static __inline void
275907bdbc2SJeff Roberson sched_load_add(void)
276907bdbc2SJeff Roberson {
2778f51ad55SJeff Roberson 
278907bdbc2SJeff Roberson 	sched_tdcnt++;
2798f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
280b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , load_change, NOCPU, sched_tdcnt);
281907bdbc2SJeff Roberson }
282907bdbc2SJeff Roberson 
283907bdbc2SJeff Roberson static __inline void
284907bdbc2SJeff Roberson sched_load_rem(void)
285907bdbc2SJeff Roberson {
2868f51ad55SJeff Roberson 
287907bdbc2SJeff Roberson 	sched_tdcnt--;
2888f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
289b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , load_change, NOCPU, sched_tdcnt);
290907bdbc2SJeff Roberson }
291b43179fbSJeff Roberson /*
292b43179fbSJeff Roberson  * Arrange to reschedule if necessary, taking the priorities and
293b43179fbSJeff Roberson  * schedulers into account.
294b43179fbSJeff Roberson  */
295b43179fbSJeff Roberson static void
296b43179fbSJeff Roberson maybe_resched(struct thread *td)
297b43179fbSJeff Roberson {
298b43179fbSJeff Roberson 
2997b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
300ed062c8dSJulian Elischer 	if (td->td_priority < curthread->td_priority)
3014a338afdSJulian Elischer 		curthread->td_flags |= TDF_NEEDRESCHED;
302b43179fbSJeff Roberson }
303b43179fbSJeff Roberson 
304b43179fbSJeff Roberson /*
305a90f3f25SJeff Roberson  * This function is called when a thread is about to be put on run queue
306a90f3f25SJeff Roberson  * because it has been made runnable or its priority has been adjusted.  It
307a90f3f25SJeff Roberson  * determines if the new thread should be immediately preempted to.  If so,
308a90f3f25SJeff Roberson  * it switches to it and eventually returns true.  If not, it returns false
309a90f3f25SJeff Roberson  * so that the caller may place the thread on an appropriate run queue.
310a90f3f25SJeff Roberson  */
311a90f3f25SJeff Roberson int
312a90f3f25SJeff Roberson maybe_preempt(struct thread *td)
313a90f3f25SJeff Roberson {
314a90f3f25SJeff Roberson #ifdef PREEMPTION
315a90f3f25SJeff Roberson 	struct thread *ctd;
316a90f3f25SJeff Roberson 	int cpri, pri;
317a90f3f25SJeff Roberson 
318a90f3f25SJeff Roberson 	/*
319a90f3f25SJeff Roberson 	 * The new thread should not preempt the current thread if any of the
320a90f3f25SJeff Roberson 	 * following conditions are true:
321a90f3f25SJeff Roberson 	 *
322a90f3f25SJeff Roberson 	 *  - The kernel is in the throes of crashing (panicstr).
323a90f3f25SJeff Roberson 	 *  - The current thread has a higher (numerically lower) or
324a90f3f25SJeff Roberson 	 *    equivalent priority.  Note that this prevents curthread from
325a90f3f25SJeff Roberson 	 *    trying to preempt to itself.
326a90f3f25SJeff Roberson 	 *  - It is too early in the boot for context switches (cold is set).
327a90f3f25SJeff Roberson 	 *  - The current thread has an inhibitor set or is in the process of
328a90f3f25SJeff Roberson 	 *    exiting.  In this case, the current thread is about to switch
329a90f3f25SJeff Roberson 	 *    out anyways, so there's no point in preempting.  If we did,
330a90f3f25SJeff Roberson 	 *    the current thread would not be properly resumed as well, so
331a90f3f25SJeff Roberson 	 *    just avoid that whole landmine.
332a90f3f25SJeff Roberson 	 *  - If the new thread's priority is not a realtime priority and
333a90f3f25SJeff Roberson 	 *    the current thread's priority is not an idle priority and
334a90f3f25SJeff Roberson 	 *    FULL_PREEMPTION is disabled.
335a90f3f25SJeff Roberson 	 *
336a90f3f25SJeff Roberson 	 * If all of these conditions are false, but the current thread is in
337a90f3f25SJeff Roberson 	 * a nested critical section, then we have to defer the preemption
338a90f3f25SJeff Roberson 	 * until we exit the critical section.  Otherwise, switch immediately
339a90f3f25SJeff Roberson 	 * to the new thread.
340a90f3f25SJeff Roberson 	 */
341a90f3f25SJeff Roberson 	ctd = curthread;
342a90f3f25SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
343a90f3f25SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
344a90f3f25SJeff Roberson 			("maybe_preempt: trying to run inhibited thread"));
345a90f3f25SJeff Roberson 	pri = td->td_priority;
346a90f3f25SJeff Roberson 	cpri = ctd->td_priority;
347a90f3f25SJeff Roberson 	if (panicstr != NULL || pri >= cpri || cold /* || dumping */ ||
348a90f3f25SJeff Roberson 	    TD_IS_INHIBITED(ctd))
349a90f3f25SJeff Roberson 		return (0);
350a90f3f25SJeff Roberson #ifndef FULL_PREEMPTION
351a90f3f25SJeff Roberson 	if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
352a90f3f25SJeff Roberson 		return (0);
353a90f3f25SJeff Roberson #endif
354a90f3f25SJeff Roberson 
355a90f3f25SJeff Roberson 	if (ctd->td_critnest > 1) {
356a90f3f25SJeff Roberson 		CTR1(KTR_PROC, "maybe_preempt: in critical section %d",
357a90f3f25SJeff Roberson 		    ctd->td_critnest);
358a90f3f25SJeff Roberson 		ctd->td_owepreempt = 1;
359a90f3f25SJeff Roberson 		return (0);
360a90f3f25SJeff Roberson 	}
361a90f3f25SJeff Roberson 	/*
362a90f3f25SJeff Roberson 	 * Thread is runnable but not yet put on system run queue.
363a90f3f25SJeff Roberson 	 */
364a90f3f25SJeff Roberson 	MPASS(ctd->td_lock == td->td_lock);
365a90f3f25SJeff Roberson 	MPASS(TD_ON_RUNQ(td));
366a90f3f25SJeff Roberson 	TD_SET_RUNNING(td);
367a90f3f25SJeff Roberson 	CTR3(KTR_PROC, "preempting to thread %p (pid %d, %s)\n", td,
368a90f3f25SJeff Roberson 	    td->td_proc->p_pid, td->td_name);
3698df78c41SJeff Roberson 	mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, td);
370a90f3f25SJeff Roberson 	/*
371a90f3f25SJeff Roberson 	 * td's lock pointer may have changed.  We have to return with it
372a90f3f25SJeff Roberson 	 * locked.
373a90f3f25SJeff Roberson 	 */
374a90f3f25SJeff Roberson 	spinlock_enter();
375a90f3f25SJeff Roberson 	thread_unlock(ctd);
376a90f3f25SJeff Roberson 	thread_lock(td);
377a90f3f25SJeff Roberson 	spinlock_exit();
378a90f3f25SJeff Roberson 	return (1);
379a90f3f25SJeff Roberson #else
380a90f3f25SJeff Roberson 	return (0);
381a90f3f25SJeff Roberson #endif
382a90f3f25SJeff Roberson }
383a90f3f25SJeff Roberson 
384a90f3f25SJeff Roberson /*
385b43179fbSJeff Roberson  * Constants for digital decay and forget:
3868460a577SJohn Birrell  *	90% of (td_estcpu) usage in 5 * loadav time
387ad1e7d28SJulian Elischer  *	95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
388b43179fbSJeff Roberson  *          Note that, as ps(1) mentions, this can let percentages
389b43179fbSJeff Roberson  *          total over 100% (I've seen 137.9% for 3 processes).
390b43179fbSJeff Roberson  *
3918460a577SJohn Birrell  * Note that schedclock() updates td_estcpu and p_cpticks asynchronously.
392b43179fbSJeff Roberson  *
3938460a577SJohn Birrell  * We wish to decay away 90% of td_estcpu in (5 * loadavg) seconds.
394b43179fbSJeff Roberson  * That is, the system wants to compute a value of decay such
395b43179fbSJeff Roberson  * that the following for loop:
396b43179fbSJeff Roberson  * 	for (i = 0; i < (5 * loadavg); i++)
3978460a577SJohn Birrell  * 		td_estcpu *= decay;
398b43179fbSJeff Roberson  * will compute
3998460a577SJohn Birrell  * 	td_estcpu *= 0.1;
400b43179fbSJeff Roberson  * for all values of loadavg:
401b43179fbSJeff Roberson  *
402b43179fbSJeff Roberson  * Mathematically this loop can be expressed by saying:
403b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
404b43179fbSJeff Roberson  *
405b43179fbSJeff Roberson  * The system computes decay as:
406b43179fbSJeff Roberson  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
407b43179fbSJeff Roberson  *
408b43179fbSJeff Roberson  * We wish to prove that the system's computation of decay
409b43179fbSJeff Roberson  * will always fulfill the equation:
410b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
411b43179fbSJeff Roberson  *
412b43179fbSJeff Roberson  * If we compute b as:
413b43179fbSJeff Roberson  * 	b = 2 * loadavg
414b43179fbSJeff Roberson  * then
415b43179fbSJeff Roberson  * 	decay = b / (b + 1)
416b43179fbSJeff Roberson  *
417b43179fbSJeff Roberson  * We now need to prove two things:
418b43179fbSJeff Roberson  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
419b43179fbSJeff Roberson  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
420b43179fbSJeff Roberson  *
421b43179fbSJeff Roberson  * Facts:
422b43179fbSJeff Roberson  *         For x close to zero, exp(x) =~ 1 + x, since
423b43179fbSJeff Roberson  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
424b43179fbSJeff Roberson  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
425b43179fbSJeff Roberson  *         For x close to zero, ln(1+x) =~ x, since
426b43179fbSJeff Roberson  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
427b43179fbSJeff Roberson  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
428b43179fbSJeff Roberson  *         ln(.1) =~ -2.30
429b43179fbSJeff Roberson  *
430b43179fbSJeff Roberson  * Proof of (1):
431b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
432b43179fbSJeff Roberson  *	solving for factor,
433b43179fbSJeff Roberson  *      ln(factor) =~ (-2.30/5*loadav), or
434b43179fbSJeff Roberson  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
435b43179fbSJeff Roberson  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
436b43179fbSJeff Roberson  *
437b43179fbSJeff Roberson  * Proof of (2):
438b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
439b43179fbSJeff Roberson  *	solving for power,
440b43179fbSJeff Roberson  *      power*ln(b/(b+1)) =~ -2.30, or
441b43179fbSJeff Roberson  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
442b43179fbSJeff Roberson  *
443b43179fbSJeff Roberson  * Actual power values for the implemented algorithm are as follows:
444b43179fbSJeff Roberson  *      loadav: 1       2       3       4
445b43179fbSJeff Roberson  *      power:  5.68    10.32   14.94   19.55
446b43179fbSJeff Roberson  */
447b43179fbSJeff Roberson 
448b43179fbSJeff Roberson /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
449b43179fbSJeff Roberson #define	loadfactor(loadav)	(2 * (loadav))
450b43179fbSJeff Roberson #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
451b43179fbSJeff Roberson 
452ad1e7d28SJulian Elischer /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
453b43179fbSJeff Roberson static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
45452c0b557SMatthew D Fleming SYSCTL_UINT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
455b43179fbSJeff Roberson 
456b43179fbSJeff Roberson /*
457b43179fbSJeff Roberson  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
458b43179fbSJeff Roberson  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
459b43179fbSJeff Roberson  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
460b43179fbSJeff Roberson  *
461b43179fbSJeff Roberson  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
462b43179fbSJeff Roberson  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
463b43179fbSJeff Roberson  *
464b43179fbSJeff Roberson  * If you don't want to bother with the faster/more-accurate formula, you
465b43179fbSJeff Roberson  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
466b43179fbSJeff Roberson  * (more general) method of calculating the %age of CPU used by a process.
467b43179fbSJeff Roberson  */
468b43179fbSJeff Roberson #define	CCPU_SHIFT	11
469b43179fbSJeff Roberson 
470b43179fbSJeff Roberson /*
471b43179fbSJeff Roberson  * Recompute process priorities, every hz ticks.
472b43179fbSJeff Roberson  * MP-safe, called without the Giant mutex.
473b43179fbSJeff Roberson  */
474b43179fbSJeff Roberson /* ARGSUSED */
475b43179fbSJeff Roberson static void
476c55bbb6cSJohn Baldwin schedcpu(void)
477b43179fbSJeff Roberson {
478b43179fbSJeff Roberson 	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
479b43179fbSJeff Roberson 	struct thread *td;
480b43179fbSJeff Roberson 	struct proc *p;
481ad1e7d28SJulian Elischer 	struct td_sched *ts;
48248317e9eSAlexander Motin 	int awake;
483b43179fbSJeff Roberson 
484b43179fbSJeff Roberson 	sx_slock(&allproc_lock);
485b43179fbSJeff Roberson 	FOREACH_PROC_IN_SYSTEM(p) {
486374ae2a3SJeff Roberson 		PROC_LOCK(p);
487e806d352SJohn Baldwin 		if (p->p_state == PRS_NEW) {
488e806d352SJohn Baldwin 			PROC_UNLOCK(p);
489e806d352SJohn Baldwin 			continue;
490e806d352SJohn Baldwin 		}
4918460a577SJohn Birrell 		FOREACH_THREAD_IN_PROC(p, td) {
492b43179fbSJeff Roberson 			awake = 0;
4937b20fb19SJeff Roberson 			thread_lock(td);
494ad1e7d28SJulian Elischer 			ts = td->td_sched;
495b43179fbSJeff Roberson 			/*
49670fca427SJohn Baldwin 			 * Increment sleep time (if sleeping).  We
49770fca427SJohn Baldwin 			 * ignore overflow, as above.
498b43179fbSJeff Roberson 			 */
499b43179fbSJeff Roberson 			/*
500ad1e7d28SJulian Elischer 			 * The td_sched slptimes are not touched in wakeup
501ad1e7d28SJulian Elischer 			 * because the thread may not HAVE everything in
502ad1e7d28SJulian Elischer 			 * memory? XXX I think this is out of date.
503b43179fbSJeff Roberson 			 */
504f0393f06SJeff Roberson 			if (TD_ON_RUNQ(td)) {
505b43179fbSJeff Roberson 				awake = 1;
5069727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
507f0393f06SJeff Roberson 			} else if (TD_IS_RUNNING(td)) {
508b43179fbSJeff Roberson 				awake = 1;
5099727e637SJeff Roberson 				/* Do not clear TDF_DIDRUN */
5109727e637SJeff Roberson 			} else if (td->td_flags & TDF_DIDRUN) {
511b43179fbSJeff Roberson 				awake = 1;
5129727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
513b43179fbSJeff Roberson 			}
514b43179fbSJeff Roberson 
515b43179fbSJeff Roberson 			/*
516ad1e7d28SJulian Elischer 			 * ts_pctcpu is only for ps and ttyinfo().
517b43179fbSJeff Roberson 			 */
518ad1e7d28SJulian Elischer 			ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
519b43179fbSJeff Roberson 			/*
520ad1e7d28SJulian Elischer 			 * If the td_sched has been idle the entire second,
521b43179fbSJeff Roberson 			 * stop recalculating its priority until
522b43179fbSJeff Roberson 			 * it wakes up.
523b43179fbSJeff Roberson 			 */
524ad1e7d28SJulian Elischer 			if (ts->ts_cpticks != 0) {
525b43179fbSJeff Roberson #if	(FSHIFT >= CCPU_SHIFT)
526ad1e7d28SJulian Elischer 				ts->ts_pctcpu += (realstathz == 100)
527ad1e7d28SJulian Elischer 				    ? ((fixpt_t) ts->ts_cpticks) <<
528b43179fbSJeff Roberson 				    (FSHIFT - CCPU_SHIFT) :
529ad1e7d28SJulian Elischer 				    100 * (((fixpt_t) ts->ts_cpticks)
530bcb06d59SJeff Roberson 				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
531b43179fbSJeff Roberson #else
532ad1e7d28SJulian Elischer 				ts->ts_pctcpu += ((FSCALE - ccpu) *
533ad1e7d28SJulian Elischer 				    (ts->ts_cpticks *
534bcb06d59SJeff Roberson 				    FSCALE / realstathz)) >> FSHIFT;
535b43179fbSJeff Roberson #endif
536ad1e7d28SJulian Elischer 				ts->ts_cpticks = 0;
5378460a577SJohn Birrell 			}
5388460a577SJohn Birrell 			/*
5398460a577SJohn Birrell 			 * If there are ANY running threads in this process,
540b43179fbSJeff Roberson 			 * then don't count it as sleeping.
5418aa3d7ffSJohn Baldwin 			 * XXX: this is broken.
542b43179fbSJeff Roberson 			 */
543b43179fbSJeff Roberson 			if (awake) {
54454b0e65fSJeff Roberson 				if (ts->ts_slptime > 1) {
545b43179fbSJeff Roberson 					/*
546b43179fbSJeff Roberson 					 * In an ideal world, this should not
547b43179fbSJeff Roberson 					 * happen, because whoever woke us
548b43179fbSJeff Roberson 					 * up from the long sleep should have
549b43179fbSJeff Roberson 					 * unwound the slptime and reset our
550b43179fbSJeff Roberson 					 * priority before we run at the stale
551b43179fbSJeff Roberson 					 * priority.  Should KASSERT at some
552b43179fbSJeff Roberson 					 * point when all the cases are fixed.
553b43179fbSJeff Roberson 					 */
5548460a577SJohn Birrell 					updatepri(td);
5558460a577SJohn Birrell 				}
55654b0e65fSJeff Roberson 				ts->ts_slptime = 0;
5578460a577SJohn Birrell 			} else
55854b0e65fSJeff Roberson 				ts->ts_slptime++;
55954b0e65fSJeff Roberson 			if (ts->ts_slptime > 1) {
5607b20fb19SJeff Roberson 				thread_unlock(td);
5618460a577SJohn Birrell 				continue;
5627b20fb19SJeff Roberson 			}
5638460a577SJohn Birrell 			td->td_estcpu = decay_cpu(loadfac, td->td_estcpu);
5648460a577SJohn Birrell 		      	resetpriority(td);
5658460a577SJohn Birrell 			resetpriority_thread(td);
5667b20fb19SJeff Roberson 			thread_unlock(td);
5678aa3d7ffSJohn Baldwin 		}
568374ae2a3SJeff Roberson 		PROC_UNLOCK(p);
5698aa3d7ffSJohn Baldwin 	}
570b43179fbSJeff Roberson 	sx_sunlock(&allproc_lock);
571c55bbb6cSJohn Baldwin }
572c55bbb6cSJohn Baldwin 
573c55bbb6cSJohn Baldwin /*
574c55bbb6cSJohn Baldwin  * Main loop for a kthread that executes schedcpu once a second.
575c55bbb6cSJohn Baldwin  */
576c55bbb6cSJohn Baldwin static void
577e17c57b1SJeff Roberson schedcpu_thread(void)
578c55bbb6cSJohn Baldwin {
579c55bbb6cSJohn Baldwin 
580c55bbb6cSJohn Baldwin 	for (;;) {
581c55bbb6cSJohn Baldwin 		schedcpu();
5824d70511aSJohn Baldwin 		pause("-", hz);
583c55bbb6cSJohn Baldwin 	}
584b43179fbSJeff Roberson }
585b43179fbSJeff Roberson 
586b43179fbSJeff Roberson /*
587b43179fbSJeff Roberson  * Recalculate the priority of a process after it has slept for a while.
5888460a577SJohn Birrell  * For all load averages >= 1 and max td_estcpu of 255, sleeping for at
5898460a577SJohn Birrell  * least six times the loadfactor will decay td_estcpu to zero.
590b43179fbSJeff Roberson  */
591b43179fbSJeff Roberson static void
5928460a577SJohn Birrell updatepri(struct thread *td)
593b43179fbSJeff Roberson {
59454b0e65fSJeff Roberson 	struct td_sched *ts;
59554b0e65fSJeff Roberson 	fixpt_t loadfac;
59654b0e65fSJeff Roberson 	unsigned int newcpu;
597b43179fbSJeff Roberson 
59854b0e65fSJeff Roberson 	ts = td->td_sched;
59970fca427SJohn Baldwin 	loadfac = loadfactor(averunnable.ldavg[0]);
60054b0e65fSJeff Roberson 	if (ts->ts_slptime > 5 * loadfac)
6018460a577SJohn Birrell 		td->td_estcpu = 0;
602b43179fbSJeff Roberson 	else {
6038460a577SJohn Birrell 		newcpu = td->td_estcpu;
60454b0e65fSJeff Roberson 		ts->ts_slptime--;	/* was incremented in schedcpu() */
60554b0e65fSJeff Roberson 		while (newcpu && --ts->ts_slptime)
606b43179fbSJeff Roberson 			newcpu = decay_cpu(loadfac, newcpu);
6078460a577SJohn Birrell 		td->td_estcpu = newcpu;
608b43179fbSJeff Roberson 	}
609b43179fbSJeff Roberson }
610b43179fbSJeff Roberson 
611b43179fbSJeff Roberson /*
612b43179fbSJeff Roberson  * Compute the priority of a process when running in user mode.
613b43179fbSJeff Roberson  * Arrange to reschedule if the resulting priority is better
614b43179fbSJeff Roberson  * than that of the current process.
615b43179fbSJeff Roberson  */
616b43179fbSJeff Roberson static void
6178460a577SJohn Birrell resetpriority(struct thread *td)
618b43179fbSJeff Roberson {
619b43179fbSJeff Roberson 	register unsigned int newpriority;
620b43179fbSJeff Roberson 
6218460a577SJohn Birrell 	if (td->td_pri_class == PRI_TIMESHARE) {
6228460a577SJohn Birrell 		newpriority = PUSER + td->td_estcpu / INVERSE_ESTCPU_WEIGHT +
6238460a577SJohn Birrell 		    NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
624b43179fbSJeff Roberson 		newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
625b43179fbSJeff Roberson 		    PRI_MAX_TIMESHARE);
6268460a577SJohn Birrell 		sched_user_prio(td, newpriority);
627b43179fbSJeff Roberson 	}
628b43179fbSJeff Roberson }
629f5c157d9SJohn Baldwin 
630f5c157d9SJohn Baldwin /*
631ad1e7d28SJulian Elischer  * Update the thread's priority when the associated process's user
632f5c157d9SJohn Baldwin  * priority changes.
633f5c157d9SJohn Baldwin  */
634f5c157d9SJohn Baldwin static void
6358460a577SJohn Birrell resetpriority_thread(struct thread *td)
636f5c157d9SJohn Baldwin {
637f5c157d9SJohn Baldwin 
638f5c157d9SJohn Baldwin 	/* Only change threads with a time sharing user priority. */
639f5c157d9SJohn Baldwin 	if (td->td_priority < PRI_MIN_TIMESHARE ||
640f5c157d9SJohn Baldwin 	    td->td_priority > PRI_MAX_TIMESHARE)
641f5c157d9SJohn Baldwin 		return;
642f5c157d9SJohn Baldwin 
643f5c157d9SJohn Baldwin 	/* XXX the whole needresched thing is broken, but not silly. */
644f5c157d9SJohn Baldwin 	maybe_resched(td);
645f5c157d9SJohn Baldwin 
6468460a577SJohn Birrell 	sched_prio(td, td->td_user_pri);
647b43179fbSJeff Roberson }
648b43179fbSJeff Roberson 
649b43179fbSJeff Roberson /* ARGSUSED */
650b43179fbSJeff Roberson static void
651b43179fbSJeff Roberson sched_setup(void *dummy)
652b43179fbSJeff Roberson {
65370fca427SJohn Baldwin 
654579895dfSAlexander Motin 	setup_runqs();
655b43179fbSJeff Roberson 
656ca59f152SJeff Roberson 	/* Account for thread0. */
657907bdbc2SJeff Roberson 	sched_load_add();
658b43179fbSJeff Roberson }
659b43179fbSJeff Roberson 
66048317e9eSAlexander Motin /*
661579895dfSAlexander Motin  * This routine determines time constants after stathz and hz are setup.
66248317e9eSAlexander Motin  */
66348317e9eSAlexander Motin static void
66448317e9eSAlexander Motin sched_initticks(void *dummy)
66548317e9eSAlexander Motin {
66648317e9eSAlexander Motin 
66748317e9eSAlexander Motin 	realstathz = stathz ? stathz : hz;
66848317e9eSAlexander Motin 	sched_slice = realstathz / 10;	/* ~100ms */
66937f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
67037f4e025SAlexander Motin 	    realstathz);
67148317e9eSAlexander Motin }
67248317e9eSAlexander Motin 
673b43179fbSJeff Roberson /* External interfaces start here */
6748aa3d7ffSJohn Baldwin 
675ed062c8dSJulian Elischer /*
676ed062c8dSJulian Elischer  * Very early in the boot some setup of scheduler-specific
677f3050486SMaxim Konovalov  * parts of proc0 and of some scheduler resources needs to be done.
678ed062c8dSJulian Elischer  * Called from:
679ed062c8dSJulian Elischer  *  proc0_init()
680ed062c8dSJulian Elischer  */
681ed062c8dSJulian Elischer void
682ed062c8dSJulian Elischer schedinit(void)
683ed062c8dSJulian Elischer {
684ed062c8dSJulian Elischer 	/*
685ed062c8dSJulian Elischer 	 * Set up the scheduler specific parts of proc0.
686ed062c8dSJulian Elischer 	 */
687ed062c8dSJulian Elischer 	proc0.p_sched = NULL; /* XXX */
688ad1e7d28SJulian Elischer 	thread0.td_sched = &td_sched0;
6897b20fb19SJeff Roberson 	thread0.td_lock = &sched_lock;
69048317e9eSAlexander Motin 	td_sched0.ts_slice = sched_slice;
6916ea38de8SJeff Roberson 	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
692ed062c8dSJulian Elischer }
693ed062c8dSJulian Elischer 
694b43179fbSJeff Roberson int
695b43179fbSJeff Roberson sched_runnable(void)
696b43179fbSJeff Roberson {
697e17c57b1SJeff Roberson #ifdef SMP
698e17c57b1SJeff Roberson 	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
699e17c57b1SJeff Roberson #else
700b43179fbSJeff Roberson 	return runq_check(&runq);
701e17c57b1SJeff Roberson #endif
702b43179fbSJeff Roberson }
703b43179fbSJeff Roberson 
704b43179fbSJeff Roberson int
705b43179fbSJeff Roberson sched_rr_interval(void)
706b43179fbSJeff Roberson {
70748317e9eSAlexander Motin 
70848317e9eSAlexander Motin 	/* Convert sched_slice from stathz to hz. */
70937f4e025SAlexander Motin 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
710b43179fbSJeff Roberson }
711b43179fbSJeff Roberson 
712b43179fbSJeff Roberson /*
713b43179fbSJeff Roberson  * We adjust the priority of the current process.  The priority of
714b43179fbSJeff Roberson  * a process gets worse as it accumulates CPU time.  The cpu usage
7158460a577SJohn Birrell  * estimator (td_estcpu) is increased here.  resetpriority() will
7168460a577SJohn Birrell  * compute a different priority each time td_estcpu increases by
717b43179fbSJeff Roberson  * INVERSE_ESTCPU_WEIGHT
718b43179fbSJeff Roberson  * (until MAXPRI is reached).  The cpu usage estimator ramps up
719b43179fbSJeff Roberson  * quite quickly when the process is running (linearly), and decays
720b43179fbSJeff Roberson  * away exponentially, at a rate which is proportionally slower when
721b43179fbSJeff Roberson  * the system is busy.  The basic principle is that the system will
722b43179fbSJeff Roberson  * 90% forget that the process used a lot of CPU time in 5 * loadav
723b43179fbSJeff Roberson  * seconds.  This causes the system to favor processes which haven't
724b43179fbSJeff Roberson  * run much recently, and to round-robin among other processes.
725b43179fbSJeff Roberson  */
726b43179fbSJeff Roberson void
7277cf90fb3SJeff Roberson sched_clock(struct thread *td)
728b43179fbSJeff Roberson {
729b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
730ad1e7d28SJulian Elischer 	struct td_sched *ts;
731b43179fbSJeff Roberson 
7327b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
733ad1e7d28SJulian Elischer 	ts = td->td_sched;
734f7f9e7f3SJeff Roberson 
735ad1e7d28SJulian Elischer 	ts->ts_cpticks++;
7368460a577SJohn Birrell 	td->td_estcpu = ESTCPULIM(td->td_estcpu + 1);
7378460a577SJohn Birrell 	if ((td->td_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
7388460a577SJohn Birrell 		resetpriority(td);
7398460a577SJohn Birrell 		resetpriority_thread(td);
740b43179fbSJeff Roberson 	}
7419dddab6fSJohn Baldwin 
7429dddab6fSJohn Baldwin 	/*
7439dddab6fSJohn Baldwin 	 * Force a context switch if the current thread has used up a full
744579895dfSAlexander Motin 	 * time slice (default is 100ms).
7459dddab6fSJohn Baldwin 	 */
746579895dfSAlexander Motin 	if (!TD_IS_IDLETHREAD(td) && --ts->ts_slice <= 0) {
74748317e9eSAlexander Motin 		ts->ts_slice = sched_slice;
7483d7f4117SAlexander Motin 		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
74948317e9eSAlexander Motin 	}
750b722ad00SAlexander Motin 
751b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
752b722ad00SAlexander Motin 	stat->oldidlecalls = stat->idlecalls;
753b722ad00SAlexander Motin 	stat->idlecalls = 0;
754b43179fbSJeff Roberson }
75570fca427SJohn Baldwin 
7568460a577SJohn Birrell /*
7578aa3d7ffSJohn Baldwin  * Charge child's scheduling CPU usage to parent.
7588460a577SJohn Birrell  */
759b43179fbSJeff Roberson void
76055d44f79SJulian Elischer sched_exit(struct proc *p, struct thread *td)
761f7f9e7f3SJeff Roberson {
7628460a577SJohn Birrell 
7638f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "proc exit",
764cd39bb09SXin LI 	    "prio:%d", td->td_priority);
7658f51ad55SJeff Roberson 
766374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
767ad1e7d28SJulian Elischer 	sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
768b43179fbSJeff Roberson }
769b43179fbSJeff Roberson 
770b43179fbSJeff Roberson void
771f7f9e7f3SJeff Roberson sched_exit_thread(struct thread *td, struct thread *child)
772b43179fbSJeff Roberson {
773ad1e7d28SJulian Elischer 
7748f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "exit",
775cd39bb09SXin LI 	    "prio:%d", child->td_priority);
7767b20fb19SJeff Roberson 	thread_lock(td);
777ad1e7d28SJulian Elischer 	td->td_estcpu = ESTCPULIM(td->td_estcpu + child->td_estcpu);
7787b20fb19SJeff Roberson 	thread_unlock(td);
7791b9d701fSAttilio Rao 	thread_lock(child);
7801b9d701fSAttilio Rao 	if ((child->td_flags & TDF_NOLOAD) == 0)
781907bdbc2SJeff Roberson 		sched_load_rem();
7821b9d701fSAttilio Rao 	thread_unlock(child);
783f7f9e7f3SJeff Roberson }
784bcb06d59SJeff Roberson 
785f7f9e7f3SJeff Roberson void
786ed062c8dSJulian Elischer sched_fork(struct thread *td, struct thread *childtd)
787f7f9e7f3SJeff Roberson {
788ed062c8dSJulian Elischer 	sched_fork_thread(td, childtd);
789f7f9e7f3SJeff Roberson }
790bcb06d59SJeff Roberson 
791f7f9e7f3SJeff Roberson void
792ed062c8dSJulian Elischer sched_fork_thread(struct thread *td, struct thread *childtd)
793f7f9e7f3SJeff Roberson {
7948b16c208SJeff Roberson 	struct td_sched *ts;
7958b16c208SJeff Roberson 
796ad1e7d28SJulian Elischer 	childtd->td_estcpu = td->td_estcpu;
7977b20fb19SJeff Roberson 	childtd->td_lock = &sched_lock;
798f5a3ef99SMarcel Moolenaar 	childtd->td_cpuset = cpuset_ref(td->td_cpuset);
79922d19207SJohn Baldwin 	childtd->td_priority = childtd->td_base_pri;
8008b16c208SJeff Roberson 	ts = childtd->td_sched;
8018b16c208SJeff Roberson 	bzero(ts, sizeof(*ts));
802f200843bSJohn Baldwin 	ts->ts_flags |= (td->td_sched->ts_flags & TSF_AFFINITY);
80348317e9eSAlexander Motin 	ts->ts_slice = 1;
804b43179fbSJeff Roberson }
805b43179fbSJeff Roberson 
806b43179fbSJeff Roberson void
807fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
808b43179fbSJeff Roberson {
809f5c157d9SJohn Baldwin 	struct thread *td;
8100b5318c8SJohn Baldwin 
811fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
812fa885116SJulian Elischer 	p->p_nice = nice;
8138460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
8147b20fb19SJeff Roberson 		thread_lock(td);
8158460a577SJohn Birrell 		resetpriority(td);
8168460a577SJohn Birrell 		resetpriority_thread(td);
8177b20fb19SJeff Roberson 		thread_unlock(td);
8188460a577SJohn Birrell 	}
819fa885116SJulian Elischer }
820b43179fbSJeff Roberson 
821f7f9e7f3SJeff Roberson void
8228460a577SJohn Birrell sched_class(struct thread *td, int class)
823f7f9e7f3SJeff Roberson {
8247b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
8258460a577SJohn Birrell 	td->td_pri_class = class;
826f7f9e7f3SJeff Roberson }
827f7f9e7f3SJeff Roberson 
8288460a577SJohn Birrell /*
8298460a577SJohn Birrell  * Adjust the priority of a thread.
8308460a577SJohn Birrell  */
831f5c157d9SJohn Baldwin static void
832f5c157d9SJohn Baldwin sched_priority(struct thread *td, u_char prio)
833b43179fbSJeff Roberson {
834b43179fbSJeff Roberson 
8358f51ad55SJeff Roberson 
8368f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
8378f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
8388f51ad55SJeff Roberson 	    sched_tdname(curthread));
839b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , change_pri, td, td->td_proc, prio);
8408f51ad55SJeff Roberson 	if (td != curthread && prio > td->td_priority) {
8418f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
8428f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
8438f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
844b3e9e682SRyan Stone 		SDT_PROBE4(sched, , , lend_pri, td, td->td_proc, prio,
845b3e9e682SRyan Stone 		    curthread);
8468f51ad55SJeff Roberson 	}
8477b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
848f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
849f5c157d9SJohn Baldwin 		return;
8501f955e2dSJulian Elischer 	td->td_priority = prio;
8519727e637SJeff Roberson 	if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
852f0393f06SJeff Roberson 		sched_rem(td);
853f0393f06SJeff Roberson 		sched_add(td, SRQ_BORING);
854b43179fbSJeff Roberson 	}
855b43179fbSJeff Roberson }
856b43179fbSJeff Roberson 
857f5c157d9SJohn Baldwin /*
858f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
859f5c157d9SJohn Baldwin  * priority.
860f5c157d9SJohn Baldwin  */
861f5c157d9SJohn Baldwin void
862f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
863f5c157d9SJohn Baldwin {
864f5c157d9SJohn Baldwin 
865f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
866f5c157d9SJohn Baldwin 	sched_priority(td, prio);
867f5c157d9SJohn Baldwin }
868f5c157d9SJohn Baldwin 
869f5c157d9SJohn Baldwin /*
870f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
871f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
872f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
873f5c157d9SJohn Baldwin  * requests.  If the thread's regulary priority is less
874f5c157d9SJohn Baldwin  * important than prio the thread will keep a priority boost
875f5c157d9SJohn Baldwin  * of prio.
876f5c157d9SJohn Baldwin  */
877f5c157d9SJohn Baldwin void
878f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
879f5c157d9SJohn Baldwin {
880f5c157d9SJohn Baldwin 	u_char base_pri;
881f5c157d9SJohn Baldwin 
882f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
883f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
8848460a577SJohn Birrell 		base_pri = td->td_user_pri;
885f5c157d9SJohn Baldwin 	else
886f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
887f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
888f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
889f5c157d9SJohn Baldwin 		sched_prio(td, base_pri);
890f5c157d9SJohn Baldwin 	} else
891f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
892f5c157d9SJohn Baldwin }
893f5c157d9SJohn Baldwin 
894f5c157d9SJohn Baldwin void
895f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
896f5c157d9SJohn Baldwin {
897f5c157d9SJohn Baldwin 	u_char oldprio;
898f5c157d9SJohn Baldwin 
899f5c157d9SJohn Baldwin 	/* First, update the base priority. */
900f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
901f5c157d9SJohn Baldwin 
902f5c157d9SJohn Baldwin 	/*
903f5c157d9SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't ever
904f5c157d9SJohn Baldwin 	 * lower the priority.
905f5c157d9SJohn Baldwin 	 */
906f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
907f5c157d9SJohn Baldwin 		return;
908f5c157d9SJohn Baldwin 
909f5c157d9SJohn Baldwin 	/* Change the real priority. */
910f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
911f5c157d9SJohn Baldwin 	sched_priority(td, prio);
912f5c157d9SJohn Baldwin 
913f5c157d9SJohn Baldwin 	/*
914f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
915f5c157d9SJohn Baldwin 	 * its state.
916f5c157d9SJohn Baldwin 	 */
917f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
918f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
919f5c157d9SJohn Baldwin }
920f5c157d9SJohn Baldwin 
921b43179fbSJeff Roberson void
9228460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
9233db720fdSDavid Xu {
9243db720fdSDavid Xu 
925435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
9268460a577SJohn Birrell 	td->td_base_user_pri = prio;
927acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
9285a215147SDavid Xu 		return;
9298460a577SJohn Birrell 	td->td_user_pri = prio;
9303db720fdSDavid Xu }
9313db720fdSDavid Xu 
9323db720fdSDavid Xu void
9333db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
9343db720fdSDavid Xu {
9353db720fdSDavid Xu 
936435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
937acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
938c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
939c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
940c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
941c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
942c8e368a9SDavid Xu 		td->td_flags |= TDF_NEEDRESCHED;
943435806d3SDavid Xu }
9443db720fdSDavid Xu 
9453db720fdSDavid Xu void
946c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int pri)
947b43179fbSJeff Roberson {
9482056d0a1SJohn Baldwin 
9497b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
95054b0e65fSJeff Roberson 	td->td_slptick = ticks;
95154b0e65fSJeff Roberson 	td->td_sched->ts_slptime = 0;
9522dc29adbSJohn Baldwin 	if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
953c5aa6b58SJeff Roberson 		sched_prio(td, pri);
95417c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
955c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
956b43179fbSJeff Roberson }
957b43179fbSJeff Roberson 
958b43179fbSJeff Roberson void
9593389af30SJulian Elischer sched_switch(struct thread *td, struct thread *newtd, int flags)
960b43179fbSJeff Roberson {
961b0b9dee5SAttilio Rao 	struct mtx *tmtx;
962ad1e7d28SJulian Elischer 	struct td_sched *ts;
963b43179fbSJeff Roberson 	struct proc *p;
9643d7f4117SAlexander Motin 	int preempted;
965b43179fbSJeff Roberson 
966b0b9dee5SAttilio Rao 	tmtx = NULL;
967ad1e7d28SJulian Elischer 	ts = td->td_sched;
968b43179fbSJeff Roberson 	p = td->td_proc;
969b43179fbSJeff Roberson 
9707b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
9718aa3d7ffSJohn Baldwin 
9727b20fb19SJeff Roberson 	/*
9737b20fb19SJeff Roberson 	 * Switch to the sched lock to fix things up and pick
9747b20fb19SJeff Roberson 	 * a new thread.
975b0b9dee5SAttilio Rao 	 * Block the td_lock in order to avoid breaking the critical path.
9767b20fb19SJeff Roberson 	 */
9777b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
9787b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
979b0b9dee5SAttilio Rao 		tmtx = thread_lock_block(td);
9807b20fb19SJeff Roberson 	}
981b43179fbSJeff Roberson 
9821b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
983907bdbc2SJeff Roberson 		sched_load_rem();
9843389af30SJulian Elischer 
985060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
9863d7f4117SAlexander Motin 	preempted = !(td->td_flags & TDF_SLICEEND);
9873d7f4117SAlexander Motin 	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
98877918643SStephan Uphoff 	td->td_owepreempt = 0;
989ca59f152SJeff Roberson 	td->td_oncpu = NOCPU;
9908aa3d7ffSJohn Baldwin 
991b43179fbSJeff Roberson 	/*
992b43179fbSJeff Roberson 	 * At the last moment, if this thread is still marked RUNNING,
993b43179fbSJeff Roberson 	 * then put it back on the run queue as it has not been suspended
994bf0acc27SJohn Baldwin 	 * or stopped or any thing else similar.  We never put the idle
995bf0acc27SJohn Baldwin 	 * threads on the run queue, however.
996b43179fbSJeff Roberson 	 */
997c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD) {
998bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
999c6226eeaSJulian Elischer #ifdef SMP
1000a38f1f26SAttilio Rao 		CPU_CLR(PCPU_GET(cpuid), &idle_cpus_mask);
1001c6226eeaSJulian Elischer #endif
1002c6226eeaSJulian Elischer 	} else {
1003ed062c8dSJulian Elischer 		if (TD_IS_RUNNING(td)) {
1004ad1e7d28SJulian Elischer 			/* Put us back on the run queue. */
10053d7f4117SAlexander Motin 			sched_add(td, preempted ?
1006c20c691bSJulian Elischer 			    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1007c20c691bSJulian Elischer 			    SRQ_OURSELF|SRQ_YIELDING);
1008ed062c8dSJulian Elischer 		}
1009b43179fbSJeff Roberson 	}
1010c20c691bSJulian Elischer 	if (newtd) {
1011c20c691bSJulian Elischer 		/*
1012c20c691bSJulian Elischer 		 * The thread we are about to run needs to be counted
1013c20c691bSJulian Elischer 		 * as if it had been added to the run queue and selected.
1014c20c691bSJulian Elischer 		 * It came from:
1015c20c691bSJulian Elischer 		 * * A preemption
1016c20c691bSJulian Elischer 		 * * An upcall
1017c20c691bSJulian Elischer 		 * * A followon
1018c20c691bSJulian Elischer 		 */
1019c20c691bSJulian Elischer 		KASSERT((newtd->td_inhibitors == 0),
10202da78e38SRobert Watson 			("trying to run inhibited thread"));
10219727e637SJeff Roberson 		newtd->td_flags |= TDF_DIDRUN;
1022c20c691bSJulian Elischer         	TD_SET_RUNNING(newtd);
10231b9d701fSAttilio Rao 		if ((newtd->td_flags & TDF_NOLOAD) == 0)
1024907bdbc2SJeff Roberson 			sched_load_add();
1025c20c691bSJulian Elischer 	} else {
1026ae53b483SJeff Roberson 		newtd = choosethread();
10277b20fb19SJeff Roberson 		MPASS(newtd->td_lock == &sched_lock);
102858060789SAttilio Rao 	}
1029c20c691bSJulian Elischer 
1030ebccf1e3SJoseph Koshy 	if (td != newtd) {
1031ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1032ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1033ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1034ebccf1e3SJoseph Koshy #endif
1035b3e9e682SRyan Stone 
1036b3e9e682SRyan Stone 		SDT_PROBE2(sched, , , off_cpu, td, td->td_proc);
1037b3e9e682SRyan Stone 
1038c6226eeaSJulian Elischer                 /* I feel sleepy */
1039eea4f254SJeff Roberson 		lock_profile_release_lock(&sched_lock.lock_object);
10406f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
10416f5f25e5SJohn Birrell 		/*
10426f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
10436f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
10446f5f25e5SJohn Birrell 		 * function to call.
10456f5f25e5SJohn Birrell 		 */
10466f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
10476f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
10486f5f25e5SJohn Birrell #endif
10496f5f25e5SJohn Birrell 
1050b0b9dee5SAttilio Rao 		cpu_switch(td, newtd, tmtx != NULL ? tmtx : td->td_lock);
1051eea4f254SJeff Roberson 		lock_profile_obtain_lock_success(&sched_lock.lock_object,
1052eea4f254SJeff Roberson 		    0, 0, __FILE__, __LINE__);
1053c6226eeaSJulian Elischer 		/*
1054c6226eeaSJulian Elischer 		 * Where am I?  What year is it?
1055c6226eeaSJulian Elischer 		 * We are in the same thread that went to sleep above,
10568aa3d7ffSJohn Baldwin 		 * but any amount of time may have passed. All our context
1057c6226eeaSJulian Elischer 		 * will still be available as will local variables.
1058c6226eeaSJulian Elischer 		 * PCPU values however may have changed as we may have
1059c6226eeaSJulian Elischer 		 * changed CPU so don't trust cached values of them.
1060c6226eeaSJulian Elischer 		 * New threads will go to fork_exit() instead of here
1061c6226eeaSJulian Elischer 		 * so if you change things here you may need to change
1062c6226eeaSJulian Elischer 		 * things there too.
10638aa3d7ffSJohn Baldwin 		 *
1064c6226eeaSJulian Elischer 		 * If the thread above was exiting it will never wake
1065c6226eeaSJulian Elischer 		 * up again here, so either it has saved everything it
1066c6226eeaSJulian Elischer 		 * needed to, or the thread_wait() or wait() will
1067c6226eeaSJulian Elischer 		 * need to reap it.
1068c6226eeaSJulian Elischer 		 */
1069b3e9e682SRyan Stone 
1070b3e9e682SRyan Stone 		SDT_PROBE0(sched, , , on_cpu);
1071ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1072ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1073ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1074ebccf1e3SJoseph Koshy #endif
1075b3e9e682SRyan Stone 	} else
1076b3e9e682SRyan Stone 		SDT_PROBE0(sched, , , remain_cpu);
1077ebccf1e3SJoseph Koshy 
1078c6226eeaSJulian Elischer #ifdef SMP
1079c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD)
1080a38f1f26SAttilio Rao 		CPU_SET(PCPU_GET(cpuid), &idle_cpus_mask);
1081c6226eeaSJulian Elischer #endif
1082ae53b483SJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
1083ae53b483SJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
10847b20fb19SJeff Roberson 	MPASS(td->td_lock == &sched_lock);
1085b43179fbSJeff Roberson }
1086b43179fbSJeff Roberson 
1087b43179fbSJeff Roberson void
1088b43179fbSJeff Roberson sched_wakeup(struct thread *td)
1089b43179fbSJeff Roberson {
109054b0e65fSJeff Roberson 	struct td_sched *ts;
109154b0e65fSJeff Roberson 
10927b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
109354b0e65fSJeff Roberson 	ts = td->td_sched;
1094c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
109554b0e65fSJeff Roberson 	if (ts->ts_slptime > 1) {
10968460a577SJohn Birrell 		updatepri(td);
10978460a577SJohn Birrell 		resetpriority(td);
10988460a577SJohn Birrell 	}
10996eac7e57SAttilio Rao 	td->td_slptick = 0;
110054b0e65fSJeff Roberson 	ts->ts_slptime = 0;
110148317e9eSAlexander Motin 	ts->ts_slice = sched_slice;
1102f0393f06SJeff Roberson 	sched_add(td, SRQ_BORING);
1103b43179fbSJeff Roberson }
1104b43179fbSJeff Roberson 
110537c28a02SJulian Elischer #ifdef SMP
110682a1dfc1SJulian Elischer static int
110782a1dfc1SJulian Elischer forward_wakeup(int cpunum)
110882a1dfc1SJulian Elischer {
110982a1dfc1SJulian Elischer 	struct pcpu *pc;
1110a38f1f26SAttilio Rao 	cpuset_t dontuse, map, map2;
1111a38f1f26SAttilio Rao 	u_int id, me;
111271a19bdcSAttilio Rao 	int iscpuset;
111382a1dfc1SJulian Elischer 
111482a1dfc1SJulian Elischer 	mtx_assert(&sched_lock, MA_OWNED);
111582a1dfc1SJulian Elischer 
1116ed062c8dSJulian Elischer 	CTR0(KTR_RUNQ, "forward_wakeup()");
111782a1dfc1SJulian Elischer 
111882a1dfc1SJulian Elischer 	if ((!forward_wakeup_enabled) ||
111982a1dfc1SJulian Elischer 	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
112082a1dfc1SJulian Elischer 		return (0);
112182a1dfc1SJulian Elischer 	if (!smp_started || cold || panicstr)
112282a1dfc1SJulian Elischer 		return (0);
112382a1dfc1SJulian Elischer 
112482a1dfc1SJulian Elischer 	forward_wakeups_requested++;
112582a1dfc1SJulian Elischer 
112682a1dfc1SJulian Elischer 	/*
11278aa3d7ffSJohn Baldwin 	 * Check the idle mask we received against what we calculated
11288aa3d7ffSJohn Baldwin 	 * before in the old version.
112982a1dfc1SJulian Elischer 	 */
1130a38f1f26SAttilio Rao 	me = PCPU_GET(cpuid);
11318aa3d7ffSJohn Baldwin 
11328aa3d7ffSJohn Baldwin 	/* Don't bother if we should be doing it ourself. */
1133a38f1f26SAttilio Rao 	if (CPU_ISSET(me, &idle_cpus_mask) &&
1134a38f1f26SAttilio Rao 	    (cpunum == NOCPU || me == cpunum))
113582a1dfc1SJulian Elischer 		return (0);
113682a1dfc1SJulian Elischer 
1137a38f1f26SAttilio Rao 	CPU_SETOF(me, &dontuse);
113871a19bdcSAttilio Rao 	CPU_OR(&dontuse, &stopped_cpus);
113971a19bdcSAttilio Rao 	CPU_OR(&dontuse, &hlt_cpus_mask);
114071a19bdcSAttilio Rao 	CPU_ZERO(&map2);
114182a1dfc1SJulian Elischer 	if (forward_wakeup_use_loop) {
1142d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1143a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1144a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &dontuse) &&
114582a1dfc1SJulian Elischer 			    pc->pc_curthread == pc->pc_idlethread) {
1146a38f1f26SAttilio Rao 				CPU_SET(id, &map2);
114782a1dfc1SJulian Elischer 			}
114882a1dfc1SJulian Elischer 		}
114982a1dfc1SJulian Elischer 	}
115082a1dfc1SJulian Elischer 
115182a1dfc1SJulian Elischer 	if (forward_wakeup_use_mask) {
115271a19bdcSAttilio Rao 		map = idle_cpus_mask;
115371a19bdcSAttilio Rao 		CPU_NAND(&map, &dontuse);
115482a1dfc1SJulian Elischer 
11558aa3d7ffSJohn Baldwin 		/* If they are both on, compare and use loop if different. */
115682a1dfc1SJulian Elischer 		if (forward_wakeup_use_loop) {
115771a19bdcSAttilio Rao 			if (CPU_CMP(&map, &map2)) {
1158f0283a73SAttilio Rao 				printf("map != map2, loop method preferred\n");
1159f0283a73SAttilio Rao 				map = map2;
116082a1dfc1SJulian Elischer 			}
116182a1dfc1SJulian Elischer 		}
116282a1dfc1SJulian Elischer 	} else {
1163f0283a73SAttilio Rao 		map = map2;
116482a1dfc1SJulian Elischer 	}
11658aa3d7ffSJohn Baldwin 
11668aa3d7ffSJohn Baldwin 	/* If we only allow a specific CPU, then mask off all the others. */
116782a1dfc1SJulian Elischer 	if (cpunum != NOCPU) {
116882a1dfc1SJulian Elischer 		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
116971a19bdcSAttilio Rao 		iscpuset = CPU_ISSET(cpunum, &map);
117071a19bdcSAttilio Rao 		if (iscpuset == 0)
117171a19bdcSAttilio Rao 			CPU_ZERO(&map);
117271a19bdcSAttilio Rao 		else
117371a19bdcSAttilio Rao 			CPU_SETOF(cpunum, &map);
117482a1dfc1SJulian Elischer 	}
117571a19bdcSAttilio Rao 	if (!CPU_EMPTY(&map)) {
117682a1dfc1SJulian Elischer 		forward_wakeups_delivered++;
1177d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1178a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1179a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &map))
1180b722ad00SAlexander Motin 				continue;
1181b722ad00SAlexander Motin 			if (cpu_idle_wakeup(pc->pc_cpuid))
1182a38f1f26SAttilio Rao 				CPU_CLR(id, &map);
1183b722ad00SAlexander Motin 		}
118471a19bdcSAttilio Rao 		if (!CPU_EMPTY(&map))
118582a1dfc1SJulian Elischer 			ipi_selected(map, IPI_AST);
118682a1dfc1SJulian Elischer 		return (1);
118782a1dfc1SJulian Elischer 	}
118882a1dfc1SJulian Elischer 	if (cpunum == NOCPU)
118982a1dfc1SJulian Elischer 		printf("forward_wakeup: Idle processor not found\n");
119082a1dfc1SJulian Elischer 	return (0);
119182a1dfc1SJulian Elischer }
1192f3a0f873SStephan Uphoff 
1193f3a0f873SStephan Uphoff static void
1194f3a0f873SStephan Uphoff kick_other_cpu(int pri, int cpuid)
1195f3a0f873SStephan Uphoff {
11968aa3d7ffSJohn Baldwin 	struct pcpu *pcpu;
11978aa3d7ffSJohn Baldwin 	int cpri;
1198f3a0f873SStephan Uphoff 
11998aa3d7ffSJohn Baldwin 	pcpu = pcpu_find(cpuid);
1200a38f1f26SAttilio Rao 	if (CPU_ISSET(cpuid, &idle_cpus_mask)) {
1201f3a0f873SStephan Uphoff 		forward_wakeups_delivered++;
1202b722ad00SAlexander Motin 		if (!cpu_idle_wakeup(cpuid))
1203d9d8d144SJohn Baldwin 			ipi_cpu(cpuid, IPI_AST);
1204f3a0f873SStephan Uphoff 		return;
1205f3a0f873SStephan Uphoff 	}
1206f3a0f873SStephan Uphoff 
12078aa3d7ffSJohn Baldwin 	cpri = pcpu->pc_curthread->td_priority;
1208f3a0f873SStephan Uphoff 	if (pri >= cpri)
1209f3a0f873SStephan Uphoff 		return;
1210f3a0f873SStephan Uphoff 
1211f3a0f873SStephan Uphoff #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1212f3a0f873SStephan Uphoff #if !defined(FULL_PREEMPTION)
1213f3a0f873SStephan Uphoff 	if (pri <= PRI_MAX_ITHD)
1214f3a0f873SStephan Uphoff #endif /* ! FULL_PREEMPTION */
1215f3a0f873SStephan Uphoff 	{
1216d9d8d144SJohn Baldwin 		ipi_cpu(cpuid, IPI_PREEMPT);
1217f3a0f873SStephan Uphoff 		return;
1218f3a0f873SStephan Uphoff 	}
1219f3a0f873SStephan Uphoff #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1220f3a0f873SStephan Uphoff 
1221f3a0f873SStephan Uphoff 	pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1222d9d8d144SJohn Baldwin 	ipi_cpu(cpuid, IPI_AST);
1223f3a0f873SStephan Uphoff 	return;
1224f3a0f873SStephan Uphoff }
1225f3a0f873SStephan Uphoff #endif /* SMP */
1226f3a0f873SStephan Uphoff 
1227f200843bSJohn Baldwin #ifdef SMP
1228f200843bSJohn Baldwin static int
1229f200843bSJohn Baldwin sched_pickcpu(struct thread *td)
1230f200843bSJohn Baldwin {
1231f200843bSJohn Baldwin 	int best, cpu;
1232f200843bSJohn Baldwin 
1233f200843bSJohn Baldwin 	mtx_assert(&sched_lock, MA_OWNED);
1234f200843bSJohn Baldwin 
1235c3ea3378SJohn Baldwin 	if (THREAD_CAN_SCHED(td, td->td_lastcpu))
1236c3ea3378SJohn Baldwin 		best = td->td_lastcpu;
1237c3ea3378SJohn Baldwin 	else
1238f200843bSJohn Baldwin 		best = NOCPU;
12393aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1240f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu))
1241f200843bSJohn Baldwin 			continue;
1242f200843bSJohn Baldwin 
1243f200843bSJohn Baldwin 		if (best == NOCPU)
1244f200843bSJohn Baldwin 			best = cpu;
1245f200843bSJohn Baldwin 		else if (runq_length[cpu] < runq_length[best])
1246f200843bSJohn Baldwin 			best = cpu;
1247f200843bSJohn Baldwin 	}
1248f200843bSJohn Baldwin 	KASSERT(best != NOCPU, ("no valid CPUs"));
1249f200843bSJohn Baldwin 
1250f200843bSJohn Baldwin 	return (best);
1251f200843bSJohn Baldwin }
1252f200843bSJohn Baldwin #endif
1253f200843bSJohn Baldwin 
1254b43179fbSJeff Roberson void
12552630e4c9SJulian Elischer sched_add(struct thread *td, int flags)
12566804a3abSJulian Elischer #ifdef SMP
1257f3a0f873SStephan Uphoff {
1258a38f1f26SAttilio Rao 	cpuset_t tidlemsk;
1259ad1e7d28SJulian Elischer 	struct td_sched *ts;
1260a38f1f26SAttilio Rao 	u_int cpu, cpuid;
12616804a3abSJulian Elischer 	int forwarded = 0;
1262f3a0f873SStephan Uphoff 	int single_cpu = 0;
12637cf90fb3SJeff Roberson 
1264ad1e7d28SJulian Elischer 	ts = td->td_sched;
12657b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1266f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1267f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1268f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1269f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1270b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1271b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
12728f51ad55SJeff Roberson 
12738f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
12748f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
12758f51ad55SJeff Roberson 	    sched_tdname(curthread));
12768f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
12778f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
1278b3e9e682SRyan Stone 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1279b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
12808f51ad55SJeff Roberson 
12818aa3d7ffSJohn Baldwin 
12827b20fb19SJeff Roberson 	/*
12837b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
12847b20fb19SJeff Roberson 	 * to the scheduler's lock.
12857b20fb19SJeff Roberson 	 */
12867b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
12877b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
12887b20fb19SJeff Roberson 		thread_lock_set(td, &sched_lock);
12897b20fb19SJeff Roberson 	}
1290f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1291f3a0f873SStephan Uphoff 
129260dd73b7SRyan Stone 	/*
129360dd73b7SRyan Stone 	 * If SMP is started and the thread is pinned or otherwise limited to
129460dd73b7SRyan Stone 	 * a specific set of CPUs, queue the thread to a per-CPU run queue.
129560dd73b7SRyan Stone 	 * Otherwise, queue the thread to the global run queue.
129660dd73b7SRyan Stone 	 *
129760dd73b7SRyan Stone 	 * If SMP has not yet been started we must use the global run queue
129860dd73b7SRyan Stone 	 * as per-CPU state may not be initialized yet and we may crash if we
129960dd73b7SRyan Stone 	 * try to access the per-CPU run queues.
130060dd73b7SRyan Stone 	 */
130160dd73b7SRyan Stone 	if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
130260dd73b7SRyan Stone 	    ts->ts_flags & TSF_AFFINITY)) {
130360dd73b7SRyan Stone 		if (td->td_pinned != 0)
1304f3a0f873SStephan Uphoff 			cpu = td->td_lastcpu;
130560dd73b7SRyan Stone 		else if (td->td_flags & TDF_BOUND) {
13068aa3d7ffSJohn Baldwin 			/* Find CPU from bound runq. */
13078aa3d7ffSJohn Baldwin 			KASSERT(SKE_RUNQ_PCPU(ts),
13088aa3d7ffSJohn Baldwin 			    ("sched_add: bound td_sched not on cpu runq"));
1309ad1e7d28SJulian Elischer 			cpu = ts->ts_runq - &runq_pcpu[0];
131060dd73b7SRyan Stone 		} else
1311f200843bSJohn Baldwin 			/* Find a valid CPU for our cpuset */
1312f200843bSJohn Baldwin 			cpu = sched_pickcpu(td);
1313f200843bSJohn Baldwin 		ts->ts_runq = &runq_pcpu[cpu];
1314f200843bSJohn Baldwin 		single_cpu = 1;
1315f200843bSJohn Baldwin 		CTR3(KTR_RUNQ,
1316f200843bSJohn Baldwin 		    "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1317f200843bSJohn Baldwin 		    cpu);
1318f3a0f873SStephan Uphoff 	} else {
13196804a3abSJulian Elischer 		CTR2(KTR_RUNQ,
13208aa3d7ffSJohn Baldwin 		    "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
13218aa3d7ffSJohn Baldwin 		    td);
13226804a3abSJulian Elischer 		cpu = NOCPU;
1323ad1e7d28SJulian Elischer 		ts->ts_runq = &runq;
1324e17c57b1SJeff Roberson 	}
1325f3a0f873SStephan Uphoff 
1326a38f1f26SAttilio Rao 	cpuid = PCPU_GET(cpuid);
1327a38f1f26SAttilio Rao 	if (single_cpu && cpu != cpuid) {
1328f3a0f873SStephan Uphoff 	        kick_other_cpu(td->td_priority, cpu);
1329f3a0f873SStephan Uphoff 	} else {
1330f3a0f873SStephan Uphoff 		if (!single_cpu) {
1331a38f1f26SAttilio Rao 			tidlemsk = idle_cpus_mask;
1332a38f1f26SAttilio Rao 			CPU_NAND(&tidlemsk, &hlt_cpus_mask);
1333a38f1f26SAttilio Rao 			CPU_CLR(cpuid, &tidlemsk);
1334f3a0f873SStephan Uphoff 
1335a38f1f26SAttilio Rao 			if (!CPU_ISSET(cpuid, &idle_cpus_mask) &&
1336a38f1f26SAttilio Rao 			    ((flags & SRQ_INTR) == 0) &&
133771a19bdcSAttilio Rao 			    !CPU_EMPTY(&tidlemsk))
1338f3a0f873SStephan Uphoff 				forwarded = forward_wakeup(cpu);
1339f3a0f873SStephan Uphoff 		}
1340f3a0f873SStephan Uphoff 
1341f3a0f873SStephan Uphoff 		if (!forwarded) {
1342a3f2d842SStephan Uphoff 			if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1343f3a0f873SStephan Uphoff 				return;
1344f3a0f873SStephan Uphoff 			else
1345f3a0f873SStephan Uphoff 				maybe_resched(td);
1346f3a0f873SStephan Uphoff 		}
1347f3a0f873SStephan Uphoff 	}
1348f3a0f873SStephan Uphoff 
13491b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1350f3a0f873SStephan Uphoff 		sched_load_add();
13519727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
1352f200843bSJohn Baldwin 	if (cpu != NOCPU)
1353f200843bSJohn Baldwin 		runq_length[cpu]++;
1354f3a0f873SStephan Uphoff }
1355f3a0f873SStephan Uphoff #else /* SMP */
1356f3a0f873SStephan Uphoff {
1357ad1e7d28SJulian Elischer 	struct td_sched *ts;
1358f200843bSJohn Baldwin 
1359ad1e7d28SJulian Elischer 	ts = td->td_sched;
13607b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1361f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1362f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1363f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1364f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1365b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1366b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
13678f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
13688f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
13698f51ad55SJeff Roberson 	    sched_tdname(curthread));
13708f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
13718f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
13722aaae99dSSergey Kandaurov 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1373b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
13748aa3d7ffSJohn Baldwin 
13757b20fb19SJeff Roberson 	/*
13767b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
13777b20fb19SJeff Roberson 	 * to the scheduler's lock.
13787b20fb19SJeff Roberson 	 */
13797b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
13807b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
13817b20fb19SJeff Roberson 		thread_lock_set(td, &sched_lock);
13827b20fb19SJeff Roberson 	}
1383f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1384ad1e7d28SJulian Elischer 	CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1385ad1e7d28SJulian Elischer 	ts->ts_runq = &runq;
13866804a3abSJulian Elischer 
13876804a3abSJulian Elischer 	/*
13888aa3d7ffSJohn Baldwin 	 * If we are yielding (on the way out anyhow) or the thread
13898aa3d7ffSJohn Baldwin 	 * being saved is US, then don't try be smart about preemption
13908aa3d7ffSJohn Baldwin 	 * or kicking off another CPU as it won't help and may hinder.
13918aa3d7ffSJohn Baldwin 	 * In the YIEDLING case, we are about to run whoever is being
13928aa3d7ffSJohn Baldwin 	 * put in the queue anyhow, and in the OURSELF case, we are
13938aa3d7ffSJohn Baldwin 	 * puting ourself on the run queue which also only happens
13948aa3d7ffSJohn Baldwin 	 * when we are about to yield.
13956804a3abSJulian Elischer 	 */
13966804a3abSJulian Elischer 	if ((flags & SRQ_YIELDING) == 0) {
13976804a3abSJulian Elischer 		if (maybe_preempt(td))
13986804a3abSJulian Elischer 			return;
13996804a3abSJulian Elischer 	}
14001b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1401907bdbc2SJeff Roberson 		sched_load_add();
14029727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
14036942d433SJohn Baldwin 	maybe_resched(td);
1404b43179fbSJeff Roberson }
1405f3a0f873SStephan Uphoff #endif /* SMP */
1406f3a0f873SStephan Uphoff 
1407b43179fbSJeff Roberson void
14087cf90fb3SJeff Roberson sched_rem(struct thread *td)
1409b43179fbSJeff Roberson {
1410ad1e7d28SJulian Elischer 	struct td_sched *ts;
14117cf90fb3SJeff Roberson 
1412ad1e7d28SJulian Elischer 	ts = td->td_sched;
1413b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1414b61ce5b0SJeff Roberson 	    ("sched_rem: thread swapped out"));
1415f0393f06SJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
1416ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
1417b43179fbSJeff Roberson 	mtx_assert(&sched_lock, MA_OWNED);
14188f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
14198f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
14208f51ad55SJeff Roberson 	    sched_tdname(curthread));
1421b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
1422b43179fbSJeff Roberson 
14231b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1424907bdbc2SJeff Roberson 		sched_load_rem();
1425f200843bSJohn Baldwin #ifdef SMP
1426f200843bSJohn Baldwin 	if (ts->ts_runq != &runq)
1427f200843bSJohn Baldwin 		runq_length[ts->ts_runq - runq_pcpu]--;
1428f200843bSJohn Baldwin #endif
14299727e637SJeff Roberson 	runq_remove(ts->ts_runq, td);
1430f0393f06SJeff Roberson 	TD_SET_CAN_RUN(td);
1431b43179fbSJeff Roberson }
1432b43179fbSJeff Roberson 
143314f0e2e9SJulian Elischer /*
14348aa3d7ffSJohn Baldwin  * Select threads to run.  Note that running threads still consume a
14358aa3d7ffSJohn Baldwin  * slot.
143614f0e2e9SJulian Elischer  */
1437f0393f06SJeff Roberson struct thread *
1438b43179fbSJeff Roberson sched_choose(void)
1439b43179fbSJeff Roberson {
14409727e637SJeff Roberson 	struct thread *td;
1441e17c57b1SJeff Roberson 	struct runq *rq;
1442b43179fbSJeff Roberson 
14437b20fb19SJeff Roberson 	mtx_assert(&sched_lock,  MA_OWNED);
1444e17c57b1SJeff Roberson #ifdef SMP
14459727e637SJeff Roberson 	struct thread *tdcpu;
1446e17c57b1SJeff Roberson 
1447e17c57b1SJeff Roberson 	rq = &runq;
14489727e637SJeff Roberson 	td = runq_choose_fuzz(&runq, runq_fuzz);
14499727e637SJeff Roberson 	tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1450e17c57b1SJeff Roberson 
14519727e637SJeff Roberson 	if (td == NULL ||
14529727e637SJeff Roberson 	    (tdcpu != NULL &&
14539727e637SJeff Roberson 	     tdcpu->td_priority < td->td_priority)) {
14549727e637SJeff Roberson 		CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1455e17c57b1SJeff Roberson 		     PCPU_GET(cpuid));
14569727e637SJeff Roberson 		td = tdcpu;
1457e17c57b1SJeff Roberson 		rq = &runq_pcpu[PCPU_GET(cpuid)];
1458e17c57b1SJeff Roberson 	} else {
14599727e637SJeff Roberson 		CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1460e17c57b1SJeff Roberson 	}
1461e17c57b1SJeff Roberson 
1462e17c57b1SJeff Roberson #else
1463e17c57b1SJeff Roberson 	rq = &runq;
14649727e637SJeff Roberson 	td = runq_choose(&runq);
1465e17c57b1SJeff Roberson #endif
1466b43179fbSJeff Roberson 
14679727e637SJeff Roberson 	if (td) {
1468f200843bSJohn Baldwin #ifdef SMP
1469f200843bSJohn Baldwin 		if (td == tdcpu)
1470f200843bSJohn Baldwin 			runq_length[PCPU_GET(cpuid)]--;
1471f200843bSJohn Baldwin #endif
14729727e637SJeff Roberson 		runq_remove(rq, td);
14739727e637SJeff Roberson 		td->td_flags |= TDF_DIDRUN;
1474b43179fbSJeff Roberson 
14759727e637SJeff Roberson 		KASSERT(td->td_flags & TDF_INMEM,
1476b61ce5b0SJeff Roberson 		    ("sched_choose: thread swapped out"));
14779727e637SJeff Roberson 		return (td);
1478b43179fbSJeff Roberson 	}
1479f0393f06SJeff Roberson 	return (PCPU_GET(idlethread));
1480b43179fbSJeff Roberson }
1481b43179fbSJeff Roberson 
1482b43179fbSJeff Roberson void
14831e24c28fSJeff Roberson sched_preempt(struct thread *td)
14841e24c28fSJeff Roberson {
1485b3e9e682SRyan Stone 
1486b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
14871e24c28fSJeff Roberson 	thread_lock(td);
14881e24c28fSJeff Roberson 	if (td->td_critnest > 1)
14891e24c28fSJeff Roberson 		td->td_owepreempt = 1;
14901e24c28fSJeff Roberson 	else
14918df78c41SJeff Roberson 		mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, NULL);
14921e24c28fSJeff Roberson 	thread_unlock(td);
14931e24c28fSJeff Roberson }
14941e24c28fSJeff Roberson 
14951e24c28fSJeff Roberson void
1496b43179fbSJeff Roberson sched_userret(struct thread *td)
1497b43179fbSJeff Roberson {
1498b43179fbSJeff Roberson 	/*
1499b43179fbSJeff Roberson 	 * XXX we cheat slightly on the locking here to avoid locking in
1500b43179fbSJeff Roberson 	 * the usual case.  Setting td_priority here is essentially an
1501b43179fbSJeff Roberson 	 * incomplete workaround for not setting it properly elsewhere.
1502b43179fbSJeff Roberson 	 * Now that some interrupt handlers are threads, not setting it
1503b43179fbSJeff Roberson 	 * properly elsewhere can clobber it in the window between setting
1504b43179fbSJeff Roberson 	 * it here and returning to user mode, so don't waste time setting
1505b43179fbSJeff Roberson 	 * it perfectly here.
1506b43179fbSJeff Roberson 	 */
1507f5c157d9SJohn Baldwin 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
1508f5c157d9SJohn Baldwin 	    ("thread with borrowed priority returning to userland"));
15098460a577SJohn Birrell 	if (td->td_priority != td->td_user_pri) {
15107b20fb19SJeff Roberson 		thread_lock(td);
15118460a577SJohn Birrell 		td->td_priority = td->td_user_pri;
15128460a577SJohn Birrell 		td->td_base_pri = td->td_user_pri;
15137b20fb19SJeff Roberson 		thread_unlock(td);
15148460a577SJohn Birrell 	}
1515b43179fbSJeff Roberson }
1516de028f5aSJeff Roberson 
1517e17c57b1SJeff Roberson void
1518e17c57b1SJeff Roberson sched_bind(struct thread *td, int cpu)
1519e17c57b1SJeff Roberson {
1520ad1e7d28SJulian Elischer 	struct td_sched *ts;
1521e17c57b1SJeff Roberson 
15221d7830edSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
15231d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1524e17c57b1SJeff Roberson 
1525ad1e7d28SJulian Elischer 	ts = td->td_sched;
1526e17c57b1SJeff Roberson 
15279727e637SJeff Roberson 	td->td_flags |= TDF_BOUND;
1528e17c57b1SJeff Roberson #ifdef SMP
1529ad1e7d28SJulian Elischer 	ts->ts_runq = &runq_pcpu[cpu];
1530e17c57b1SJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
1531e17c57b1SJeff Roberson 		return;
1532e17c57b1SJeff Roberson 
1533bf0acc27SJohn Baldwin 	mi_switch(SW_VOL, NULL);
1534e17c57b1SJeff Roberson #endif
1535e17c57b1SJeff Roberson }
1536e17c57b1SJeff Roberson 
1537e17c57b1SJeff Roberson void
1538e17c57b1SJeff Roberson sched_unbind(struct thread* td)
1539e17c57b1SJeff Roberson {
15407b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
15411d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
15429727e637SJeff Roberson 	td->td_flags &= ~TDF_BOUND;
1543e17c57b1SJeff Roberson }
1544e17c57b1SJeff Roberson 
1545de028f5aSJeff Roberson int
1546ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
1547ebccf1e3SJoseph Koshy {
15487b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
15499727e637SJeff Roberson 	return (td->td_flags & TDF_BOUND);
1550ebccf1e3SJoseph Koshy }
1551ebccf1e3SJoseph Koshy 
155236ec198bSDavid Xu void
155336ec198bSDavid Xu sched_relinquish(struct thread *td)
155436ec198bSDavid Xu {
15557b20fb19SJeff Roberson 	thread_lock(td);
15568df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
15577b20fb19SJeff Roberson 	thread_unlock(td);
155836ec198bSDavid Xu }
155936ec198bSDavid Xu 
1560ebccf1e3SJoseph Koshy int
1561ca59f152SJeff Roberson sched_load(void)
1562ca59f152SJeff Roberson {
1563ca59f152SJeff Roberson 	return (sched_tdcnt);
1564ca59f152SJeff Roberson }
1565ca59f152SJeff Roberson 
1566de028f5aSJeff Roberson int
1567de028f5aSJeff Roberson sched_sizeof_proc(void)
1568de028f5aSJeff Roberson {
1569de028f5aSJeff Roberson 	return (sizeof(struct proc));
1570de028f5aSJeff Roberson }
157136ec198bSDavid Xu 
1572de028f5aSJeff Roberson int
1573de028f5aSJeff Roberson sched_sizeof_thread(void)
1574de028f5aSJeff Roberson {
1575ad1e7d28SJulian Elischer 	return (sizeof(struct thread) + sizeof(struct td_sched));
1576de028f5aSJeff Roberson }
157779acfc49SJeff Roberson 
157879acfc49SJeff Roberson fixpt_t
15797cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
158079acfc49SJeff Roberson {
1581ad1e7d28SJulian Elischer 	struct td_sched *ts;
158255f2099aSJeff Roberson 
15833da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1584ad1e7d28SJulian Elischer 	ts = td->td_sched;
1585ad1e7d28SJulian Elischer 	return (ts->ts_pctcpu);
158679acfc49SJeff Roberson }
1587b41f1452SDavid Xu 
158836af9869SEdward Tomasz Napierala #ifdef	RACCT
158936af9869SEdward Tomasz Napierala /*
159036af9869SEdward Tomasz Napierala  * Calculates the contribution to the thread cpu usage for the latest
159136af9869SEdward Tomasz Napierala  * (unfinished) second.
159236af9869SEdward Tomasz Napierala  */
159336af9869SEdward Tomasz Napierala fixpt_t
159436af9869SEdward Tomasz Napierala sched_pctcpu_delta(struct thread *td)
159536af9869SEdward Tomasz Napierala {
159636af9869SEdward Tomasz Napierala 	struct td_sched *ts;
159736af9869SEdward Tomasz Napierala 	fixpt_t delta;
159836af9869SEdward Tomasz Napierala 	int realstathz;
159936af9869SEdward Tomasz Napierala 
160036af9869SEdward Tomasz Napierala 	THREAD_LOCK_ASSERT(td, MA_OWNED);
160136af9869SEdward Tomasz Napierala 	ts = td->td_sched;
160236af9869SEdward Tomasz Napierala 	delta = 0;
160336af9869SEdward Tomasz Napierala 	realstathz = stathz ? stathz : hz;
160436af9869SEdward Tomasz Napierala 	if (ts->ts_cpticks != 0) {
160536af9869SEdward Tomasz Napierala #if	(FSHIFT >= CCPU_SHIFT)
160636af9869SEdward Tomasz Napierala 		delta = (realstathz == 100)
160736af9869SEdward Tomasz Napierala 		    ? ((fixpt_t) ts->ts_cpticks) <<
160836af9869SEdward Tomasz Napierala 		    (FSHIFT - CCPU_SHIFT) :
160936af9869SEdward Tomasz Napierala 		    100 * (((fixpt_t) ts->ts_cpticks)
161036af9869SEdward Tomasz Napierala 		    << (FSHIFT - CCPU_SHIFT)) / realstathz;
161136af9869SEdward Tomasz Napierala #else
161236af9869SEdward Tomasz Napierala 		delta = ((FSCALE - ccpu) *
161336af9869SEdward Tomasz Napierala 		    (ts->ts_cpticks *
161436af9869SEdward Tomasz Napierala 		    FSCALE / realstathz)) >> FSHIFT;
161536af9869SEdward Tomasz Napierala #endif
161636af9869SEdward Tomasz Napierala 	}
161736af9869SEdward Tomasz Napierala 
161836af9869SEdward Tomasz Napierala 	return (delta);
161936af9869SEdward Tomasz Napierala }
162036af9869SEdward Tomasz Napierala #endif
162136af9869SEdward Tomasz Napierala 
1622b41f1452SDavid Xu void
1623a157e425SAlexander Motin sched_tick(int cnt)
1624b41f1452SDavid Xu {
1625b41f1452SDavid Xu }
1626f0393f06SJeff Roberson 
1627f0393f06SJeff Roberson /*
1628f0393f06SJeff Roberson  * The actual idle process.
1629f0393f06SJeff Roberson  */
1630f0393f06SJeff Roberson void
1631f0393f06SJeff Roberson sched_idletd(void *dummy)
1632f0393f06SJeff Roberson {
1633b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
1634f0393f06SJeff Roberson 
1635ba96d2d8SJohn Baldwin 	THREAD_NO_SLEEPING();
1636b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
1637f0393f06SJeff Roberson 	for (;;) {
1638f0393f06SJeff Roberson 		mtx_assert(&Giant, MA_NOTOWNED);
1639f0393f06SJeff Roberson 
1640b722ad00SAlexander Motin 		while (sched_runnable() == 0) {
1641b722ad00SAlexander Motin 			cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1642b722ad00SAlexander Motin 			stat->idlecalls++;
1643b722ad00SAlexander Motin 		}
1644f0393f06SJeff Roberson 
1645f0393f06SJeff Roberson 		mtx_lock_spin(&sched_lock);
16468df78c41SJeff Roberson 		mi_switch(SW_VOL | SWT_IDLE, NULL);
1647f0393f06SJeff Roberson 		mtx_unlock_spin(&sched_lock);
1648f0393f06SJeff Roberson 	}
1649f0393f06SJeff Roberson }
1650f0393f06SJeff Roberson 
16517b20fb19SJeff Roberson /*
16527b20fb19SJeff Roberson  * A CPU is entering for the first time or a thread is exiting.
16537b20fb19SJeff Roberson  */
16547b20fb19SJeff Roberson void
16557b20fb19SJeff Roberson sched_throw(struct thread *td)
16567b20fb19SJeff Roberson {
16577b20fb19SJeff Roberson 	/*
16587b20fb19SJeff Roberson 	 * Correct spinlock nesting.  The idle thread context that we are
16597b20fb19SJeff Roberson 	 * borrowing was created so that it would start out with a single
16607b20fb19SJeff Roberson 	 * spin lock (sched_lock) held in fork_trampoline().  Since we've
16617b20fb19SJeff Roberson 	 * explicitly acquired locks in this function, the nesting count
16627b20fb19SJeff Roberson 	 * is now 2 rather than 1.  Since we are nested, calling
16637b20fb19SJeff Roberson 	 * spinlock_exit() will simply adjust the counts without allowing
16647b20fb19SJeff Roberson 	 * spin lock using code to interrupt us.
16657b20fb19SJeff Roberson 	 */
16667b20fb19SJeff Roberson 	if (td == NULL) {
16677b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
16687b20fb19SJeff Roberson 		spinlock_exit();
16697e3a96eaSJohn Baldwin 		PCPU_SET(switchtime, cpu_ticks());
16707e3a96eaSJohn Baldwin 		PCPU_SET(switchticks, ticks);
16717b20fb19SJeff Roberson 	} else {
1672eea4f254SJeff Roberson 		lock_profile_release_lock(&sched_lock.lock_object);
16737b20fb19SJeff Roberson 		MPASS(td->td_lock == &sched_lock);
16747b20fb19SJeff Roberson 	}
16757b20fb19SJeff Roberson 	mtx_assert(&sched_lock, MA_OWNED);
16767b20fb19SJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
16777b20fb19SJeff Roberson 	cpu_throw(td, choosethread());	/* doesn't return */
16787b20fb19SJeff Roberson }
16797b20fb19SJeff Roberson 
16807b20fb19SJeff Roberson void
1681fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
16827b20fb19SJeff Roberson {
16837b20fb19SJeff Roberson 
16847b20fb19SJeff Roberson 	/*
16857b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
16867b20fb19SJeff Roberson 	 * non-nested critical section with sched_lock held but not recursed.
16877b20fb19SJeff Roberson 	 */
1688fe54587fSJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
1689fe54587fSJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
1690eea4f254SJeff Roberson 	lock_profile_obtain_lock_success(&sched_lock.lock_object,
1691eea4f254SJeff Roberson 	    0, 0, __FILE__, __LINE__);
1692fe54587fSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
16937b20fb19SJeff Roberson }
16947b20fb19SJeff Roberson 
16958f51ad55SJeff Roberson char *
16968f51ad55SJeff Roberson sched_tdname(struct thread *td)
16978f51ad55SJeff Roberson {
16988f51ad55SJeff Roberson #ifdef KTR
16998f51ad55SJeff Roberson 	struct td_sched *ts;
17008f51ad55SJeff Roberson 
17018f51ad55SJeff Roberson 	ts = td->td_sched;
17028f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
17038f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
17048f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
17058f51ad55SJeff Roberson 	return (ts->ts_name);
17068f51ad55SJeff Roberson #else
17078f51ad55SJeff Roberson 	return (td->td_name);
17088f51ad55SJeff Roberson #endif
17098f51ad55SJeff Roberson }
17108f51ad55SJeff Roberson 
171144ad5475SJohn Baldwin #ifdef KTR
171244ad5475SJohn Baldwin void
171344ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
171444ad5475SJohn Baldwin {
171544ad5475SJohn Baldwin 	struct td_sched *ts;
171644ad5475SJohn Baldwin 
171744ad5475SJohn Baldwin 	ts = td->td_sched;
171844ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
171944ad5475SJohn Baldwin }
172044ad5475SJohn Baldwin #endif
172144ad5475SJohn Baldwin 
1722885d51a3SJeff Roberson void
1723885d51a3SJeff Roberson sched_affinity(struct thread *td)
1724885d51a3SJeff Roberson {
1725f200843bSJohn Baldwin #ifdef SMP
1726f200843bSJohn Baldwin 	struct td_sched *ts;
1727f200843bSJohn Baldwin 	int cpu;
1728f200843bSJohn Baldwin 
1729f200843bSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1730f200843bSJohn Baldwin 
1731f200843bSJohn Baldwin 	/*
1732f200843bSJohn Baldwin 	 * Set the TSF_AFFINITY flag if there is at least one CPU this
1733f200843bSJohn Baldwin 	 * thread can't run on.
1734f200843bSJohn Baldwin 	 */
1735f200843bSJohn Baldwin 	ts = td->td_sched;
1736f200843bSJohn Baldwin 	ts->ts_flags &= ~TSF_AFFINITY;
17373aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1738f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu)) {
1739f200843bSJohn Baldwin 			ts->ts_flags |= TSF_AFFINITY;
1740f200843bSJohn Baldwin 			break;
1741f200843bSJohn Baldwin 		}
1742f200843bSJohn Baldwin 	}
1743f200843bSJohn Baldwin 
1744f200843bSJohn Baldwin 	/*
1745f200843bSJohn Baldwin 	 * If this thread can run on all CPUs, nothing else to do.
1746f200843bSJohn Baldwin 	 */
1747f200843bSJohn Baldwin 	if (!(ts->ts_flags & TSF_AFFINITY))
1748f200843bSJohn Baldwin 		return;
1749f200843bSJohn Baldwin 
1750f200843bSJohn Baldwin 	/* Pinned threads and bound threads should be left alone. */
1751f200843bSJohn Baldwin 	if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1752f200843bSJohn Baldwin 		return;
1753f200843bSJohn Baldwin 
1754f200843bSJohn Baldwin 	switch (td->td_state) {
1755f200843bSJohn Baldwin 	case TDS_RUNQ:
1756f200843bSJohn Baldwin 		/*
1757f200843bSJohn Baldwin 		 * If we are on a per-CPU runqueue that is in the set,
1758f200843bSJohn Baldwin 		 * then nothing needs to be done.
1759f200843bSJohn Baldwin 		 */
1760f200843bSJohn Baldwin 		if (ts->ts_runq != &runq &&
1761f200843bSJohn Baldwin 		    THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1762f200843bSJohn Baldwin 			return;
1763f200843bSJohn Baldwin 
1764f200843bSJohn Baldwin 		/* Put this thread on a valid per-CPU runqueue. */
1765f200843bSJohn Baldwin 		sched_rem(td);
1766f200843bSJohn Baldwin 		sched_add(td, SRQ_BORING);
1767f200843bSJohn Baldwin 		break;
1768f200843bSJohn Baldwin 	case TDS_RUNNING:
1769f200843bSJohn Baldwin 		/*
1770f200843bSJohn Baldwin 		 * See if our current CPU is in the set.  If not, force a
1771f200843bSJohn Baldwin 		 * context switch.
1772f200843bSJohn Baldwin 		 */
1773f200843bSJohn Baldwin 		if (THREAD_CAN_SCHED(td, td->td_oncpu))
1774f200843bSJohn Baldwin 			return;
1775f200843bSJohn Baldwin 
1776f200843bSJohn Baldwin 		td->td_flags |= TDF_NEEDRESCHED;
1777f200843bSJohn Baldwin 		if (td != curthread)
1778d9d8d144SJohn Baldwin 			ipi_cpu(cpu, IPI_AST);
1779f200843bSJohn Baldwin 		break;
1780f200843bSJohn Baldwin 	default:
1781f200843bSJohn Baldwin 		break;
1782f200843bSJohn Baldwin 	}
1783f200843bSJohn Baldwin #endif
1784885d51a3SJeff Roberson }
1785