xref: /freebsd/sys/kern/sched_4bsd.c (revision e24a65528388f4debfb12e936f314f85ba6ac407)
1b43179fbSJeff Roberson /*-
251369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
351369649SPedro F. Giffuni  *
4b43179fbSJeff Roberson  * Copyright (c) 1982, 1986, 1990, 1991, 1993
5b43179fbSJeff Roberson  *	The Regents of the University of California.  All rights reserved.
6b43179fbSJeff Roberson  * (c) UNIX System Laboratories, Inc.
7b43179fbSJeff Roberson  * All or some portions of this file are derived from material licensed
8b43179fbSJeff Roberson  * to the University of California by American Telephone and Telegraph
9b43179fbSJeff Roberson  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10b43179fbSJeff Roberson  * the permission of UNIX System Laboratories, Inc.
11b43179fbSJeff Roberson  *
12b43179fbSJeff Roberson  * Redistribution and use in source and binary forms, with or without
13b43179fbSJeff Roberson  * modification, are permitted provided that the following conditions
14b43179fbSJeff Roberson  * are met:
15b43179fbSJeff Roberson  * 1. Redistributions of source code must retain the above copyright
16b43179fbSJeff Roberson  *    notice, this list of conditions and the following disclaimer.
17b43179fbSJeff Roberson  * 2. Redistributions in binary form must reproduce the above copyright
18b43179fbSJeff Roberson  *    notice, this list of conditions and the following disclaimer in the
19b43179fbSJeff Roberson  *    documentation and/or other materials provided with the distribution.
2069a28758SEd Maste  * 3. Neither the name of the University nor the names of its contributors
21b43179fbSJeff Roberson  *    may be used to endorse or promote products derived from this software
22b43179fbSJeff Roberson  *    without specific prior written permission.
23b43179fbSJeff Roberson  *
24b43179fbSJeff Roberson  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25b43179fbSJeff Roberson  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26b43179fbSJeff Roberson  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27b43179fbSJeff Roberson  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28b43179fbSJeff Roberson  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29b43179fbSJeff Roberson  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30b43179fbSJeff Roberson  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31b43179fbSJeff Roberson  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32b43179fbSJeff Roberson  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33b43179fbSJeff Roberson  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34b43179fbSJeff Roberson  * SUCH DAMAGE.
35b43179fbSJeff Roberson  */
36b43179fbSJeff Roberson 
37677b542eSDavid E. O'Brien #include <sys/cdefs.h>
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>
57af29f399SDmitry Chagin #include <sys/umtxvar.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>
6761322a0aSAlexander Motin int __read_mostly		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 
12093ccd6bfSKonstantin Belousov _Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
12193ccd6bfSKonstantin Belousov     sizeof(struct thread0_storage),
12293ccd6bfSKonstantin Belousov     "increase struct thread0_storage.t0st_sched size");
12393ccd6bfSKonstantin 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 };
1772bf95012SAndrew Turner DPCPU_DEFINE_STATIC(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 
2107029da5cSPawel Biernacki SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2117029da5cSPawel Biernacki     "Scheduler");
212dc095794SScott Long 
213e038d354SScott Long SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
214e038d354SScott Long     "Scheduler name");
2157029da5cSPawel Biernacki SYSCTL_PROC(_kern_sched, OID_AUTO, quantum,
2167029da5cSPawel Biernacki     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
2177029da5cSPawel Biernacki     sysctl_kern_quantum, "I",
21837f4e025SAlexander Motin     "Quantum for timeshare threads in microseconds");
21948317e9eSAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
22037f4e025SAlexander Motin     "Quantum for timeshare threads in stathz ticks");
22137c28a02SJulian Elischer #ifdef SMP
22282a1dfc1SJulian Elischer /* Enable forwarding of wakeups to all other cpus */
2237029da5cSPawel Biernacki static SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup,
2247029da5cSPawel Biernacki     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
2256472ac3dSEd Schouten     "Kernel SMP");
22682a1dfc1SJulian Elischer 
227a90f3f25SJeff Roberson static int runq_fuzz = 1;
228a90f3f25SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
229a90f3f25SJeff Roberson 
230bce73aedSJulian Elischer static int forward_wakeup_enabled = 1;
23182a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
23282a1dfc1SJulian Elischer 	   &forward_wakeup_enabled, 0,
23382a1dfc1SJulian Elischer 	   "Forwarding of wakeup to idle CPUs");
23482a1dfc1SJulian Elischer 
23582a1dfc1SJulian Elischer static int forward_wakeups_requested = 0;
23682a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
23782a1dfc1SJulian Elischer 	   &forward_wakeups_requested, 0,
23882a1dfc1SJulian Elischer 	   "Requests for Forwarding of wakeup to idle CPUs");
23982a1dfc1SJulian Elischer 
24082a1dfc1SJulian Elischer static int forward_wakeups_delivered = 0;
24182a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
24282a1dfc1SJulian Elischer 	   &forward_wakeups_delivered, 0,
24382a1dfc1SJulian Elischer 	   "Completed Forwarding of wakeup to idle CPUs");
24482a1dfc1SJulian Elischer 
245bce73aedSJulian Elischer static int forward_wakeup_use_mask = 1;
24682a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
24782a1dfc1SJulian Elischer 	   &forward_wakeup_use_mask, 0,
24882a1dfc1SJulian Elischer 	   "Use the mask of idle cpus");
24982a1dfc1SJulian Elischer 
25082a1dfc1SJulian Elischer static int forward_wakeup_use_loop = 0;
25182a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
25282a1dfc1SJulian Elischer 	   &forward_wakeup_use_loop, 0,
25382a1dfc1SJulian Elischer 	   "Use a loop to find idle cpus");
25482a1dfc1SJulian Elischer 
25537c28a02SJulian Elischer #endif
256ad1e7d28SJulian Elischer #if 0
2573389af30SJulian Elischer static int sched_followon = 0;
2583389af30SJulian Elischer SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
2593389af30SJulian Elischer 	   &sched_followon, 0,
2603389af30SJulian Elischer 	   "allow threads to share a quantum");
2618460a577SJohn Birrell #endif
26282a1dfc1SJulian Elischer 
263b3e9e682SRyan Stone SDT_PROVIDER_DEFINE(sched);
264b3e9e682SRyan Stone 
265d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
266b3e9e682SRyan Stone     "struct proc *", "uint8_t");
267d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
268b3e9e682SRyan Stone     "struct proc *", "void *");
269d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
270b3e9e682SRyan Stone     "struct proc *", "void *", "int");
271d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
272b3e9e682SRyan Stone     "struct proc *", "uint8_t", "struct thread *");
273d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
274d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
275b3e9e682SRyan Stone     "struct proc *");
276d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , on__cpu);
277d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , remain__cpu);
278d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
279b3e9e682SRyan Stone     "struct proc *");
280b3e9e682SRyan Stone 
281907bdbc2SJeff Roberson static __inline void
282907bdbc2SJeff Roberson sched_load_add(void)
283907bdbc2SJeff Roberson {
2848f51ad55SJeff Roberson 
285907bdbc2SJeff Roberson 	sched_tdcnt++;
2868f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
287d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
288907bdbc2SJeff Roberson }
289907bdbc2SJeff Roberson 
290907bdbc2SJeff Roberson static __inline void
291907bdbc2SJeff Roberson sched_load_rem(void)
292907bdbc2SJeff Roberson {
2938f51ad55SJeff Roberson 
294907bdbc2SJeff Roberson 	sched_tdcnt--;
2958f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
296d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
297907bdbc2SJeff Roberson }
298b43179fbSJeff Roberson /*
299b43179fbSJeff Roberson  * Arrange to reschedule if necessary, taking the priorities and
300b43179fbSJeff Roberson  * schedulers into account.
301b43179fbSJeff Roberson  */
302b43179fbSJeff Roberson static void
303b43179fbSJeff Roberson maybe_resched(struct thread *td)
304b43179fbSJeff Roberson {
305b43179fbSJeff Roberson 
3067b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
307ed062c8dSJulian Elischer 	if (td->td_priority < curthread->td_priority)
308c6d31b83SKonstantin Belousov 		ast_sched_locked(curthread, TDA_SCHED);
309b43179fbSJeff Roberson }
310b43179fbSJeff Roberson 
311b43179fbSJeff Roberson /*
312a90f3f25SJeff Roberson  * This function is called when a thread is about to be put on run queue
313a90f3f25SJeff Roberson  * because it has been made runnable or its priority has been adjusted.  It
314a6b91f0fSJohn Baldwin  * determines if the new thread should preempt the current thread.  If so,
315a6b91f0fSJohn Baldwin  * it sets td_owepreempt to request a preemption.
316a90f3f25SJeff Roberson  */
317a90f3f25SJeff Roberson int
318a90f3f25SJeff Roberson maybe_preempt(struct thread *td)
319a90f3f25SJeff Roberson {
320a90f3f25SJeff Roberson #ifdef PREEMPTION
321a90f3f25SJeff Roberson 	struct thread *ctd;
322a90f3f25SJeff Roberson 	int cpri, pri;
323a90f3f25SJeff Roberson 
324a90f3f25SJeff Roberson 	/*
325a90f3f25SJeff Roberson 	 * The new thread should not preempt the current thread if any of the
326a90f3f25SJeff Roberson 	 * following conditions are true:
327a90f3f25SJeff Roberson 	 *
328a90f3f25SJeff Roberson 	 *  - The kernel is in the throes of crashing (panicstr).
329a90f3f25SJeff Roberson 	 *  - The current thread has a higher (numerically lower) or
330a90f3f25SJeff Roberson 	 *    equivalent priority.  Note that this prevents curthread from
331a90f3f25SJeff Roberson 	 *    trying to preempt to itself.
332a90f3f25SJeff Roberson 	 *  - The current thread has an inhibitor set or is in the process of
333a90f3f25SJeff Roberson 	 *    exiting.  In this case, the current thread is about to switch
334a90f3f25SJeff Roberson 	 *    out anyways, so there's no point in preempting.  If we did,
335a90f3f25SJeff Roberson 	 *    the current thread would not be properly resumed as well, so
336a90f3f25SJeff Roberson 	 *    just avoid that whole landmine.
337a90f3f25SJeff Roberson 	 *  - If the new thread's priority is not a realtime priority and
338a90f3f25SJeff Roberson 	 *    the current thread's priority is not an idle priority and
339a90f3f25SJeff Roberson 	 *    FULL_PREEMPTION is disabled.
340a90f3f25SJeff Roberson 	 *
341a90f3f25SJeff Roberson 	 * If all of these conditions are false, but the current thread is in
342a90f3f25SJeff Roberson 	 * a nested critical section, then we have to defer the preemption
343a90f3f25SJeff Roberson 	 * until we exit the critical section.  Otherwise, switch immediately
344a90f3f25SJeff Roberson 	 * to the new thread.
345a90f3f25SJeff Roberson 	 */
346a90f3f25SJeff Roberson 	ctd = curthread;
347a90f3f25SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
348a90f3f25SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
349a90f3f25SJeff Roberson 			("maybe_preempt: trying to run inhibited thread"));
350a90f3f25SJeff Roberson 	pri = td->td_priority;
351a90f3f25SJeff Roberson 	cpri = ctd->td_priority;
352879e0604SMateusz Guzik 	if (KERNEL_PANICKED() || pri >= cpri /* || dumping */ ||
353a90f3f25SJeff Roberson 	    TD_IS_INHIBITED(ctd))
354a90f3f25SJeff Roberson 		return (0);
355a90f3f25SJeff Roberson #ifndef FULL_PREEMPTION
356a90f3f25SJeff Roberson 	if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
357a90f3f25SJeff Roberson 		return (0);
358a90f3f25SJeff Roberson #endif
359a90f3f25SJeff Roberson 
360a6b91f0fSJohn Baldwin 	CTR0(KTR_PROC, "maybe_preempt: scheduling preemption");
361a90f3f25SJeff Roberson 	ctd->td_owepreempt = 1;
362a90f3f25SJeff Roberson 	return (1);
363a90f3f25SJeff Roberson #else
364a90f3f25SJeff Roberson 	return (0);
365a90f3f25SJeff Roberson #endif
366a90f3f25SJeff Roberson }
367a90f3f25SJeff Roberson 
368a90f3f25SJeff Roberson /*
369b43179fbSJeff Roberson  * Constants for digital decay and forget:
370ccd0ec40SKonstantin Belousov  *	90% of (ts_estcpu) usage in 5 * loadav time
371ad1e7d28SJulian Elischer  *	95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
372b43179fbSJeff Roberson  *          Note that, as ps(1) mentions, this can let percentages
373b43179fbSJeff Roberson  *          total over 100% (I've seen 137.9% for 3 processes).
374b43179fbSJeff Roberson  *
375ccd0ec40SKonstantin Belousov  * Note that schedclock() updates ts_estcpu and p_cpticks asynchronously.
376b43179fbSJeff Roberson  *
377ccd0ec40SKonstantin Belousov  * We wish to decay away 90% of ts_estcpu in (5 * loadavg) seconds.
378b43179fbSJeff Roberson  * That is, the system wants to compute a value of decay such
379b43179fbSJeff Roberson  * that the following for loop:
380b43179fbSJeff Roberson  * 	for (i = 0; i < (5 * loadavg); i++)
381ccd0ec40SKonstantin Belousov  * 		ts_estcpu *= decay;
382b43179fbSJeff Roberson  * will compute
383ccd0ec40SKonstantin Belousov  * 	ts_estcpu *= 0.1;
384b43179fbSJeff Roberson  * for all values of loadavg:
385b43179fbSJeff Roberson  *
386b43179fbSJeff Roberson  * Mathematically this loop can be expressed by saying:
387b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
388b43179fbSJeff Roberson  *
389b43179fbSJeff Roberson  * The system computes decay as:
390b43179fbSJeff Roberson  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
391b43179fbSJeff Roberson  *
392b43179fbSJeff Roberson  * We wish to prove that the system's computation of decay
393b43179fbSJeff Roberson  * will always fulfill the equation:
394b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
395b43179fbSJeff Roberson  *
396b43179fbSJeff Roberson  * If we compute b as:
397b43179fbSJeff Roberson  * 	b = 2 * loadavg
398b43179fbSJeff Roberson  * then
399b43179fbSJeff Roberson  * 	decay = b / (b + 1)
400b43179fbSJeff Roberson  *
401b43179fbSJeff Roberson  * We now need to prove two things:
402b43179fbSJeff Roberson  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
403b43179fbSJeff Roberson  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
404b43179fbSJeff Roberson  *
405b43179fbSJeff Roberson  * Facts:
406b43179fbSJeff Roberson  *         For x close to zero, exp(x) =~ 1 + x, since
407b43179fbSJeff Roberson  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
408b43179fbSJeff Roberson  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
409b43179fbSJeff Roberson  *         For x close to zero, ln(1+x) =~ x, since
410b43179fbSJeff Roberson  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
411b43179fbSJeff Roberson  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
412b43179fbSJeff Roberson  *         ln(.1) =~ -2.30
413b43179fbSJeff Roberson  *
414b43179fbSJeff Roberson  * Proof of (1):
415b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
416b43179fbSJeff Roberson  *	solving for factor,
417b43179fbSJeff Roberson  *      ln(factor) =~ (-2.30/5*loadav), or
418b43179fbSJeff Roberson  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
419b43179fbSJeff Roberson  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
420b43179fbSJeff Roberson  *
421b43179fbSJeff Roberson  * Proof of (2):
422b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
423b43179fbSJeff Roberson  *	solving for power,
424b43179fbSJeff Roberson  *      power*ln(b/(b+1)) =~ -2.30, or
425b43179fbSJeff Roberson  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
426b43179fbSJeff Roberson  *
427b43179fbSJeff Roberson  * Actual power values for the implemented algorithm are as follows:
428b43179fbSJeff Roberson  *      loadav: 1       2       3       4
429b43179fbSJeff Roberson  *      power:  5.68    10.32   14.94   19.55
430b43179fbSJeff Roberson  */
431b43179fbSJeff Roberson 
432b43179fbSJeff Roberson /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
433b43179fbSJeff Roberson #define	loadfactor(loadav)	(2 * (loadav))
434b43179fbSJeff Roberson #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
435b43179fbSJeff Roberson 
436ad1e7d28SJulian Elischer /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
437b43179fbSJeff Roberson static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
438b05ca429SPawel Biernacki SYSCTL_UINT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0,
439b05ca429SPawel Biernacki     "Decay factor used for updating %CPU");
440b43179fbSJeff Roberson 
441b43179fbSJeff Roberson /*
442b43179fbSJeff Roberson  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
443b43179fbSJeff Roberson  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
444b43179fbSJeff Roberson  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
445b43179fbSJeff Roberson  *
446b43179fbSJeff Roberson  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
447b43179fbSJeff Roberson  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
448b43179fbSJeff Roberson  *
449b43179fbSJeff Roberson  * If you don't want to bother with the faster/more-accurate formula, you
450b43179fbSJeff Roberson  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
451b43179fbSJeff Roberson  * (more general) method of calculating the %age of CPU used by a process.
452b43179fbSJeff Roberson  */
453b43179fbSJeff Roberson #define	CCPU_SHIFT	11
454b43179fbSJeff Roberson 
455b43179fbSJeff Roberson /*
456b43179fbSJeff Roberson  * Recompute process priorities, every hz ticks.
457b43179fbSJeff Roberson  * MP-safe, called without the Giant mutex.
458b43179fbSJeff Roberson  */
459b43179fbSJeff Roberson /* ARGSUSED */
460b43179fbSJeff Roberson static void
461c55bbb6cSJohn Baldwin schedcpu(void)
462b43179fbSJeff Roberson {
4633e85b721SEd Maste 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
464b43179fbSJeff Roberson 	struct thread *td;
465b43179fbSJeff Roberson 	struct proc *p;
466ad1e7d28SJulian Elischer 	struct td_sched *ts;
46748317e9eSAlexander Motin 	int awake;
468b43179fbSJeff Roberson 
469b43179fbSJeff Roberson 	sx_slock(&allproc_lock);
470b43179fbSJeff Roberson 	FOREACH_PROC_IN_SYSTEM(p) {
471374ae2a3SJeff Roberson 		PROC_LOCK(p);
472e806d352SJohn Baldwin 		if (p->p_state == PRS_NEW) {
473e806d352SJohn Baldwin 			PROC_UNLOCK(p);
474e806d352SJohn Baldwin 			continue;
475e806d352SJohn Baldwin 		}
4768460a577SJohn Birrell 		FOREACH_THREAD_IN_PROC(p, td) {
477b43179fbSJeff Roberson 			awake = 0;
47893ccd6bfSKonstantin Belousov 			ts = td_get_sched(td);
4797b20fb19SJeff Roberson 			thread_lock(td);
480b43179fbSJeff Roberson 			/*
48170fca427SJohn Baldwin 			 * Increment sleep time (if sleeping).  We
48270fca427SJohn Baldwin 			 * ignore overflow, as above.
483b43179fbSJeff Roberson 			 */
484b43179fbSJeff Roberson 			/*
485ad1e7d28SJulian Elischer 			 * The td_sched slptimes are not touched in wakeup
486ad1e7d28SJulian Elischer 			 * because the thread may not HAVE everything in
487ad1e7d28SJulian Elischer 			 * memory? XXX I think this is out of date.
488b43179fbSJeff Roberson 			 */
489f0393f06SJeff Roberson 			if (TD_ON_RUNQ(td)) {
490b43179fbSJeff Roberson 				awake = 1;
4919727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
492f0393f06SJeff Roberson 			} else if (TD_IS_RUNNING(td)) {
493b43179fbSJeff Roberson 				awake = 1;
4949727e637SJeff Roberson 				/* Do not clear TDF_DIDRUN */
4959727e637SJeff Roberson 			} else if (td->td_flags & TDF_DIDRUN) {
496b43179fbSJeff Roberson 				awake = 1;
4979727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
498b43179fbSJeff Roberson 			}
499b43179fbSJeff Roberson 
500b43179fbSJeff Roberson 			/*
501ad1e7d28SJulian Elischer 			 * ts_pctcpu is only for ps and ttyinfo().
502b43179fbSJeff Roberson 			 */
503ad1e7d28SJulian Elischer 			ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
504b43179fbSJeff Roberson 			/*
505ad1e7d28SJulian Elischer 			 * If the td_sched has been idle the entire second,
506b43179fbSJeff Roberson 			 * stop recalculating its priority until
507b43179fbSJeff Roberson 			 * it wakes up.
508b43179fbSJeff Roberson 			 */
509ad1e7d28SJulian Elischer 			if (ts->ts_cpticks != 0) {
510b43179fbSJeff Roberson #if	(FSHIFT >= CCPU_SHIFT)
511ad1e7d28SJulian Elischer 				ts->ts_pctcpu += (realstathz == 100)
512ad1e7d28SJulian Elischer 				    ? ((fixpt_t) ts->ts_cpticks) <<
513b43179fbSJeff Roberson 				    (FSHIFT - CCPU_SHIFT) :
514ad1e7d28SJulian Elischer 				    100 * (((fixpt_t) ts->ts_cpticks)
515bcb06d59SJeff Roberson 				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
516b43179fbSJeff Roberson #else
517ad1e7d28SJulian Elischer 				ts->ts_pctcpu += ((FSCALE - ccpu) *
518ad1e7d28SJulian Elischer 				    (ts->ts_cpticks *
519bcb06d59SJeff Roberson 				    FSCALE / realstathz)) >> FSHIFT;
520b43179fbSJeff Roberson #endif
521ad1e7d28SJulian Elischer 				ts->ts_cpticks = 0;
5228460a577SJohn Birrell 			}
5238460a577SJohn Birrell 			/*
5248460a577SJohn Birrell 			 * If there are ANY running threads in this process,
525b43179fbSJeff Roberson 			 * then don't count it as sleeping.
5268aa3d7ffSJohn Baldwin 			 * XXX: this is broken.
527b43179fbSJeff Roberson 			 */
528b43179fbSJeff Roberson 			if (awake) {
52954b0e65fSJeff Roberson 				if (ts->ts_slptime > 1) {
530b43179fbSJeff Roberson 					/*
531b43179fbSJeff Roberson 					 * In an ideal world, this should not
532b43179fbSJeff Roberson 					 * happen, because whoever woke us
533b43179fbSJeff Roberson 					 * up from the long sleep should have
534b43179fbSJeff Roberson 					 * unwound the slptime and reset our
535b43179fbSJeff Roberson 					 * priority before we run at the stale
536b43179fbSJeff Roberson 					 * priority.  Should KASSERT at some
537b43179fbSJeff Roberson 					 * point when all the cases are fixed.
538b43179fbSJeff Roberson 					 */
5398460a577SJohn Birrell 					updatepri(td);
5408460a577SJohn Birrell 				}
54154b0e65fSJeff Roberson 				ts->ts_slptime = 0;
5428460a577SJohn Birrell 			} else
54354b0e65fSJeff Roberson 				ts->ts_slptime++;
54454b0e65fSJeff Roberson 			if (ts->ts_slptime > 1) {
5457b20fb19SJeff Roberson 				thread_unlock(td);
5468460a577SJohn Birrell 				continue;
5477b20fb19SJeff Roberson 			}
548ccd0ec40SKonstantin Belousov 			ts->ts_estcpu = decay_cpu(loadfac, ts->ts_estcpu);
5498460a577SJohn Birrell 		      	resetpriority(td);
5508460a577SJohn Birrell 			resetpriority_thread(td);
5517b20fb19SJeff Roberson 			thread_unlock(td);
5528aa3d7ffSJohn Baldwin 		}
553374ae2a3SJeff Roberson 		PROC_UNLOCK(p);
5548aa3d7ffSJohn Baldwin 	}
555b43179fbSJeff Roberson 	sx_sunlock(&allproc_lock);
556c55bbb6cSJohn Baldwin }
557c55bbb6cSJohn Baldwin 
558c55bbb6cSJohn Baldwin /*
559c55bbb6cSJohn Baldwin  * Main loop for a kthread that executes schedcpu once a second.
560c55bbb6cSJohn Baldwin  */
561c55bbb6cSJohn Baldwin static void
562e17c57b1SJeff Roberson schedcpu_thread(void)
563c55bbb6cSJohn Baldwin {
564c55bbb6cSJohn Baldwin 
565c55bbb6cSJohn Baldwin 	for (;;) {
566c55bbb6cSJohn Baldwin 		schedcpu();
5674d70511aSJohn Baldwin 		pause("-", hz);
568c55bbb6cSJohn Baldwin 	}
569b43179fbSJeff Roberson }
570b43179fbSJeff Roberson 
571b43179fbSJeff Roberson /*
572b43179fbSJeff Roberson  * Recalculate the priority of a process after it has slept for a while.
573ccd0ec40SKonstantin Belousov  * For all load averages >= 1 and max ts_estcpu of 255, sleeping for at
574ccd0ec40SKonstantin Belousov  * least six times the loadfactor will decay ts_estcpu to zero.
575b43179fbSJeff Roberson  */
576b43179fbSJeff Roberson static void
5778460a577SJohn Birrell updatepri(struct thread *td)
578b43179fbSJeff Roberson {
57954b0e65fSJeff Roberson 	struct td_sched *ts;
58054b0e65fSJeff Roberson 	fixpt_t loadfac;
58154b0e65fSJeff Roberson 	unsigned int newcpu;
582b43179fbSJeff Roberson 
58393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
58470fca427SJohn Baldwin 	loadfac = loadfactor(averunnable.ldavg[0]);
58554b0e65fSJeff Roberson 	if (ts->ts_slptime > 5 * loadfac)
586ccd0ec40SKonstantin Belousov 		ts->ts_estcpu = 0;
587b43179fbSJeff Roberson 	else {
588ccd0ec40SKonstantin Belousov 		newcpu = ts->ts_estcpu;
58954b0e65fSJeff Roberson 		ts->ts_slptime--;	/* was incremented in schedcpu() */
59054b0e65fSJeff Roberson 		while (newcpu && --ts->ts_slptime)
591b43179fbSJeff Roberson 			newcpu = decay_cpu(loadfac, newcpu);
592ccd0ec40SKonstantin Belousov 		ts->ts_estcpu = newcpu;
593b43179fbSJeff Roberson 	}
594b43179fbSJeff Roberson }
595b43179fbSJeff Roberson 
596b43179fbSJeff Roberson /*
597b43179fbSJeff Roberson  * Compute the priority of a process when running in user mode.
598b43179fbSJeff Roberson  * Arrange to reschedule if the resulting priority is better
599b43179fbSJeff Roberson  * than that of the current process.
600b43179fbSJeff Roberson  */
601b43179fbSJeff Roberson static void
6028460a577SJohn Birrell resetpriority(struct thread *td)
603b43179fbSJeff Roberson {
604ccd0ec40SKonstantin Belousov 	u_int newpriority;
605b43179fbSJeff Roberson 
606ccd0ec40SKonstantin Belousov 	if (td->td_pri_class != PRI_TIMESHARE)
607ccd0ec40SKonstantin Belousov 		return;
60893ccd6bfSKonstantin Belousov 	newpriority = PUSER +
60993ccd6bfSKonstantin Belousov 	    td_get_sched(td)->ts_estcpu / INVERSE_ESTCPU_WEIGHT +
6108460a577SJohn Birrell 	    NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
611b43179fbSJeff Roberson 	newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
612b43179fbSJeff Roberson 	    PRI_MAX_TIMESHARE);
6138460a577SJohn Birrell 	sched_user_prio(td, newpriority);
614b43179fbSJeff Roberson }
615f5c157d9SJohn Baldwin 
616f5c157d9SJohn Baldwin /*
617ad1e7d28SJulian Elischer  * Update the thread's priority when the associated process's user
618f5c157d9SJohn Baldwin  * priority changes.
619f5c157d9SJohn Baldwin  */
620f5c157d9SJohn Baldwin static void
6218460a577SJohn Birrell resetpriority_thread(struct thread *td)
622f5c157d9SJohn Baldwin {
623f5c157d9SJohn Baldwin 
624f5c157d9SJohn Baldwin 	/* Only change threads with a time sharing user priority. */
625f5c157d9SJohn Baldwin 	if (td->td_priority < PRI_MIN_TIMESHARE ||
626f5c157d9SJohn Baldwin 	    td->td_priority > PRI_MAX_TIMESHARE)
627f5c157d9SJohn Baldwin 		return;
628f5c157d9SJohn Baldwin 
629f5c157d9SJohn Baldwin 	/* XXX the whole needresched thing is broken, but not silly. */
630f5c157d9SJohn Baldwin 	maybe_resched(td);
631f5c157d9SJohn Baldwin 
6328460a577SJohn Birrell 	sched_prio(td, td->td_user_pri);
633b43179fbSJeff Roberson }
634b43179fbSJeff Roberson 
635b43179fbSJeff Roberson /* ARGSUSED */
636b43179fbSJeff Roberson static void
637b43179fbSJeff Roberson sched_setup(void *dummy)
638b43179fbSJeff Roberson {
63970fca427SJohn Baldwin 
640579895dfSAlexander Motin 	setup_runqs();
641b43179fbSJeff Roberson 
642ca59f152SJeff Roberson 	/* Account for thread0. */
643907bdbc2SJeff Roberson 	sched_load_add();
644b43179fbSJeff Roberson }
645b43179fbSJeff Roberson 
64648317e9eSAlexander Motin /*
647579895dfSAlexander Motin  * This routine determines time constants after stathz and hz are setup.
64848317e9eSAlexander Motin  */
64948317e9eSAlexander Motin static void
65048317e9eSAlexander Motin sched_initticks(void *dummy)
65148317e9eSAlexander Motin {
65248317e9eSAlexander Motin 
65348317e9eSAlexander Motin 	realstathz = stathz ? stathz : hz;
65448317e9eSAlexander Motin 	sched_slice = realstathz / 10;	/* ~100ms */
65537f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
65637f4e025SAlexander Motin 	    realstathz);
65748317e9eSAlexander Motin }
65848317e9eSAlexander Motin 
659b43179fbSJeff Roberson /* External interfaces start here */
6608aa3d7ffSJohn Baldwin 
661ed062c8dSJulian Elischer /*
662ed062c8dSJulian Elischer  * Very early in the boot some setup of scheduler-specific
663f3050486SMaxim Konovalov  * parts of proc0 and of some scheduler resources needs to be done.
664ed062c8dSJulian Elischer  * Called from:
665ed062c8dSJulian Elischer  *  proc0_init()
666ed062c8dSJulian Elischer  */
667ed062c8dSJulian Elischer void
668ed062c8dSJulian Elischer schedinit(void)
669ed062c8dSJulian Elischer {
67093ccd6bfSKonstantin Belousov 
671ed062c8dSJulian Elischer 	/*
67293ccd6bfSKonstantin Belousov 	 * Set up the scheduler specific parts of thread0.
673ed062c8dSJulian Elischer 	 */
6747b20fb19SJeff Roberson 	thread0.td_lock = &sched_lock;
67593ccd6bfSKonstantin Belousov 	td_get_sched(&thread0)->ts_slice = sched_slice;
676686bcb5cSJeff Roberson 	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN);
677ed062c8dSJulian Elischer }
678ed062c8dSJulian Elischer 
679589aed00SKyle Evans void
680589aed00SKyle Evans schedinit_ap(void)
681589aed00SKyle Evans {
682589aed00SKyle Evans 
683589aed00SKyle Evans 	/* Nothing needed. */
684589aed00SKyle Evans }
685589aed00SKyle Evans 
686b43179fbSJeff Roberson int
687b43179fbSJeff Roberson sched_runnable(void)
688b43179fbSJeff Roberson {
689e17c57b1SJeff Roberson #ifdef SMP
690e17c57b1SJeff Roberson 	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
691e17c57b1SJeff Roberson #else
692b43179fbSJeff Roberson 	return runq_check(&runq);
693e17c57b1SJeff Roberson #endif
694b43179fbSJeff Roberson }
695b43179fbSJeff Roberson 
696b43179fbSJeff Roberson int
697b43179fbSJeff Roberson sched_rr_interval(void)
698b43179fbSJeff Roberson {
69948317e9eSAlexander Motin 
70048317e9eSAlexander Motin 	/* Convert sched_slice from stathz to hz. */
70137f4e025SAlexander Motin 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
702b43179fbSJeff Roberson }
703b43179fbSJeff Roberson 
70440efe743SJohn Baldwin SCHED_STAT_DEFINE(ithread_demotions, "Interrupt thread priority demotions");
70540efe743SJohn Baldwin SCHED_STAT_DEFINE(ithread_preemptions,
70640efe743SJohn Baldwin     "Interrupt thread preemptions due to time-sharing");
70740efe743SJohn Baldwin 
708b43179fbSJeff Roberson /*
709ccd0ec40SKonstantin Belousov  * We adjust the priority of the current process.  The priority of a
710ccd0ec40SKonstantin Belousov  * process gets worse as it accumulates CPU time.  The cpu usage
711ccd0ec40SKonstantin Belousov  * estimator (ts_estcpu) is increased here.  resetpriority() will
712ccd0ec40SKonstantin Belousov  * compute a different priority each time ts_estcpu increases by
713ccd0ec40SKonstantin Belousov  * INVERSE_ESTCPU_WEIGHT (until PRI_MAX_TIMESHARE is reached).  The
714ccd0ec40SKonstantin Belousov  * cpu usage estimator ramps up quite quickly when the process is
715ccd0ec40SKonstantin Belousov  * running (linearly), and decays away exponentially, at a rate which
716ccd0ec40SKonstantin Belousov  * is proportionally slower when the system is busy.  The basic
717ccd0ec40SKonstantin Belousov  * principle is that the system will 90% forget that the process used
718ccd0ec40SKonstantin Belousov  * a lot of CPU time in 5 * loadav seconds.  This causes the system to
719ccd0ec40SKonstantin Belousov  * favor processes which haven't run much recently, and to round-robin
720ccd0ec40SKonstantin Belousov  * among other processes.
721b43179fbSJeff Roberson  */
722c3cccf95SJeff Roberson static void
723c3cccf95SJeff Roberson sched_clock_tick(struct thread *td)
724b43179fbSJeff Roberson {
725b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
726ad1e7d28SJulian Elischer 	struct td_sched *ts;
727b43179fbSJeff Roberson 
7287b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
72993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
730f7f9e7f3SJeff Roberson 
731ad1e7d28SJulian Elischer 	ts->ts_cpticks++;
732ccd0ec40SKonstantin Belousov 	ts->ts_estcpu = ESTCPULIM(ts->ts_estcpu + 1);
733ccd0ec40SKonstantin Belousov 	if ((ts->ts_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
7348460a577SJohn Birrell 		resetpriority(td);
7358460a577SJohn Birrell 		resetpriority_thread(td);
736b43179fbSJeff Roberson 	}
7379dddab6fSJohn Baldwin 
7389dddab6fSJohn Baldwin 	/*
7399dddab6fSJohn Baldwin 	 * Force a context switch if the current thread has used up a full
740579895dfSAlexander Motin 	 * time slice (default is 100ms).
7419dddab6fSJohn Baldwin 	 */
742579895dfSAlexander Motin 	if (!TD_IS_IDLETHREAD(td) && --ts->ts_slice <= 0) {
74348317e9eSAlexander Motin 		ts->ts_slice = sched_slice;
74440efe743SJohn Baldwin 
74540efe743SJohn Baldwin 		/*
74640efe743SJohn Baldwin 		 * If an ithread uses a full quantum, demote its
74740efe743SJohn Baldwin 		 * priority and preempt it.
74840efe743SJohn Baldwin 		 */
74940efe743SJohn Baldwin 		if (PRI_BASE(td->td_pri_class) == PRI_ITHD) {
75040efe743SJohn Baldwin 			SCHED_STAT_INC(ithread_preemptions);
75140efe743SJohn Baldwin 			td->td_owepreempt = 1;
75240efe743SJohn Baldwin 			if (td->td_base_pri + RQ_PPQ < PRI_MAX_ITHD) {
75340efe743SJohn Baldwin 				SCHED_STAT_INC(ithread_demotions);
75440efe743SJohn Baldwin 				sched_prio(td, td->td_base_pri + RQ_PPQ);
75540efe743SJohn Baldwin 			}
756c6d31b83SKonstantin Belousov 		} else {
757c6d31b83SKonstantin Belousov 			td->td_flags |= TDF_SLICEEND;
758c6d31b83SKonstantin Belousov 			ast_sched_locked(td, TDA_SCHED);
759c6d31b83SKonstantin Belousov 		}
76048317e9eSAlexander Motin 	}
761b722ad00SAlexander Motin 
762b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
763b722ad00SAlexander Motin 	stat->oldidlecalls = stat->idlecalls;
764b722ad00SAlexander Motin 	stat->idlecalls = 0;
765b43179fbSJeff Roberson }
76670fca427SJohn Baldwin 
767c3cccf95SJeff Roberson void
768c3cccf95SJeff Roberson sched_clock(struct thread *td, int cnt)
769c3cccf95SJeff Roberson {
770c3cccf95SJeff Roberson 
771c3cccf95SJeff Roberson 	for ( ; cnt > 0; cnt--)
772c3cccf95SJeff Roberson 		sched_clock_tick(td);
773c3cccf95SJeff Roberson }
774c3cccf95SJeff Roberson 
7758460a577SJohn Birrell /*
7768aa3d7ffSJohn Baldwin  * Charge child's scheduling CPU usage to parent.
7778460a577SJohn Birrell  */
778b43179fbSJeff Roberson void
77955d44f79SJulian Elischer sched_exit(struct proc *p, struct thread *td)
780f7f9e7f3SJeff Roberson {
7818460a577SJohn Birrell 
7828f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "proc exit",
783cd39bb09SXin LI 	    "prio:%d", td->td_priority);
7848f51ad55SJeff Roberson 
785374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
786ad1e7d28SJulian Elischer 	sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
787b43179fbSJeff Roberson }
788b43179fbSJeff Roberson 
789b43179fbSJeff Roberson void
790f7f9e7f3SJeff Roberson sched_exit_thread(struct thread *td, struct thread *child)
791b43179fbSJeff Roberson {
792ad1e7d28SJulian Elischer 
7938f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "exit",
794cd39bb09SXin LI 	    "prio:%d", child->td_priority);
7957b20fb19SJeff Roberson 	thread_lock(td);
79693ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_estcpu = ESTCPULIM(td_get_sched(td)->ts_estcpu +
79793ccd6bfSKonstantin Belousov 	    td_get_sched(child)->ts_estcpu);
7987b20fb19SJeff Roberson 	thread_unlock(td);
7991b9d701fSAttilio Rao 	thread_lock(child);
8001b9d701fSAttilio Rao 	if ((child->td_flags & TDF_NOLOAD) == 0)
801907bdbc2SJeff Roberson 		sched_load_rem();
8021b9d701fSAttilio Rao 	thread_unlock(child);
803f7f9e7f3SJeff Roberson }
804bcb06d59SJeff Roberson 
805f7f9e7f3SJeff Roberson void
806ed062c8dSJulian Elischer sched_fork(struct thread *td, struct thread *childtd)
807f7f9e7f3SJeff Roberson {
808ed062c8dSJulian Elischer 	sched_fork_thread(td, childtd);
809f7f9e7f3SJeff Roberson }
810bcb06d59SJeff Roberson 
811f7f9e7f3SJeff Roberson void
812ed062c8dSJulian Elischer sched_fork_thread(struct thread *td, struct thread *childtd)
813f7f9e7f3SJeff Roberson {
81493ccd6bfSKonstantin Belousov 	struct td_sched *ts, *tsc;
8158b16c208SJeff Roberson 
81692de34dfSJohn Baldwin 	childtd->td_oncpu = NOCPU;
81792de34dfSJohn Baldwin 	childtd->td_lastcpu = NOCPU;
8187b20fb19SJeff Roberson 	childtd->td_lock = &sched_lock;
819f5a3ef99SMarcel Moolenaar 	childtd->td_cpuset = cpuset_ref(td->td_cpuset);
8203f289c3fSJeff Roberson 	childtd->td_domain.dr_policy = td->td_cpuset->cs_domain;
82122d19207SJohn Baldwin 	childtd->td_priority = childtd->td_base_pri;
82293ccd6bfSKonstantin Belousov 	ts = td_get_sched(childtd);
8238b16c208SJeff Roberson 	bzero(ts, sizeof(*ts));
82493ccd6bfSKonstantin Belousov 	tsc = td_get_sched(td);
82593ccd6bfSKonstantin Belousov 	ts->ts_estcpu = tsc->ts_estcpu;
82693ccd6bfSKonstantin Belousov 	ts->ts_flags |= (tsc->ts_flags & TSF_AFFINITY);
82748317e9eSAlexander Motin 	ts->ts_slice = 1;
828b43179fbSJeff Roberson }
829b43179fbSJeff Roberson 
830b43179fbSJeff Roberson void
831fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
832b43179fbSJeff Roberson {
833f5c157d9SJohn Baldwin 	struct thread *td;
8340b5318c8SJohn Baldwin 
835fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
836fa885116SJulian Elischer 	p->p_nice = nice;
8378460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
8387b20fb19SJeff Roberson 		thread_lock(td);
8398460a577SJohn Birrell 		resetpriority(td);
8408460a577SJohn Birrell 		resetpriority_thread(td);
8417b20fb19SJeff Roberson 		thread_unlock(td);
8428460a577SJohn Birrell 	}
843fa885116SJulian Elischer }
844b43179fbSJeff Roberson 
845f7f9e7f3SJeff Roberson void
8468460a577SJohn Birrell sched_class(struct thread *td, int class)
847f7f9e7f3SJeff Roberson {
8487b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
8498460a577SJohn Birrell 	td->td_pri_class = class;
850f7f9e7f3SJeff Roberson }
851f7f9e7f3SJeff Roberson 
8528460a577SJohn Birrell /*
8538460a577SJohn Birrell  * Adjust the priority of a thread.
8548460a577SJohn Birrell  */
855f5c157d9SJohn Baldwin static void
856f5c157d9SJohn Baldwin sched_priority(struct thread *td, u_char prio)
857b43179fbSJeff Roberson {
85827ee18adSRyan Stone 
8598f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
8608f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
8618f51ad55SJeff Roberson 	    sched_tdname(curthread));
862d9fae5abSAndriy Gapon 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
8638f51ad55SJeff Roberson 	if (td != curthread && prio > td->td_priority) {
8648f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
8658f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
8668f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
867d9fae5abSAndriy Gapon 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
868b3e9e682SRyan Stone 		    curthread);
8698f51ad55SJeff Roberson 	}
8707b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
871f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
872f5c157d9SJohn Baldwin 		return;
8731f955e2dSJulian Elischer 	td->td_priority = prio;
8749727e637SJeff Roberson 	if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
875f0393f06SJeff Roberson 		sched_rem(td);
87661a74c5cSJeff Roberson 		sched_add(td, SRQ_BORING | SRQ_HOLDTD);
877b43179fbSJeff Roberson 	}
878b43179fbSJeff Roberson }
879b43179fbSJeff Roberson 
880f5c157d9SJohn Baldwin /*
881f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
882f5c157d9SJohn Baldwin  * priority.
883f5c157d9SJohn Baldwin  */
884f5c157d9SJohn Baldwin void
885f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
886f5c157d9SJohn Baldwin {
887f5c157d9SJohn Baldwin 
888f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
889f5c157d9SJohn Baldwin 	sched_priority(td, prio);
890f5c157d9SJohn Baldwin }
891f5c157d9SJohn Baldwin 
892f5c157d9SJohn Baldwin /*
893f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
894f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
895f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
896f5c157d9SJohn Baldwin  * requests.  If the thread's regulary priority is less
897f5c157d9SJohn Baldwin  * important than prio the thread will keep a priority boost
898f5c157d9SJohn Baldwin  * of prio.
899f5c157d9SJohn Baldwin  */
900f5c157d9SJohn Baldwin void
901f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
902f5c157d9SJohn Baldwin {
903f5c157d9SJohn Baldwin 	u_char base_pri;
904f5c157d9SJohn Baldwin 
905f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
906f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
9078460a577SJohn Birrell 		base_pri = td->td_user_pri;
908f5c157d9SJohn Baldwin 	else
909f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
910f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
911f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
912f5c157d9SJohn Baldwin 		sched_prio(td, base_pri);
913f5c157d9SJohn Baldwin 	} else
914f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
915f5c157d9SJohn Baldwin }
916f5c157d9SJohn Baldwin 
917f5c157d9SJohn Baldwin void
918f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
919f5c157d9SJohn Baldwin {
920f5c157d9SJohn Baldwin 	u_char oldprio;
921f5c157d9SJohn Baldwin 
922f5c157d9SJohn Baldwin 	/* First, update the base priority. */
923f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
924f5c157d9SJohn Baldwin 
925f5c157d9SJohn Baldwin 	/*
926f5c157d9SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't ever
927f5c157d9SJohn Baldwin 	 * lower the priority.
928f5c157d9SJohn Baldwin 	 */
929f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
930f5c157d9SJohn Baldwin 		return;
931f5c157d9SJohn Baldwin 
932f5c157d9SJohn Baldwin 	/* Change the real priority. */
933f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
934f5c157d9SJohn Baldwin 	sched_priority(td, prio);
935f5c157d9SJohn Baldwin 
936f5c157d9SJohn Baldwin 	/*
937f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
938f5c157d9SJohn Baldwin 	 * its state.
939f5c157d9SJohn Baldwin 	 */
940f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
941f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
942f5c157d9SJohn Baldwin }
943f5c157d9SJohn Baldwin 
944b43179fbSJeff Roberson void
945fea89a28SJohn Baldwin sched_ithread_prio(struct thread *td, u_char prio)
946fea89a28SJohn Baldwin {
947fea89a28SJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
948fea89a28SJohn Baldwin 	MPASS(td->td_pri_class == PRI_ITHD);
949fea89a28SJohn Baldwin 	td->td_base_ithread_pri = prio;
950fea89a28SJohn Baldwin 	sched_prio(td, prio);
951fea89a28SJohn Baldwin }
952fea89a28SJohn Baldwin 
953fea89a28SJohn Baldwin void
9548460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
9553db720fdSDavid Xu {
9563db720fdSDavid Xu 
957435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
9588460a577SJohn Birrell 	td->td_base_user_pri = prio;
959acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
9605a215147SDavid Xu 		return;
9618460a577SJohn Birrell 	td->td_user_pri = prio;
9623db720fdSDavid Xu }
9633db720fdSDavid Xu 
9643db720fdSDavid Xu void
9653db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
9663db720fdSDavid Xu {
9673db720fdSDavid Xu 
968435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
969acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
970c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
971c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
972c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
973c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
974c6d31b83SKonstantin Belousov 		ast_sched_locked(td, TDA_SCHED);
975435806d3SDavid Xu }
9763db720fdSDavid Xu 
977ac97da9aSMateusz Guzik /*
978ac97da9aSMateusz Guzik  * Like the above but first check if there is anything to do.
979ac97da9aSMateusz Guzik  */
980ac97da9aSMateusz Guzik void
981ac97da9aSMateusz Guzik sched_lend_user_prio_cond(struct thread *td, u_char prio)
982ac97da9aSMateusz Guzik {
983ac97da9aSMateusz Guzik 
984*aeff15b3SOlivier Certner 	if (td->td_lend_user_pri == prio)
985ac97da9aSMateusz Guzik 		return;
986ac97da9aSMateusz Guzik 
987ac97da9aSMateusz Guzik 	thread_lock(td);
988ac97da9aSMateusz Guzik 	sched_lend_user_prio(td, prio);
989ac97da9aSMateusz Guzik 	thread_unlock(td);
990ac97da9aSMateusz Guzik }
991ac97da9aSMateusz Guzik 
9923db720fdSDavid Xu void
993c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int pri)
994b43179fbSJeff Roberson {
9952056d0a1SJohn Baldwin 
9967b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
99754b0e65fSJeff Roberson 	td->td_slptick = ticks;
99893ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_slptime = 0;
9992dc29adbSJohn Baldwin 	if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
1000c5aa6b58SJeff Roberson 		sched_prio(td, pri);
1001b43179fbSJeff Roberson }
1002b43179fbSJeff Roberson 
1003b43179fbSJeff Roberson void
1004686bcb5cSJeff Roberson sched_switch(struct thread *td, int flags)
1005b43179fbSJeff Roberson {
1006686bcb5cSJeff Roberson 	struct thread *newtd;
1007b0b9dee5SAttilio Rao 	struct mtx *tmtx;
10083d7f4117SAlexander Motin 	int preempted;
1009b43179fbSJeff Roberson 
101061a74c5cSJeff Roberson 	tmtx = &sched_lock;
1011b43179fbSJeff Roberson 
10127b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
10138aa3d7ffSJohn Baldwin 
1014060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
1015ad9dadc4SAndriy Gapon 	preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
1016ad9dadc4SAndriy Gapon 	    (flags & SW_PREEMPT) != 0;
1017c6d31b83SKonstantin Belousov 	td->td_flags &= ~TDF_SLICEEND;
1018c6d31b83SKonstantin Belousov 	ast_unsched_locked(td, TDA_SCHED);
101977918643SStephan Uphoff 	td->td_owepreempt = 0;
1020ca59f152SJeff Roberson 	td->td_oncpu = NOCPU;
10218aa3d7ffSJohn Baldwin 
1022b43179fbSJeff Roberson 	/*
1023b43179fbSJeff Roberson 	 * At the last moment, if this thread is still marked RUNNING,
1024b43179fbSJeff Roberson 	 * then put it back on the run queue as it has not been suspended
1025bf0acc27SJohn Baldwin 	 * or stopped or any thing else similar.  We never put the idle
1026bf0acc27SJohn Baldwin 	 * threads on the run queue, however.
1027b43179fbSJeff Roberson 	 */
1028c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD) {
1029bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
1030c6226eeaSJulian Elischer #ifdef SMP
1031a38f1f26SAttilio Rao 		CPU_CLR(PCPU_GET(cpuid), &idle_cpus_mask);
1032c6226eeaSJulian Elischer #endif
1033c6226eeaSJulian Elischer 	} else {
1034ed062c8dSJulian Elischer 		if (TD_IS_RUNNING(td)) {
1035ad1e7d28SJulian Elischer 			/* Put us back on the run queue. */
10366a3c02bcSOlivier Certner 			sched_add(td, SRQ_HOLDTD | SRQ_OURSELF | SRQ_YIELDING |
10376a3c02bcSOlivier Certner 			    (preempted ? SRQ_PREEMPTED : 0));
1038ed062c8dSJulian Elischer 		}
1039b43179fbSJeff Roberson 	}
104061a74c5cSJeff Roberson 
104161a74c5cSJeff Roberson 	/*
104261a74c5cSJeff Roberson 	 * Switch to the sched lock to fix things up and pick
104361a74c5cSJeff Roberson 	 * a new thread.  Block the td_lock in order to avoid
104461a74c5cSJeff Roberson 	 * breaking the critical path.
104561a74c5cSJeff Roberson 	 */
104661a74c5cSJeff Roberson 	if (td->td_lock != &sched_lock) {
104761a74c5cSJeff Roberson 		mtx_lock_spin(&sched_lock);
104861a74c5cSJeff Roberson 		tmtx = thread_lock_block(td);
104961a74c5cSJeff Roberson 		mtx_unlock_spin(tmtx);
105061a74c5cSJeff Roberson 	}
105161a74c5cSJeff Roberson 
105261a74c5cSJeff Roberson 	if ((td->td_flags & TDF_NOLOAD) == 0)
105361a74c5cSJeff Roberson 		sched_load_rem();
105461a74c5cSJeff Roberson 
1055ae53b483SJeff Roberson 	newtd = choosethread();
105661a74c5cSJeff Roberson 	MPASS(newtd->td_lock == &sched_lock);
105761a74c5cSJeff Roberson 
1058afa0a46cSAndriy Gapon #if (KTR_COMPILE & KTR_SCHED) != 0
1059afa0a46cSAndriy Gapon 	if (TD_IS_IDLETHREAD(td))
1060afa0a46cSAndriy Gapon 		KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
1061afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority);
1062afa0a46cSAndriy Gapon 	else
1063afa0a46cSAndriy Gapon 		KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
1064afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
1065afa0a46cSAndriy Gapon 		    "lockname:\"%s\"", td->td_lockname);
1066afa0a46cSAndriy Gapon #endif
1067afa0a46cSAndriy Gapon 
1068ebccf1e3SJoseph Koshy 	if (td != newtd) {
1069ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1070ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1071ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1072ebccf1e3SJoseph Koshy #endif
1073b3e9e682SRyan Stone 
10747dba7849SMark Johnston 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1075b3e9e682SRyan Stone 
1076c6226eeaSJulian Elischer                 /* I feel sleepy */
10776a467cc5SMateusz Guzik 		lock_profile_release_lock(&sched_lock.lock_object, true);
10786f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
10796f5f25e5SJohn Birrell 		/*
10806f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
10816f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
10826f5f25e5SJohn Birrell 		 * function to call.
10836f5f25e5SJohn Birrell 		 */
10846f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
10856f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
10866f5f25e5SJohn Birrell #endif
10876f5f25e5SJohn Birrell 
108861a74c5cSJeff Roberson 		cpu_switch(td, newtd, tmtx);
10896a467cc5SMateusz Guzik 		lock_profile_obtain_lock_success(&sched_lock.lock_object, true,
1090eea4f254SJeff Roberson 		    0, 0, __FILE__, __LINE__);
1091c6226eeaSJulian Elischer 		/*
1092c6226eeaSJulian Elischer 		 * Where am I?  What year is it?
1093c6226eeaSJulian Elischer 		 * We are in the same thread that went to sleep above,
10948aa3d7ffSJohn Baldwin 		 * but any amount of time may have passed. All our context
1095c6226eeaSJulian Elischer 		 * will still be available as will local variables.
1096c6226eeaSJulian Elischer 		 * PCPU values however may have changed as we may have
1097c6226eeaSJulian Elischer 		 * changed CPU so don't trust cached values of them.
1098c6226eeaSJulian Elischer 		 * New threads will go to fork_exit() instead of here
1099c6226eeaSJulian Elischer 		 * so if you change things here you may need to change
1100c6226eeaSJulian Elischer 		 * things there too.
11018aa3d7ffSJohn Baldwin 		 *
1102c6226eeaSJulian Elischer 		 * If the thread above was exiting it will never wake
1103c6226eeaSJulian Elischer 		 * up again here, so either it has saved everything it
1104c6226eeaSJulian Elischer 		 * needed to, or the thread_wait() or wait() will
1105c6226eeaSJulian Elischer 		 * need to reap it.
1106c6226eeaSJulian Elischer 		 */
1107b3e9e682SRyan Stone 
1108d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , on__cpu);
1109ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1110ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1111ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1112ebccf1e3SJoseph Koshy #endif
111361a74c5cSJeff Roberson 	} else {
111461a74c5cSJeff Roberson 		td->td_lock = &sched_lock;
1115d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , remain__cpu);
111661a74c5cSJeff Roberson 	}
1117ebccf1e3SJoseph Koshy 
1118afa0a46cSAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
1119afa0a46cSAndriy Gapon 	    "prio:%d", td->td_priority);
1120afa0a46cSAndriy Gapon 
1121c6226eeaSJulian Elischer #ifdef SMP
1122c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD)
1123a38f1f26SAttilio Rao 		CPU_SET(PCPU_GET(cpuid), &idle_cpus_mask);
1124c6226eeaSJulian Elischer #endif
1125ae53b483SJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
1126ae53b483SJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
1127686bcb5cSJeff Roberson 	spinlock_enter();
1128686bcb5cSJeff Roberson 	mtx_unlock_spin(&sched_lock);
1129b43179fbSJeff Roberson }
1130b43179fbSJeff Roberson 
1131b43179fbSJeff Roberson void
113261a74c5cSJeff Roberson sched_wakeup(struct thread *td, int srqflags)
1133b43179fbSJeff Roberson {
113454b0e65fSJeff Roberson 	struct td_sched *ts;
113554b0e65fSJeff Roberson 
11367b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
113793ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
113854b0e65fSJeff Roberson 	if (ts->ts_slptime > 1) {
11398460a577SJohn Birrell 		updatepri(td);
11408460a577SJohn Birrell 		resetpriority(td);
11418460a577SJohn Birrell 	}
11426eac7e57SAttilio Rao 	td->td_slptick = 0;
114354b0e65fSJeff Roberson 	ts->ts_slptime = 0;
114448317e9eSAlexander Motin 	ts->ts_slice = sched_slice;
114540efe743SJohn Baldwin 
114640efe743SJohn Baldwin 	/*
114740efe743SJohn Baldwin 	 * When resuming an idle ithread, restore its base ithread
114840efe743SJohn Baldwin 	 * priority.
114940efe743SJohn Baldwin 	 */
115040efe743SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) == PRI_ITHD &&
115140efe743SJohn Baldwin 	    td->td_base_pri != td->td_base_ithread_pri)
115240efe743SJohn Baldwin 		sched_prio(td, td->td_base_ithread_pri);
115340efe743SJohn Baldwin 
115461a74c5cSJeff Roberson 	sched_add(td, srqflags);
1155b43179fbSJeff Roberson }
1156b43179fbSJeff Roberson 
115737c28a02SJulian Elischer #ifdef SMP
115882a1dfc1SJulian Elischer static int
115982a1dfc1SJulian Elischer forward_wakeup(int cpunum)
116082a1dfc1SJulian Elischer {
116182a1dfc1SJulian Elischer 	struct pcpu *pc;
1162a38f1f26SAttilio Rao 	cpuset_t dontuse, map, map2;
1163a38f1f26SAttilio Rao 	u_int id, me;
116471a19bdcSAttilio Rao 	int iscpuset;
116582a1dfc1SJulian Elischer 
116682a1dfc1SJulian Elischer 	mtx_assert(&sched_lock, MA_OWNED);
116782a1dfc1SJulian Elischer 
1168ed062c8dSJulian Elischer 	CTR0(KTR_RUNQ, "forward_wakeup()");
116982a1dfc1SJulian Elischer 
117082a1dfc1SJulian Elischer 	if ((!forward_wakeup_enabled) ||
117182a1dfc1SJulian Elischer 	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
117282a1dfc1SJulian Elischer 		return (0);
1173879e0604SMateusz Guzik 	if (!smp_started || KERNEL_PANICKED())
117482a1dfc1SJulian Elischer 		return (0);
117582a1dfc1SJulian Elischer 
117682a1dfc1SJulian Elischer 	forward_wakeups_requested++;
117782a1dfc1SJulian Elischer 
117882a1dfc1SJulian Elischer 	/*
11798aa3d7ffSJohn Baldwin 	 * Check the idle mask we received against what we calculated
11808aa3d7ffSJohn Baldwin 	 * before in the old version.
118182a1dfc1SJulian Elischer 	 */
1182a38f1f26SAttilio Rao 	me = PCPU_GET(cpuid);
11838aa3d7ffSJohn Baldwin 
11848aa3d7ffSJohn Baldwin 	/* Don't bother if we should be doing it ourself. */
1185a38f1f26SAttilio Rao 	if (CPU_ISSET(me, &idle_cpus_mask) &&
1186a38f1f26SAttilio Rao 	    (cpunum == NOCPU || me == cpunum))
118782a1dfc1SJulian Elischer 		return (0);
118882a1dfc1SJulian Elischer 
1189a38f1f26SAttilio Rao 	CPU_SETOF(me, &dontuse);
1190e2650af1SStefan Eßer 	CPU_OR(&dontuse, &dontuse, &stopped_cpus);
1191e2650af1SStefan Eßer 	CPU_OR(&dontuse, &dontuse, &hlt_cpus_mask);
119271a19bdcSAttilio Rao 	CPU_ZERO(&map2);
119382a1dfc1SJulian Elischer 	if (forward_wakeup_use_loop) {
1194d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1195a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1196a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &dontuse) &&
119782a1dfc1SJulian Elischer 			    pc->pc_curthread == pc->pc_idlethread) {
1198a38f1f26SAttilio Rao 				CPU_SET(id, &map2);
119982a1dfc1SJulian Elischer 			}
120082a1dfc1SJulian Elischer 		}
120182a1dfc1SJulian Elischer 	}
120282a1dfc1SJulian Elischer 
120382a1dfc1SJulian Elischer 	if (forward_wakeup_use_mask) {
1204ec3af9d0SStefan Eßer 		map = idle_cpus_mask;
1205a19bd8e3SStefan Eßer 		CPU_ANDNOT(&map, &map, &dontuse);
120682a1dfc1SJulian Elischer 
12078aa3d7ffSJohn Baldwin 		/* If they are both on, compare and use loop if different. */
120882a1dfc1SJulian Elischer 		if (forward_wakeup_use_loop) {
120971a19bdcSAttilio Rao 			if (CPU_CMP(&map, &map2)) {
1210f0283a73SAttilio Rao 				printf("map != map2, loop method preferred\n");
1211f0283a73SAttilio Rao 				map = map2;
121282a1dfc1SJulian Elischer 			}
121382a1dfc1SJulian Elischer 		}
121482a1dfc1SJulian Elischer 	} else {
1215f0283a73SAttilio Rao 		map = map2;
121682a1dfc1SJulian Elischer 	}
12178aa3d7ffSJohn Baldwin 
12188aa3d7ffSJohn Baldwin 	/* If we only allow a specific CPU, then mask off all the others. */
121982a1dfc1SJulian Elischer 	if (cpunum != NOCPU) {
122082a1dfc1SJulian Elischer 		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
122171a19bdcSAttilio Rao 		iscpuset = CPU_ISSET(cpunum, &map);
122271a19bdcSAttilio Rao 		if (iscpuset == 0)
122371a19bdcSAttilio Rao 			CPU_ZERO(&map);
122471a19bdcSAttilio Rao 		else
122571a19bdcSAttilio Rao 			CPU_SETOF(cpunum, &map);
122682a1dfc1SJulian Elischer 	}
122771a19bdcSAttilio Rao 	if (!CPU_EMPTY(&map)) {
122882a1dfc1SJulian Elischer 		forward_wakeups_delivered++;
1229d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1230a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1231a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &map))
1232b722ad00SAlexander Motin 				continue;
1233b722ad00SAlexander Motin 			if (cpu_idle_wakeup(pc->pc_cpuid))
1234a38f1f26SAttilio Rao 				CPU_CLR(id, &map);
1235b722ad00SAlexander Motin 		}
123671a19bdcSAttilio Rao 		if (!CPU_EMPTY(&map))
123782a1dfc1SJulian Elischer 			ipi_selected(map, IPI_AST);
123882a1dfc1SJulian Elischer 		return (1);
123982a1dfc1SJulian Elischer 	}
124082a1dfc1SJulian Elischer 	if (cpunum == NOCPU)
124182a1dfc1SJulian Elischer 		printf("forward_wakeup: Idle processor not found\n");
124282a1dfc1SJulian Elischer 	return (0);
124382a1dfc1SJulian Elischer }
1244f3a0f873SStephan Uphoff 
1245f3a0f873SStephan Uphoff static void
1246f3a0f873SStephan Uphoff kick_other_cpu(int pri, int cpuid)
1247f3a0f873SStephan Uphoff {
12488aa3d7ffSJohn Baldwin 	struct pcpu *pcpu;
12498aa3d7ffSJohn Baldwin 	int cpri;
1250f3a0f873SStephan Uphoff 
12518aa3d7ffSJohn Baldwin 	pcpu = pcpu_find(cpuid);
1252a38f1f26SAttilio Rao 	if (CPU_ISSET(cpuid, &idle_cpus_mask)) {
1253f3a0f873SStephan Uphoff 		forward_wakeups_delivered++;
1254b722ad00SAlexander Motin 		if (!cpu_idle_wakeup(cpuid))
1255d9d8d144SJohn Baldwin 			ipi_cpu(cpuid, IPI_AST);
1256f3a0f873SStephan Uphoff 		return;
1257f3a0f873SStephan Uphoff 	}
1258f3a0f873SStephan Uphoff 
12598aa3d7ffSJohn Baldwin 	cpri = pcpu->pc_curthread->td_priority;
1260f3a0f873SStephan Uphoff 	if (pri >= cpri)
1261f3a0f873SStephan Uphoff 		return;
1262f3a0f873SStephan Uphoff 
1263f3a0f873SStephan Uphoff #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1264f3a0f873SStephan Uphoff #if !defined(FULL_PREEMPTION)
1265f3a0f873SStephan Uphoff 	if (pri <= PRI_MAX_ITHD)
1266f3a0f873SStephan Uphoff #endif /* ! FULL_PREEMPTION */
1267f3a0f873SStephan Uphoff 	{
1268d9d8d144SJohn Baldwin 		ipi_cpu(cpuid, IPI_PREEMPT);
1269f3a0f873SStephan Uphoff 		return;
1270f3a0f873SStephan Uphoff 	}
1271f3a0f873SStephan Uphoff #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1272f3a0f873SStephan Uphoff 
1273c2d27b0eSMark Johnston 	if (pcpu->pc_curthread->td_lock == &sched_lock) {
1274c6d31b83SKonstantin Belousov 		ast_sched_locked(pcpu->pc_curthread, TDA_SCHED);
1275d9d8d144SJohn Baldwin 		ipi_cpu(cpuid, IPI_AST);
1276c2d27b0eSMark Johnston 	}
1277f3a0f873SStephan Uphoff }
1278f3a0f873SStephan Uphoff #endif /* SMP */
1279f3a0f873SStephan Uphoff 
1280f200843bSJohn Baldwin #ifdef SMP
1281f200843bSJohn Baldwin static int
1282f200843bSJohn Baldwin sched_pickcpu(struct thread *td)
1283f200843bSJohn Baldwin {
1284f200843bSJohn Baldwin 	int best, cpu;
1285f200843bSJohn Baldwin 
1286f200843bSJohn Baldwin 	mtx_assert(&sched_lock, MA_OWNED);
1287f200843bSJohn Baldwin 
1288e2325d82SJohn Baldwin 	if (td->td_lastcpu != NOCPU && THREAD_CAN_SCHED(td, td->td_lastcpu))
1289c3ea3378SJohn Baldwin 		best = td->td_lastcpu;
1290c3ea3378SJohn Baldwin 	else
1291f200843bSJohn Baldwin 		best = NOCPU;
12923aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1293f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu))
1294f200843bSJohn Baldwin 			continue;
1295f200843bSJohn Baldwin 
1296f200843bSJohn Baldwin 		if (best == NOCPU)
1297f200843bSJohn Baldwin 			best = cpu;
1298f200843bSJohn Baldwin 		else if (runq_length[cpu] < runq_length[best])
1299f200843bSJohn Baldwin 			best = cpu;
1300f200843bSJohn Baldwin 	}
1301f200843bSJohn Baldwin 	KASSERT(best != NOCPU, ("no valid CPUs"));
1302f200843bSJohn Baldwin 
1303f200843bSJohn Baldwin 	return (best);
1304f200843bSJohn Baldwin }
1305f200843bSJohn Baldwin #endif
1306f200843bSJohn Baldwin 
1307b43179fbSJeff Roberson void
13082630e4c9SJulian Elischer sched_add(struct thread *td, int flags)
13096804a3abSJulian Elischer #ifdef SMP
1310f3a0f873SStephan Uphoff {
1311a38f1f26SAttilio Rao 	cpuset_t tidlemsk;
1312ad1e7d28SJulian Elischer 	struct td_sched *ts;
1313a38f1f26SAttilio Rao 	u_int cpu, cpuid;
13146804a3abSJulian Elischer 	int forwarded = 0;
1315f3a0f873SStephan Uphoff 	int single_cpu = 0;
13167cf90fb3SJeff Roberson 
131793ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
13187b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1319f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1320f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1321f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1322f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1323b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1324b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
13258f51ad55SJeff Roberson 
13268f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
13278f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
13288f51ad55SJeff Roberson 	    sched_tdname(curthread));
13298f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
13308f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
1331b3e9e682SRyan Stone 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1332b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
13338f51ad55SJeff Roberson 
13347b20fb19SJeff Roberson 	/*
13357b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
13367b20fb19SJeff Roberson 	 * to the scheduler's lock.
13377b20fb19SJeff Roberson 	 */
13387b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
13397b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
134061a74c5cSJeff Roberson 		if ((flags & SRQ_HOLD) != 0)
134161a74c5cSJeff Roberson 			td->td_lock = &sched_lock;
134261a74c5cSJeff Roberson 		else
13437b20fb19SJeff Roberson 			thread_lock_set(td, &sched_lock);
13447b20fb19SJeff Roberson 	}
1345f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1346f3a0f873SStephan Uphoff 
134760dd73b7SRyan Stone 	/*
134860dd73b7SRyan Stone 	 * If SMP is started and the thread is pinned or otherwise limited to
134960dd73b7SRyan Stone 	 * a specific set of CPUs, queue the thread to a per-CPU run queue.
135060dd73b7SRyan Stone 	 * Otherwise, queue the thread to the global run queue.
135160dd73b7SRyan Stone 	 *
135260dd73b7SRyan Stone 	 * If SMP has not yet been started we must use the global run queue
135360dd73b7SRyan Stone 	 * as per-CPU state may not be initialized yet and we may crash if we
135460dd73b7SRyan Stone 	 * try to access the per-CPU run queues.
135560dd73b7SRyan Stone 	 */
135660dd73b7SRyan Stone 	if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
135760dd73b7SRyan Stone 	    ts->ts_flags & TSF_AFFINITY)) {
135860dd73b7SRyan Stone 		if (td->td_pinned != 0)
1359f3a0f873SStephan Uphoff 			cpu = td->td_lastcpu;
136060dd73b7SRyan Stone 		else if (td->td_flags & TDF_BOUND) {
13618aa3d7ffSJohn Baldwin 			/* Find CPU from bound runq. */
13628aa3d7ffSJohn Baldwin 			KASSERT(SKE_RUNQ_PCPU(ts),
13638aa3d7ffSJohn Baldwin 			    ("sched_add: bound td_sched not on cpu runq"));
1364ad1e7d28SJulian Elischer 			cpu = ts->ts_runq - &runq_pcpu[0];
136560dd73b7SRyan Stone 		} else
1366f200843bSJohn Baldwin 			/* Find a valid CPU for our cpuset */
1367f200843bSJohn Baldwin 			cpu = sched_pickcpu(td);
1368f200843bSJohn Baldwin 		ts->ts_runq = &runq_pcpu[cpu];
1369f200843bSJohn Baldwin 		single_cpu = 1;
1370f200843bSJohn Baldwin 		CTR3(KTR_RUNQ,
1371f200843bSJohn Baldwin 		    "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1372f200843bSJohn Baldwin 		    cpu);
1373f3a0f873SStephan Uphoff 	} else {
13746804a3abSJulian Elischer 		CTR2(KTR_RUNQ,
13758aa3d7ffSJohn Baldwin 		    "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
13768aa3d7ffSJohn Baldwin 		    td);
13776804a3abSJulian Elischer 		cpu = NOCPU;
1378ad1e7d28SJulian Elischer 		ts->ts_runq = &runq;
1379e17c57b1SJeff Roberson 	}
1380f3a0f873SStephan Uphoff 
1381a6b91f0fSJohn Baldwin 	if ((td->td_flags & TDF_NOLOAD) == 0)
1382a6b91f0fSJohn Baldwin 		sched_load_add();
1383a6b91f0fSJohn Baldwin 	runq_add(ts->ts_runq, td, flags);
1384a6b91f0fSJohn Baldwin 	if (cpu != NOCPU)
1385a6b91f0fSJohn Baldwin 		runq_length[cpu]++;
1386a6b91f0fSJohn Baldwin 
1387a38f1f26SAttilio Rao 	cpuid = PCPU_GET(cpuid);
1388a38f1f26SAttilio Rao 	if (single_cpu && cpu != cpuid) {
1389f3a0f873SStephan Uphoff 	        kick_other_cpu(td->td_priority, cpu);
1390f3a0f873SStephan Uphoff 	} else {
1391f3a0f873SStephan Uphoff 		if (!single_cpu) {
1392a19bd8e3SStefan Eßer 			tidlemsk = idle_cpus_mask;
1393a19bd8e3SStefan Eßer 			CPU_ANDNOT(&tidlemsk, &tidlemsk, &hlt_cpus_mask);
1394a38f1f26SAttilio Rao 			CPU_CLR(cpuid, &tidlemsk);
1395f3a0f873SStephan Uphoff 
1396a38f1f26SAttilio Rao 			if (!CPU_ISSET(cpuid, &idle_cpus_mask) &&
1397a38f1f26SAttilio Rao 			    ((flags & SRQ_INTR) == 0) &&
139871a19bdcSAttilio Rao 			    !CPU_EMPTY(&tidlemsk))
1399f3a0f873SStephan Uphoff 				forwarded = forward_wakeup(cpu);
1400f3a0f873SStephan Uphoff 		}
1401f3a0f873SStephan Uphoff 
1402f3a0f873SStephan Uphoff 		if (!forwarded) {
1403a6b91f0fSJohn Baldwin 			if (!maybe_preempt(td))
1404f3a0f873SStephan Uphoff 				maybe_resched(td);
1405f3a0f873SStephan Uphoff 		}
1406f3a0f873SStephan Uphoff 	}
140761a74c5cSJeff Roberson 	if ((flags & SRQ_HOLDTD) == 0)
140861a74c5cSJeff Roberson 		thread_unlock(td);
1409f3a0f873SStephan Uphoff }
1410f3a0f873SStephan Uphoff #else /* SMP */
1411f3a0f873SStephan Uphoff {
1412ad1e7d28SJulian Elischer 	struct td_sched *ts;
1413f200843bSJohn Baldwin 
141493ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
14157b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1416f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1417f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1418f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1419f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1420b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1421b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
14228f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
14238f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
14248f51ad55SJeff Roberson 	    sched_tdname(curthread));
14258f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
14268f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
14272aaae99dSSergey Kandaurov 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1428b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
14298aa3d7ffSJohn Baldwin 
14307b20fb19SJeff Roberson 	/*
14317b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
14327b20fb19SJeff Roberson 	 * to the scheduler's lock.
14337b20fb19SJeff Roberson 	 */
14347b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
14357b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
143661a74c5cSJeff Roberson 		if ((flags & SRQ_HOLD) != 0)
143761a74c5cSJeff Roberson 			td->td_lock = &sched_lock;
143861a74c5cSJeff Roberson 		else
14397b20fb19SJeff Roberson 			thread_lock_set(td, &sched_lock);
14407b20fb19SJeff Roberson 	}
1441f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1442ad1e7d28SJulian Elischer 	CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1443ad1e7d28SJulian Elischer 	ts->ts_runq = &runq;
14446804a3abSJulian Elischer 
14451b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1446907bdbc2SJeff Roberson 		sched_load_add();
14479727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
1448a6b91f0fSJohn Baldwin 	if (!maybe_preempt(td))
14496942d433SJohn Baldwin 		maybe_resched(td);
145061a74c5cSJeff Roberson 	if ((flags & SRQ_HOLDTD) == 0)
145161a74c5cSJeff Roberson 		thread_unlock(td);
1452b43179fbSJeff Roberson }
1453f3a0f873SStephan Uphoff #endif /* SMP */
1454f3a0f873SStephan Uphoff 
1455b43179fbSJeff Roberson void
14567cf90fb3SJeff Roberson sched_rem(struct thread *td)
1457b43179fbSJeff Roberson {
1458ad1e7d28SJulian Elischer 	struct td_sched *ts;
14597cf90fb3SJeff Roberson 
146093ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1461b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1462b61ce5b0SJeff Roberson 	    ("sched_rem: thread swapped out"));
1463f0393f06SJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
1464ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
1465b43179fbSJeff Roberson 	mtx_assert(&sched_lock, MA_OWNED);
14668f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
14678f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
14688f51ad55SJeff Roberson 	    sched_tdname(curthread));
1469b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
1470b43179fbSJeff Roberson 
14711b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1472907bdbc2SJeff Roberson 		sched_load_rem();
1473f200843bSJohn Baldwin #ifdef SMP
1474f200843bSJohn Baldwin 	if (ts->ts_runq != &runq)
1475f200843bSJohn Baldwin 		runq_length[ts->ts_runq - runq_pcpu]--;
1476f200843bSJohn Baldwin #endif
14779727e637SJeff Roberson 	runq_remove(ts->ts_runq, td);
1478f0393f06SJeff Roberson 	TD_SET_CAN_RUN(td);
1479b43179fbSJeff Roberson }
1480b43179fbSJeff Roberson 
148114f0e2e9SJulian Elischer /*
14828aa3d7ffSJohn Baldwin  * Select threads to run.  Note that running threads still consume a
14838aa3d7ffSJohn Baldwin  * slot.
148414f0e2e9SJulian Elischer  */
1485f0393f06SJeff Roberson struct thread *
1486b43179fbSJeff Roberson sched_choose(void)
1487b43179fbSJeff Roberson {
14889727e637SJeff Roberson 	struct thread *td;
1489e17c57b1SJeff Roberson 	struct runq *rq;
1490b43179fbSJeff Roberson 
14917b20fb19SJeff Roberson 	mtx_assert(&sched_lock,  MA_OWNED);
1492e17c57b1SJeff Roberson #ifdef SMP
14939727e637SJeff Roberson 	struct thread *tdcpu;
1494e17c57b1SJeff Roberson 
1495e17c57b1SJeff Roberson 	rq = &runq;
14969727e637SJeff Roberson 	td = runq_choose_fuzz(&runq, runq_fuzz);
14979727e637SJeff Roberson 	tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1498e17c57b1SJeff Roberson 
14999727e637SJeff Roberson 	if (td == NULL ||
15009727e637SJeff Roberson 	    (tdcpu != NULL &&
15019727e637SJeff Roberson 	     tdcpu->td_priority < td->td_priority)) {
15029727e637SJeff Roberson 		CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1503e17c57b1SJeff Roberson 		     PCPU_GET(cpuid));
15049727e637SJeff Roberson 		td = tdcpu;
1505e17c57b1SJeff Roberson 		rq = &runq_pcpu[PCPU_GET(cpuid)];
1506e17c57b1SJeff Roberson 	} else {
15079727e637SJeff Roberson 		CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1508e17c57b1SJeff Roberson 	}
1509e17c57b1SJeff Roberson 
1510e17c57b1SJeff Roberson #else
1511e17c57b1SJeff Roberson 	rq = &runq;
15129727e637SJeff Roberson 	td = runq_choose(&runq);
1513e17c57b1SJeff Roberson #endif
1514b43179fbSJeff Roberson 
15159727e637SJeff Roberson 	if (td) {
1516f200843bSJohn Baldwin #ifdef SMP
1517f200843bSJohn Baldwin 		if (td == tdcpu)
1518f200843bSJohn Baldwin 			runq_length[PCPU_GET(cpuid)]--;
1519f200843bSJohn Baldwin #endif
15209727e637SJeff Roberson 		runq_remove(rq, td);
15219727e637SJeff Roberson 		td->td_flags |= TDF_DIDRUN;
1522b43179fbSJeff Roberson 
15239727e637SJeff Roberson 		KASSERT(td->td_flags & TDF_INMEM,
1524b61ce5b0SJeff Roberson 		    ("sched_choose: thread swapped out"));
15259727e637SJeff Roberson 		return (td);
1526b43179fbSJeff Roberson 	}
1527f0393f06SJeff Roberson 	return (PCPU_GET(idlethread));
1528b43179fbSJeff Roberson }
1529b43179fbSJeff Roberson 
1530b43179fbSJeff Roberson void
15311e24c28fSJeff Roberson sched_preempt(struct thread *td)
15321e24c28fSJeff Roberson {
1533bff02948SMitchell Horne 	int flags;
1534b3e9e682SRyan Stone 
1535b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
1536686bcb5cSJeff Roberson 	if (td->td_critnest > 1) {
15371e24c28fSJeff Roberson 		td->td_owepreempt = 1;
1538686bcb5cSJeff Roberson 	} else {
1539686bcb5cSJeff Roberson 		thread_lock(td);
1540bff02948SMitchell Horne 		flags = SW_INVOL | SW_PREEMPT;
1541bff02948SMitchell Horne 		flags |= TD_IS_IDLETHREAD(td) ? SWT_REMOTEWAKEIDLE :
1542bff02948SMitchell Horne 		    SWT_REMOTEPREEMPT;
1543bff02948SMitchell Horne 		mi_switch(flags);
1544686bcb5cSJeff Roberson 	}
15451e24c28fSJeff Roberson }
15461e24c28fSJeff Roberson 
15471e24c28fSJeff Roberson void
154828240885SMateusz Guzik sched_userret_slowpath(struct thread *td)
1549b43179fbSJeff Roberson {
155028240885SMateusz Guzik 
15517b20fb19SJeff Roberson 	thread_lock(td);
15528460a577SJohn Birrell 	td->td_priority = td->td_user_pri;
15538460a577SJohn Birrell 	td->td_base_pri = td->td_user_pri;
15547b20fb19SJeff Roberson 	thread_unlock(td);
15558460a577SJohn Birrell }
1556de028f5aSJeff Roberson 
1557e17c57b1SJeff Roberson void
1558e17c57b1SJeff Roberson sched_bind(struct thread *td, int cpu)
1559e17c57b1SJeff Roberson {
15608758ac75SJohn Baldwin #ifdef SMP
15618758ac75SJohn Baldwin 	struct td_sched *ts = td_get_sched(td);
15628758ac75SJohn Baldwin #endif
1563e17c57b1SJeff Roberson 
15641d7830edSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
15651d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1566e17c57b1SJeff Roberson 
15679727e637SJeff Roberson 	td->td_flags |= TDF_BOUND;
1568e17c57b1SJeff Roberson #ifdef SMP
1569ad1e7d28SJulian Elischer 	ts->ts_runq = &runq_pcpu[cpu];
1570e17c57b1SJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
1571e17c57b1SJeff Roberson 		return;
1572e17c57b1SJeff Roberson 
15731029dab6SMitchell Horne 	mi_switch(SW_VOL | SWT_BIND);
1574686bcb5cSJeff Roberson 	thread_lock(td);
1575e17c57b1SJeff Roberson #endif
1576e17c57b1SJeff Roberson }
1577e17c57b1SJeff Roberson 
1578e17c57b1SJeff Roberson void
1579e17c57b1SJeff Roberson sched_unbind(struct thread* td)
1580e17c57b1SJeff Roberson {
15817b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
15821d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
15839727e637SJeff Roberson 	td->td_flags &= ~TDF_BOUND;
1584e17c57b1SJeff Roberson }
1585e17c57b1SJeff Roberson 
1586de028f5aSJeff Roberson int
1587ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
1588ebccf1e3SJoseph Koshy {
15897b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
15909727e637SJeff Roberson 	return (td->td_flags & TDF_BOUND);
1591ebccf1e3SJoseph Koshy }
1592ebccf1e3SJoseph Koshy 
159336ec198bSDavid Xu void
159436ec198bSDavid Xu sched_relinquish(struct thread *td)
159536ec198bSDavid Xu {
15967b20fb19SJeff Roberson 	thread_lock(td);
1597686bcb5cSJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH);
159836ec198bSDavid Xu }
159936ec198bSDavid Xu 
1600ebccf1e3SJoseph Koshy int
1601ca59f152SJeff Roberson sched_load(void)
1602ca59f152SJeff Roberson {
1603ca59f152SJeff Roberson 	return (sched_tdcnt);
1604ca59f152SJeff Roberson }
1605ca59f152SJeff Roberson 
1606de028f5aSJeff Roberson int
1607de028f5aSJeff Roberson sched_sizeof_proc(void)
1608de028f5aSJeff Roberson {
1609de028f5aSJeff Roberson 	return (sizeof(struct proc));
1610de028f5aSJeff Roberson }
161136ec198bSDavid Xu 
1612de028f5aSJeff Roberson int
1613de028f5aSJeff Roberson sched_sizeof_thread(void)
1614de028f5aSJeff Roberson {
1615ad1e7d28SJulian Elischer 	return (sizeof(struct thread) + sizeof(struct td_sched));
1616de028f5aSJeff Roberson }
161779acfc49SJeff Roberson 
161879acfc49SJeff Roberson fixpt_t
16197cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
162079acfc49SJeff Roberson {
1621ad1e7d28SJulian Elischer 	struct td_sched *ts;
162255f2099aSJeff Roberson 
16233da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
162493ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1625ad1e7d28SJulian Elischer 	return (ts->ts_pctcpu);
162679acfc49SJeff Roberson }
1627b41f1452SDavid Xu 
162836af9869SEdward Tomasz Napierala #ifdef RACCT
162936af9869SEdward Tomasz Napierala /*
163036af9869SEdward Tomasz Napierala  * Calculates the contribution to the thread cpu usage for the latest
163136af9869SEdward Tomasz Napierala  * (unfinished) second.
163236af9869SEdward Tomasz Napierala  */
163336af9869SEdward Tomasz Napierala fixpt_t
163436af9869SEdward Tomasz Napierala sched_pctcpu_delta(struct thread *td)
163536af9869SEdward Tomasz Napierala {
163636af9869SEdward Tomasz Napierala 	struct td_sched *ts;
163736af9869SEdward Tomasz Napierala 	fixpt_t delta;
163836af9869SEdward Tomasz Napierala 	int realstathz;
163936af9869SEdward Tomasz Napierala 
164036af9869SEdward Tomasz Napierala 	THREAD_LOCK_ASSERT(td, MA_OWNED);
164193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
164236af9869SEdward Tomasz Napierala 	delta = 0;
164336af9869SEdward Tomasz Napierala 	realstathz = stathz ? stathz : hz;
164436af9869SEdward Tomasz Napierala 	if (ts->ts_cpticks != 0) {
164536af9869SEdward Tomasz Napierala #if	(FSHIFT >= CCPU_SHIFT)
164636af9869SEdward Tomasz Napierala 		delta = (realstathz == 100)
164736af9869SEdward Tomasz Napierala 		    ? ((fixpt_t) ts->ts_cpticks) <<
164836af9869SEdward Tomasz Napierala 		    (FSHIFT - CCPU_SHIFT) :
164936af9869SEdward Tomasz Napierala 		    100 * (((fixpt_t) ts->ts_cpticks)
165036af9869SEdward Tomasz Napierala 		    << (FSHIFT - CCPU_SHIFT)) / realstathz;
165136af9869SEdward Tomasz Napierala #else
165236af9869SEdward Tomasz Napierala 		delta = ((FSCALE - ccpu) *
165336af9869SEdward Tomasz Napierala 		    (ts->ts_cpticks *
165436af9869SEdward Tomasz Napierala 		    FSCALE / realstathz)) >> FSHIFT;
165536af9869SEdward Tomasz Napierala #endif
165636af9869SEdward Tomasz Napierala 	}
165736af9869SEdward Tomasz Napierala 
165836af9869SEdward Tomasz Napierala 	return (delta);
165936af9869SEdward Tomasz Napierala }
166036af9869SEdward Tomasz Napierala #endif
166136af9869SEdward Tomasz Napierala 
1662ccd0ec40SKonstantin Belousov u_int
1663ccd0ec40SKonstantin Belousov sched_estcpu(struct thread *td)
1664b41f1452SDavid Xu {
1665ccd0ec40SKonstantin Belousov 
166693ccd6bfSKonstantin Belousov 	return (td_get_sched(td)->ts_estcpu);
1667b41f1452SDavid Xu }
1668f0393f06SJeff Roberson 
1669f0393f06SJeff Roberson /*
1670f0393f06SJeff Roberson  * The actual idle process.
1671f0393f06SJeff Roberson  */
1672f0393f06SJeff Roberson void
1673f0393f06SJeff Roberson sched_idletd(void *dummy)
1674f0393f06SJeff Roberson {
1675b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
1676f0393f06SJeff Roberson 
1677ba96d2d8SJohn Baldwin 	THREAD_NO_SLEEPING();
1678b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
1679f0393f06SJeff Roberson 	for (;;) {
1680f0393f06SJeff Roberson 		mtx_assert(&Giant, MA_NOTOWNED);
1681f0393f06SJeff Roberson 
1682b722ad00SAlexander Motin 		while (sched_runnable() == 0) {
1683b722ad00SAlexander Motin 			cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1684b722ad00SAlexander Motin 			stat->idlecalls++;
1685b722ad00SAlexander Motin 		}
1686f0393f06SJeff Roberson 
1687f0393f06SJeff Roberson 		mtx_lock_spin(&sched_lock);
1688686bcb5cSJeff Roberson 		mi_switch(SW_VOL | SWT_IDLE);
1689f0393f06SJeff Roberson 	}
1690f0393f06SJeff Roberson }
1691f0393f06SJeff Roberson 
16926a8ea6d1SKyle Evans static void
16936a8ea6d1SKyle Evans sched_throw_tail(struct thread *td)
16946a8ea6d1SKyle Evans {
16956a8ea6d1SKyle Evans 
16966a8ea6d1SKyle Evans 	mtx_assert(&sched_lock, MA_OWNED);
16976a8ea6d1SKyle Evans 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
16986a8ea6d1SKyle Evans 	cpu_throw(td, choosethread());	/* doesn't return */
16996a8ea6d1SKyle Evans }
17006a8ea6d1SKyle Evans 
17017b20fb19SJeff Roberson /*
17026a8ea6d1SKyle Evans  * A CPU is entering for the first time.
17037b20fb19SJeff Roberson  */
17047b20fb19SJeff Roberson void
17056a8ea6d1SKyle Evans sched_ap_entry(void)
17067b20fb19SJeff Roberson {
17076a8ea6d1SKyle Evans 
17087b20fb19SJeff Roberson 	/*
17097b20fb19SJeff Roberson 	 * Correct spinlock nesting.  The idle thread context that we are
17107b20fb19SJeff Roberson 	 * borrowing was created so that it would start out with a single
17117b20fb19SJeff Roberson 	 * spin lock (sched_lock) held in fork_trampoline().  Since we've
17127b20fb19SJeff Roberson 	 * explicitly acquired locks in this function, the nesting count
17137b20fb19SJeff Roberson 	 * is now 2 rather than 1.  Since we are nested, calling
17147b20fb19SJeff Roberson 	 * spinlock_exit() will simply adjust the counts without allowing
17157b20fb19SJeff Roberson 	 * spin lock using code to interrupt us.
17167b20fb19SJeff Roberson 	 */
17177b20fb19SJeff Roberson 	mtx_lock_spin(&sched_lock);
17187b20fb19SJeff Roberson 	spinlock_exit();
17197e3a96eaSJohn Baldwin 	PCPU_SET(switchtime, cpu_ticks());
17207e3a96eaSJohn Baldwin 	PCPU_SET(switchticks, ticks);
17216a8ea6d1SKyle Evans 
17226a8ea6d1SKyle Evans 	sched_throw_tail(NULL);
17236a8ea6d1SKyle Evans }
17246a8ea6d1SKyle Evans 
17256a8ea6d1SKyle Evans /*
17266a8ea6d1SKyle Evans  * A thread is exiting.
17276a8ea6d1SKyle Evans  */
17286a8ea6d1SKyle Evans void
17296a8ea6d1SKyle Evans sched_throw(struct thread *td)
17306a8ea6d1SKyle Evans {
17316a8ea6d1SKyle Evans 
17326a8ea6d1SKyle Evans 	MPASS(td != NULL);
17337b20fb19SJeff Roberson 	MPASS(td->td_lock == &sched_lock);
17346a8ea6d1SKyle Evans 
17356a8ea6d1SKyle Evans 	lock_profile_release_lock(&sched_lock.lock_object, true);
173692de34dfSJohn Baldwin 	td->td_lastcpu = td->td_oncpu;
173792de34dfSJohn Baldwin 	td->td_oncpu = NOCPU;
17386a8ea6d1SKyle Evans 
17396a8ea6d1SKyle Evans 	sched_throw_tail(td);
17407b20fb19SJeff Roberson }
17417b20fb19SJeff Roberson 
17427b20fb19SJeff Roberson void
1743fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
17447b20fb19SJeff Roberson {
17457b20fb19SJeff Roberson 
17467b20fb19SJeff Roberson 	/*
17477b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
17487b20fb19SJeff Roberson 	 * non-nested critical section with sched_lock held but not recursed.
17497b20fb19SJeff Roberson 	 */
1750fe54587fSJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
1751fe54587fSJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
17526a467cc5SMateusz Guzik 	lock_profile_obtain_lock_success(&sched_lock.lock_object, true,
1753eea4f254SJeff Roberson 	    0, 0, __FILE__, __LINE__);
1754fe54587fSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
175528ef18b8SAndriy Gapon 
175628ef18b8SAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
175728ef18b8SAndriy Gapon 	    "prio:%d", td->td_priority);
175828ef18b8SAndriy Gapon 	SDT_PROBE0(sched, , , on__cpu);
17597b20fb19SJeff Roberson }
17607b20fb19SJeff Roberson 
17618f51ad55SJeff Roberson char *
17628f51ad55SJeff Roberson sched_tdname(struct thread *td)
17638f51ad55SJeff Roberson {
17648f51ad55SJeff Roberson #ifdef KTR
17658f51ad55SJeff Roberson 	struct td_sched *ts;
17668f51ad55SJeff Roberson 
176793ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
17688f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
17698f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
17708f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
17718f51ad55SJeff Roberson 	return (ts->ts_name);
17728f51ad55SJeff Roberson #else
17738f51ad55SJeff Roberson 	return (td->td_name);
17748f51ad55SJeff Roberson #endif
17758f51ad55SJeff Roberson }
17768f51ad55SJeff Roberson 
177744ad5475SJohn Baldwin #ifdef KTR
177844ad5475SJohn Baldwin void
177944ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
178044ad5475SJohn Baldwin {
178144ad5475SJohn Baldwin 	struct td_sched *ts;
178244ad5475SJohn Baldwin 
178393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
178444ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
178544ad5475SJohn Baldwin }
178644ad5475SJohn Baldwin #endif
178744ad5475SJohn Baldwin 
1788885d51a3SJeff Roberson void
1789885d51a3SJeff Roberson sched_affinity(struct thread *td)
1790885d51a3SJeff Roberson {
1791f200843bSJohn Baldwin #ifdef SMP
1792f200843bSJohn Baldwin 	struct td_sched *ts;
1793f200843bSJohn Baldwin 	int cpu;
1794f200843bSJohn Baldwin 
1795f200843bSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1796f200843bSJohn Baldwin 
1797f200843bSJohn Baldwin 	/*
1798f200843bSJohn Baldwin 	 * Set the TSF_AFFINITY flag if there is at least one CPU this
1799f200843bSJohn Baldwin 	 * thread can't run on.
1800f200843bSJohn Baldwin 	 */
180193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1802f200843bSJohn Baldwin 	ts->ts_flags &= ~TSF_AFFINITY;
18033aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1804f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu)) {
1805f200843bSJohn Baldwin 			ts->ts_flags |= TSF_AFFINITY;
1806f200843bSJohn Baldwin 			break;
1807f200843bSJohn Baldwin 		}
1808f200843bSJohn Baldwin 	}
1809f200843bSJohn Baldwin 
1810f200843bSJohn Baldwin 	/*
1811f200843bSJohn Baldwin 	 * If this thread can run on all CPUs, nothing else to do.
1812f200843bSJohn Baldwin 	 */
1813f200843bSJohn Baldwin 	if (!(ts->ts_flags & TSF_AFFINITY))
1814f200843bSJohn Baldwin 		return;
1815f200843bSJohn Baldwin 
1816f200843bSJohn Baldwin 	/* Pinned threads and bound threads should be left alone. */
1817f200843bSJohn Baldwin 	if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1818f200843bSJohn Baldwin 		return;
1819f200843bSJohn Baldwin 
1820fa2528acSAlex Richardson 	switch (TD_GET_STATE(td)) {
1821f200843bSJohn Baldwin 	case TDS_RUNQ:
1822f200843bSJohn Baldwin 		/*
1823f200843bSJohn Baldwin 		 * If we are on a per-CPU runqueue that is in the set,
1824f200843bSJohn Baldwin 		 * then nothing needs to be done.
1825f200843bSJohn Baldwin 		 */
1826f200843bSJohn Baldwin 		if (ts->ts_runq != &runq &&
1827f200843bSJohn Baldwin 		    THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1828f200843bSJohn Baldwin 			return;
1829f200843bSJohn Baldwin 
1830f200843bSJohn Baldwin 		/* Put this thread on a valid per-CPU runqueue. */
1831f200843bSJohn Baldwin 		sched_rem(td);
183261a74c5cSJeff Roberson 		sched_add(td, SRQ_HOLDTD | SRQ_BORING);
1833f200843bSJohn Baldwin 		break;
1834f200843bSJohn Baldwin 	case TDS_RUNNING:
1835f200843bSJohn Baldwin 		/*
1836f200843bSJohn Baldwin 		 * See if our current CPU is in the set.  If not, force a
1837f200843bSJohn Baldwin 		 * context switch.
1838f200843bSJohn Baldwin 		 */
1839f200843bSJohn Baldwin 		if (THREAD_CAN_SCHED(td, td->td_oncpu))
1840f200843bSJohn Baldwin 			return;
1841f200843bSJohn Baldwin 
1842c6d31b83SKonstantin Belousov 		ast_sched_locked(td, TDA_SCHED);
1843f200843bSJohn Baldwin 		if (td != curthread)
1844d9d8d144SJohn Baldwin 			ipi_cpu(cpu, IPI_AST);
1845f200843bSJohn Baldwin 		break;
1846f200843bSJohn Baldwin 	default:
1847f200843bSJohn Baldwin 		break;
1848f200843bSJohn Baldwin 	}
1849f200843bSJohn Baldwin #endif
1850885d51a3SJeff Roberson }
1851