xref: /freebsd/sys/kern/sched_4bsd.c (revision 93ccd6bf87c7e1f94fb672f08b52a120c00e6f9d)
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"
404da0d332SPeter Wemm 
41b43179fbSJeff Roberson #include <sys/param.h>
42b43179fbSJeff Roberson #include <sys/systm.h>
43f5a3ef99SMarcel Moolenaar #include <sys/cpuset.h>
44b43179fbSJeff Roberson #include <sys/kernel.h>
45b43179fbSJeff Roberson #include <sys/ktr.h>
46b43179fbSJeff Roberson #include <sys/lock.h>
47c55bbb6cSJohn Baldwin #include <sys/kthread.h>
48b43179fbSJeff Roberson #include <sys/mutex.h>
49b43179fbSJeff Roberson #include <sys/proc.h>
50b43179fbSJeff Roberson #include <sys/resourcevar.h>
51b43179fbSJeff Roberson #include <sys/sched.h>
52b3e9e682SRyan Stone #include <sys/sdt.h>
53b43179fbSJeff Roberson #include <sys/smp.h>
54b43179fbSJeff Roberson #include <sys/sysctl.h>
55b43179fbSJeff Roberson #include <sys/sx.h>
56f5c157d9SJohn Baldwin #include <sys/turnstile.h>
573db720fdSDavid Xu #include <sys/umtx.h>
582e4db89cSDavid E. O'Brien #include <machine/pcb.h>
59293968d8SJulian Elischer #include <machine/smp.h>
60b43179fbSJeff Roberson 
61ebccf1e3SJoseph Koshy #ifdef HWPMC_HOOKS
62ebccf1e3SJoseph Koshy #include <sys/pmckern.h>
63ebccf1e3SJoseph Koshy #endif
64ebccf1e3SJoseph Koshy 
656f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
666f5f25e5SJohn Birrell #include <sys/dtrace_bsd.h>
676f5f25e5SJohn Birrell int				dtrace_vtime_active;
686f5f25e5SJohn Birrell dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
696f5f25e5SJohn Birrell #endif
706f5f25e5SJohn Birrell 
7106439a04SJeff Roberson /*
7206439a04SJeff Roberson  * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
7306439a04SJeff Roberson  * the range 100-256 Hz (approximately).
7406439a04SJeff Roberson  */
7506439a04SJeff Roberson #define	ESTCPULIM(e) \
7606439a04SJeff Roberson     min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
7706439a04SJeff Roberson     RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
78b698380fSBruce Evans #ifdef SMP
79b698380fSBruce Evans #define	INVERSE_ESTCPU_WEIGHT	(8 * smp_cpus)
80b698380fSBruce Evans #else
8106439a04SJeff Roberson #define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
82b698380fSBruce Evans #endif
8306439a04SJeff Roberson #define	NICE_WEIGHT		1	/* Priorities per nice level. */
8406439a04SJeff Roberson 
850d2cf837SJeff Roberson #define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
868f51ad55SJeff Roberson 
878460a577SJohn Birrell /*
888460a577SJohn Birrell  * The schedulable entity that runs a context.
89ad1e7d28SJulian Elischer  * This is  an extension to the thread structure and is tailored to
90ccd0ec40SKonstantin Belousov  * the requirements of this scheduler.
91ccd0ec40SKonstantin Belousov  * All fields are protected by the scheduler lock.
928460a577SJohn Birrell  */
93ad1e7d28SJulian Elischer struct td_sched {
94ccd0ec40SKonstantin Belousov 	fixpt_t		ts_pctcpu;	/* %cpu during p_swtime. */
95ccd0ec40SKonstantin Belousov 	u_int		ts_estcpu;	/* Estimated cpu utilization. */
96ccd0ec40SKonstantin Belousov 	int		ts_cpticks;	/* Ticks of cpu time. */
97ccd0ec40SKonstantin Belousov 	int		ts_slptime;	/* Seconds !RUNNING. */
9848317e9eSAlexander Motin 	int		ts_slice;	/* Remaining part of time slice. */
99f200843bSJohn Baldwin 	int		ts_flags;
100ad1e7d28SJulian Elischer 	struct runq	*ts_runq;	/* runq the thread is currently on */
1018f51ad55SJeff Roberson #ifdef KTR
1028f51ad55SJeff Roberson 	char		ts_name[TS_NAME_LEN];
1038f51ad55SJeff Roberson #endif
104bcb06d59SJeff Roberson };
105ed062c8dSJulian Elischer 
106ed062c8dSJulian Elischer /* flags kept in td_flags */
107ad1e7d28SJulian Elischer #define TDF_DIDRUN	TDF_SCHED0	/* thread actually ran. */
1089727e637SJeff Roberson #define TDF_BOUND	TDF_SCHED1	/* Bound to one CPU. */
1093d7f4117SAlexander Motin #define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
110bcb06d59SJeff Roberson 
111f200843bSJohn Baldwin /* flags kept in ts_flags */
112f200843bSJohn Baldwin #define	TSF_AFFINITY	0x0001		/* Has a non-"full" CPU set. */
113f200843bSJohn Baldwin 
114ad1e7d28SJulian Elischer #define SKE_RUNQ_PCPU(ts)						\
115ad1e7d28SJulian Elischer     ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
116e17c57b1SJeff Roberson 
117f200843bSJohn Baldwin #define	THREAD_CAN_SCHED(td, cpu)	\
118f200843bSJohn Baldwin     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
119f200843bSJohn Baldwin 
120*93ccd6bfSKonstantin Belousov _Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
121*93ccd6bfSKonstantin Belousov     sizeof(struct thread0_storage),
122*93ccd6bfSKonstantin Belousov     "increase struct thread0_storage.t0st_sched size");
123*93ccd6bfSKonstantin Belousov 
1240d13d5fcSMarius Strobl static struct mtx sched_lock;
125b43179fbSJeff Roberson 
126579895dfSAlexander Motin static int	realstathz = 127; /* stathz is sometimes 0 and run off of hz. */
127ca59f152SJeff Roberson static int	sched_tdcnt;	/* Total runnable threads in the system. */
128579895dfSAlexander Motin static int	sched_slice = 12; /* Thread run time before rescheduling. */
129b43179fbSJeff Roberson 
130e17c57b1SJeff Roberson static void	setup_runqs(void);
131c55bbb6cSJohn Baldwin static void	schedcpu(void);
132e17c57b1SJeff Roberson static void	schedcpu_thread(void);
133f5c157d9SJohn Baldwin static void	sched_priority(struct thread *td, u_char prio);
134b43179fbSJeff Roberson static void	sched_setup(void *dummy);
135b43179fbSJeff Roberson static void	maybe_resched(struct thread *td);
1368460a577SJohn Birrell static void	updatepri(struct thread *td);
1378460a577SJohn Birrell static void	resetpriority(struct thread *td);
1388460a577SJohn Birrell static void	resetpriority_thread(struct thread *td);
13900b0483dSJulian Elischer #ifdef SMP
140f200843bSJohn Baldwin static int	sched_pickcpu(struct thread *td);
14182a1dfc1SJulian Elischer static int	forward_wakeup(int cpunum);
1428aa3d7ffSJohn Baldwin static void	kick_other_cpu(int pri, int cpuid);
14300b0483dSJulian Elischer #endif
144b43179fbSJeff Roberson 
145e17c57b1SJeff Roberson static struct kproc_desc sched_kp = {
146e17c57b1SJeff Roberson         "schedcpu",
147e17c57b1SJeff Roberson         schedcpu_thread,
148e17c57b1SJeff Roberson         NULL
149e17c57b1SJeff Roberson };
150785797c3SAndriy Gapon SYSINIT(schedcpu, SI_SUB_LAST, SI_ORDER_FIRST, kproc_start,
151237fdd78SRobert Watson     &sched_kp);
152237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
153b43179fbSJeff Roberson 
15448317e9eSAlexander Motin static void sched_initticks(void *dummy);
15548317e9eSAlexander Motin SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
15648317e9eSAlexander Motin     NULL);
15748317e9eSAlexander Motin 
158b43179fbSJeff Roberson /*
159b43179fbSJeff Roberson  * Global run queue.
160b43179fbSJeff Roberson  */
161b43179fbSJeff Roberson static struct runq runq;
162e17c57b1SJeff Roberson 
163e17c57b1SJeff Roberson #ifdef SMP
164e17c57b1SJeff Roberson /*
165e17c57b1SJeff Roberson  * Per-CPU run queues
166e17c57b1SJeff Roberson  */
167e17c57b1SJeff Roberson static struct runq runq_pcpu[MAXCPU];
168f200843bSJohn Baldwin long runq_length[MAXCPU];
1693121f534SAttilio Rao 
17071a19bdcSAttilio Rao static cpuset_t idle_cpus_mask;
171e17c57b1SJeff Roberson #endif
172e17c57b1SJeff Roberson 
173b722ad00SAlexander Motin struct pcpuidlestat {
174b722ad00SAlexander Motin 	u_int idlecalls;
175b722ad00SAlexander Motin 	u_int oldidlecalls;
176b722ad00SAlexander Motin };
1773e288e62SDimitry Andric static DPCPU_DEFINE(struct pcpuidlestat, idlestat);
178b722ad00SAlexander Motin 
179e17c57b1SJeff Roberson static void
180e17c57b1SJeff Roberson setup_runqs(void)
181e17c57b1SJeff Roberson {
182e17c57b1SJeff Roberson #ifdef SMP
183e17c57b1SJeff Roberson 	int i;
184e17c57b1SJeff Roberson 
185e17c57b1SJeff Roberson 	for (i = 0; i < MAXCPU; ++i)
186e17c57b1SJeff Roberson 		runq_init(&runq_pcpu[i]);
187e17c57b1SJeff Roberson #endif
188e17c57b1SJeff Roberson 
189e17c57b1SJeff Roberson 	runq_init(&runq);
190e17c57b1SJeff Roberson }
191b43179fbSJeff Roberson 
192579895dfSAlexander Motin static int
193579895dfSAlexander Motin sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
194579895dfSAlexander Motin {
195579895dfSAlexander Motin 	int error, new_val, period;
196579895dfSAlexander Motin 
197579895dfSAlexander Motin 	period = 1000000 / realstathz;
198579895dfSAlexander Motin 	new_val = period * sched_slice;
199579895dfSAlexander Motin 	error = sysctl_handle_int(oidp, &new_val, 0, req);
200579895dfSAlexander Motin 	if (error != 0 || req->newptr == NULL)
201579895dfSAlexander Motin 		return (error);
202579895dfSAlexander Motin 	if (new_val <= 0)
203579895dfSAlexander Motin 		return (EINVAL);
20437f4e025SAlexander Motin 	sched_slice = imax(1, (new_val + period / 2) / period);
20537f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
20637f4e025SAlexander Motin 	    realstathz);
207579895dfSAlexander Motin 	return (0);
208579895dfSAlexander Motin }
209579895dfSAlexander Motin 
210e038d354SScott Long SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
211dc095794SScott Long 
212e038d354SScott Long SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
213e038d354SScott Long     "Scheduler name");
214579895dfSAlexander Motin SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
215579895dfSAlexander Motin     NULL, 0, sysctl_kern_quantum, "I",
21637f4e025SAlexander Motin     "Quantum for timeshare threads in microseconds");
21748317e9eSAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
21837f4e025SAlexander Motin     "Quantum for timeshare threads in stathz ticks");
21937c28a02SJulian Elischer #ifdef SMP
22082a1dfc1SJulian Elischer /* Enable forwarding of wakeups to all other cpus */
2216472ac3dSEd Schouten static SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL,
2226472ac3dSEd Schouten     "Kernel SMP");
22382a1dfc1SJulian Elischer 
224a90f3f25SJeff Roberson static int runq_fuzz = 1;
225a90f3f25SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
226a90f3f25SJeff Roberson 
227bce73aedSJulian Elischer static int forward_wakeup_enabled = 1;
22882a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
22982a1dfc1SJulian Elischer 	   &forward_wakeup_enabled, 0,
23082a1dfc1SJulian Elischer 	   "Forwarding of wakeup to idle CPUs");
23182a1dfc1SJulian Elischer 
23282a1dfc1SJulian Elischer static int forward_wakeups_requested = 0;
23382a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
23482a1dfc1SJulian Elischer 	   &forward_wakeups_requested, 0,
23582a1dfc1SJulian Elischer 	   "Requests for Forwarding of wakeup to idle CPUs");
23682a1dfc1SJulian Elischer 
23782a1dfc1SJulian Elischer static int forward_wakeups_delivered = 0;
23882a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
23982a1dfc1SJulian Elischer 	   &forward_wakeups_delivered, 0,
24082a1dfc1SJulian Elischer 	   "Completed Forwarding of wakeup to idle CPUs");
24182a1dfc1SJulian Elischer 
242bce73aedSJulian Elischer static int forward_wakeup_use_mask = 1;
24382a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
24482a1dfc1SJulian Elischer 	   &forward_wakeup_use_mask, 0,
24582a1dfc1SJulian Elischer 	   "Use the mask of idle cpus");
24682a1dfc1SJulian Elischer 
24782a1dfc1SJulian Elischer static int forward_wakeup_use_loop = 0;
24882a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
24982a1dfc1SJulian Elischer 	   &forward_wakeup_use_loop, 0,
25082a1dfc1SJulian Elischer 	   "Use a loop to find idle cpus");
25182a1dfc1SJulian Elischer 
25237c28a02SJulian Elischer #endif
253ad1e7d28SJulian Elischer #if 0
2543389af30SJulian Elischer static int sched_followon = 0;
2553389af30SJulian Elischer SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
2563389af30SJulian Elischer 	   &sched_followon, 0,
2573389af30SJulian Elischer 	   "allow threads to share a quantum");
2588460a577SJohn Birrell #endif
25982a1dfc1SJulian Elischer 
260b3e9e682SRyan Stone SDT_PROVIDER_DEFINE(sched);
261b3e9e682SRyan Stone 
262d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
263b3e9e682SRyan Stone     "struct proc *", "uint8_t");
264d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
265b3e9e682SRyan Stone     "struct proc *", "void *");
266d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
267b3e9e682SRyan Stone     "struct proc *", "void *", "int");
268d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
269b3e9e682SRyan Stone     "struct proc *", "uint8_t", "struct thread *");
270d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
271d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
272b3e9e682SRyan Stone     "struct proc *");
273d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , on__cpu);
274d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , remain__cpu);
275d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
276b3e9e682SRyan Stone     "struct proc *");
277b3e9e682SRyan Stone 
278907bdbc2SJeff Roberson static __inline void
279907bdbc2SJeff Roberson sched_load_add(void)
280907bdbc2SJeff Roberson {
2818f51ad55SJeff Roberson 
282907bdbc2SJeff Roberson 	sched_tdcnt++;
2838f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
284d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
285907bdbc2SJeff Roberson }
286907bdbc2SJeff Roberson 
287907bdbc2SJeff Roberson static __inline void
288907bdbc2SJeff Roberson sched_load_rem(void)
289907bdbc2SJeff Roberson {
2908f51ad55SJeff Roberson 
291907bdbc2SJeff Roberson 	sched_tdcnt--;
2928f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
293d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
294907bdbc2SJeff Roberson }
295b43179fbSJeff Roberson /*
296b43179fbSJeff Roberson  * Arrange to reschedule if necessary, taking the priorities and
297b43179fbSJeff Roberson  * schedulers into account.
298b43179fbSJeff Roberson  */
299b43179fbSJeff Roberson static void
300b43179fbSJeff Roberson maybe_resched(struct thread *td)
301b43179fbSJeff Roberson {
302b43179fbSJeff Roberson 
3037b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
304ed062c8dSJulian Elischer 	if (td->td_priority < curthread->td_priority)
3054a338afdSJulian Elischer 		curthread->td_flags |= TDF_NEEDRESCHED;
306b43179fbSJeff Roberson }
307b43179fbSJeff Roberson 
308b43179fbSJeff Roberson /*
309a90f3f25SJeff Roberson  * This function is called when a thread is about to be put on run queue
310a90f3f25SJeff Roberson  * because it has been made runnable or its priority has been adjusted.  It
311a90f3f25SJeff Roberson  * determines if the new thread should be immediately preempted to.  If so,
312a90f3f25SJeff Roberson  * it switches to it and eventually returns true.  If not, it returns false
313a90f3f25SJeff Roberson  * so that the caller may place the thread on an appropriate run queue.
314a90f3f25SJeff Roberson  */
315a90f3f25SJeff Roberson int
316a90f3f25SJeff Roberson maybe_preempt(struct thread *td)
317a90f3f25SJeff Roberson {
318a90f3f25SJeff Roberson #ifdef PREEMPTION
319a90f3f25SJeff Roberson 	struct thread *ctd;
320a90f3f25SJeff Roberson 	int cpri, pri;
321a90f3f25SJeff Roberson 
322a90f3f25SJeff Roberson 	/*
323a90f3f25SJeff Roberson 	 * The new thread should not preempt the current thread if any of the
324a90f3f25SJeff Roberson 	 * following conditions are true:
325a90f3f25SJeff Roberson 	 *
326a90f3f25SJeff Roberson 	 *  - The kernel is in the throes of crashing (panicstr).
327a90f3f25SJeff Roberson 	 *  - The current thread has a higher (numerically lower) or
328a90f3f25SJeff Roberson 	 *    equivalent priority.  Note that this prevents curthread from
329a90f3f25SJeff Roberson 	 *    trying to preempt to itself.
330a90f3f25SJeff Roberson 	 *  - It is too early in the boot for context switches (cold is set).
331a90f3f25SJeff Roberson 	 *  - The current thread has an inhibitor set or is in the process of
332a90f3f25SJeff Roberson 	 *    exiting.  In this case, the current thread is about to switch
333a90f3f25SJeff Roberson 	 *    out anyways, so there's no point in preempting.  If we did,
334a90f3f25SJeff Roberson 	 *    the current thread would not be properly resumed as well, so
335a90f3f25SJeff Roberson 	 *    just avoid that whole landmine.
336a90f3f25SJeff Roberson 	 *  - If the new thread's priority is not a realtime priority and
337a90f3f25SJeff Roberson 	 *    the current thread's priority is not an idle priority and
338a90f3f25SJeff Roberson 	 *    FULL_PREEMPTION is disabled.
339a90f3f25SJeff Roberson 	 *
340a90f3f25SJeff Roberson 	 * If all of these conditions are false, but the current thread is in
341a90f3f25SJeff Roberson 	 * a nested critical section, then we have to defer the preemption
342a90f3f25SJeff Roberson 	 * until we exit the critical section.  Otherwise, switch immediately
343a90f3f25SJeff Roberson 	 * to the new thread.
344a90f3f25SJeff Roberson 	 */
345a90f3f25SJeff Roberson 	ctd = curthread;
346a90f3f25SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
347a90f3f25SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
348a90f3f25SJeff Roberson 			("maybe_preempt: trying to run inhibited thread"));
349a90f3f25SJeff Roberson 	pri = td->td_priority;
350a90f3f25SJeff Roberson 	cpri = ctd->td_priority;
351a90f3f25SJeff Roberson 	if (panicstr != NULL || pri >= cpri || cold /* || dumping */ ||
352a90f3f25SJeff Roberson 	    TD_IS_INHIBITED(ctd))
353a90f3f25SJeff Roberson 		return (0);
354a90f3f25SJeff Roberson #ifndef FULL_PREEMPTION
355a90f3f25SJeff Roberson 	if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
356a90f3f25SJeff Roberson 		return (0);
357a90f3f25SJeff Roberson #endif
358a90f3f25SJeff Roberson 
359a90f3f25SJeff Roberson 	if (ctd->td_critnest > 1) {
360a90f3f25SJeff Roberson 		CTR1(KTR_PROC, "maybe_preempt: in critical section %d",
361a90f3f25SJeff Roberson 		    ctd->td_critnest);
362a90f3f25SJeff Roberson 		ctd->td_owepreempt = 1;
363a90f3f25SJeff Roberson 		return (0);
364a90f3f25SJeff Roberson 	}
365a90f3f25SJeff Roberson 	/*
366a90f3f25SJeff Roberson 	 * Thread is runnable but not yet put on system run queue.
367a90f3f25SJeff Roberson 	 */
368a90f3f25SJeff Roberson 	MPASS(ctd->td_lock == td->td_lock);
369a90f3f25SJeff Roberson 	MPASS(TD_ON_RUNQ(td));
370a90f3f25SJeff Roberson 	TD_SET_RUNNING(td);
371a90f3f25SJeff Roberson 	CTR3(KTR_PROC, "preempting to thread %p (pid %d, %s)\n", td,
372a90f3f25SJeff Roberson 	    td->td_proc->p_pid, td->td_name);
3738df78c41SJeff Roberson 	mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, td);
374a90f3f25SJeff Roberson 	/*
375a90f3f25SJeff Roberson 	 * td's lock pointer may have changed.  We have to return with it
376a90f3f25SJeff Roberson 	 * locked.
377a90f3f25SJeff Roberson 	 */
378a90f3f25SJeff Roberson 	spinlock_enter();
379a90f3f25SJeff Roberson 	thread_unlock(ctd);
380a90f3f25SJeff Roberson 	thread_lock(td);
381a90f3f25SJeff Roberson 	spinlock_exit();
382a90f3f25SJeff Roberson 	return (1);
383a90f3f25SJeff Roberson #else
384a90f3f25SJeff Roberson 	return (0);
385a90f3f25SJeff Roberson #endif
386a90f3f25SJeff Roberson }
387a90f3f25SJeff Roberson 
388a90f3f25SJeff Roberson /*
389b43179fbSJeff Roberson  * Constants for digital decay and forget:
390ccd0ec40SKonstantin Belousov  *	90% of (ts_estcpu) usage in 5 * loadav time
391ad1e7d28SJulian Elischer  *	95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
392b43179fbSJeff Roberson  *          Note that, as ps(1) mentions, this can let percentages
393b43179fbSJeff Roberson  *          total over 100% (I've seen 137.9% for 3 processes).
394b43179fbSJeff Roberson  *
395ccd0ec40SKonstantin Belousov  * Note that schedclock() updates ts_estcpu and p_cpticks asynchronously.
396b43179fbSJeff Roberson  *
397ccd0ec40SKonstantin Belousov  * We wish to decay away 90% of ts_estcpu in (5 * loadavg) seconds.
398b43179fbSJeff Roberson  * That is, the system wants to compute a value of decay such
399b43179fbSJeff Roberson  * that the following for loop:
400b43179fbSJeff Roberson  * 	for (i = 0; i < (5 * loadavg); i++)
401ccd0ec40SKonstantin Belousov  * 		ts_estcpu *= decay;
402b43179fbSJeff Roberson  * will compute
403ccd0ec40SKonstantin Belousov  * 	ts_estcpu *= 0.1;
404b43179fbSJeff Roberson  * for all values of loadavg:
405b43179fbSJeff Roberson  *
406b43179fbSJeff Roberson  * Mathematically this loop can be expressed by saying:
407b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
408b43179fbSJeff Roberson  *
409b43179fbSJeff Roberson  * The system computes decay as:
410b43179fbSJeff Roberson  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
411b43179fbSJeff Roberson  *
412b43179fbSJeff Roberson  * We wish to prove that the system's computation of decay
413b43179fbSJeff Roberson  * will always fulfill the equation:
414b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
415b43179fbSJeff Roberson  *
416b43179fbSJeff Roberson  * If we compute b as:
417b43179fbSJeff Roberson  * 	b = 2 * loadavg
418b43179fbSJeff Roberson  * then
419b43179fbSJeff Roberson  * 	decay = b / (b + 1)
420b43179fbSJeff Roberson  *
421b43179fbSJeff Roberson  * We now need to prove two things:
422b43179fbSJeff Roberson  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
423b43179fbSJeff Roberson  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
424b43179fbSJeff Roberson  *
425b43179fbSJeff Roberson  * Facts:
426b43179fbSJeff Roberson  *         For x close to zero, exp(x) =~ 1 + x, since
427b43179fbSJeff Roberson  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
428b43179fbSJeff Roberson  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
429b43179fbSJeff Roberson  *         For x close to zero, ln(1+x) =~ x, since
430b43179fbSJeff Roberson  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
431b43179fbSJeff Roberson  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
432b43179fbSJeff Roberson  *         ln(.1) =~ -2.30
433b43179fbSJeff Roberson  *
434b43179fbSJeff Roberson  * Proof of (1):
435b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
436b43179fbSJeff Roberson  *	solving for factor,
437b43179fbSJeff Roberson  *      ln(factor) =~ (-2.30/5*loadav), or
438b43179fbSJeff Roberson  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
439b43179fbSJeff Roberson  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
440b43179fbSJeff Roberson  *
441b43179fbSJeff Roberson  * Proof of (2):
442b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
443b43179fbSJeff Roberson  *	solving for power,
444b43179fbSJeff Roberson  *      power*ln(b/(b+1)) =~ -2.30, or
445b43179fbSJeff Roberson  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
446b43179fbSJeff Roberson  *
447b43179fbSJeff Roberson  * Actual power values for the implemented algorithm are as follows:
448b43179fbSJeff Roberson  *      loadav: 1       2       3       4
449b43179fbSJeff Roberson  *      power:  5.68    10.32   14.94   19.55
450b43179fbSJeff Roberson  */
451b43179fbSJeff Roberson 
452b43179fbSJeff Roberson /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
453b43179fbSJeff Roberson #define	loadfactor(loadav)	(2 * (loadav))
454b43179fbSJeff Roberson #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
455b43179fbSJeff Roberson 
456ad1e7d28SJulian Elischer /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
457b43179fbSJeff Roberson static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
45852c0b557SMatthew D Fleming SYSCTL_UINT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
459b43179fbSJeff Roberson 
460b43179fbSJeff Roberson /*
461b43179fbSJeff Roberson  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
462b43179fbSJeff Roberson  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
463b43179fbSJeff Roberson  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
464b43179fbSJeff Roberson  *
465b43179fbSJeff Roberson  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
466b43179fbSJeff Roberson  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
467b43179fbSJeff Roberson  *
468b43179fbSJeff Roberson  * If you don't want to bother with the faster/more-accurate formula, you
469b43179fbSJeff Roberson  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
470b43179fbSJeff Roberson  * (more general) method of calculating the %age of CPU used by a process.
471b43179fbSJeff Roberson  */
472b43179fbSJeff Roberson #define	CCPU_SHIFT	11
473b43179fbSJeff Roberson 
474b43179fbSJeff Roberson /*
475b43179fbSJeff Roberson  * Recompute process priorities, every hz ticks.
476b43179fbSJeff Roberson  * MP-safe, called without the Giant mutex.
477b43179fbSJeff Roberson  */
478b43179fbSJeff Roberson /* ARGSUSED */
479b43179fbSJeff Roberson static void
480c55bbb6cSJohn Baldwin schedcpu(void)
481b43179fbSJeff Roberson {
482b43179fbSJeff Roberson 	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
483b43179fbSJeff Roberson 	struct thread *td;
484b43179fbSJeff Roberson 	struct proc *p;
485ad1e7d28SJulian Elischer 	struct td_sched *ts;
48648317e9eSAlexander Motin 	int awake;
487b43179fbSJeff Roberson 
488b43179fbSJeff Roberson 	sx_slock(&allproc_lock);
489b43179fbSJeff Roberson 	FOREACH_PROC_IN_SYSTEM(p) {
490374ae2a3SJeff Roberson 		PROC_LOCK(p);
491e806d352SJohn Baldwin 		if (p->p_state == PRS_NEW) {
492e806d352SJohn Baldwin 			PROC_UNLOCK(p);
493e806d352SJohn Baldwin 			continue;
494e806d352SJohn Baldwin 		}
4958460a577SJohn Birrell 		FOREACH_THREAD_IN_PROC(p, td) {
496b43179fbSJeff Roberson 			awake = 0;
497*93ccd6bfSKonstantin Belousov 			ts = td_get_sched(td);
4987b20fb19SJeff Roberson 			thread_lock(td);
499b43179fbSJeff Roberson 			/*
50070fca427SJohn Baldwin 			 * Increment sleep time (if sleeping).  We
50170fca427SJohn Baldwin 			 * ignore overflow, as above.
502b43179fbSJeff Roberson 			 */
503b43179fbSJeff Roberson 			/*
504ad1e7d28SJulian Elischer 			 * The td_sched slptimes are not touched in wakeup
505ad1e7d28SJulian Elischer 			 * because the thread may not HAVE everything in
506ad1e7d28SJulian Elischer 			 * memory? XXX I think this is out of date.
507b43179fbSJeff Roberson 			 */
508f0393f06SJeff Roberson 			if (TD_ON_RUNQ(td)) {
509b43179fbSJeff Roberson 				awake = 1;
5109727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
511f0393f06SJeff Roberson 			} else if (TD_IS_RUNNING(td)) {
512b43179fbSJeff Roberson 				awake = 1;
5139727e637SJeff Roberson 				/* Do not clear TDF_DIDRUN */
5149727e637SJeff Roberson 			} else if (td->td_flags & TDF_DIDRUN) {
515b43179fbSJeff Roberson 				awake = 1;
5169727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
517b43179fbSJeff Roberson 			}
518b43179fbSJeff Roberson 
519b43179fbSJeff Roberson 			/*
520ad1e7d28SJulian Elischer 			 * ts_pctcpu is only for ps and ttyinfo().
521b43179fbSJeff Roberson 			 */
522ad1e7d28SJulian Elischer 			ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
523b43179fbSJeff Roberson 			/*
524ad1e7d28SJulian Elischer 			 * If the td_sched has been idle the entire second,
525b43179fbSJeff Roberson 			 * stop recalculating its priority until
526b43179fbSJeff Roberson 			 * it wakes up.
527b43179fbSJeff Roberson 			 */
528ad1e7d28SJulian Elischer 			if (ts->ts_cpticks != 0) {
529b43179fbSJeff Roberson #if	(FSHIFT >= CCPU_SHIFT)
530ad1e7d28SJulian Elischer 				ts->ts_pctcpu += (realstathz == 100)
531ad1e7d28SJulian Elischer 				    ? ((fixpt_t) ts->ts_cpticks) <<
532b43179fbSJeff Roberson 				    (FSHIFT - CCPU_SHIFT) :
533ad1e7d28SJulian Elischer 				    100 * (((fixpt_t) ts->ts_cpticks)
534bcb06d59SJeff Roberson 				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
535b43179fbSJeff Roberson #else
536ad1e7d28SJulian Elischer 				ts->ts_pctcpu += ((FSCALE - ccpu) *
537ad1e7d28SJulian Elischer 				    (ts->ts_cpticks *
538bcb06d59SJeff Roberson 				    FSCALE / realstathz)) >> FSHIFT;
539b43179fbSJeff Roberson #endif
540ad1e7d28SJulian Elischer 				ts->ts_cpticks = 0;
5418460a577SJohn Birrell 			}
5428460a577SJohn Birrell 			/*
5438460a577SJohn Birrell 			 * If there are ANY running threads in this process,
544b43179fbSJeff Roberson 			 * then don't count it as sleeping.
5458aa3d7ffSJohn Baldwin 			 * XXX: this is broken.
546b43179fbSJeff Roberson 			 */
547b43179fbSJeff Roberson 			if (awake) {
54854b0e65fSJeff Roberson 				if (ts->ts_slptime > 1) {
549b43179fbSJeff Roberson 					/*
550b43179fbSJeff Roberson 					 * In an ideal world, this should not
551b43179fbSJeff Roberson 					 * happen, because whoever woke us
552b43179fbSJeff Roberson 					 * up from the long sleep should have
553b43179fbSJeff Roberson 					 * unwound the slptime and reset our
554b43179fbSJeff Roberson 					 * priority before we run at the stale
555b43179fbSJeff Roberson 					 * priority.  Should KASSERT at some
556b43179fbSJeff Roberson 					 * point when all the cases are fixed.
557b43179fbSJeff Roberson 					 */
5588460a577SJohn Birrell 					updatepri(td);
5598460a577SJohn Birrell 				}
56054b0e65fSJeff Roberson 				ts->ts_slptime = 0;
5618460a577SJohn Birrell 			} else
56254b0e65fSJeff Roberson 				ts->ts_slptime++;
56354b0e65fSJeff Roberson 			if (ts->ts_slptime > 1) {
5647b20fb19SJeff Roberson 				thread_unlock(td);
5658460a577SJohn Birrell 				continue;
5667b20fb19SJeff Roberson 			}
567ccd0ec40SKonstantin Belousov 			ts->ts_estcpu = decay_cpu(loadfac, ts->ts_estcpu);
5688460a577SJohn Birrell 		      	resetpriority(td);
5698460a577SJohn Birrell 			resetpriority_thread(td);
5707b20fb19SJeff Roberson 			thread_unlock(td);
5718aa3d7ffSJohn Baldwin 		}
572374ae2a3SJeff Roberson 		PROC_UNLOCK(p);
5738aa3d7ffSJohn Baldwin 	}
574b43179fbSJeff Roberson 	sx_sunlock(&allproc_lock);
575c55bbb6cSJohn Baldwin }
576c55bbb6cSJohn Baldwin 
577c55bbb6cSJohn Baldwin /*
578c55bbb6cSJohn Baldwin  * Main loop for a kthread that executes schedcpu once a second.
579c55bbb6cSJohn Baldwin  */
580c55bbb6cSJohn Baldwin static void
581e17c57b1SJeff Roberson schedcpu_thread(void)
582c55bbb6cSJohn Baldwin {
583c55bbb6cSJohn Baldwin 
584c55bbb6cSJohn Baldwin 	for (;;) {
585c55bbb6cSJohn Baldwin 		schedcpu();
5864d70511aSJohn Baldwin 		pause("-", hz);
587c55bbb6cSJohn Baldwin 	}
588b43179fbSJeff Roberson }
589b43179fbSJeff Roberson 
590b43179fbSJeff Roberson /*
591b43179fbSJeff Roberson  * Recalculate the priority of a process after it has slept for a while.
592ccd0ec40SKonstantin Belousov  * For all load averages >= 1 and max ts_estcpu of 255, sleeping for at
593ccd0ec40SKonstantin Belousov  * least six times the loadfactor will decay ts_estcpu to zero.
594b43179fbSJeff Roberson  */
595b43179fbSJeff Roberson static void
5968460a577SJohn Birrell updatepri(struct thread *td)
597b43179fbSJeff Roberson {
59854b0e65fSJeff Roberson 	struct td_sched *ts;
59954b0e65fSJeff Roberson 	fixpt_t loadfac;
60054b0e65fSJeff Roberson 	unsigned int newcpu;
601b43179fbSJeff Roberson 
602*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
60370fca427SJohn Baldwin 	loadfac = loadfactor(averunnable.ldavg[0]);
60454b0e65fSJeff Roberson 	if (ts->ts_slptime > 5 * loadfac)
605ccd0ec40SKonstantin Belousov 		ts->ts_estcpu = 0;
606b43179fbSJeff Roberson 	else {
607ccd0ec40SKonstantin Belousov 		newcpu = ts->ts_estcpu;
60854b0e65fSJeff Roberson 		ts->ts_slptime--;	/* was incremented in schedcpu() */
60954b0e65fSJeff Roberson 		while (newcpu && --ts->ts_slptime)
610b43179fbSJeff Roberson 			newcpu = decay_cpu(loadfac, newcpu);
611ccd0ec40SKonstantin Belousov 		ts->ts_estcpu = newcpu;
612b43179fbSJeff Roberson 	}
613b43179fbSJeff Roberson }
614b43179fbSJeff Roberson 
615b43179fbSJeff Roberson /*
616b43179fbSJeff Roberson  * Compute the priority of a process when running in user mode.
617b43179fbSJeff Roberson  * Arrange to reschedule if the resulting priority is better
618b43179fbSJeff Roberson  * than that of the current process.
619b43179fbSJeff Roberson  */
620b43179fbSJeff Roberson static void
6218460a577SJohn Birrell resetpriority(struct thread *td)
622b43179fbSJeff Roberson {
623ccd0ec40SKonstantin Belousov 	u_int newpriority;
624b43179fbSJeff Roberson 
625ccd0ec40SKonstantin Belousov 	if (td->td_pri_class != PRI_TIMESHARE)
626ccd0ec40SKonstantin Belousov 		return;
627*93ccd6bfSKonstantin Belousov 	newpriority = PUSER +
628*93ccd6bfSKonstantin Belousov 	    td_get_sched(td)->ts_estcpu / INVERSE_ESTCPU_WEIGHT +
6298460a577SJohn Birrell 	    NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
630b43179fbSJeff Roberson 	newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
631b43179fbSJeff Roberson 	    PRI_MAX_TIMESHARE);
6328460a577SJohn Birrell 	sched_user_prio(td, newpriority);
633b43179fbSJeff Roberson }
634f5c157d9SJohn Baldwin 
635f5c157d9SJohn Baldwin /*
636ad1e7d28SJulian Elischer  * Update the thread's priority when the associated process's user
637f5c157d9SJohn Baldwin  * priority changes.
638f5c157d9SJohn Baldwin  */
639f5c157d9SJohn Baldwin static void
6408460a577SJohn Birrell resetpriority_thread(struct thread *td)
641f5c157d9SJohn Baldwin {
642f5c157d9SJohn Baldwin 
643f5c157d9SJohn Baldwin 	/* Only change threads with a time sharing user priority. */
644f5c157d9SJohn Baldwin 	if (td->td_priority < PRI_MIN_TIMESHARE ||
645f5c157d9SJohn Baldwin 	    td->td_priority > PRI_MAX_TIMESHARE)
646f5c157d9SJohn Baldwin 		return;
647f5c157d9SJohn Baldwin 
648f5c157d9SJohn Baldwin 	/* XXX the whole needresched thing is broken, but not silly. */
649f5c157d9SJohn Baldwin 	maybe_resched(td);
650f5c157d9SJohn Baldwin 
6518460a577SJohn Birrell 	sched_prio(td, td->td_user_pri);
652b43179fbSJeff Roberson }
653b43179fbSJeff Roberson 
654b43179fbSJeff Roberson /* ARGSUSED */
655b43179fbSJeff Roberson static void
656b43179fbSJeff Roberson sched_setup(void *dummy)
657b43179fbSJeff Roberson {
65870fca427SJohn Baldwin 
659579895dfSAlexander Motin 	setup_runqs();
660b43179fbSJeff Roberson 
661ca59f152SJeff Roberson 	/* Account for thread0. */
662907bdbc2SJeff Roberson 	sched_load_add();
663b43179fbSJeff Roberson }
664b43179fbSJeff Roberson 
66548317e9eSAlexander Motin /*
666579895dfSAlexander Motin  * This routine determines time constants after stathz and hz are setup.
66748317e9eSAlexander Motin  */
66848317e9eSAlexander Motin static void
66948317e9eSAlexander Motin sched_initticks(void *dummy)
67048317e9eSAlexander Motin {
67148317e9eSAlexander Motin 
67248317e9eSAlexander Motin 	realstathz = stathz ? stathz : hz;
67348317e9eSAlexander Motin 	sched_slice = realstathz / 10;	/* ~100ms */
67437f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
67537f4e025SAlexander Motin 	    realstathz);
67648317e9eSAlexander Motin }
67748317e9eSAlexander Motin 
678b43179fbSJeff Roberson /* External interfaces start here */
6798aa3d7ffSJohn Baldwin 
680ed062c8dSJulian Elischer /*
681ed062c8dSJulian Elischer  * Very early in the boot some setup of scheduler-specific
682f3050486SMaxim Konovalov  * parts of proc0 and of some scheduler resources needs to be done.
683ed062c8dSJulian Elischer  * Called from:
684ed062c8dSJulian Elischer  *  proc0_init()
685ed062c8dSJulian Elischer  */
686ed062c8dSJulian Elischer void
687ed062c8dSJulian Elischer schedinit(void)
688ed062c8dSJulian Elischer {
689*93ccd6bfSKonstantin Belousov 
690ed062c8dSJulian Elischer 	/*
691*93ccd6bfSKonstantin Belousov 	 * Set up the scheduler specific parts of thread0.
692ed062c8dSJulian Elischer 	 */
6937b20fb19SJeff Roberson 	thread0.td_lock = &sched_lock;
694*93ccd6bfSKonstantin Belousov 	td_get_sched(&thread0)->ts_slice = sched_slice;
6956ea38de8SJeff Roberson 	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
696ed062c8dSJulian Elischer }
697ed062c8dSJulian Elischer 
698b43179fbSJeff Roberson int
699b43179fbSJeff Roberson sched_runnable(void)
700b43179fbSJeff Roberson {
701e17c57b1SJeff Roberson #ifdef SMP
702e17c57b1SJeff Roberson 	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
703e17c57b1SJeff Roberson #else
704b43179fbSJeff Roberson 	return runq_check(&runq);
705e17c57b1SJeff Roberson #endif
706b43179fbSJeff Roberson }
707b43179fbSJeff Roberson 
708b43179fbSJeff Roberson int
709b43179fbSJeff Roberson sched_rr_interval(void)
710b43179fbSJeff Roberson {
71148317e9eSAlexander Motin 
71248317e9eSAlexander Motin 	/* Convert sched_slice from stathz to hz. */
71337f4e025SAlexander Motin 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
714b43179fbSJeff Roberson }
715b43179fbSJeff Roberson 
716b43179fbSJeff Roberson /*
717ccd0ec40SKonstantin Belousov  * We adjust the priority of the current process.  The priority of a
718ccd0ec40SKonstantin Belousov  * process gets worse as it accumulates CPU time.  The cpu usage
719ccd0ec40SKonstantin Belousov  * estimator (ts_estcpu) is increased here.  resetpriority() will
720ccd0ec40SKonstantin Belousov  * compute a different priority each time ts_estcpu increases by
721ccd0ec40SKonstantin Belousov  * INVERSE_ESTCPU_WEIGHT (until PRI_MAX_TIMESHARE is reached).  The
722ccd0ec40SKonstantin Belousov  * cpu usage estimator ramps up quite quickly when the process is
723ccd0ec40SKonstantin Belousov  * running (linearly), and decays away exponentially, at a rate which
724ccd0ec40SKonstantin Belousov  * is proportionally slower when the system is busy.  The basic
725ccd0ec40SKonstantin Belousov  * principle is that the system will 90% forget that the process used
726ccd0ec40SKonstantin Belousov  * a lot of CPU time in 5 * loadav seconds.  This causes the system to
727ccd0ec40SKonstantin Belousov  * favor processes which haven't run much recently, and to round-robin
728ccd0ec40SKonstantin Belousov  * among other processes.
729b43179fbSJeff Roberson  */
730b43179fbSJeff Roberson void
7317cf90fb3SJeff Roberson sched_clock(struct thread *td)
732b43179fbSJeff Roberson {
733b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
734ad1e7d28SJulian Elischer 	struct td_sched *ts;
735b43179fbSJeff Roberson 
7367b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
737*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
738f7f9e7f3SJeff Roberson 
739ad1e7d28SJulian Elischer 	ts->ts_cpticks++;
740ccd0ec40SKonstantin Belousov 	ts->ts_estcpu = ESTCPULIM(ts->ts_estcpu + 1);
741ccd0ec40SKonstantin Belousov 	if ((ts->ts_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
7428460a577SJohn Birrell 		resetpriority(td);
7438460a577SJohn Birrell 		resetpriority_thread(td);
744b43179fbSJeff Roberson 	}
7459dddab6fSJohn Baldwin 
7469dddab6fSJohn Baldwin 	/*
7479dddab6fSJohn Baldwin 	 * Force a context switch if the current thread has used up a full
748579895dfSAlexander Motin 	 * time slice (default is 100ms).
7499dddab6fSJohn Baldwin 	 */
750579895dfSAlexander Motin 	if (!TD_IS_IDLETHREAD(td) && --ts->ts_slice <= 0) {
75148317e9eSAlexander Motin 		ts->ts_slice = sched_slice;
7523d7f4117SAlexander Motin 		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
75348317e9eSAlexander Motin 	}
754b722ad00SAlexander Motin 
755b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
756b722ad00SAlexander Motin 	stat->oldidlecalls = stat->idlecalls;
757b722ad00SAlexander Motin 	stat->idlecalls = 0;
758b43179fbSJeff Roberson }
75970fca427SJohn Baldwin 
7608460a577SJohn Birrell /*
7618aa3d7ffSJohn Baldwin  * Charge child's scheduling CPU usage to parent.
7628460a577SJohn Birrell  */
763b43179fbSJeff Roberson void
76455d44f79SJulian Elischer sched_exit(struct proc *p, struct thread *td)
765f7f9e7f3SJeff Roberson {
7668460a577SJohn Birrell 
7678f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "proc exit",
768cd39bb09SXin LI 	    "prio:%d", td->td_priority);
7698f51ad55SJeff Roberson 
770374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
771ad1e7d28SJulian Elischer 	sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
772b43179fbSJeff Roberson }
773b43179fbSJeff Roberson 
774b43179fbSJeff Roberson void
775f7f9e7f3SJeff Roberson sched_exit_thread(struct thread *td, struct thread *child)
776b43179fbSJeff Roberson {
777ad1e7d28SJulian Elischer 
7788f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "exit",
779cd39bb09SXin LI 	    "prio:%d", child->td_priority);
7807b20fb19SJeff Roberson 	thread_lock(td);
781*93ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_estcpu = ESTCPULIM(td_get_sched(td)->ts_estcpu +
782*93ccd6bfSKonstantin Belousov 	    td_get_sched(child)->ts_estcpu);
7837b20fb19SJeff Roberson 	thread_unlock(td);
7841b9d701fSAttilio Rao 	thread_lock(child);
7851b9d701fSAttilio Rao 	if ((child->td_flags & TDF_NOLOAD) == 0)
786907bdbc2SJeff Roberson 		sched_load_rem();
7871b9d701fSAttilio Rao 	thread_unlock(child);
788f7f9e7f3SJeff Roberson }
789bcb06d59SJeff Roberson 
790f7f9e7f3SJeff Roberson void
791ed062c8dSJulian Elischer sched_fork(struct thread *td, struct thread *childtd)
792f7f9e7f3SJeff Roberson {
793ed062c8dSJulian Elischer 	sched_fork_thread(td, childtd);
794f7f9e7f3SJeff Roberson }
795bcb06d59SJeff Roberson 
796f7f9e7f3SJeff Roberson void
797ed062c8dSJulian Elischer sched_fork_thread(struct thread *td, struct thread *childtd)
798f7f9e7f3SJeff Roberson {
799*93ccd6bfSKonstantin Belousov 	struct td_sched *ts, *tsc;
8008b16c208SJeff Roberson 
80192de34dfSJohn Baldwin 	childtd->td_oncpu = NOCPU;
80292de34dfSJohn Baldwin 	childtd->td_lastcpu = NOCPU;
8037b20fb19SJeff Roberson 	childtd->td_lock = &sched_lock;
804f5a3ef99SMarcel Moolenaar 	childtd->td_cpuset = cpuset_ref(td->td_cpuset);
80522d19207SJohn Baldwin 	childtd->td_priority = childtd->td_base_pri;
806*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(childtd);
8078b16c208SJeff Roberson 	bzero(ts, sizeof(*ts));
808*93ccd6bfSKonstantin Belousov 	tsc = td_get_sched(td);
809*93ccd6bfSKonstantin Belousov 	ts->ts_estcpu = tsc->ts_estcpu;
810*93ccd6bfSKonstantin Belousov 	ts->ts_flags |= (tsc->ts_flags & TSF_AFFINITY);
81148317e9eSAlexander Motin 	ts->ts_slice = 1;
812b43179fbSJeff Roberson }
813b43179fbSJeff Roberson 
814b43179fbSJeff Roberson void
815fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
816b43179fbSJeff Roberson {
817f5c157d9SJohn Baldwin 	struct thread *td;
8180b5318c8SJohn Baldwin 
819fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
820fa885116SJulian Elischer 	p->p_nice = nice;
8218460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
8227b20fb19SJeff Roberson 		thread_lock(td);
8238460a577SJohn Birrell 		resetpriority(td);
8248460a577SJohn Birrell 		resetpriority_thread(td);
8257b20fb19SJeff Roberson 		thread_unlock(td);
8268460a577SJohn Birrell 	}
827fa885116SJulian Elischer }
828b43179fbSJeff Roberson 
829f7f9e7f3SJeff Roberson void
8308460a577SJohn Birrell sched_class(struct thread *td, int class)
831f7f9e7f3SJeff Roberson {
8327b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
8338460a577SJohn Birrell 	td->td_pri_class = class;
834f7f9e7f3SJeff Roberson }
835f7f9e7f3SJeff Roberson 
8368460a577SJohn Birrell /*
8378460a577SJohn Birrell  * Adjust the priority of a thread.
8388460a577SJohn Birrell  */
839f5c157d9SJohn Baldwin static void
840f5c157d9SJohn Baldwin sched_priority(struct thread *td, u_char prio)
841b43179fbSJeff Roberson {
842b43179fbSJeff Roberson 
8438f51ad55SJeff Roberson 
8448f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
8458f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
8468f51ad55SJeff Roberson 	    sched_tdname(curthread));
847d9fae5abSAndriy Gapon 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
8488f51ad55SJeff Roberson 	if (td != curthread && prio > td->td_priority) {
8498f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
8508f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
8518f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
852d9fae5abSAndriy Gapon 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
853b3e9e682SRyan Stone 		    curthread);
8548f51ad55SJeff Roberson 	}
8557b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
856f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
857f5c157d9SJohn Baldwin 		return;
8581f955e2dSJulian Elischer 	td->td_priority = prio;
8599727e637SJeff Roberson 	if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
860f0393f06SJeff Roberson 		sched_rem(td);
861f0393f06SJeff Roberson 		sched_add(td, SRQ_BORING);
862b43179fbSJeff Roberson 	}
863b43179fbSJeff Roberson }
864b43179fbSJeff Roberson 
865f5c157d9SJohn Baldwin /*
866f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
867f5c157d9SJohn Baldwin  * priority.
868f5c157d9SJohn Baldwin  */
869f5c157d9SJohn Baldwin void
870f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
871f5c157d9SJohn Baldwin {
872f5c157d9SJohn Baldwin 
873f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
874f5c157d9SJohn Baldwin 	sched_priority(td, prio);
875f5c157d9SJohn Baldwin }
876f5c157d9SJohn Baldwin 
877f5c157d9SJohn Baldwin /*
878f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
879f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
880f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
881f5c157d9SJohn Baldwin  * requests.  If the thread's regulary priority is less
882f5c157d9SJohn Baldwin  * important than prio the thread will keep a priority boost
883f5c157d9SJohn Baldwin  * of prio.
884f5c157d9SJohn Baldwin  */
885f5c157d9SJohn Baldwin void
886f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
887f5c157d9SJohn Baldwin {
888f5c157d9SJohn Baldwin 	u_char base_pri;
889f5c157d9SJohn Baldwin 
890f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
891f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
8928460a577SJohn Birrell 		base_pri = td->td_user_pri;
893f5c157d9SJohn Baldwin 	else
894f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
895f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
896f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
897f5c157d9SJohn Baldwin 		sched_prio(td, base_pri);
898f5c157d9SJohn Baldwin 	} else
899f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
900f5c157d9SJohn Baldwin }
901f5c157d9SJohn Baldwin 
902f5c157d9SJohn Baldwin void
903f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
904f5c157d9SJohn Baldwin {
905f5c157d9SJohn Baldwin 	u_char oldprio;
906f5c157d9SJohn Baldwin 
907f5c157d9SJohn Baldwin 	/* First, update the base priority. */
908f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
909f5c157d9SJohn Baldwin 
910f5c157d9SJohn Baldwin 	/*
911f5c157d9SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't ever
912f5c157d9SJohn Baldwin 	 * lower the priority.
913f5c157d9SJohn Baldwin 	 */
914f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
915f5c157d9SJohn Baldwin 		return;
916f5c157d9SJohn Baldwin 
917f5c157d9SJohn Baldwin 	/* Change the real priority. */
918f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
919f5c157d9SJohn Baldwin 	sched_priority(td, prio);
920f5c157d9SJohn Baldwin 
921f5c157d9SJohn Baldwin 	/*
922f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
923f5c157d9SJohn Baldwin 	 * its state.
924f5c157d9SJohn Baldwin 	 */
925f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
926f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
927f5c157d9SJohn Baldwin }
928f5c157d9SJohn Baldwin 
929b43179fbSJeff Roberson void
9308460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
9313db720fdSDavid Xu {
9323db720fdSDavid Xu 
933435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
9348460a577SJohn Birrell 	td->td_base_user_pri = prio;
935acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
9365a215147SDavid Xu 		return;
9378460a577SJohn Birrell 	td->td_user_pri = prio;
9383db720fdSDavid Xu }
9393db720fdSDavid Xu 
9403db720fdSDavid Xu void
9413db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
9423db720fdSDavid Xu {
9433db720fdSDavid Xu 
944435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
945acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
946c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
947c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
948c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
949c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
950c8e368a9SDavid Xu 		td->td_flags |= TDF_NEEDRESCHED;
951435806d3SDavid Xu }
9523db720fdSDavid Xu 
9533db720fdSDavid Xu void
954c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int pri)
955b43179fbSJeff Roberson {
9562056d0a1SJohn Baldwin 
9577b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
95854b0e65fSJeff Roberson 	td->td_slptick = ticks;
959*93ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_slptime = 0;
9602dc29adbSJohn Baldwin 	if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
961c5aa6b58SJeff Roberson 		sched_prio(td, pri);
96217c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
963c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
964b43179fbSJeff Roberson }
965b43179fbSJeff Roberson 
966b43179fbSJeff Roberson void
9673389af30SJulian Elischer sched_switch(struct thread *td, struct thread *newtd, int flags)
968b43179fbSJeff Roberson {
969b0b9dee5SAttilio Rao 	struct mtx *tmtx;
970ad1e7d28SJulian Elischer 	struct td_sched *ts;
971b43179fbSJeff Roberson 	struct proc *p;
9723d7f4117SAlexander Motin 	int preempted;
973b43179fbSJeff Roberson 
974b0b9dee5SAttilio Rao 	tmtx = NULL;
975*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
976b43179fbSJeff Roberson 	p = td->td_proc;
977b43179fbSJeff Roberson 
9787b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
9798aa3d7ffSJohn Baldwin 
9807b20fb19SJeff Roberson 	/*
9817b20fb19SJeff Roberson 	 * Switch to the sched lock to fix things up and pick
9827b20fb19SJeff Roberson 	 * a new thread.
983b0b9dee5SAttilio Rao 	 * Block the td_lock in order to avoid breaking the critical path.
9847b20fb19SJeff Roberson 	 */
9857b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
9867b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
987b0b9dee5SAttilio Rao 		tmtx = thread_lock_block(td);
9887b20fb19SJeff Roberson 	}
989b43179fbSJeff Roberson 
9901b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
991907bdbc2SJeff Roberson 		sched_load_rem();
9923389af30SJulian Elischer 
993060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
9942e7d7bb2SAlexander Motin 	preempted = !((td->td_flags & TDF_SLICEEND) ||
9952e7d7bb2SAlexander Motin 	    (flags & SWT_RELINQUISH));
9963d7f4117SAlexander Motin 	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
99777918643SStephan Uphoff 	td->td_owepreempt = 0;
998ca59f152SJeff Roberson 	td->td_oncpu = NOCPU;
9998aa3d7ffSJohn Baldwin 
1000b43179fbSJeff Roberson 	/*
1001b43179fbSJeff Roberson 	 * At the last moment, if this thread is still marked RUNNING,
1002b43179fbSJeff Roberson 	 * then put it back on the run queue as it has not been suspended
1003bf0acc27SJohn Baldwin 	 * or stopped or any thing else similar.  We never put the idle
1004bf0acc27SJohn Baldwin 	 * threads on the run queue, however.
1005b43179fbSJeff Roberson 	 */
1006c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD) {
1007bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
1008c6226eeaSJulian Elischer #ifdef SMP
1009a38f1f26SAttilio Rao 		CPU_CLR(PCPU_GET(cpuid), &idle_cpus_mask);
1010c6226eeaSJulian Elischer #endif
1011c6226eeaSJulian Elischer 	} else {
1012ed062c8dSJulian Elischer 		if (TD_IS_RUNNING(td)) {
1013ad1e7d28SJulian Elischer 			/* Put us back on the run queue. */
10143d7f4117SAlexander Motin 			sched_add(td, preempted ?
1015c20c691bSJulian Elischer 			    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1016c20c691bSJulian Elischer 			    SRQ_OURSELF|SRQ_YIELDING);
1017ed062c8dSJulian Elischer 		}
1018b43179fbSJeff Roberson 	}
1019c20c691bSJulian Elischer 	if (newtd) {
1020c20c691bSJulian Elischer 		/*
1021c20c691bSJulian Elischer 		 * The thread we are about to run needs to be counted
1022c20c691bSJulian Elischer 		 * as if it had been added to the run queue and selected.
1023c20c691bSJulian Elischer 		 * It came from:
1024c20c691bSJulian Elischer 		 * * A preemption
1025c20c691bSJulian Elischer 		 * * An upcall
1026c20c691bSJulian Elischer 		 * * A followon
1027c20c691bSJulian Elischer 		 */
1028c20c691bSJulian Elischer 		KASSERT((newtd->td_inhibitors == 0),
10292da78e38SRobert Watson 			("trying to run inhibited thread"));
10309727e637SJeff Roberson 		newtd->td_flags |= TDF_DIDRUN;
1031c20c691bSJulian Elischer         	TD_SET_RUNNING(newtd);
10321b9d701fSAttilio Rao 		if ((newtd->td_flags & TDF_NOLOAD) == 0)
1033907bdbc2SJeff Roberson 			sched_load_add();
1034c20c691bSJulian Elischer 	} else {
1035ae53b483SJeff Roberson 		newtd = choosethread();
10367b20fb19SJeff Roberson 		MPASS(newtd->td_lock == &sched_lock);
103758060789SAttilio Rao 	}
1038c20c691bSJulian Elischer 
1039ebccf1e3SJoseph Koshy 	if (td != newtd) {
1040ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1041ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1042ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1043ebccf1e3SJoseph Koshy #endif
1044b3e9e682SRyan Stone 
10457dba7849SMark Johnston 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1046b3e9e682SRyan Stone 
1047c6226eeaSJulian Elischer                 /* I feel sleepy */
1048eea4f254SJeff Roberson 		lock_profile_release_lock(&sched_lock.lock_object);
10496f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
10506f5f25e5SJohn Birrell 		/*
10516f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
10526f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
10536f5f25e5SJohn Birrell 		 * function to call.
10546f5f25e5SJohn Birrell 		 */
10556f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
10566f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
10576f5f25e5SJohn Birrell #endif
10586f5f25e5SJohn Birrell 
1059b0b9dee5SAttilio Rao 		cpu_switch(td, newtd, tmtx != NULL ? tmtx : td->td_lock);
1060eea4f254SJeff Roberson 		lock_profile_obtain_lock_success(&sched_lock.lock_object,
1061eea4f254SJeff Roberson 		    0, 0, __FILE__, __LINE__);
1062c6226eeaSJulian Elischer 		/*
1063c6226eeaSJulian Elischer 		 * Where am I?  What year is it?
1064c6226eeaSJulian Elischer 		 * We are in the same thread that went to sleep above,
10658aa3d7ffSJohn Baldwin 		 * but any amount of time may have passed. All our context
1066c6226eeaSJulian Elischer 		 * will still be available as will local variables.
1067c6226eeaSJulian Elischer 		 * PCPU values however may have changed as we may have
1068c6226eeaSJulian Elischer 		 * changed CPU so don't trust cached values of them.
1069c6226eeaSJulian Elischer 		 * New threads will go to fork_exit() instead of here
1070c6226eeaSJulian Elischer 		 * so if you change things here you may need to change
1071c6226eeaSJulian Elischer 		 * things there too.
10728aa3d7ffSJohn Baldwin 		 *
1073c6226eeaSJulian Elischer 		 * If the thread above was exiting it will never wake
1074c6226eeaSJulian Elischer 		 * up again here, so either it has saved everything it
1075c6226eeaSJulian Elischer 		 * needed to, or the thread_wait() or wait() will
1076c6226eeaSJulian Elischer 		 * need to reap it.
1077c6226eeaSJulian Elischer 		 */
1078b3e9e682SRyan Stone 
1079d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , on__cpu);
1080ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1081ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1082ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1083ebccf1e3SJoseph Koshy #endif
1084b3e9e682SRyan Stone 	} else
1085d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , remain__cpu);
1086ebccf1e3SJoseph Koshy 
1087c6226eeaSJulian Elischer #ifdef SMP
1088c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD)
1089a38f1f26SAttilio Rao 		CPU_SET(PCPU_GET(cpuid), &idle_cpus_mask);
1090c6226eeaSJulian Elischer #endif
1091ae53b483SJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
1092ae53b483SJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
10937b20fb19SJeff Roberson 	MPASS(td->td_lock == &sched_lock);
1094b43179fbSJeff Roberson }
1095b43179fbSJeff Roberson 
1096b43179fbSJeff Roberson void
1097b43179fbSJeff Roberson sched_wakeup(struct thread *td)
1098b43179fbSJeff Roberson {
109954b0e65fSJeff Roberson 	struct td_sched *ts;
110054b0e65fSJeff Roberson 
11017b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1102*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1103c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
110454b0e65fSJeff Roberson 	if (ts->ts_slptime > 1) {
11058460a577SJohn Birrell 		updatepri(td);
11068460a577SJohn Birrell 		resetpriority(td);
11078460a577SJohn Birrell 	}
11086eac7e57SAttilio Rao 	td->td_slptick = 0;
110954b0e65fSJeff Roberson 	ts->ts_slptime = 0;
111048317e9eSAlexander Motin 	ts->ts_slice = sched_slice;
1111f0393f06SJeff Roberson 	sched_add(td, SRQ_BORING);
1112b43179fbSJeff Roberson }
1113b43179fbSJeff Roberson 
111437c28a02SJulian Elischer #ifdef SMP
111582a1dfc1SJulian Elischer static int
111682a1dfc1SJulian Elischer forward_wakeup(int cpunum)
111782a1dfc1SJulian Elischer {
111882a1dfc1SJulian Elischer 	struct pcpu *pc;
1119a38f1f26SAttilio Rao 	cpuset_t dontuse, map, map2;
1120a38f1f26SAttilio Rao 	u_int id, me;
112171a19bdcSAttilio Rao 	int iscpuset;
112282a1dfc1SJulian Elischer 
112382a1dfc1SJulian Elischer 	mtx_assert(&sched_lock, MA_OWNED);
112482a1dfc1SJulian Elischer 
1125ed062c8dSJulian Elischer 	CTR0(KTR_RUNQ, "forward_wakeup()");
112682a1dfc1SJulian Elischer 
112782a1dfc1SJulian Elischer 	if ((!forward_wakeup_enabled) ||
112882a1dfc1SJulian Elischer 	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
112982a1dfc1SJulian Elischer 		return (0);
113082a1dfc1SJulian Elischer 	if (!smp_started || cold || panicstr)
113182a1dfc1SJulian Elischer 		return (0);
113282a1dfc1SJulian Elischer 
113382a1dfc1SJulian Elischer 	forward_wakeups_requested++;
113482a1dfc1SJulian Elischer 
113582a1dfc1SJulian Elischer 	/*
11368aa3d7ffSJohn Baldwin 	 * Check the idle mask we received against what we calculated
11378aa3d7ffSJohn Baldwin 	 * before in the old version.
113882a1dfc1SJulian Elischer 	 */
1139a38f1f26SAttilio Rao 	me = PCPU_GET(cpuid);
11408aa3d7ffSJohn Baldwin 
11418aa3d7ffSJohn Baldwin 	/* Don't bother if we should be doing it ourself. */
1142a38f1f26SAttilio Rao 	if (CPU_ISSET(me, &idle_cpus_mask) &&
1143a38f1f26SAttilio Rao 	    (cpunum == NOCPU || me == cpunum))
114482a1dfc1SJulian Elischer 		return (0);
114582a1dfc1SJulian Elischer 
1146a38f1f26SAttilio Rao 	CPU_SETOF(me, &dontuse);
114771a19bdcSAttilio Rao 	CPU_OR(&dontuse, &stopped_cpus);
114871a19bdcSAttilio Rao 	CPU_OR(&dontuse, &hlt_cpus_mask);
114971a19bdcSAttilio Rao 	CPU_ZERO(&map2);
115082a1dfc1SJulian Elischer 	if (forward_wakeup_use_loop) {
1151d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1152a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1153a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &dontuse) &&
115482a1dfc1SJulian Elischer 			    pc->pc_curthread == pc->pc_idlethread) {
1155a38f1f26SAttilio Rao 				CPU_SET(id, &map2);
115682a1dfc1SJulian Elischer 			}
115782a1dfc1SJulian Elischer 		}
115882a1dfc1SJulian Elischer 	}
115982a1dfc1SJulian Elischer 
116082a1dfc1SJulian Elischer 	if (forward_wakeup_use_mask) {
116171a19bdcSAttilio Rao 		map = idle_cpus_mask;
116271a19bdcSAttilio Rao 		CPU_NAND(&map, &dontuse);
116382a1dfc1SJulian Elischer 
11648aa3d7ffSJohn Baldwin 		/* If they are both on, compare and use loop if different. */
116582a1dfc1SJulian Elischer 		if (forward_wakeup_use_loop) {
116671a19bdcSAttilio Rao 			if (CPU_CMP(&map, &map2)) {
1167f0283a73SAttilio Rao 				printf("map != map2, loop method preferred\n");
1168f0283a73SAttilio Rao 				map = map2;
116982a1dfc1SJulian Elischer 			}
117082a1dfc1SJulian Elischer 		}
117182a1dfc1SJulian Elischer 	} else {
1172f0283a73SAttilio Rao 		map = map2;
117382a1dfc1SJulian Elischer 	}
11748aa3d7ffSJohn Baldwin 
11758aa3d7ffSJohn Baldwin 	/* If we only allow a specific CPU, then mask off all the others. */
117682a1dfc1SJulian Elischer 	if (cpunum != NOCPU) {
117782a1dfc1SJulian Elischer 		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
117871a19bdcSAttilio Rao 		iscpuset = CPU_ISSET(cpunum, &map);
117971a19bdcSAttilio Rao 		if (iscpuset == 0)
118071a19bdcSAttilio Rao 			CPU_ZERO(&map);
118171a19bdcSAttilio Rao 		else
118271a19bdcSAttilio Rao 			CPU_SETOF(cpunum, &map);
118382a1dfc1SJulian Elischer 	}
118471a19bdcSAttilio Rao 	if (!CPU_EMPTY(&map)) {
118582a1dfc1SJulian Elischer 		forward_wakeups_delivered++;
1186d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1187a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1188a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &map))
1189b722ad00SAlexander Motin 				continue;
1190b722ad00SAlexander Motin 			if (cpu_idle_wakeup(pc->pc_cpuid))
1191a38f1f26SAttilio Rao 				CPU_CLR(id, &map);
1192b722ad00SAlexander Motin 		}
119371a19bdcSAttilio Rao 		if (!CPU_EMPTY(&map))
119482a1dfc1SJulian Elischer 			ipi_selected(map, IPI_AST);
119582a1dfc1SJulian Elischer 		return (1);
119682a1dfc1SJulian Elischer 	}
119782a1dfc1SJulian Elischer 	if (cpunum == NOCPU)
119882a1dfc1SJulian Elischer 		printf("forward_wakeup: Idle processor not found\n");
119982a1dfc1SJulian Elischer 	return (0);
120082a1dfc1SJulian Elischer }
1201f3a0f873SStephan Uphoff 
1202f3a0f873SStephan Uphoff static void
1203f3a0f873SStephan Uphoff kick_other_cpu(int pri, int cpuid)
1204f3a0f873SStephan Uphoff {
12058aa3d7ffSJohn Baldwin 	struct pcpu *pcpu;
12068aa3d7ffSJohn Baldwin 	int cpri;
1207f3a0f873SStephan Uphoff 
12088aa3d7ffSJohn Baldwin 	pcpu = pcpu_find(cpuid);
1209a38f1f26SAttilio Rao 	if (CPU_ISSET(cpuid, &idle_cpus_mask)) {
1210f3a0f873SStephan Uphoff 		forward_wakeups_delivered++;
1211b722ad00SAlexander Motin 		if (!cpu_idle_wakeup(cpuid))
1212d9d8d144SJohn Baldwin 			ipi_cpu(cpuid, IPI_AST);
1213f3a0f873SStephan Uphoff 		return;
1214f3a0f873SStephan Uphoff 	}
1215f3a0f873SStephan Uphoff 
12168aa3d7ffSJohn Baldwin 	cpri = pcpu->pc_curthread->td_priority;
1217f3a0f873SStephan Uphoff 	if (pri >= cpri)
1218f3a0f873SStephan Uphoff 		return;
1219f3a0f873SStephan Uphoff 
1220f3a0f873SStephan Uphoff #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1221f3a0f873SStephan Uphoff #if !defined(FULL_PREEMPTION)
1222f3a0f873SStephan Uphoff 	if (pri <= PRI_MAX_ITHD)
1223f3a0f873SStephan Uphoff #endif /* ! FULL_PREEMPTION */
1224f3a0f873SStephan Uphoff 	{
1225d9d8d144SJohn Baldwin 		ipi_cpu(cpuid, IPI_PREEMPT);
1226f3a0f873SStephan Uphoff 		return;
1227f3a0f873SStephan Uphoff 	}
1228f3a0f873SStephan Uphoff #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1229f3a0f873SStephan Uphoff 
1230f3a0f873SStephan Uphoff 	pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1231d9d8d144SJohn Baldwin 	ipi_cpu(cpuid, IPI_AST);
1232f3a0f873SStephan Uphoff 	return;
1233f3a0f873SStephan Uphoff }
1234f3a0f873SStephan Uphoff #endif /* SMP */
1235f3a0f873SStephan Uphoff 
1236f200843bSJohn Baldwin #ifdef SMP
1237f200843bSJohn Baldwin static int
1238f200843bSJohn Baldwin sched_pickcpu(struct thread *td)
1239f200843bSJohn Baldwin {
1240f200843bSJohn Baldwin 	int best, cpu;
1241f200843bSJohn Baldwin 
1242f200843bSJohn Baldwin 	mtx_assert(&sched_lock, MA_OWNED);
1243f200843bSJohn Baldwin 
1244c3ea3378SJohn Baldwin 	if (THREAD_CAN_SCHED(td, td->td_lastcpu))
1245c3ea3378SJohn Baldwin 		best = td->td_lastcpu;
1246c3ea3378SJohn Baldwin 	else
1247f200843bSJohn Baldwin 		best = NOCPU;
12483aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1249f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu))
1250f200843bSJohn Baldwin 			continue;
1251f200843bSJohn Baldwin 
1252f200843bSJohn Baldwin 		if (best == NOCPU)
1253f200843bSJohn Baldwin 			best = cpu;
1254f200843bSJohn Baldwin 		else if (runq_length[cpu] < runq_length[best])
1255f200843bSJohn Baldwin 			best = cpu;
1256f200843bSJohn Baldwin 	}
1257f200843bSJohn Baldwin 	KASSERT(best != NOCPU, ("no valid CPUs"));
1258f200843bSJohn Baldwin 
1259f200843bSJohn Baldwin 	return (best);
1260f200843bSJohn Baldwin }
1261f200843bSJohn Baldwin #endif
1262f200843bSJohn Baldwin 
1263b43179fbSJeff Roberson void
12642630e4c9SJulian Elischer sched_add(struct thread *td, int flags)
12656804a3abSJulian Elischer #ifdef SMP
1266f3a0f873SStephan Uphoff {
1267a38f1f26SAttilio Rao 	cpuset_t tidlemsk;
1268ad1e7d28SJulian Elischer 	struct td_sched *ts;
1269a38f1f26SAttilio Rao 	u_int cpu, cpuid;
12706804a3abSJulian Elischer 	int forwarded = 0;
1271f3a0f873SStephan Uphoff 	int single_cpu = 0;
12727cf90fb3SJeff Roberson 
1273*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
12747b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1275f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1276f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1277f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1278f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1279b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1280b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
12818f51ad55SJeff Roberson 
12828f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
12838f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
12848f51ad55SJeff Roberson 	    sched_tdname(curthread));
12858f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
12868f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
1287b3e9e682SRyan Stone 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1288b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
12898f51ad55SJeff Roberson 
12908aa3d7ffSJohn Baldwin 
12917b20fb19SJeff Roberson 	/*
12927b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
12937b20fb19SJeff Roberson 	 * to the scheduler's lock.
12947b20fb19SJeff Roberson 	 */
12957b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
12967b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
12977b20fb19SJeff Roberson 		thread_lock_set(td, &sched_lock);
12987b20fb19SJeff Roberson 	}
1299f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1300f3a0f873SStephan Uphoff 
130160dd73b7SRyan Stone 	/*
130260dd73b7SRyan Stone 	 * If SMP is started and the thread is pinned or otherwise limited to
130360dd73b7SRyan Stone 	 * a specific set of CPUs, queue the thread to a per-CPU run queue.
130460dd73b7SRyan Stone 	 * Otherwise, queue the thread to the global run queue.
130560dd73b7SRyan Stone 	 *
130660dd73b7SRyan Stone 	 * If SMP has not yet been started we must use the global run queue
130760dd73b7SRyan Stone 	 * as per-CPU state may not be initialized yet and we may crash if we
130860dd73b7SRyan Stone 	 * try to access the per-CPU run queues.
130960dd73b7SRyan Stone 	 */
131060dd73b7SRyan Stone 	if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
131160dd73b7SRyan Stone 	    ts->ts_flags & TSF_AFFINITY)) {
131260dd73b7SRyan Stone 		if (td->td_pinned != 0)
1313f3a0f873SStephan Uphoff 			cpu = td->td_lastcpu;
131460dd73b7SRyan Stone 		else if (td->td_flags & TDF_BOUND) {
13158aa3d7ffSJohn Baldwin 			/* Find CPU from bound runq. */
13168aa3d7ffSJohn Baldwin 			KASSERT(SKE_RUNQ_PCPU(ts),
13178aa3d7ffSJohn Baldwin 			    ("sched_add: bound td_sched not on cpu runq"));
1318ad1e7d28SJulian Elischer 			cpu = ts->ts_runq - &runq_pcpu[0];
131960dd73b7SRyan Stone 		} else
1320f200843bSJohn Baldwin 			/* Find a valid CPU for our cpuset */
1321f200843bSJohn Baldwin 			cpu = sched_pickcpu(td);
1322f200843bSJohn Baldwin 		ts->ts_runq = &runq_pcpu[cpu];
1323f200843bSJohn Baldwin 		single_cpu = 1;
1324f200843bSJohn Baldwin 		CTR3(KTR_RUNQ,
1325f200843bSJohn Baldwin 		    "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1326f200843bSJohn Baldwin 		    cpu);
1327f3a0f873SStephan Uphoff 	} else {
13286804a3abSJulian Elischer 		CTR2(KTR_RUNQ,
13298aa3d7ffSJohn Baldwin 		    "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
13308aa3d7ffSJohn Baldwin 		    td);
13316804a3abSJulian Elischer 		cpu = NOCPU;
1332ad1e7d28SJulian Elischer 		ts->ts_runq = &runq;
1333e17c57b1SJeff Roberson 	}
1334f3a0f873SStephan Uphoff 
1335a38f1f26SAttilio Rao 	cpuid = PCPU_GET(cpuid);
1336a38f1f26SAttilio Rao 	if (single_cpu && cpu != cpuid) {
1337f3a0f873SStephan Uphoff 	        kick_other_cpu(td->td_priority, cpu);
1338f3a0f873SStephan Uphoff 	} else {
1339f3a0f873SStephan Uphoff 		if (!single_cpu) {
1340a38f1f26SAttilio Rao 			tidlemsk = idle_cpus_mask;
1341a38f1f26SAttilio Rao 			CPU_NAND(&tidlemsk, &hlt_cpus_mask);
1342a38f1f26SAttilio Rao 			CPU_CLR(cpuid, &tidlemsk);
1343f3a0f873SStephan Uphoff 
1344a38f1f26SAttilio Rao 			if (!CPU_ISSET(cpuid, &idle_cpus_mask) &&
1345a38f1f26SAttilio Rao 			    ((flags & SRQ_INTR) == 0) &&
134671a19bdcSAttilio Rao 			    !CPU_EMPTY(&tidlemsk))
1347f3a0f873SStephan Uphoff 				forwarded = forward_wakeup(cpu);
1348f3a0f873SStephan Uphoff 		}
1349f3a0f873SStephan Uphoff 
1350f3a0f873SStephan Uphoff 		if (!forwarded) {
1351a3f2d842SStephan Uphoff 			if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1352f3a0f873SStephan Uphoff 				return;
1353f3a0f873SStephan Uphoff 			else
1354f3a0f873SStephan Uphoff 				maybe_resched(td);
1355f3a0f873SStephan Uphoff 		}
1356f3a0f873SStephan Uphoff 	}
1357f3a0f873SStephan Uphoff 
13581b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1359f3a0f873SStephan Uphoff 		sched_load_add();
13609727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
1361f200843bSJohn Baldwin 	if (cpu != NOCPU)
1362f200843bSJohn Baldwin 		runq_length[cpu]++;
1363f3a0f873SStephan Uphoff }
1364f3a0f873SStephan Uphoff #else /* SMP */
1365f3a0f873SStephan Uphoff {
1366ad1e7d28SJulian Elischer 	struct td_sched *ts;
1367f200843bSJohn Baldwin 
1368*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
13697b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1370f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1371f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1372f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1373f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1374b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1375b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
13768f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
13778f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
13788f51ad55SJeff Roberson 	    sched_tdname(curthread));
13798f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
13808f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
13812aaae99dSSergey Kandaurov 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1382b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
13838aa3d7ffSJohn Baldwin 
13847b20fb19SJeff Roberson 	/*
13857b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
13867b20fb19SJeff Roberson 	 * to the scheduler's lock.
13877b20fb19SJeff Roberson 	 */
13887b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
13897b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
13907b20fb19SJeff Roberson 		thread_lock_set(td, &sched_lock);
13917b20fb19SJeff Roberson 	}
1392f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1393ad1e7d28SJulian Elischer 	CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1394ad1e7d28SJulian Elischer 	ts->ts_runq = &runq;
13956804a3abSJulian Elischer 
13966804a3abSJulian Elischer 	/*
13978aa3d7ffSJohn Baldwin 	 * If we are yielding (on the way out anyhow) or the thread
13988aa3d7ffSJohn Baldwin 	 * being saved is US, then don't try be smart about preemption
13998aa3d7ffSJohn Baldwin 	 * or kicking off another CPU as it won't help and may hinder.
14008aa3d7ffSJohn Baldwin 	 * In the YIEDLING case, we are about to run whoever is being
14018aa3d7ffSJohn Baldwin 	 * put in the queue anyhow, and in the OURSELF case, we are
1402e3043798SPedro F. Giffuni 	 * putting ourself on the run queue which also only happens
14038aa3d7ffSJohn Baldwin 	 * when we are about to yield.
14046804a3abSJulian Elischer 	 */
14056804a3abSJulian Elischer 	if ((flags & SRQ_YIELDING) == 0) {
14066804a3abSJulian Elischer 		if (maybe_preempt(td))
14076804a3abSJulian Elischer 			return;
14086804a3abSJulian Elischer 	}
14091b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1410907bdbc2SJeff Roberson 		sched_load_add();
14119727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
14126942d433SJohn Baldwin 	maybe_resched(td);
1413b43179fbSJeff Roberson }
1414f3a0f873SStephan Uphoff #endif /* SMP */
1415f3a0f873SStephan Uphoff 
1416b43179fbSJeff Roberson void
14177cf90fb3SJeff Roberson sched_rem(struct thread *td)
1418b43179fbSJeff Roberson {
1419ad1e7d28SJulian Elischer 	struct td_sched *ts;
14207cf90fb3SJeff Roberson 
1421*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1422b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1423b61ce5b0SJeff Roberson 	    ("sched_rem: thread swapped out"));
1424f0393f06SJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
1425ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
1426b43179fbSJeff Roberson 	mtx_assert(&sched_lock, MA_OWNED);
14278f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
14288f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
14298f51ad55SJeff Roberson 	    sched_tdname(curthread));
1430b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
1431b43179fbSJeff Roberson 
14321b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1433907bdbc2SJeff Roberson 		sched_load_rem();
1434f200843bSJohn Baldwin #ifdef SMP
1435f200843bSJohn Baldwin 	if (ts->ts_runq != &runq)
1436f200843bSJohn Baldwin 		runq_length[ts->ts_runq - runq_pcpu]--;
1437f200843bSJohn Baldwin #endif
14389727e637SJeff Roberson 	runq_remove(ts->ts_runq, td);
1439f0393f06SJeff Roberson 	TD_SET_CAN_RUN(td);
1440b43179fbSJeff Roberson }
1441b43179fbSJeff Roberson 
144214f0e2e9SJulian Elischer /*
14438aa3d7ffSJohn Baldwin  * Select threads to run.  Note that running threads still consume a
14448aa3d7ffSJohn Baldwin  * slot.
144514f0e2e9SJulian Elischer  */
1446f0393f06SJeff Roberson struct thread *
1447b43179fbSJeff Roberson sched_choose(void)
1448b43179fbSJeff Roberson {
14499727e637SJeff Roberson 	struct thread *td;
1450e17c57b1SJeff Roberson 	struct runq *rq;
1451b43179fbSJeff Roberson 
14527b20fb19SJeff Roberson 	mtx_assert(&sched_lock,  MA_OWNED);
1453e17c57b1SJeff Roberson #ifdef SMP
14549727e637SJeff Roberson 	struct thread *tdcpu;
1455e17c57b1SJeff Roberson 
1456e17c57b1SJeff Roberson 	rq = &runq;
14579727e637SJeff Roberson 	td = runq_choose_fuzz(&runq, runq_fuzz);
14589727e637SJeff Roberson 	tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1459e17c57b1SJeff Roberson 
14609727e637SJeff Roberson 	if (td == NULL ||
14619727e637SJeff Roberson 	    (tdcpu != NULL &&
14629727e637SJeff Roberson 	     tdcpu->td_priority < td->td_priority)) {
14639727e637SJeff Roberson 		CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1464e17c57b1SJeff Roberson 		     PCPU_GET(cpuid));
14659727e637SJeff Roberson 		td = tdcpu;
1466e17c57b1SJeff Roberson 		rq = &runq_pcpu[PCPU_GET(cpuid)];
1467e17c57b1SJeff Roberson 	} else {
14689727e637SJeff Roberson 		CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1469e17c57b1SJeff Roberson 	}
1470e17c57b1SJeff Roberson 
1471e17c57b1SJeff Roberson #else
1472e17c57b1SJeff Roberson 	rq = &runq;
14739727e637SJeff Roberson 	td = runq_choose(&runq);
1474e17c57b1SJeff Roberson #endif
1475b43179fbSJeff Roberson 
14769727e637SJeff Roberson 	if (td) {
1477f200843bSJohn Baldwin #ifdef SMP
1478f200843bSJohn Baldwin 		if (td == tdcpu)
1479f200843bSJohn Baldwin 			runq_length[PCPU_GET(cpuid)]--;
1480f200843bSJohn Baldwin #endif
14819727e637SJeff Roberson 		runq_remove(rq, td);
14829727e637SJeff Roberson 		td->td_flags |= TDF_DIDRUN;
1483b43179fbSJeff Roberson 
14849727e637SJeff Roberson 		KASSERT(td->td_flags & TDF_INMEM,
1485b61ce5b0SJeff Roberson 		    ("sched_choose: thread swapped out"));
14869727e637SJeff Roberson 		return (td);
1487b43179fbSJeff Roberson 	}
1488f0393f06SJeff Roberson 	return (PCPU_GET(idlethread));
1489b43179fbSJeff Roberson }
1490b43179fbSJeff Roberson 
1491b43179fbSJeff Roberson void
14921e24c28fSJeff Roberson sched_preempt(struct thread *td)
14931e24c28fSJeff Roberson {
1494b3e9e682SRyan Stone 
1495b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
14961e24c28fSJeff Roberson 	thread_lock(td);
14971e24c28fSJeff Roberson 	if (td->td_critnest > 1)
14981e24c28fSJeff Roberson 		td->td_owepreempt = 1;
14991e24c28fSJeff Roberson 	else
15008df78c41SJeff Roberson 		mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, NULL);
15011e24c28fSJeff Roberson 	thread_unlock(td);
15021e24c28fSJeff Roberson }
15031e24c28fSJeff Roberson 
15041e24c28fSJeff Roberson void
1505b43179fbSJeff Roberson sched_userret(struct thread *td)
1506b43179fbSJeff Roberson {
1507b43179fbSJeff Roberson 	/*
1508b43179fbSJeff Roberson 	 * XXX we cheat slightly on the locking here to avoid locking in
1509b43179fbSJeff Roberson 	 * the usual case.  Setting td_priority here is essentially an
1510b43179fbSJeff Roberson 	 * incomplete workaround for not setting it properly elsewhere.
1511b43179fbSJeff Roberson 	 * Now that some interrupt handlers are threads, not setting it
1512b43179fbSJeff Roberson 	 * properly elsewhere can clobber it in the window between setting
1513b43179fbSJeff Roberson 	 * it here and returning to user mode, so don't waste time setting
1514b43179fbSJeff Roberson 	 * it perfectly here.
1515b43179fbSJeff Roberson 	 */
1516f5c157d9SJohn Baldwin 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
1517f5c157d9SJohn Baldwin 	    ("thread with borrowed priority returning to userland"));
15188460a577SJohn Birrell 	if (td->td_priority != td->td_user_pri) {
15197b20fb19SJeff Roberson 		thread_lock(td);
15208460a577SJohn Birrell 		td->td_priority = td->td_user_pri;
15218460a577SJohn Birrell 		td->td_base_pri = td->td_user_pri;
15227b20fb19SJeff Roberson 		thread_unlock(td);
15238460a577SJohn Birrell 	}
1524b43179fbSJeff Roberson }
1525de028f5aSJeff Roberson 
1526e17c57b1SJeff Roberson void
1527e17c57b1SJeff Roberson sched_bind(struct thread *td, int cpu)
1528e17c57b1SJeff Roberson {
1529ad1e7d28SJulian Elischer 	struct td_sched *ts;
1530e17c57b1SJeff Roberson 
15311d7830edSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
15321d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1533e17c57b1SJeff Roberson 
1534*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1535e17c57b1SJeff Roberson 
15369727e637SJeff Roberson 	td->td_flags |= TDF_BOUND;
1537e17c57b1SJeff Roberson #ifdef SMP
1538ad1e7d28SJulian Elischer 	ts->ts_runq = &runq_pcpu[cpu];
1539e17c57b1SJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
1540e17c57b1SJeff Roberson 		return;
1541e17c57b1SJeff Roberson 
1542bf0acc27SJohn Baldwin 	mi_switch(SW_VOL, NULL);
1543e17c57b1SJeff Roberson #endif
1544e17c57b1SJeff Roberson }
1545e17c57b1SJeff Roberson 
1546e17c57b1SJeff Roberson void
1547e17c57b1SJeff Roberson sched_unbind(struct thread* td)
1548e17c57b1SJeff Roberson {
15497b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
15501d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
15519727e637SJeff Roberson 	td->td_flags &= ~TDF_BOUND;
1552e17c57b1SJeff Roberson }
1553e17c57b1SJeff Roberson 
1554de028f5aSJeff Roberson int
1555ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
1556ebccf1e3SJoseph Koshy {
15577b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
15589727e637SJeff Roberson 	return (td->td_flags & TDF_BOUND);
1559ebccf1e3SJoseph Koshy }
1560ebccf1e3SJoseph Koshy 
156136ec198bSDavid Xu void
156236ec198bSDavid Xu sched_relinquish(struct thread *td)
156336ec198bSDavid Xu {
15647b20fb19SJeff Roberson 	thread_lock(td);
15658df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
15667b20fb19SJeff Roberson 	thread_unlock(td);
156736ec198bSDavid Xu }
156836ec198bSDavid Xu 
1569ebccf1e3SJoseph Koshy int
1570ca59f152SJeff Roberson sched_load(void)
1571ca59f152SJeff Roberson {
1572ca59f152SJeff Roberson 	return (sched_tdcnt);
1573ca59f152SJeff Roberson }
1574ca59f152SJeff Roberson 
1575de028f5aSJeff Roberson int
1576de028f5aSJeff Roberson sched_sizeof_proc(void)
1577de028f5aSJeff Roberson {
1578de028f5aSJeff Roberson 	return (sizeof(struct proc));
1579de028f5aSJeff Roberson }
158036ec198bSDavid Xu 
1581de028f5aSJeff Roberson int
1582de028f5aSJeff Roberson sched_sizeof_thread(void)
1583de028f5aSJeff Roberson {
1584ad1e7d28SJulian Elischer 	return (sizeof(struct thread) + sizeof(struct td_sched));
1585de028f5aSJeff Roberson }
158679acfc49SJeff Roberson 
158779acfc49SJeff Roberson fixpt_t
15887cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
158979acfc49SJeff Roberson {
1590ad1e7d28SJulian Elischer 	struct td_sched *ts;
159155f2099aSJeff Roberson 
15923da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1593*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1594ad1e7d28SJulian Elischer 	return (ts->ts_pctcpu);
159579acfc49SJeff Roberson }
1596b41f1452SDavid Xu 
159736af9869SEdward Tomasz Napierala #ifdef RACCT
159836af9869SEdward Tomasz Napierala /*
159936af9869SEdward Tomasz Napierala  * Calculates the contribution to the thread cpu usage for the latest
160036af9869SEdward Tomasz Napierala  * (unfinished) second.
160136af9869SEdward Tomasz Napierala  */
160236af9869SEdward Tomasz Napierala fixpt_t
160336af9869SEdward Tomasz Napierala sched_pctcpu_delta(struct thread *td)
160436af9869SEdward Tomasz Napierala {
160536af9869SEdward Tomasz Napierala 	struct td_sched *ts;
160636af9869SEdward Tomasz Napierala 	fixpt_t delta;
160736af9869SEdward Tomasz Napierala 	int realstathz;
160836af9869SEdward Tomasz Napierala 
160936af9869SEdward Tomasz Napierala 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1610*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
161136af9869SEdward Tomasz Napierala 	delta = 0;
161236af9869SEdward Tomasz Napierala 	realstathz = stathz ? stathz : hz;
161336af9869SEdward Tomasz Napierala 	if (ts->ts_cpticks != 0) {
161436af9869SEdward Tomasz Napierala #if	(FSHIFT >= CCPU_SHIFT)
161536af9869SEdward Tomasz Napierala 		delta = (realstathz == 100)
161636af9869SEdward Tomasz Napierala 		    ? ((fixpt_t) ts->ts_cpticks) <<
161736af9869SEdward Tomasz Napierala 		    (FSHIFT - CCPU_SHIFT) :
161836af9869SEdward Tomasz Napierala 		    100 * (((fixpt_t) ts->ts_cpticks)
161936af9869SEdward Tomasz Napierala 		    << (FSHIFT - CCPU_SHIFT)) / realstathz;
162036af9869SEdward Tomasz Napierala #else
162136af9869SEdward Tomasz Napierala 		delta = ((FSCALE - ccpu) *
162236af9869SEdward Tomasz Napierala 		    (ts->ts_cpticks *
162336af9869SEdward Tomasz Napierala 		    FSCALE / realstathz)) >> FSHIFT;
162436af9869SEdward Tomasz Napierala #endif
162536af9869SEdward Tomasz Napierala 	}
162636af9869SEdward Tomasz Napierala 
162736af9869SEdward Tomasz Napierala 	return (delta);
162836af9869SEdward Tomasz Napierala }
162936af9869SEdward Tomasz Napierala #endif
163036af9869SEdward Tomasz Napierala 
1631ccd0ec40SKonstantin Belousov u_int
1632ccd0ec40SKonstantin Belousov sched_estcpu(struct thread *td)
1633b41f1452SDavid Xu {
1634ccd0ec40SKonstantin Belousov 
1635*93ccd6bfSKonstantin Belousov 	return (td_get_sched(td)->ts_estcpu);
1636b41f1452SDavid Xu }
1637f0393f06SJeff Roberson 
1638f0393f06SJeff Roberson /*
1639f0393f06SJeff Roberson  * The actual idle process.
1640f0393f06SJeff Roberson  */
1641f0393f06SJeff Roberson void
1642f0393f06SJeff Roberson sched_idletd(void *dummy)
1643f0393f06SJeff Roberson {
1644b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
1645f0393f06SJeff Roberson 
1646ba96d2d8SJohn Baldwin 	THREAD_NO_SLEEPING();
1647b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
1648f0393f06SJeff Roberson 	for (;;) {
1649f0393f06SJeff Roberson 		mtx_assert(&Giant, MA_NOTOWNED);
1650f0393f06SJeff Roberson 
1651b722ad00SAlexander Motin 		while (sched_runnable() == 0) {
1652b722ad00SAlexander Motin 			cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1653b722ad00SAlexander Motin 			stat->idlecalls++;
1654b722ad00SAlexander Motin 		}
1655f0393f06SJeff Roberson 
1656f0393f06SJeff Roberson 		mtx_lock_spin(&sched_lock);
16578df78c41SJeff Roberson 		mi_switch(SW_VOL | SWT_IDLE, NULL);
1658f0393f06SJeff Roberson 		mtx_unlock_spin(&sched_lock);
1659f0393f06SJeff Roberson 	}
1660f0393f06SJeff Roberson }
1661f0393f06SJeff Roberson 
16627b20fb19SJeff Roberson /*
16637b20fb19SJeff Roberson  * A CPU is entering for the first time or a thread is exiting.
16647b20fb19SJeff Roberson  */
16657b20fb19SJeff Roberson void
16667b20fb19SJeff Roberson sched_throw(struct thread *td)
16677b20fb19SJeff Roberson {
16687b20fb19SJeff Roberson 	/*
16697b20fb19SJeff Roberson 	 * Correct spinlock nesting.  The idle thread context that we are
16707b20fb19SJeff Roberson 	 * borrowing was created so that it would start out with a single
16717b20fb19SJeff Roberson 	 * spin lock (sched_lock) held in fork_trampoline().  Since we've
16727b20fb19SJeff Roberson 	 * explicitly acquired locks in this function, the nesting count
16737b20fb19SJeff Roberson 	 * is now 2 rather than 1.  Since we are nested, calling
16747b20fb19SJeff Roberson 	 * spinlock_exit() will simply adjust the counts without allowing
16757b20fb19SJeff Roberson 	 * spin lock using code to interrupt us.
16767b20fb19SJeff Roberson 	 */
16777b20fb19SJeff Roberson 	if (td == NULL) {
16787b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
16797b20fb19SJeff Roberson 		spinlock_exit();
16807e3a96eaSJohn Baldwin 		PCPU_SET(switchtime, cpu_ticks());
16817e3a96eaSJohn Baldwin 		PCPU_SET(switchticks, ticks);
16827b20fb19SJeff Roberson 	} else {
1683eea4f254SJeff Roberson 		lock_profile_release_lock(&sched_lock.lock_object);
16847b20fb19SJeff Roberson 		MPASS(td->td_lock == &sched_lock);
168592de34dfSJohn Baldwin 		td->td_lastcpu = td->td_oncpu;
168692de34dfSJohn Baldwin 		td->td_oncpu = NOCPU;
16877b20fb19SJeff Roberson 	}
16887b20fb19SJeff Roberson 	mtx_assert(&sched_lock, MA_OWNED);
16897b20fb19SJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
16907b20fb19SJeff Roberson 	cpu_throw(td, choosethread());	/* doesn't return */
16917b20fb19SJeff Roberson }
16927b20fb19SJeff Roberson 
16937b20fb19SJeff Roberson void
1694fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
16957b20fb19SJeff Roberson {
16967b20fb19SJeff Roberson 
16977b20fb19SJeff Roberson 	/*
16987b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
16997b20fb19SJeff Roberson 	 * non-nested critical section with sched_lock held but not recursed.
17007b20fb19SJeff Roberson 	 */
1701fe54587fSJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
1702fe54587fSJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
1703eea4f254SJeff Roberson 	lock_profile_obtain_lock_success(&sched_lock.lock_object,
1704eea4f254SJeff Roberson 	    0, 0, __FILE__, __LINE__);
1705fe54587fSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
17067b20fb19SJeff Roberson }
17077b20fb19SJeff Roberson 
17088f51ad55SJeff Roberson char *
17098f51ad55SJeff Roberson sched_tdname(struct thread *td)
17108f51ad55SJeff Roberson {
17118f51ad55SJeff Roberson #ifdef KTR
17128f51ad55SJeff Roberson 	struct td_sched *ts;
17138f51ad55SJeff Roberson 
1714*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
17158f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
17168f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
17178f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
17188f51ad55SJeff Roberson 	return (ts->ts_name);
17198f51ad55SJeff Roberson #else
17208f51ad55SJeff Roberson 	return (td->td_name);
17218f51ad55SJeff Roberson #endif
17228f51ad55SJeff Roberson }
17238f51ad55SJeff Roberson 
172444ad5475SJohn Baldwin #ifdef KTR
172544ad5475SJohn Baldwin void
172644ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
172744ad5475SJohn Baldwin {
172844ad5475SJohn Baldwin 	struct td_sched *ts;
172944ad5475SJohn Baldwin 
1730*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
173144ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
173244ad5475SJohn Baldwin }
173344ad5475SJohn Baldwin #endif
173444ad5475SJohn Baldwin 
1735885d51a3SJeff Roberson void
1736885d51a3SJeff Roberson sched_affinity(struct thread *td)
1737885d51a3SJeff Roberson {
1738f200843bSJohn Baldwin #ifdef SMP
1739f200843bSJohn Baldwin 	struct td_sched *ts;
1740f200843bSJohn Baldwin 	int cpu;
1741f200843bSJohn Baldwin 
1742f200843bSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1743f200843bSJohn Baldwin 
1744f200843bSJohn Baldwin 	/*
1745f200843bSJohn Baldwin 	 * Set the TSF_AFFINITY flag if there is at least one CPU this
1746f200843bSJohn Baldwin 	 * thread can't run on.
1747f200843bSJohn Baldwin 	 */
1748*93ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1749f200843bSJohn Baldwin 	ts->ts_flags &= ~TSF_AFFINITY;
17503aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1751f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu)) {
1752f200843bSJohn Baldwin 			ts->ts_flags |= TSF_AFFINITY;
1753f200843bSJohn Baldwin 			break;
1754f200843bSJohn Baldwin 		}
1755f200843bSJohn Baldwin 	}
1756f200843bSJohn Baldwin 
1757f200843bSJohn Baldwin 	/*
1758f200843bSJohn Baldwin 	 * If this thread can run on all CPUs, nothing else to do.
1759f200843bSJohn Baldwin 	 */
1760f200843bSJohn Baldwin 	if (!(ts->ts_flags & TSF_AFFINITY))
1761f200843bSJohn Baldwin 		return;
1762f200843bSJohn Baldwin 
1763f200843bSJohn Baldwin 	/* Pinned threads and bound threads should be left alone. */
1764f200843bSJohn Baldwin 	if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1765f200843bSJohn Baldwin 		return;
1766f200843bSJohn Baldwin 
1767f200843bSJohn Baldwin 	switch (td->td_state) {
1768f200843bSJohn Baldwin 	case TDS_RUNQ:
1769f200843bSJohn Baldwin 		/*
1770f200843bSJohn Baldwin 		 * If we are on a per-CPU runqueue that is in the set,
1771f200843bSJohn Baldwin 		 * then nothing needs to be done.
1772f200843bSJohn Baldwin 		 */
1773f200843bSJohn Baldwin 		if (ts->ts_runq != &runq &&
1774f200843bSJohn Baldwin 		    THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1775f200843bSJohn Baldwin 			return;
1776f200843bSJohn Baldwin 
1777f200843bSJohn Baldwin 		/* Put this thread on a valid per-CPU runqueue. */
1778f200843bSJohn Baldwin 		sched_rem(td);
1779f200843bSJohn Baldwin 		sched_add(td, SRQ_BORING);
1780f200843bSJohn Baldwin 		break;
1781f200843bSJohn Baldwin 	case TDS_RUNNING:
1782f200843bSJohn Baldwin 		/*
1783f200843bSJohn Baldwin 		 * See if our current CPU is in the set.  If not, force a
1784f200843bSJohn Baldwin 		 * context switch.
1785f200843bSJohn Baldwin 		 */
1786f200843bSJohn Baldwin 		if (THREAD_CAN_SCHED(td, td->td_oncpu))
1787f200843bSJohn Baldwin 			return;
1788f200843bSJohn Baldwin 
1789f200843bSJohn Baldwin 		td->td_flags |= TDF_NEEDRESCHED;
1790f200843bSJohn Baldwin 		if (td != curthread)
1791d9d8d144SJohn Baldwin 			ipi_cpu(cpu, IPI_AST);
1792f200843bSJohn Baldwin 		break;
1793f200843bSJohn Baldwin 	default:
1794f200843bSJohn Baldwin 		break;
1795f200843bSJohn Baldwin 	}
1796f200843bSJohn Baldwin #endif
1797885d51a3SJeff Roberson }
1798