xref: /freebsd/sys/kern/sched_4bsd.c (revision 686bcb5c14aba6e67524be84e125bfdd3514db9e)
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>
38677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
39677b542eSDavid E. O'Brien 
404da0d332SPeter Wemm #include "opt_hwpmc_hooks.h"
41a564bfc7SJeff Roberson #include "opt_sched.h"
424da0d332SPeter Wemm 
43b43179fbSJeff Roberson #include <sys/param.h>
44b43179fbSJeff Roberson #include <sys/systm.h>
45f5a3ef99SMarcel Moolenaar #include <sys/cpuset.h>
46b43179fbSJeff Roberson #include <sys/kernel.h>
47b43179fbSJeff Roberson #include <sys/ktr.h>
48b43179fbSJeff Roberson #include <sys/lock.h>
49c55bbb6cSJohn Baldwin #include <sys/kthread.h>
50b43179fbSJeff Roberson #include <sys/mutex.h>
51b43179fbSJeff Roberson #include <sys/proc.h>
52b43179fbSJeff Roberson #include <sys/resourcevar.h>
53b43179fbSJeff Roberson #include <sys/sched.h>
54b3e9e682SRyan Stone #include <sys/sdt.h>
55b43179fbSJeff Roberson #include <sys/smp.h>
56b43179fbSJeff Roberson #include <sys/sysctl.h>
57b43179fbSJeff Roberson #include <sys/sx.h>
58f5c157d9SJohn Baldwin #include <sys/turnstile.h>
593db720fdSDavid Xu #include <sys/umtx.h>
602e4db89cSDavid E. O'Brien #include <machine/pcb.h>
61293968d8SJulian Elischer #include <machine/smp.h>
62b43179fbSJeff Roberson 
63ebccf1e3SJoseph Koshy #ifdef HWPMC_HOOKS
64ebccf1e3SJoseph Koshy #include <sys/pmckern.h>
65ebccf1e3SJoseph Koshy #endif
66ebccf1e3SJoseph Koshy 
676f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
686f5f25e5SJohn Birrell #include <sys/dtrace_bsd.h>
6961322a0aSAlexander Motin int __read_mostly		dtrace_vtime_active;
706f5f25e5SJohn Birrell dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
716f5f25e5SJohn Birrell #endif
726f5f25e5SJohn Birrell 
7306439a04SJeff Roberson /*
7406439a04SJeff Roberson  * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
7506439a04SJeff Roberson  * the range 100-256 Hz (approximately).
7606439a04SJeff Roberson  */
7706439a04SJeff Roberson #define	ESTCPULIM(e) \
7806439a04SJeff Roberson     min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
7906439a04SJeff Roberson     RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
80b698380fSBruce Evans #ifdef SMP
81b698380fSBruce Evans #define	INVERSE_ESTCPU_WEIGHT	(8 * smp_cpus)
82b698380fSBruce Evans #else
8306439a04SJeff Roberson #define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
84b698380fSBruce Evans #endif
8506439a04SJeff Roberson #define	NICE_WEIGHT		1	/* Priorities per nice level. */
8606439a04SJeff Roberson 
870d2cf837SJeff Roberson #define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
888f51ad55SJeff Roberson 
898460a577SJohn Birrell /*
908460a577SJohn Birrell  * The schedulable entity that runs a context.
91ad1e7d28SJulian Elischer  * This is  an extension to the thread structure and is tailored to
92ccd0ec40SKonstantin Belousov  * the requirements of this scheduler.
93ccd0ec40SKonstantin Belousov  * All fields are protected by the scheduler lock.
948460a577SJohn Birrell  */
95ad1e7d28SJulian Elischer struct td_sched {
96ccd0ec40SKonstantin Belousov 	fixpt_t		ts_pctcpu;	/* %cpu during p_swtime. */
97ccd0ec40SKonstantin Belousov 	u_int		ts_estcpu;	/* Estimated cpu utilization. */
98ccd0ec40SKonstantin Belousov 	int		ts_cpticks;	/* Ticks of cpu time. */
99ccd0ec40SKonstantin Belousov 	int		ts_slptime;	/* Seconds !RUNNING. */
10048317e9eSAlexander Motin 	int		ts_slice;	/* Remaining part of time slice. */
101f200843bSJohn Baldwin 	int		ts_flags;
102ad1e7d28SJulian Elischer 	struct runq	*ts_runq;	/* runq the thread is currently on */
1038f51ad55SJeff Roberson #ifdef KTR
1048f51ad55SJeff Roberson 	char		ts_name[TS_NAME_LEN];
1058f51ad55SJeff Roberson #endif
106bcb06d59SJeff Roberson };
107ed062c8dSJulian Elischer 
108ed062c8dSJulian Elischer /* flags kept in td_flags */
109ad1e7d28SJulian Elischer #define TDF_DIDRUN	TDF_SCHED0	/* thread actually ran. */
1109727e637SJeff Roberson #define TDF_BOUND	TDF_SCHED1	/* Bound to one CPU. */
1113d7f4117SAlexander Motin #define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
112bcb06d59SJeff Roberson 
113f200843bSJohn Baldwin /* flags kept in ts_flags */
114f200843bSJohn Baldwin #define	TSF_AFFINITY	0x0001		/* Has a non-"full" CPU set. */
115f200843bSJohn Baldwin 
116ad1e7d28SJulian Elischer #define SKE_RUNQ_PCPU(ts)						\
117ad1e7d28SJulian Elischer     ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
118e17c57b1SJeff Roberson 
119f200843bSJohn Baldwin #define	THREAD_CAN_SCHED(td, cpu)	\
120f200843bSJohn Baldwin     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
121f200843bSJohn Baldwin 
12293ccd6bfSKonstantin Belousov _Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
12393ccd6bfSKonstantin Belousov     sizeof(struct thread0_storage),
12493ccd6bfSKonstantin Belousov     "increase struct thread0_storage.t0st_sched size");
12593ccd6bfSKonstantin Belousov 
1260d13d5fcSMarius Strobl static struct mtx sched_lock;
127b43179fbSJeff Roberson 
128579895dfSAlexander Motin static int	realstathz = 127; /* stathz is sometimes 0 and run off of hz. */
129ca59f152SJeff Roberson static int	sched_tdcnt;	/* Total runnable threads in the system. */
130579895dfSAlexander Motin static int	sched_slice = 12; /* Thread run time before rescheduling. */
131b43179fbSJeff Roberson 
132e17c57b1SJeff Roberson static void	setup_runqs(void);
133c55bbb6cSJohn Baldwin static void	schedcpu(void);
134e17c57b1SJeff Roberson static void	schedcpu_thread(void);
135f5c157d9SJohn Baldwin static void	sched_priority(struct thread *td, u_char prio);
136b43179fbSJeff Roberson static void	sched_setup(void *dummy);
137b43179fbSJeff Roberson static void	maybe_resched(struct thread *td);
1388460a577SJohn Birrell static void	updatepri(struct thread *td);
1398460a577SJohn Birrell static void	resetpriority(struct thread *td);
1408460a577SJohn Birrell static void	resetpriority_thread(struct thread *td);
14100b0483dSJulian Elischer #ifdef SMP
142f200843bSJohn Baldwin static int	sched_pickcpu(struct thread *td);
14382a1dfc1SJulian Elischer static int	forward_wakeup(int cpunum);
1448aa3d7ffSJohn Baldwin static void	kick_other_cpu(int pri, int cpuid);
14500b0483dSJulian Elischer #endif
146b43179fbSJeff Roberson 
147e17c57b1SJeff Roberson static struct kproc_desc sched_kp = {
148e17c57b1SJeff Roberson         "schedcpu",
149e17c57b1SJeff Roberson         schedcpu_thread,
150e17c57b1SJeff Roberson         NULL
151e17c57b1SJeff Roberson };
152785797c3SAndriy Gapon SYSINIT(schedcpu, SI_SUB_LAST, SI_ORDER_FIRST, kproc_start,
153237fdd78SRobert Watson     &sched_kp);
154237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
155b43179fbSJeff Roberson 
15648317e9eSAlexander Motin static void sched_initticks(void *dummy);
15748317e9eSAlexander Motin SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
15848317e9eSAlexander Motin     NULL);
15948317e9eSAlexander Motin 
160b43179fbSJeff Roberson /*
161b43179fbSJeff Roberson  * Global run queue.
162b43179fbSJeff Roberson  */
163b43179fbSJeff Roberson static struct runq runq;
164e17c57b1SJeff Roberson 
165e17c57b1SJeff Roberson #ifdef SMP
166e17c57b1SJeff Roberson /*
167e17c57b1SJeff Roberson  * Per-CPU run queues
168e17c57b1SJeff Roberson  */
169e17c57b1SJeff Roberson static struct runq runq_pcpu[MAXCPU];
170f200843bSJohn Baldwin long runq_length[MAXCPU];
1713121f534SAttilio Rao 
17271a19bdcSAttilio Rao static cpuset_t idle_cpus_mask;
173e17c57b1SJeff Roberson #endif
174e17c57b1SJeff Roberson 
175b722ad00SAlexander Motin struct pcpuidlestat {
176b722ad00SAlexander Motin 	u_int idlecalls;
177b722ad00SAlexander Motin 	u_int oldidlecalls;
178b722ad00SAlexander Motin };
1792bf95012SAndrew Turner DPCPU_DEFINE_STATIC(struct pcpuidlestat, idlestat);
180b722ad00SAlexander Motin 
181e17c57b1SJeff Roberson static void
182e17c57b1SJeff Roberson setup_runqs(void)
183e17c57b1SJeff Roberson {
184e17c57b1SJeff Roberson #ifdef SMP
185e17c57b1SJeff Roberson 	int i;
186e17c57b1SJeff Roberson 
187e17c57b1SJeff Roberson 	for (i = 0; i < MAXCPU; ++i)
188e17c57b1SJeff Roberson 		runq_init(&runq_pcpu[i]);
189e17c57b1SJeff Roberson #endif
190e17c57b1SJeff Roberson 
191e17c57b1SJeff Roberson 	runq_init(&runq);
192e17c57b1SJeff Roberson }
193b43179fbSJeff Roberson 
194579895dfSAlexander Motin static int
195579895dfSAlexander Motin sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
196579895dfSAlexander Motin {
197579895dfSAlexander Motin 	int error, new_val, period;
198579895dfSAlexander Motin 
199579895dfSAlexander Motin 	period = 1000000 / realstathz;
200579895dfSAlexander Motin 	new_val = period * sched_slice;
201579895dfSAlexander Motin 	error = sysctl_handle_int(oidp, &new_val, 0, req);
202579895dfSAlexander Motin 	if (error != 0 || req->newptr == NULL)
203579895dfSAlexander Motin 		return (error);
204579895dfSAlexander Motin 	if (new_val <= 0)
205579895dfSAlexander Motin 		return (EINVAL);
20637f4e025SAlexander Motin 	sched_slice = imax(1, (new_val + period / 2) / period);
20737f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
20837f4e025SAlexander Motin 	    realstathz);
209579895dfSAlexander Motin 	return (0);
210579895dfSAlexander Motin }
211579895dfSAlexander Motin 
212e038d354SScott Long SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
213dc095794SScott Long 
214e038d354SScott Long SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
215e038d354SScott Long     "Scheduler name");
216579895dfSAlexander Motin SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
217579895dfSAlexander Motin     NULL, 0, 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 */
2236472ac3dSEd Schouten static SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL,
2246472ac3dSEd Schouten     "Kernel SMP");
22582a1dfc1SJulian Elischer 
226a90f3f25SJeff Roberson static int runq_fuzz = 1;
227a90f3f25SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
228a90f3f25SJeff Roberson 
229bce73aedSJulian Elischer static int forward_wakeup_enabled = 1;
23082a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
23182a1dfc1SJulian Elischer 	   &forward_wakeup_enabled, 0,
23282a1dfc1SJulian Elischer 	   "Forwarding of wakeup to idle CPUs");
23382a1dfc1SJulian Elischer 
23482a1dfc1SJulian Elischer static int forward_wakeups_requested = 0;
23582a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
23682a1dfc1SJulian Elischer 	   &forward_wakeups_requested, 0,
23782a1dfc1SJulian Elischer 	   "Requests for Forwarding of wakeup to idle CPUs");
23882a1dfc1SJulian Elischer 
23982a1dfc1SJulian Elischer static int forward_wakeups_delivered = 0;
24082a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
24182a1dfc1SJulian Elischer 	   &forward_wakeups_delivered, 0,
24282a1dfc1SJulian Elischer 	   "Completed Forwarding of wakeup to idle CPUs");
24382a1dfc1SJulian Elischer 
244bce73aedSJulian Elischer static int forward_wakeup_use_mask = 1;
24582a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
24682a1dfc1SJulian Elischer 	   &forward_wakeup_use_mask, 0,
24782a1dfc1SJulian Elischer 	   "Use the mask of idle cpus");
24882a1dfc1SJulian Elischer 
24982a1dfc1SJulian Elischer static int forward_wakeup_use_loop = 0;
25082a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
25182a1dfc1SJulian Elischer 	   &forward_wakeup_use_loop, 0,
25282a1dfc1SJulian Elischer 	   "Use a loop to find idle cpus");
25382a1dfc1SJulian Elischer 
25437c28a02SJulian Elischer #endif
255ad1e7d28SJulian Elischer #if 0
2563389af30SJulian Elischer static int sched_followon = 0;
2573389af30SJulian Elischer SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
2583389af30SJulian Elischer 	   &sched_followon, 0,
2593389af30SJulian Elischer 	   "allow threads to share a quantum");
2608460a577SJohn Birrell #endif
26182a1dfc1SJulian Elischer 
262b3e9e682SRyan Stone SDT_PROVIDER_DEFINE(sched);
263b3e9e682SRyan Stone 
264d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
265b3e9e682SRyan Stone     "struct proc *", "uint8_t");
266d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
267b3e9e682SRyan Stone     "struct proc *", "void *");
268d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
269b3e9e682SRyan Stone     "struct proc *", "void *", "int");
270d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
271b3e9e682SRyan Stone     "struct proc *", "uint8_t", "struct thread *");
272d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
273d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
274b3e9e682SRyan Stone     "struct proc *");
275d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , on__cpu);
276d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , remain__cpu);
277d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
278b3e9e682SRyan Stone     "struct proc *");
279b3e9e682SRyan Stone 
280907bdbc2SJeff Roberson static __inline void
281907bdbc2SJeff Roberson sched_load_add(void)
282907bdbc2SJeff Roberson {
2838f51ad55SJeff Roberson 
284907bdbc2SJeff Roberson 	sched_tdcnt++;
2858f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
286d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
287907bdbc2SJeff Roberson }
288907bdbc2SJeff Roberson 
289907bdbc2SJeff Roberson static __inline void
290907bdbc2SJeff Roberson sched_load_rem(void)
291907bdbc2SJeff Roberson {
2928f51ad55SJeff Roberson 
293907bdbc2SJeff Roberson 	sched_tdcnt--;
2948f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
295d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
296907bdbc2SJeff Roberson }
297b43179fbSJeff Roberson /*
298b43179fbSJeff Roberson  * Arrange to reschedule if necessary, taking the priorities and
299b43179fbSJeff Roberson  * schedulers into account.
300b43179fbSJeff Roberson  */
301b43179fbSJeff Roberson static void
302b43179fbSJeff Roberson maybe_resched(struct thread *td)
303b43179fbSJeff Roberson {
304b43179fbSJeff Roberson 
3057b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
306ed062c8dSJulian Elischer 	if (td->td_priority < curthread->td_priority)
3074a338afdSJulian Elischer 		curthread->td_flags |= TDF_NEEDRESCHED;
308b43179fbSJeff Roberson }
309b43179fbSJeff Roberson 
310b43179fbSJeff Roberson /*
311a90f3f25SJeff Roberson  * This function is called when a thread is about to be put on run queue
312a90f3f25SJeff Roberson  * because it has been made runnable or its priority has been adjusted.  It
313a6b91f0fSJohn Baldwin  * determines if the new thread should preempt the current thread.  If so,
314a6b91f0fSJohn Baldwin  * it sets td_owepreempt to request a preemption.
315a90f3f25SJeff Roberson  */
316a90f3f25SJeff Roberson int
317a90f3f25SJeff Roberson maybe_preempt(struct thread *td)
318a90f3f25SJeff Roberson {
319a90f3f25SJeff Roberson #ifdef PREEMPTION
320a90f3f25SJeff Roberson 	struct thread *ctd;
321a90f3f25SJeff Roberson 	int cpri, pri;
322a90f3f25SJeff Roberson 
323a90f3f25SJeff Roberson 	/*
324a90f3f25SJeff Roberson 	 * The new thread should not preempt the current thread if any of the
325a90f3f25SJeff Roberson 	 * following conditions are true:
326a90f3f25SJeff Roberson 	 *
327a90f3f25SJeff Roberson 	 *  - The kernel is in the throes of crashing (panicstr).
328a90f3f25SJeff Roberson 	 *  - The current thread has a higher (numerically lower) or
329a90f3f25SJeff Roberson 	 *    equivalent priority.  Note that this prevents curthread from
330a90f3f25SJeff Roberson 	 *    trying to preempt to itself.
331a90f3f25SJeff Roberson 	 *  - The current thread has an inhibitor set or is in the process of
332a90f3f25SJeff Roberson 	 *    exiting.  In this case, the current thread is about to switch
333a90f3f25SJeff Roberson 	 *    out anyways, so there's no point in preempting.  If we did,
334a90f3f25SJeff Roberson 	 *    the current thread would not be properly resumed as well, so
335a90f3f25SJeff Roberson 	 *    just avoid that whole landmine.
336a90f3f25SJeff Roberson 	 *  - If the new thread's priority is not a realtime priority and
337a90f3f25SJeff Roberson 	 *    the current thread's priority is not an idle priority and
338a90f3f25SJeff Roberson 	 *    FULL_PREEMPTION is disabled.
339a90f3f25SJeff Roberson 	 *
340a90f3f25SJeff Roberson 	 * If all of these conditions are false, but the current thread is in
341a90f3f25SJeff Roberson 	 * a nested critical section, then we have to defer the preemption
342a90f3f25SJeff Roberson 	 * until we exit the critical section.  Otherwise, switch immediately
343a90f3f25SJeff Roberson 	 * to the new thread.
344a90f3f25SJeff Roberson 	 */
345a90f3f25SJeff Roberson 	ctd = curthread;
346a90f3f25SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
347a90f3f25SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
348a90f3f25SJeff Roberson 			("maybe_preempt: trying to run inhibited thread"));
349a90f3f25SJeff Roberson 	pri = td->td_priority;
350a90f3f25SJeff Roberson 	cpri = ctd->td_priority;
351892f0ab0SJohn Baldwin 	if (panicstr != NULL || pri >= cpri /* || dumping */ ||
352a90f3f25SJeff Roberson 	    TD_IS_INHIBITED(ctd))
353a90f3f25SJeff Roberson 		return (0);
354a90f3f25SJeff Roberson #ifndef FULL_PREEMPTION
355a90f3f25SJeff Roberson 	if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
356a90f3f25SJeff Roberson 		return (0);
357a90f3f25SJeff Roberson #endif
358a90f3f25SJeff Roberson 
359a6b91f0fSJohn Baldwin 	CTR0(KTR_PROC, "maybe_preempt: scheduling preemption");
360a90f3f25SJeff Roberson 	ctd->td_owepreempt = 1;
361a90f3f25SJeff Roberson 	return (1);
362a90f3f25SJeff Roberson #else
363a90f3f25SJeff Roberson 	return (0);
364a90f3f25SJeff Roberson #endif
365a90f3f25SJeff Roberson }
366a90f3f25SJeff Roberson 
367a90f3f25SJeff Roberson /*
368b43179fbSJeff Roberson  * Constants for digital decay and forget:
369ccd0ec40SKonstantin Belousov  *	90% of (ts_estcpu) usage in 5 * loadav time
370ad1e7d28SJulian Elischer  *	95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
371b43179fbSJeff Roberson  *          Note that, as ps(1) mentions, this can let percentages
372b43179fbSJeff Roberson  *          total over 100% (I've seen 137.9% for 3 processes).
373b43179fbSJeff Roberson  *
374ccd0ec40SKonstantin Belousov  * Note that schedclock() updates ts_estcpu and p_cpticks asynchronously.
375b43179fbSJeff Roberson  *
376ccd0ec40SKonstantin Belousov  * We wish to decay away 90% of ts_estcpu in (5 * loadavg) seconds.
377b43179fbSJeff Roberson  * That is, the system wants to compute a value of decay such
378b43179fbSJeff Roberson  * that the following for loop:
379b43179fbSJeff Roberson  * 	for (i = 0; i < (5 * loadavg); i++)
380ccd0ec40SKonstantin Belousov  * 		ts_estcpu *= decay;
381b43179fbSJeff Roberson  * will compute
382ccd0ec40SKonstantin Belousov  * 	ts_estcpu *= 0.1;
383b43179fbSJeff Roberson  * for all values of loadavg:
384b43179fbSJeff Roberson  *
385b43179fbSJeff Roberson  * Mathematically this loop can be expressed by saying:
386b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
387b43179fbSJeff Roberson  *
388b43179fbSJeff Roberson  * The system computes decay as:
389b43179fbSJeff Roberson  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
390b43179fbSJeff Roberson  *
391b43179fbSJeff Roberson  * We wish to prove that the system's computation of decay
392b43179fbSJeff Roberson  * will always fulfill the equation:
393b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
394b43179fbSJeff Roberson  *
395b43179fbSJeff Roberson  * If we compute b as:
396b43179fbSJeff Roberson  * 	b = 2 * loadavg
397b43179fbSJeff Roberson  * then
398b43179fbSJeff Roberson  * 	decay = b / (b + 1)
399b43179fbSJeff Roberson  *
400b43179fbSJeff Roberson  * We now need to prove two things:
401b43179fbSJeff Roberson  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
402b43179fbSJeff Roberson  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
403b43179fbSJeff Roberson  *
404b43179fbSJeff Roberson  * Facts:
405b43179fbSJeff Roberson  *         For x close to zero, exp(x) =~ 1 + x, since
406b43179fbSJeff Roberson  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
407b43179fbSJeff Roberson  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
408b43179fbSJeff Roberson  *         For x close to zero, ln(1+x) =~ x, since
409b43179fbSJeff Roberson  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
410b43179fbSJeff Roberson  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
411b43179fbSJeff Roberson  *         ln(.1) =~ -2.30
412b43179fbSJeff Roberson  *
413b43179fbSJeff Roberson  * Proof of (1):
414b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
415b43179fbSJeff Roberson  *	solving for factor,
416b43179fbSJeff Roberson  *      ln(factor) =~ (-2.30/5*loadav), or
417b43179fbSJeff Roberson  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
418b43179fbSJeff Roberson  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
419b43179fbSJeff Roberson  *
420b43179fbSJeff Roberson  * Proof of (2):
421b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
422b43179fbSJeff Roberson  *	solving for power,
423b43179fbSJeff Roberson  *      power*ln(b/(b+1)) =~ -2.30, or
424b43179fbSJeff Roberson  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
425b43179fbSJeff Roberson  *
426b43179fbSJeff Roberson  * Actual power values for the implemented algorithm are as follows:
427b43179fbSJeff Roberson  *      loadav: 1       2       3       4
428b43179fbSJeff Roberson  *      power:  5.68    10.32   14.94   19.55
429b43179fbSJeff Roberson  */
430b43179fbSJeff Roberson 
431b43179fbSJeff Roberson /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
432b43179fbSJeff Roberson #define	loadfactor(loadav)	(2 * (loadav))
433b43179fbSJeff Roberson #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
434b43179fbSJeff Roberson 
435ad1e7d28SJulian Elischer /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
436b43179fbSJeff Roberson static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
43752c0b557SMatthew D Fleming SYSCTL_UINT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
438b43179fbSJeff Roberson 
439b43179fbSJeff Roberson /*
440b43179fbSJeff Roberson  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
441b43179fbSJeff Roberson  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
442b43179fbSJeff Roberson  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
443b43179fbSJeff Roberson  *
444b43179fbSJeff Roberson  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
445b43179fbSJeff Roberson  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
446b43179fbSJeff Roberson  *
447b43179fbSJeff Roberson  * If you don't want to bother with the faster/more-accurate formula, you
448b43179fbSJeff Roberson  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
449b43179fbSJeff Roberson  * (more general) method of calculating the %age of CPU used by a process.
450b43179fbSJeff Roberson  */
451b43179fbSJeff Roberson #define	CCPU_SHIFT	11
452b43179fbSJeff Roberson 
453b43179fbSJeff Roberson /*
454b43179fbSJeff Roberson  * Recompute process priorities, every hz ticks.
455b43179fbSJeff Roberson  * MP-safe, called without the Giant mutex.
456b43179fbSJeff Roberson  */
457b43179fbSJeff Roberson /* ARGSUSED */
458b43179fbSJeff Roberson static void
459c55bbb6cSJohn Baldwin schedcpu(void)
460b43179fbSJeff Roberson {
4613e85b721SEd Maste 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
462b43179fbSJeff Roberson 	struct thread *td;
463b43179fbSJeff Roberson 	struct proc *p;
464ad1e7d28SJulian Elischer 	struct td_sched *ts;
46548317e9eSAlexander Motin 	int awake;
466b43179fbSJeff Roberson 
467b43179fbSJeff Roberson 	sx_slock(&allproc_lock);
468b43179fbSJeff Roberson 	FOREACH_PROC_IN_SYSTEM(p) {
469374ae2a3SJeff Roberson 		PROC_LOCK(p);
470e806d352SJohn Baldwin 		if (p->p_state == PRS_NEW) {
471e806d352SJohn Baldwin 			PROC_UNLOCK(p);
472e806d352SJohn Baldwin 			continue;
473e806d352SJohn Baldwin 		}
4748460a577SJohn Birrell 		FOREACH_THREAD_IN_PROC(p, td) {
475b43179fbSJeff Roberson 			awake = 0;
47693ccd6bfSKonstantin Belousov 			ts = td_get_sched(td);
4777b20fb19SJeff Roberson 			thread_lock(td);
478b43179fbSJeff Roberson 			/*
47970fca427SJohn Baldwin 			 * Increment sleep time (if sleeping).  We
48070fca427SJohn Baldwin 			 * ignore overflow, as above.
481b43179fbSJeff Roberson 			 */
482b43179fbSJeff Roberson 			/*
483ad1e7d28SJulian Elischer 			 * The td_sched slptimes are not touched in wakeup
484ad1e7d28SJulian Elischer 			 * because the thread may not HAVE everything in
485ad1e7d28SJulian Elischer 			 * memory? XXX I think this is out of date.
486b43179fbSJeff Roberson 			 */
487f0393f06SJeff Roberson 			if (TD_ON_RUNQ(td)) {
488b43179fbSJeff Roberson 				awake = 1;
4899727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
490f0393f06SJeff Roberson 			} else if (TD_IS_RUNNING(td)) {
491b43179fbSJeff Roberson 				awake = 1;
4929727e637SJeff Roberson 				/* Do not clear TDF_DIDRUN */
4939727e637SJeff Roberson 			} else if (td->td_flags & TDF_DIDRUN) {
494b43179fbSJeff Roberson 				awake = 1;
4959727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
496b43179fbSJeff Roberson 			}
497b43179fbSJeff Roberson 
498b43179fbSJeff Roberson 			/*
499ad1e7d28SJulian Elischer 			 * ts_pctcpu is only for ps and ttyinfo().
500b43179fbSJeff Roberson 			 */
501ad1e7d28SJulian Elischer 			ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
502b43179fbSJeff Roberson 			/*
503ad1e7d28SJulian Elischer 			 * If the td_sched has been idle the entire second,
504b43179fbSJeff Roberson 			 * stop recalculating its priority until
505b43179fbSJeff Roberson 			 * it wakes up.
506b43179fbSJeff Roberson 			 */
507ad1e7d28SJulian Elischer 			if (ts->ts_cpticks != 0) {
508b43179fbSJeff Roberson #if	(FSHIFT >= CCPU_SHIFT)
509ad1e7d28SJulian Elischer 				ts->ts_pctcpu += (realstathz == 100)
510ad1e7d28SJulian Elischer 				    ? ((fixpt_t) ts->ts_cpticks) <<
511b43179fbSJeff Roberson 				    (FSHIFT - CCPU_SHIFT) :
512ad1e7d28SJulian Elischer 				    100 * (((fixpt_t) ts->ts_cpticks)
513bcb06d59SJeff Roberson 				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
514b43179fbSJeff Roberson #else
515ad1e7d28SJulian Elischer 				ts->ts_pctcpu += ((FSCALE - ccpu) *
516ad1e7d28SJulian Elischer 				    (ts->ts_cpticks *
517bcb06d59SJeff Roberson 				    FSCALE / realstathz)) >> FSHIFT;
518b43179fbSJeff Roberson #endif
519ad1e7d28SJulian Elischer 				ts->ts_cpticks = 0;
5208460a577SJohn Birrell 			}
5218460a577SJohn Birrell 			/*
5228460a577SJohn Birrell 			 * If there are ANY running threads in this process,
523b43179fbSJeff Roberson 			 * then don't count it as sleeping.
5248aa3d7ffSJohn Baldwin 			 * XXX: this is broken.
525b43179fbSJeff Roberson 			 */
526b43179fbSJeff Roberson 			if (awake) {
52754b0e65fSJeff Roberson 				if (ts->ts_slptime > 1) {
528b43179fbSJeff Roberson 					/*
529b43179fbSJeff Roberson 					 * In an ideal world, this should not
530b43179fbSJeff Roberson 					 * happen, because whoever woke us
531b43179fbSJeff Roberson 					 * up from the long sleep should have
532b43179fbSJeff Roberson 					 * unwound the slptime and reset our
533b43179fbSJeff Roberson 					 * priority before we run at the stale
534b43179fbSJeff Roberson 					 * priority.  Should KASSERT at some
535b43179fbSJeff Roberson 					 * point when all the cases are fixed.
536b43179fbSJeff Roberson 					 */
5378460a577SJohn Birrell 					updatepri(td);
5388460a577SJohn Birrell 				}
53954b0e65fSJeff Roberson 				ts->ts_slptime = 0;
5408460a577SJohn Birrell 			} else
54154b0e65fSJeff Roberson 				ts->ts_slptime++;
54254b0e65fSJeff Roberson 			if (ts->ts_slptime > 1) {
5437b20fb19SJeff Roberson 				thread_unlock(td);
5448460a577SJohn Birrell 				continue;
5457b20fb19SJeff Roberson 			}
546ccd0ec40SKonstantin Belousov 			ts->ts_estcpu = decay_cpu(loadfac, ts->ts_estcpu);
5478460a577SJohn Birrell 		      	resetpriority(td);
5488460a577SJohn Birrell 			resetpriority_thread(td);
5497b20fb19SJeff Roberson 			thread_unlock(td);
5508aa3d7ffSJohn Baldwin 		}
551374ae2a3SJeff Roberson 		PROC_UNLOCK(p);
5528aa3d7ffSJohn Baldwin 	}
553b43179fbSJeff Roberson 	sx_sunlock(&allproc_lock);
554c55bbb6cSJohn Baldwin }
555c55bbb6cSJohn Baldwin 
556c55bbb6cSJohn Baldwin /*
557c55bbb6cSJohn Baldwin  * Main loop for a kthread that executes schedcpu once a second.
558c55bbb6cSJohn Baldwin  */
559c55bbb6cSJohn Baldwin static void
560e17c57b1SJeff Roberson schedcpu_thread(void)
561c55bbb6cSJohn Baldwin {
562c55bbb6cSJohn Baldwin 
563c55bbb6cSJohn Baldwin 	for (;;) {
564c55bbb6cSJohn Baldwin 		schedcpu();
5654d70511aSJohn Baldwin 		pause("-", hz);
566c55bbb6cSJohn Baldwin 	}
567b43179fbSJeff Roberson }
568b43179fbSJeff Roberson 
569b43179fbSJeff Roberson /*
570b43179fbSJeff Roberson  * Recalculate the priority of a process after it has slept for a while.
571ccd0ec40SKonstantin Belousov  * For all load averages >= 1 and max ts_estcpu of 255, sleeping for at
572ccd0ec40SKonstantin Belousov  * least six times the loadfactor will decay ts_estcpu to zero.
573b43179fbSJeff Roberson  */
574b43179fbSJeff Roberson static void
5758460a577SJohn Birrell updatepri(struct thread *td)
576b43179fbSJeff Roberson {
57754b0e65fSJeff Roberson 	struct td_sched *ts;
57854b0e65fSJeff Roberson 	fixpt_t loadfac;
57954b0e65fSJeff Roberson 	unsigned int newcpu;
580b43179fbSJeff Roberson 
58193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
58270fca427SJohn Baldwin 	loadfac = loadfactor(averunnable.ldavg[0]);
58354b0e65fSJeff Roberson 	if (ts->ts_slptime > 5 * loadfac)
584ccd0ec40SKonstantin Belousov 		ts->ts_estcpu = 0;
585b43179fbSJeff Roberson 	else {
586ccd0ec40SKonstantin Belousov 		newcpu = ts->ts_estcpu;
58754b0e65fSJeff Roberson 		ts->ts_slptime--;	/* was incremented in schedcpu() */
58854b0e65fSJeff Roberson 		while (newcpu && --ts->ts_slptime)
589b43179fbSJeff Roberson 			newcpu = decay_cpu(loadfac, newcpu);
590ccd0ec40SKonstantin Belousov 		ts->ts_estcpu = newcpu;
591b43179fbSJeff Roberson 	}
592b43179fbSJeff Roberson }
593b43179fbSJeff Roberson 
594b43179fbSJeff Roberson /*
595b43179fbSJeff Roberson  * Compute the priority of a process when running in user mode.
596b43179fbSJeff Roberson  * Arrange to reschedule if the resulting priority is better
597b43179fbSJeff Roberson  * than that of the current process.
598b43179fbSJeff Roberson  */
599b43179fbSJeff Roberson static void
6008460a577SJohn Birrell resetpriority(struct thread *td)
601b43179fbSJeff Roberson {
602ccd0ec40SKonstantin Belousov 	u_int newpriority;
603b43179fbSJeff Roberson 
604ccd0ec40SKonstantin Belousov 	if (td->td_pri_class != PRI_TIMESHARE)
605ccd0ec40SKonstantin Belousov 		return;
60693ccd6bfSKonstantin Belousov 	newpriority = PUSER +
60793ccd6bfSKonstantin Belousov 	    td_get_sched(td)->ts_estcpu / INVERSE_ESTCPU_WEIGHT +
6088460a577SJohn Birrell 	    NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
609b43179fbSJeff Roberson 	newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
610b43179fbSJeff Roberson 	    PRI_MAX_TIMESHARE);
6118460a577SJohn Birrell 	sched_user_prio(td, newpriority);
612b43179fbSJeff Roberson }
613f5c157d9SJohn Baldwin 
614f5c157d9SJohn Baldwin /*
615ad1e7d28SJulian Elischer  * Update the thread's priority when the associated process's user
616f5c157d9SJohn Baldwin  * priority changes.
617f5c157d9SJohn Baldwin  */
618f5c157d9SJohn Baldwin static void
6198460a577SJohn Birrell resetpriority_thread(struct thread *td)
620f5c157d9SJohn Baldwin {
621f5c157d9SJohn Baldwin 
622f5c157d9SJohn Baldwin 	/* Only change threads with a time sharing user priority. */
623f5c157d9SJohn Baldwin 	if (td->td_priority < PRI_MIN_TIMESHARE ||
624f5c157d9SJohn Baldwin 	    td->td_priority > PRI_MAX_TIMESHARE)
625f5c157d9SJohn Baldwin 		return;
626f5c157d9SJohn Baldwin 
627f5c157d9SJohn Baldwin 	/* XXX the whole needresched thing is broken, but not silly. */
628f5c157d9SJohn Baldwin 	maybe_resched(td);
629f5c157d9SJohn Baldwin 
6308460a577SJohn Birrell 	sched_prio(td, td->td_user_pri);
631b43179fbSJeff Roberson }
632b43179fbSJeff Roberson 
633b43179fbSJeff Roberson /* ARGSUSED */
634b43179fbSJeff Roberson static void
635b43179fbSJeff Roberson sched_setup(void *dummy)
636b43179fbSJeff Roberson {
63770fca427SJohn Baldwin 
638579895dfSAlexander Motin 	setup_runqs();
639b43179fbSJeff Roberson 
640ca59f152SJeff Roberson 	/* Account for thread0. */
641907bdbc2SJeff Roberson 	sched_load_add();
642b43179fbSJeff Roberson }
643b43179fbSJeff Roberson 
64448317e9eSAlexander Motin /*
645579895dfSAlexander Motin  * This routine determines time constants after stathz and hz are setup.
64648317e9eSAlexander Motin  */
64748317e9eSAlexander Motin static void
64848317e9eSAlexander Motin sched_initticks(void *dummy)
64948317e9eSAlexander Motin {
65048317e9eSAlexander Motin 
65148317e9eSAlexander Motin 	realstathz = stathz ? stathz : hz;
65248317e9eSAlexander Motin 	sched_slice = realstathz / 10;	/* ~100ms */
65337f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
65437f4e025SAlexander Motin 	    realstathz);
65548317e9eSAlexander Motin }
65648317e9eSAlexander Motin 
657b43179fbSJeff Roberson /* External interfaces start here */
6588aa3d7ffSJohn Baldwin 
659ed062c8dSJulian Elischer /*
660ed062c8dSJulian Elischer  * Very early in the boot some setup of scheduler-specific
661f3050486SMaxim Konovalov  * parts of proc0 and of some scheduler resources needs to be done.
662ed062c8dSJulian Elischer  * Called from:
663ed062c8dSJulian Elischer  *  proc0_init()
664ed062c8dSJulian Elischer  */
665ed062c8dSJulian Elischer void
666ed062c8dSJulian Elischer schedinit(void)
667ed062c8dSJulian Elischer {
66893ccd6bfSKonstantin Belousov 
669ed062c8dSJulian Elischer 	/*
67093ccd6bfSKonstantin Belousov 	 * Set up the scheduler specific parts of thread0.
671ed062c8dSJulian Elischer 	 */
6727b20fb19SJeff Roberson 	thread0.td_lock = &sched_lock;
67393ccd6bfSKonstantin Belousov 	td_get_sched(&thread0)->ts_slice = sched_slice;
674*686bcb5cSJeff Roberson 	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN);
675ed062c8dSJulian Elischer }
676ed062c8dSJulian Elischer 
677b43179fbSJeff Roberson int
678b43179fbSJeff Roberson sched_runnable(void)
679b43179fbSJeff Roberson {
680e17c57b1SJeff Roberson #ifdef SMP
681e17c57b1SJeff Roberson 	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
682e17c57b1SJeff Roberson #else
683b43179fbSJeff Roberson 	return runq_check(&runq);
684e17c57b1SJeff Roberson #endif
685b43179fbSJeff Roberson }
686b43179fbSJeff Roberson 
687b43179fbSJeff Roberson int
688b43179fbSJeff Roberson sched_rr_interval(void)
689b43179fbSJeff Roberson {
69048317e9eSAlexander Motin 
69148317e9eSAlexander Motin 	/* Convert sched_slice from stathz to hz. */
69237f4e025SAlexander Motin 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
693b43179fbSJeff Roberson }
694b43179fbSJeff Roberson 
695b43179fbSJeff Roberson /*
696ccd0ec40SKonstantin Belousov  * We adjust the priority of the current process.  The priority of a
697ccd0ec40SKonstantin Belousov  * process gets worse as it accumulates CPU time.  The cpu usage
698ccd0ec40SKonstantin Belousov  * estimator (ts_estcpu) is increased here.  resetpriority() will
699ccd0ec40SKonstantin Belousov  * compute a different priority each time ts_estcpu increases by
700ccd0ec40SKonstantin Belousov  * INVERSE_ESTCPU_WEIGHT (until PRI_MAX_TIMESHARE is reached).  The
701ccd0ec40SKonstantin Belousov  * cpu usage estimator ramps up quite quickly when the process is
702ccd0ec40SKonstantin Belousov  * running (linearly), and decays away exponentially, at a rate which
703ccd0ec40SKonstantin Belousov  * is proportionally slower when the system is busy.  The basic
704ccd0ec40SKonstantin Belousov  * principle is that the system will 90% forget that the process used
705ccd0ec40SKonstantin Belousov  * a lot of CPU time in 5 * loadav seconds.  This causes the system to
706ccd0ec40SKonstantin Belousov  * favor processes which haven't run much recently, and to round-robin
707ccd0ec40SKonstantin Belousov  * among other processes.
708b43179fbSJeff Roberson  */
709c3cccf95SJeff Roberson static void
710c3cccf95SJeff Roberson sched_clock_tick(struct thread *td)
711b43179fbSJeff Roberson {
712b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
713ad1e7d28SJulian Elischer 	struct td_sched *ts;
714b43179fbSJeff Roberson 
7157b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
71693ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
717f7f9e7f3SJeff Roberson 
718ad1e7d28SJulian Elischer 	ts->ts_cpticks++;
719ccd0ec40SKonstantin Belousov 	ts->ts_estcpu = ESTCPULIM(ts->ts_estcpu + 1);
720ccd0ec40SKonstantin Belousov 	if ((ts->ts_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
7218460a577SJohn Birrell 		resetpriority(td);
7228460a577SJohn Birrell 		resetpriority_thread(td);
723b43179fbSJeff Roberson 	}
7249dddab6fSJohn Baldwin 
7259dddab6fSJohn Baldwin 	/*
7269dddab6fSJohn Baldwin 	 * Force a context switch if the current thread has used up a full
727579895dfSAlexander Motin 	 * time slice (default is 100ms).
7289dddab6fSJohn Baldwin 	 */
729579895dfSAlexander Motin 	if (!TD_IS_IDLETHREAD(td) && --ts->ts_slice <= 0) {
73048317e9eSAlexander Motin 		ts->ts_slice = sched_slice;
7313d7f4117SAlexander Motin 		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
73248317e9eSAlexander Motin 	}
733b722ad00SAlexander Motin 
734b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
735b722ad00SAlexander Motin 	stat->oldidlecalls = stat->idlecalls;
736b722ad00SAlexander Motin 	stat->idlecalls = 0;
737b43179fbSJeff Roberson }
73870fca427SJohn Baldwin 
739c3cccf95SJeff Roberson void
740c3cccf95SJeff Roberson sched_clock(struct thread *td, int cnt)
741c3cccf95SJeff Roberson {
742c3cccf95SJeff Roberson 
743c3cccf95SJeff Roberson 	for ( ; cnt > 0; cnt--)
744c3cccf95SJeff Roberson 		sched_clock_tick(td);
745c3cccf95SJeff Roberson }
746c3cccf95SJeff Roberson 
7478460a577SJohn Birrell /*
7488aa3d7ffSJohn Baldwin  * Charge child's scheduling CPU usage to parent.
7498460a577SJohn Birrell  */
750b43179fbSJeff Roberson void
75155d44f79SJulian Elischer sched_exit(struct proc *p, struct thread *td)
752f7f9e7f3SJeff Roberson {
7538460a577SJohn Birrell 
7548f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "proc exit",
755cd39bb09SXin LI 	    "prio:%d", td->td_priority);
7568f51ad55SJeff Roberson 
757374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
758ad1e7d28SJulian Elischer 	sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
759b43179fbSJeff Roberson }
760b43179fbSJeff Roberson 
761b43179fbSJeff Roberson void
762f7f9e7f3SJeff Roberson sched_exit_thread(struct thread *td, struct thread *child)
763b43179fbSJeff Roberson {
764ad1e7d28SJulian Elischer 
7658f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "exit",
766cd39bb09SXin LI 	    "prio:%d", child->td_priority);
7677b20fb19SJeff Roberson 	thread_lock(td);
76893ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_estcpu = ESTCPULIM(td_get_sched(td)->ts_estcpu +
76993ccd6bfSKonstantin Belousov 	    td_get_sched(child)->ts_estcpu);
7707b20fb19SJeff Roberson 	thread_unlock(td);
7711b9d701fSAttilio Rao 	thread_lock(child);
7721b9d701fSAttilio Rao 	if ((child->td_flags & TDF_NOLOAD) == 0)
773907bdbc2SJeff Roberson 		sched_load_rem();
7741b9d701fSAttilio Rao 	thread_unlock(child);
775f7f9e7f3SJeff Roberson }
776bcb06d59SJeff Roberson 
777f7f9e7f3SJeff Roberson void
778ed062c8dSJulian Elischer sched_fork(struct thread *td, struct thread *childtd)
779f7f9e7f3SJeff Roberson {
780ed062c8dSJulian Elischer 	sched_fork_thread(td, childtd);
781f7f9e7f3SJeff Roberson }
782bcb06d59SJeff Roberson 
783f7f9e7f3SJeff Roberson void
784ed062c8dSJulian Elischer sched_fork_thread(struct thread *td, struct thread *childtd)
785f7f9e7f3SJeff Roberson {
78693ccd6bfSKonstantin Belousov 	struct td_sched *ts, *tsc;
7878b16c208SJeff Roberson 
78892de34dfSJohn Baldwin 	childtd->td_oncpu = NOCPU;
78992de34dfSJohn Baldwin 	childtd->td_lastcpu = NOCPU;
7907b20fb19SJeff Roberson 	childtd->td_lock = &sched_lock;
791f5a3ef99SMarcel Moolenaar 	childtd->td_cpuset = cpuset_ref(td->td_cpuset);
7923f289c3fSJeff Roberson 	childtd->td_domain.dr_policy = td->td_cpuset->cs_domain;
79322d19207SJohn Baldwin 	childtd->td_priority = childtd->td_base_pri;
79493ccd6bfSKonstantin Belousov 	ts = td_get_sched(childtd);
7958b16c208SJeff Roberson 	bzero(ts, sizeof(*ts));
79693ccd6bfSKonstantin Belousov 	tsc = td_get_sched(td);
79793ccd6bfSKonstantin Belousov 	ts->ts_estcpu = tsc->ts_estcpu;
79893ccd6bfSKonstantin Belousov 	ts->ts_flags |= (tsc->ts_flags & TSF_AFFINITY);
79948317e9eSAlexander Motin 	ts->ts_slice = 1;
800b43179fbSJeff Roberson }
801b43179fbSJeff Roberson 
802b43179fbSJeff Roberson void
803fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
804b43179fbSJeff Roberson {
805f5c157d9SJohn Baldwin 	struct thread *td;
8060b5318c8SJohn Baldwin 
807fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
808fa885116SJulian Elischer 	p->p_nice = nice;
8098460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
8107b20fb19SJeff Roberson 		thread_lock(td);
8118460a577SJohn Birrell 		resetpriority(td);
8128460a577SJohn Birrell 		resetpriority_thread(td);
8137b20fb19SJeff Roberson 		thread_unlock(td);
8148460a577SJohn Birrell 	}
815fa885116SJulian Elischer }
816b43179fbSJeff Roberson 
817f7f9e7f3SJeff Roberson void
8188460a577SJohn Birrell sched_class(struct thread *td, int class)
819f7f9e7f3SJeff Roberson {
8207b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
8218460a577SJohn Birrell 	td->td_pri_class = class;
822f7f9e7f3SJeff Roberson }
823f7f9e7f3SJeff Roberson 
8248460a577SJohn Birrell /*
8258460a577SJohn Birrell  * Adjust the priority of a thread.
8268460a577SJohn Birrell  */
827f5c157d9SJohn Baldwin static void
828f5c157d9SJohn Baldwin sched_priority(struct thread *td, u_char prio)
829b43179fbSJeff Roberson {
83027ee18adSRyan Stone 
8318f51ad55SJeff Roberson 
8328f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
8338f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
8348f51ad55SJeff Roberson 	    sched_tdname(curthread));
835d9fae5abSAndriy Gapon 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
8368f51ad55SJeff Roberson 	if (td != curthread && prio > td->td_priority) {
8378f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
8388f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
8398f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
840d9fae5abSAndriy Gapon 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
841b3e9e682SRyan Stone 		    curthread);
8428f51ad55SJeff Roberson 	}
8437b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
844f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
845f5c157d9SJohn Baldwin 		return;
8461f955e2dSJulian Elischer 	td->td_priority = prio;
8479727e637SJeff Roberson 	if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
848f0393f06SJeff Roberson 		sched_rem(td);
84961a74c5cSJeff Roberson 		sched_add(td, SRQ_BORING | SRQ_HOLDTD);
850b43179fbSJeff Roberson 	}
851b43179fbSJeff Roberson }
852b43179fbSJeff Roberson 
853f5c157d9SJohn Baldwin /*
854f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
855f5c157d9SJohn Baldwin  * priority.
856f5c157d9SJohn Baldwin  */
857f5c157d9SJohn Baldwin void
858f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
859f5c157d9SJohn Baldwin {
860f5c157d9SJohn Baldwin 
861f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
862f5c157d9SJohn Baldwin 	sched_priority(td, prio);
863f5c157d9SJohn Baldwin }
864f5c157d9SJohn Baldwin 
865f5c157d9SJohn Baldwin /*
866f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
867f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
868f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
869f5c157d9SJohn Baldwin  * requests.  If the thread's regulary priority is less
870f5c157d9SJohn Baldwin  * important than prio the thread will keep a priority boost
871f5c157d9SJohn Baldwin  * of prio.
872f5c157d9SJohn Baldwin  */
873f5c157d9SJohn Baldwin void
874f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
875f5c157d9SJohn Baldwin {
876f5c157d9SJohn Baldwin 	u_char base_pri;
877f5c157d9SJohn Baldwin 
878f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
879f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
8808460a577SJohn Birrell 		base_pri = td->td_user_pri;
881f5c157d9SJohn Baldwin 	else
882f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
883f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
884f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
885f5c157d9SJohn Baldwin 		sched_prio(td, base_pri);
886f5c157d9SJohn Baldwin 	} else
887f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
888f5c157d9SJohn Baldwin }
889f5c157d9SJohn Baldwin 
890f5c157d9SJohn Baldwin void
891f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
892f5c157d9SJohn Baldwin {
893f5c157d9SJohn Baldwin 	u_char oldprio;
894f5c157d9SJohn Baldwin 
895f5c157d9SJohn Baldwin 	/* First, update the base priority. */
896f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
897f5c157d9SJohn Baldwin 
898f5c157d9SJohn Baldwin 	/*
899f5c157d9SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't ever
900f5c157d9SJohn Baldwin 	 * lower the priority.
901f5c157d9SJohn Baldwin 	 */
902f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
903f5c157d9SJohn Baldwin 		return;
904f5c157d9SJohn Baldwin 
905f5c157d9SJohn Baldwin 	/* Change the real priority. */
906f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
907f5c157d9SJohn Baldwin 	sched_priority(td, prio);
908f5c157d9SJohn Baldwin 
909f5c157d9SJohn Baldwin 	/*
910f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
911f5c157d9SJohn Baldwin 	 * its state.
912f5c157d9SJohn Baldwin 	 */
913f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
914f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
915f5c157d9SJohn Baldwin }
916f5c157d9SJohn Baldwin 
917b43179fbSJeff Roberson void
9188460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
9193db720fdSDavid Xu {
9203db720fdSDavid Xu 
921435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
9228460a577SJohn Birrell 	td->td_base_user_pri = prio;
923acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
9245a215147SDavid Xu 		return;
9258460a577SJohn Birrell 	td->td_user_pri = prio;
9263db720fdSDavid Xu }
9273db720fdSDavid Xu 
9283db720fdSDavid Xu void
9293db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
9303db720fdSDavid Xu {
9313db720fdSDavid Xu 
932435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
933acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
934c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
935c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
936c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
937c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
938c8e368a9SDavid Xu 		td->td_flags |= TDF_NEEDRESCHED;
939435806d3SDavid Xu }
9403db720fdSDavid Xu 
941ac97da9aSMateusz Guzik /*
942ac97da9aSMateusz Guzik  * Like the above but first check if there is anything to do.
943ac97da9aSMateusz Guzik  */
944ac97da9aSMateusz Guzik void
945ac97da9aSMateusz Guzik sched_lend_user_prio_cond(struct thread *td, u_char prio)
946ac97da9aSMateusz Guzik {
947ac97da9aSMateusz Guzik 
948ac97da9aSMateusz Guzik 	if (td->td_lend_user_pri != prio)
949ac97da9aSMateusz Guzik 		goto lend;
950ac97da9aSMateusz Guzik 	if (td->td_user_pri != min(prio, td->td_base_user_pri))
951ac97da9aSMateusz Guzik 		goto lend;
952ac97da9aSMateusz Guzik 	if (td->td_priority >= td->td_user_pri)
953ac97da9aSMateusz Guzik 		goto lend;
954ac97da9aSMateusz Guzik 	return;
955ac97da9aSMateusz Guzik 
956ac97da9aSMateusz Guzik lend:
957ac97da9aSMateusz Guzik 	thread_lock(td);
958ac97da9aSMateusz Guzik 	sched_lend_user_prio(td, prio);
959ac97da9aSMateusz Guzik 	thread_unlock(td);
960ac97da9aSMateusz Guzik }
961ac97da9aSMateusz Guzik 
9623db720fdSDavid Xu void
963c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int pri)
964b43179fbSJeff Roberson {
9652056d0a1SJohn Baldwin 
9667b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
96754b0e65fSJeff Roberson 	td->td_slptick = ticks;
96893ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_slptime = 0;
9692dc29adbSJohn Baldwin 	if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
970c5aa6b58SJeff Roberson 		sched_prio(td, pri);
97117c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
972c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
973b43179fbSJeff Roberson }
974b43179fbSJeff Roberson 
975b43179fbSJeff Roberson void
976*686bcb5cSJeff Roberson sched_switch(struct thread *td, int flags)
977b43179fbSJeff Roberson {
978*686bcb5cSJeff Roberson 	struct thread *newtd;
979b0b9dee5SAttilio Rao 	struct mtx *tmtx;
980ad1e7d28SJulian Elischer 	struct td_sched *ts;
981b43179fbSJeff Roberson 	struct proc *p;
9823d7f4117SAlexander Motin 	int preempted;
983b43179fbSJeff Roberson 
98461a74c5cSJeff Roberson 	tmtx = &sched_lock;
98593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
986b43179fbSJeff Roberson 	p = td->td_proc;
987b43179fbSJeff Roberson 
9887b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
9898aa3d7ffSJohn Baldwin 
990060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
991ad9dadc4SAndriy Gapon 	preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
992ad9dadc4SAndriy Gapon 	    (flags & SW_PREEMPT) != 0;
9933d7f4117SAlexander Motin 	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
99477918643SStephan Uphoff 	td->td_owepreempt = 0;
995ca59f152SJeff Roberson 	td->td_oncpu = NOCPU;
9968aa3d7ffSJohn Baldwin 
997b43179fbSJeff Roberson 	/*
998b43179fbSJeff Roberson 	 * At the last moment, if this thread is still marked RUNNING,
999b43179fbSJeff Roberson 	 * then put it back on the run queue as it has not been suspended
1000bf0acc27SJohn Baldwin 	 * or stopped or any thing else similar.  We never put the idle
1001bf0acc27SJohn Baldwin 	 * threads on the run queue, however.
1002b43179fbSJeff Roberson 	 */
1003c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD) {
1004bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
1005c6226eeaSJulian Elischer #ifdef SMP
1006a38f1f26SAttilio Rao 		CPU_CLR(PCPU_GET(cpuid), &idle_cpus_mask);
1007c6226eeaSJulian Elischer #endif
1008c6226eeaSJulian Elischer 	} else {
1009ed062c8dSJulian Elischer 		if (TD_IS_RUNNING(td)) {
1010ad1e7d28SJulian Elischer 			/* Put us back on the run queue. */
10113d7f4117SAlexander Motin 			sched_add(td, preempted ?
101261a74c5cSJeff Roberson 			    SRQ_HOLDTD|SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
101361a74c5cSJeff Roberson 			    SRQ_HOLDTD|SRQ_OURSELF|SRQ_YIELDING);
1014ed062c8dSJulian Elischer 		}
1015b43179fbSJeff Roberson 	}
101661a74c5cSJeff Roberson 
101761a74c5cSJeff Roberson 	/*
101861a74c5cSJeff Roberson 	 * Switch to the sched lock to fix things up and pick
101961a74c5cSJeff Roberson 	 * a new thread.  Block the td_lock in order to avoid
102061a74c5cSJeff Roberson 	 * breaking the critical path.
102161a74c5cSJeff Roberson 	 */
102261a74c5cSJeff Roberson 	if (td->td_lock != &sched_lock) {
102361a74c5cSJeff Roberson 		mtx_lock_spin(&sched_lock);
102461a74c5cSJeff Roberson 		tmtx = thread_lock_block(td);
102561a74c5cSJeff Roberson 		mtx_unlock_spin(tmtx);
102661a74c5cSJeff Roberson 	}
102761a74c5cSJeff Roberson 
102861a74c5cSJeff Roberson 	if ((td->td_flags & TDF_NOLOAD) == 0)
102961a74c5cSJeff Roberson 		sched_load_rem();
103061a74c5cSJeff Roberson 
1031ae53b483SJeff Roberson 	newtd = choosethread();
103261a74c5cSJeff Roberson 	MPASS(newtd->td_lock == &sched_lock);
103361a74c5cSJeff Roberson 
1034afa0a46cSAndriy Gapon #if (KTR_COMPILE & KTR_SCHED) != 0
1035afa0a46cSAndriy Gapon 	if (TD_IS_IDLETHREAD(td))
1036afa0a46cSAndriy Gapon 		KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
1037afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority);
1038afa0a46cSAndriy Gapon 	else
1039afa0a46cSAndriy Gapon 		KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
1040afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
1041afa0a46cSAndriy Gapon 		    "lockname:\"%s\"", td->td_lockname);
1042afa0a46cSAndriy Gapon #endif
1043afa0a46cSAndriy Gapon 
1044ebccf1e3SJoseph Koshy 	if (td != newtd) {
1045ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1046ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1047ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1048ebccf1e3SJoseph Koshy #endif
1049b3e9e682SRyan Stone 
10507dba7849SMark Johnston 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1051b3e9e682SRyan Stone 
1052c6226eeaSJulian Elischer                 /* I feel sleepy */
1053eea4f254SJeff Roberson 		lock_profile_release_lock(&sched_lock.lock_object);
10546f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
10556f5f25e5SJohn Birrell 		/*
10566f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
10576f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
10586f5f25e5SJohn Birrell 		 * function to call.
10596f5f25e5SJohn Birrell 		 */
10606f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
10616f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
10626f5f25e5SJohn Birrell #endif
10636f5f25e5SJohn Birrell 
106461a74c5cSJeff Roberson 		cpu_switch(td, newtd, tmtx);
1065eea4f254SJeff Roberson 		lock_profile_obtain_lock_success(&sched_lock.lock_object,
1066eea4f254SJeff Roberson 		    0, 0, __FILE__, __LINE__);
1067c6226eeaSJulian Elischer 		/*
1068c6226eeaSJulian Elischer 		 * Where am I?  What year is it?
1069c6226eeaSJulian Elischer 		 * We are in the same thread that went to sleep above,
10708aa3d7ffSJohn Baldwin 		 * but any amount of time may have passed. All our context
1071c6226eeaSJulian Elischer 		 * will still be available as will local variables.
1072c6226eeaSJulian Elischer 		 * PCPU values however may have changed as we may have
1073c6226eeaSJulian Elischer 		 * changed CPU so don't trust cached values of them.
1074c6226eeaSJulian Elischer 		 * New threads will go to fork_exit() instead of here
1075c6226eeaSJulian Elischer 		 * so if you change things here you may need to change
1076c6226eeaSJulian Elischer 		 * things there too.
10778aa3d7ffSJohn Baldwin 		 *
1078c6226eeaSJulian Elischer 		 * If the thread above was exiting it will never wake
1079c6226eeaSJulian Elischer 		 * up again here, so either it has saved everything it
1080c6226eeaSJulian Elischer 		 * needed to, or the thread_wait() or wait() will
1081c6226eeaSJulian Elischer 		 * need to reap it.
1082c6226eeaSJulian Elischer 		 */
1083b3e9e682SRyan Stone 
1084d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , on__cpu);
1085ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1086ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1087ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1088ebccf1e3SJoseph Koshy #endif
108961a74c5cSJeff Roberson 	} else {
109061a74c5cSJeff Roberson 		td->td_lock = &sched_lock;
1091d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , remain__cpu);
109261a74c5cSJeff Roberson 	}
1093ebccf1e3SJoseph Koshy 
1094afa0a46cSAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
1095afa0a46cSAndriy Gapon 	    "prio:%d", td->td_priority);
1096afa0a46cSAndriy Gapon 
1097c6226eeaSJulian Elischer #ifdef SMP
1098c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD)
1099a38f1f26SAttilio Rao 		CPU_SET(PCPU_GET(cpuid), &idle_cpus_mask);
1100c6226eeaSJulian Elischer #endif
1101ae53b483SJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
1102ae53b483SJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
1103*686bcb5cSJeff Roberson 	spinlock_enter();
1104*686bcb5cSJeff Roberson 	mtx_unlock_spin(&sched_lock);
1105b43179fbSJeff Roberson }
1106b43179fbSJeff Roberson 
1107b43179fbSJeff Roberson void
110861a74c5cSJeff Roberson sched_wakeup(struct thread *td, int srqflags)
1109b43179fbSJeff Roberson {
111054b0e65fSJeff Roberson 	struct td_sched *ts;
111154b0e65fSJeff Roberson 
11127b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
111393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1114c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
111554b0e65fSJeff Roberson 	if (ts->ts_slptime > 1) {
11168460a577SJohn Birrell 		updatepri(td);
11178460a577SJohn Birrell 		resetpriority(td);
11188460a577SJohn Birrell 	}
11196eac7e57SAttilio Rao 	td->td_slptick = 0;
112054b0e65fSJeff Roberson 	ts->ts_slptime = 0;
112148317e9eSAlexander Motin 	ts->ts_slice = sched_slice;
112261a74c5cSJeff Roberson 	sched_add(td, srqflags);
1123b43179fbSJeff Roberson }
1124b43179fbSJeff Roberson 
112537c28a02SJulian Elischer #ifdef SMP
112682a1dfc1SJulian Elischer static int
112782a1dfc1SJulian Elischer forward_wakeup(int cpunum)
112882a1dfc1SJulian Elischer {
112982a1dfc1SJulian Elischer 	struct pcpu *pc;
1130a38f1f26SAttilio Rao 	cpuset_t dontuse, map, map2;
1131a38f1f26SAttilio Rao 	u_int id, me;
113271a19bdcSAttilio Rao 	int iscpuset;
113382a1dfc1SJulian Elischer 
113482a1dfc1SJulian Elischer 	mtx_assert(&sched_lock, MA_OWNED);
113582a1dfc1SJulian Elischer 
1136ed062c8dSJulian Elischer 	CTR0(KTR_RUNQ, "forward_wakeup()");
113782a1dfc1SJulian Elischer 
113882a1dfc1SJulian Elischer 	if ((!forward_wakeup_enabled) ||
113982a1dfc1SJulian Elischer 	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
114082a1dfc1SJulian Elischer 		return (0);
1141892f0ab0SJohn Baldwin 	if (!smp_started || panicstr)
114282a1dfc1SJulian Elischer 		return (0);
114382a1dfc1SJulian Elischer 
114482a1dfc1SJulian Elischer 	forward_wakeups_requested++;
114582a1dfc1SJulian Elischer 
114682a1dfc1SJulian Elischer 	/*
11478aa3d7ffSJohn Baldwin 	 * Check the idle mask we received against what we calculated
11488aa3d7ffSJohn Baldwin 	 * before in the old version.
114982a1dfc1SJulian Elischer 	 */
1150a38f1f26SAttilio Rao 	me = PCPU_GET(cpuid);
11518aa3d7ffSJohn Baldwin 
11528aa3d7ffSJohn Baldwin 	/* Don't bother if we should be doing it ourself. */
1153a38f1f26SAttilio Rao 	if (CPU_ISSET(me, &idle_cpus_mask) &&
1154a38f1f26SAttilio Rao 	    (cpunum == NOCPU || me == cpunum))
115582a1dfc1SJulian Elischer 		return (0);
115682a1dfc1SJulian Elischer 
1157a38f1f26SAttilio Rao 	CPU_SETOF(me, &dontuse);
115871a19bdcSAttilio Rao 	CPU_OR(&dontuse, &stopped_cpus);
115971a19bdcSAttilio Rao 	CPU_OR(&dontuse, &hlt_cpus_mask);
116071a19bdcSAttilio Rao 	CPU_ZERO(&map2);
116182a1dfc1SJulian Elischer 	if (forward_wakeup_use_loop) {
1162d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1163a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1164a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &dontuse) &&
116582a1dfc1SJulian Elischer 			    pc->pc_curthread == pc->pc_idlethread) {
1166a38f1f26SAttilio Rao 				CPU_SET(id, &map2);
116782a1dfc1SJulian Elischer 			}
116882a1dfc1SJulian Elischer 		}
116982a1dfc1SJulian Elischer 	}
117082a1dfc1SJulian Elischer 
117182a1dfc1SJulian Elischer 	if (forward_wakeup_use_mask) {
117271a19bdcSAttilio Rao 		map = idle_cpus_mask;
11739825eadfSRyan Libby 		CPU_ANDNOT(&map, &dontuse);
117482a1dfc1SJulian Elischer 
11758aa3d7ffSJohn Baldwin 		/* If they are both on, compare and use loop if different. */
117682a1dfc1SJulian Elischer 		if (forward_wakeup_use_loop) {
117771a19bdcSAttilio Rao 			if (CPU_CMP(&map, &map2)) {
1178f0283a73SAttilio Rao 				printf("map != map2, loop method preferred\n");
1179f0283a73SAttilio Rao 				map = map2;
118082a1dfc1SJulian Elischer 			}
118182a1dfc1SJulian Elischer 		}
118282a1dfc1SJulian Elischer 	} else {
1183f0283a73SAttilio Rao 		map = map2;
118482a1dfc1SJulian Elischer 	}
11858aa3d7ffSJohn Baldwin 
11868aa3d7ffSJohn Baldwin 	/* If we only allow a specific CPU, then mask off all the others. */
118782a1dfc1SJulian Elischer 	if (cpunum != NOCPU) {
118882a1dfc1SJulian Elischer 		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
118971a19bdcSAttilio Rao 		iscpuset = CPU_ISSET(cpunum, &map);
119071a19bdcSAttilio Rao 		if (iscpuset == 0)
119171a19bdcSAttilio Rao 			CPU_ZERO(&map);
119271a19bdcSAttilio Rao 		else
119371a19bdcSAttilio Rao 			CPU_SETOF(cpunum, &map);
119482a1dfc1SJulian Elischer 	}
119571a19bdcSAttilio Rao 	if (!CPU_EMPTY(&map)) {
119682a1dfc1SJulian Elischer 		forward_wakeups_delivered++;
1197d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1198a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1199a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &map))
1200b722ad00SAlexander Motin 				continue;
1201b722ad00SAlexander Motin 			if (cpu_idle_wakeup(pc->pc_cpuid))
1202a38f1f26SAttilio Rao 				CPU_CLR(id, &map);
1203b722ad00SAlexander Motin 		}
120471a19bdcSAttilio Rao 		if (!CPU_EMPTY(&map))
120582a1dfc1SJulian Elischer 			ipi_selected(map, IPI_AST);
120682a1dfc1SJulian Elischer 		return (1);
120782a1dfc1SJulian Elischer 	}
120882a1dfc1SJulian Elischer 	if (cpunum == NOCPU)
120982a1dfc1SJulian Elischer 		printf("forward_wakeup: Idle processor not found\n");
121082a1dfc1SJulian Elischer 	return (0);
121182a1dfc1SJulian Elischer }
1212f3a0f873SStephan Uphoff 
1213f3a0f873SStephan Uphoff static void
1214f3a0f873SStephan Uphoff kick_other_cpu(int pri, int cpuid)
1215f3a0f873SStephan Uphoff {
12168aa3d7ffSJohn Baldwin 	struct pcpu *pcpu;
12178aa3d7ffSJohn Baldwin 	int cpri;
1218f3a0f873SStephan Uphoff 
12198aa3d7ffSJohn Baldwin 	pcpu = pcpu_find(cpuid);
1220a38f1f26SAttilio Rao 	if (CPU_ISSET(cpuid, &idle_cpus_mask)) {
1221f3a0f873SStephan Uphoff 		forward_wakeups_delivered++;
1222b722ad00SAlexander Motin 		if (!cpu_idle_wakeup(cpuid))
1223d9d8d144SJohn Baldwin 			ipi_cpu(cpuid, IPI_AST);
1224f3a0f873SStephan Uphoff 		return;
1225f3a0f873SStephan Uphoff 	}
1226f3a0f873SStephan Uphoff 
12278aa3d7ffSJohn Baldwin 	cpri = pcpu->pc_curthread->td_priority;
1228f3a0f873SStephan Uphoff 	if (pri >= cpri)
1229f3a0f873SStephan Uphoff 		return;
1230f3a0f873SStephan Uphoff 
1231f3a0f873SStephan Uphoff #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1232f3a0f873SStephan Uphoff #if !defined(FULL_PREEMPTION)
1233f3a0f873SStephan Uphoff 	if (pri <= PRI_MAX_ITHD)
1234f3a0f873SStephan Uphoff #endif /* ! FULL_PREEMPTION */
1235f3a0f873SStephan Uphoff 	{
1236d9d8d144SJohn Baldwin 		ipi_cpu(cpuid, IPI_PREEMPT);
1237f3a0f873SStephan Uphoff 		return;
1238f3a0f873SStephan Uphoff 	}
1239f3a0f873SStephan Uphoff #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1240f3a0f873SStephan Uphoff 
1241f3a0f873SStephan Uphoff 	pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1242d9d8d144SJohn Baldwin 	ipi_cpu(cpuid, IPI_AST);
1243f3a0f873SStephan Uphoff 	return;
1244f3a0f873SStephan Uphoff }
1245f3a0f873SStephan Uphoff #endif /* SMP */
1246f3a0f873SStephan Uphoff 
1247f200843bSJohn Baldwin #ifdef SMP
1248f200843bSJohn Baldwin static int
1249f200843bSJohn Baldwin sched_pickcpu(struct thread *td)
1250f200843bSJohn Baldwin {
1251f200843bSJohn Baldwin 	int best, cpu;
1252f200843bSJohn Baldwin 
1253f200843bSJohn Baldwin 	mtx_assert(&sched_lock, MA_OWNED);
1254f200843bSJohn Baldwin 
1255e2325d82SJohn Baldwin 	if (td->td_lastcpu != NOCPU && THREAD_CAN_SCHED(td, td->td_lastcpu))
1256c3ea3378SJohn Baldwin 		best = td->td_lastcpu;
1257c3ea3378SJohn Baldwin 	else
1258f200843bSJohn Baldwin 		best = NOCPU;
12593aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1260f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu))
1261f200843bSJohn Baldwin 			continue;
1262f200843bSJohn Baldwin 
1263f200843bSJohn Baldwin 		if (best == NOCPU)
1264f200843bSJohn Baldwin 			best = cpu;
1265f200843bSJohn Baldwin 		else if (runq_length[cpu] < runq_length[best])
1266f200843bSJohn Baldwin 			best = cpu;
1267f200843bSJohn Baldwin 	}
1268f200843bSJohn Baldwin 	KASSERT(best != NOCPU, ("no valid CPUs"));
1269f200843bSJohn Baldwin 
1270f200843bSJohn Baldwin 	return (best);
1271f200843bSJohn Baldwin }
1272f200843bSJohn Baldwin #endif
1273f200843bSJohn Baldwin 
1274b43179fbSJeff Roberson void
12752630e4c9SJulian Elischer sched_add(struct thread *td, int flags)
12766804a3abSJulian Elischer #ifdef SMP
1277f3a0f873SStephan Uphoff {
1278a38f1f26SAttilio Rao 	cpuset_t tidlemsk;
1279ad1e7d28SJulian Elischer 	struct td_sched *ts;
1280a38f1f26SAttilio Rao 	u_int cpu, cpuid;
12816804a3abSJulian Elischer 	int forwarded = 0;
1282f3a0f873SStephan Uphoff 	int single_cpu = 0;
12837cf90fb3SJeff Roberson 
128493ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
12857b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1286f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1287f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1288f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1289f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1290b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1291b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
12928f51ad55SJeff Roberson 
12938f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
12948f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
12958f51ad55SJeff Roberson 	    sched_tdname(curthread));
12968f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
12978f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
1298b3e9e682SRyan Stone 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1299b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
13008f51ad55SJeff Roberson 
13018aa3d7ffSJohn Baldwin 
13027b20fb19SJeff Roberson 	/*
13037b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
13047b20fb19SJeff Roberson 	 * to the scheduler's lock.
13057b20fb19SJeff Roberson 	 */
13067b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
13077b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
130861a74c5cSJeff Roberson 		if ((flags & SRQ_HOLD) != 0)
130961a74c5cSJeff Roberson 			td->td_lock = &sched_lock;
131061a74c5cSJeff Roberson 		else
13117b20fb19SJeff Roberson 			thread_lock_set(td, &sched_lock);
131261a74c5cSJeff Roberson 
13137b20fb19SJeff Roberson 	}
1314f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1315f3a0f873SStephan Uphoff 
131660dd73b7SRyan Stone 	/*
131760dd73b7SRyan Stone 	 * If SMP is started and the thread is pinned or otherwise limited to
131860dd73b7SRyan Stone 	 * a specific set of CPUs, queue the thread to a per-CPU run queue.
131960dd73b7SRyan Stone 	 * Otherwise, queue the thread to the global run queue.
132060dd73b7SRyan Stone 	 *
132160dd73b7SRyan Stone 	 * If SMP has not yet been started we must use the global run queue
132260dd73b7SRyan Stone 	 * as per-CPU state may not be initialized yet and we may crash if we
132360dd73b7SRyan Stone 	 * try to access the per-CPU run queues.
132460dd73b7SRyan Stone 	 */
132560dd73b7SRyan Stone 	if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
132660dd73b7SRyan Stone 	    ts->ts_flags & TSF_AFFINITY)) {
132760dd73b7SRyan Stone 		if (td->td_pinned != 0)
1328f3a0f873SStephan Uphoff 			cpu = td->td_lastcpu;
132960dd73b7SRyan Stone 		else if (td->td_flags & TDF_BOUND) {
13308aa3d7ffSJohn Baldwin 			/* Find CPU from bound runq. */
13318aa3d7ffSJohn Baldwin 			KASSERT(SKE_RUNQ_PCPU(ts),
13328aa3d7ffSJohn Baldwin 			    ("sched_add: bound td_sched not on cpu runq"));
1333ad1e7d28SJulian Elischer 			cpu = ts->ts_runq - &runq_pcpu[0];
133460dd73b7SRyan Stone 		} else
1335f200843bSJohn Baldwin 			/* Find a valid CPU for our cpuset */
1336f200843bSJohn Baldwin 			cpu = sched_pickcpu(td);
1337f200843bSJohn Baldwin 		ts->ts_runq = &runq_pcpu[cpu];
1338f200843bSJohn Baldwin 		single_cpu = 1;
1339f200843bSJohn Baldwin 		CTR3(KTR_RUNQ,
1340f200843bSJohn Baldwin 		    "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1341f200843bSJohn Baldwin 		    cpu);
1342f3a0f873SStephan Uphoff 	} else {
13436804a3abSJulian Elischer 		CTR2(KTR_RUNQ,
13448aa3d7ffSJohn Baldwin 		    "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
13458aa3d7ffSJohn Baldwin 		    td);
13466804a3abSJulian Elischer 		cpu = NOCPU;
1347ad1e7d28SJulian Elischer 		ts->ts_runq = &runq;
1348e17c57b1SJeff Roberson 	}
1349f3a0f873SStephan Uphoff 
1350a6b91f0fSJohn Baldwin 	if ((td->td_flags & TDF_NOLOAD) == 0)
1351a6b91f0fSJohn Baldwin 		sched_load_add();
1352a6b91f0fSJohn Baldwin 	runq_add(ts->ts_runq, td, flags);
1353a6b91f0fSJohn Baldwin 	if (cpu != NOCPU)
1354a6b91f0fSJohn Baldwin 		runq_length[cpu]++;
1355a6b91f0fSJohn Baldwin 
1356a38f1f26SAttilio Rao 	cpuid = PCPU_GET(cpuid);
1357a38f1f26SAttilio Rao 	if (single_cpu && cpu != cpuid) {
1358f3a0f873SStephan Uphoff 	        kick_other_cpu(td->td_priority, cpu);
1359f3a0f873SStephan Uphoff 	} else {
1360f3a0f873SStephan Uphoff 		if (!single_cpu) {
1361a38f1f26SAttilio Rao 			tidlemsk = idle_cpus_mask;
13629825eadfSRyan Libby 			CPU_ANDNOT(&tidlemsk, &hlt_cpus_mask);
1363a38f1f26SAttilio Rao 			CPU_CLR(cpuid, &tidlemsk);
1364f3a0f873SStephan Uphoff 
1365a38f1f26SAttilio Rao 			if (!CPU_ISSET(cpuid, &idle_cpus_mask) &&
1366a38f1f26SAttilio Rao 			    ((flags & SRQ_INTR) == 0) &&
136771a19bdcSAttilio Rao 			    !CPU_EMPTY(&tidlemsk))
1368f3a0f873SStephan Uphoff 				forwarded = forward_wakeup(cpu);
1369f3a0f873SStephan Uphoff 		}
1370f3a0f873SStephan Uphoff 
1371f3a0f873SStephan Uphoff 		if (!forwarded) {
1372a6b91f0fSJohn Baldwin 			if (!maybe_preempt(td))
1373f3a0f873SStephan Uphoff 				maybe_resched(td);
1374f3a0f873SStephan Uphoff 		}
1375f3a0f873SStephan Uphoff 	}
137661a74c5cSJeff Roberson 	if ((flags & SRQ_HOLDTD) == 0)
137761a74c5cSJeff Roberson 		thread_unlock(td);
1378f3a0f873SStephan Uphoff }
1379f3a0f873SStephan Uphoff #else /* SMP */
1380f3a0f873SStephan Uphoff {
1381ad1e7d28SJulian Elischer 	struct td_sched *ts;
1382f200843bSJohn Baldwin 
138393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
13847b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1385f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1386f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1387f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1388f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1389b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1390b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
13918f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
13928f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
13938f51ad55SJeff Roberson 	    sched_tdname(curthread));
13948f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
13958f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
13962aaae99dSSergey Kandaurov 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1397b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
13988aa3d7ffSJohn Baldwin 
13997b20fb19SJeff Roberson 	/*
14007b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
14017b20fb19SJeff Roberson 	 * to the scheduler's lock.
14027b20fb19SJeff Roberson 	 */
14037b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
14047b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
140561a74c5cSJeff Roberson 		if ((flags & SRQ_HOLD) != 0)
140661a74c5cSJeff Roberson 			td->td_lock = &sched_lock;
140761a74c5cSJeff Roberson 		else
14087b20fb19SJeff Roberson 			thread_lock_set(td, &sched_lock);
14097b20fb19SJeff Roberson 	}
1410f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1411ad1e7d28SJulian Elischer 	CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1412ad1e7d28SJulian Elischer 	ts->ts_runq = &runq;
14136804a3abSJulian Elischer 
14141b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1415907bdbc2SJeff Roberson 		sched_load_add();
14169727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
1417a6b91f0fSJohn Baldwin 	if (!maybe_preempt(td))
14186942d433SJohn Baldwin 		maybe_resched(td);
141961a74c5cSJeff Roberson 	if ((flags & SRQ_HOLDTD) == 0)
142061a74c5cSJeff Roberson 		thread_unlock(td);
1421b43179fbSJeff Roberson }
1422f3a0f873SStephan Uphoff #endif /* SMP */
1423f3a0f873SStephan Uphoff 
1424b43179fbSJeff Roberson void
14257cf90fb3SJeff Roberson sched_rem(struct thread *td)
1426b43179fbSJeff Roberson {
1427ad1e7d28SJulian Elischer 	struct td_sched *ts;
14287cf90fb3SJeff Roberson 
142993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1430b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1431b61ce5b0SJeff Roberson 	    ("sched_rem: thread swapped out"));
1432f0393f06SJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
1433ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
1434b43179fbSJeff Roberson 	mtx_assert(&sched_lock, MA_OWNED);
14358f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
14368f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
14378f51ad55SJeff Roberson 	    sched_tdname(curthread));
1438b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
1439b43179fbSJeff Roberson 
14401b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1441907bdbc2SJeff Roberson 		sched_load_rem();
1442f200843bSJohn Baldwin #ifdef SMP
1443f200843bSJohn Baldwin 	if (ts->ts_runq != &runq)
1444f200843bSJohn Baldwin 		runq_length[ts->ts_runq - runq_pcpu]--;
1445f200843bSJohn Baldwin #endif
14469727e637SJeff Roberson 	runq_remove(ts->ts_runq, td);
1447f0393f06SJeff Roberson 	TD_SET_CAN_RUN(td);
1448b43179fbSJeff Roberson }
1449b43179fbSJeff Roberson 
145014f0e2e9SJulian Elischer /*
14518aa3d7ffSJohn Baldwin  * Select threads to run.  Note that running threads still consume a
14528aa3d7ffSJohn Baldwin  * slot.
145314f0e2e9SJulian Elischer  */
1454f0393f06SJeff Roberson struct thread *
1455b43179fbSJeff Roberson sched_choose(void)
1456b43179fbSJeff Roberson {
14579727e637SJeff Roberson 	struct thread *td;
1458e17c57b1SJeff Roberson 	struct runq *rq;
1459b43179fbSJeff Roberson 
14607b20fb19SJeff Roberson 	mtx_assert(&sched_lock,  MA_OWNED);
1461e17c57b1SJeff Roberson #ifdef SMP
14629727e637SJeff Roberson 	struct thread *tdcpu;
1463e17c57b1SJeff Roberson 
1464e17c57b1SJeff Roberson 	rq = &runq;
14659727e637SJeff Roberson 	td = runq_choose_fuzz(&runq, runq_fuzz);
14669727e637SJeff Roberson 	tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1467e17c57b1SJeff Roberson 
14689727e637SJeff Roberson 	if (td == NULL ||
14699727e637SJeff Roberson 	    (tdcpu != NULL &&
14709727e637SJeff Roberson 	     tdcpu->td_priority < td->td_priority)) {
14719727e637SJeff Roberson 		CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1472e17c57b1SJeff Roberson 		     PCPU_GET(cpuid));
14739727e637SJeff Roberson 		td = tdcpu;
1474e17c57b1SJeff Roberson 		rq = &runq_pcpu[PCPU_GET(cpuid)];
1475e17c57b1SJeff Roberson 	} else {
14769727e637SJeff Roberson 		CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1477e17c57b1SJeff Roberson 	}
1478e17c57b1SJeff Roberson 
1479e17c57b1SJeff Roberson #else
1480e17c57b1SJeff Roberson 	rq = &runq;
14819727e637SJeff Roberson 	td = runq_choose(&runq);
1482e17c57b1SJeff Roberson #endif
1483b43179fbSJeff Roberson 
14849727e637SJeff Roberson 	if (td) {
1485f200843bSJohn Baldwin #ifdef SMP
1486f200843bSJohn Baldwin 		if (td == tdcpu)
1487f200843bSJohn Baldwin 			runq_length[PCPU_GET(cpuid)]--;
1488f200843bSJohn Baldwin #endif
14899727e637SJeff Roberson 		runq_remove(rq, td);
14909727e637SJeff Roberson 		td->td_flags |= TDF_DIDRUN;
1491b43179fbSJeff Roberson 
14929727e637SJeff Roberson 		KASSERT(td->td_flags & TDF_INMEM,
1493b61ce5b0SJeff Roberson 		    ("sched_choose: thread swapped out"));
14949727e637SJeff Roberson 		return (td);
1495b43179fbSJeff Roberson 	}
1496f0393f06SJeff Roberson 	return (PCPU_GET(idlethread));
1497b43179fbSJeff Roberson }
1498b43179fbSJeff Roberson 
1499b43179fbSJeff Roberson void
15001e24c28fSJeff Roberson sched_preempt(struct thread *td)
15011e24c28fSJeff Roberson {
1502b3e9e682SRyan Stone 
1503b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
1504*686bcb5cSJeff Roberson 	if (td->td_critnest > 1) {
15051e24c28fSJeff Roberson 		td->td_owepreempt = 1;
1506*686bcb5cSJeff Roberson 	} else {
1507*686bcb5cSJeff Roberson 		thread_lock(td);
1508*686bcb5cSJeff Roberson 		mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT);
1509*686bcb5cSJeff Roberson 	}
15101e24c28fSJeff Roberson }
15111e24c28fSJeff Roberson 
15121e24c28fSJeff Roberson void
151328240885SMateusz Guzik sched_userret_slowpath(struct thread *td)
1514b43179fbSJeff Roberson {
151528240885SMateusz Guzik 
15167b20fb19SJeff Roberson 	thread_lock(td);
15178460a577SJohn Birrell 	td->td_priority = td->td_user_pri;
15188460a577SJohn Birrell 	td->td_base_pri = td->td_user_pri;
15197b20fb19SJeff Roberson 	thread_unlock(td);
15208460a577SJohn Birrell }
1521de028f5aSJeff Roberson 
1522e17c57b1SJeff Roberson void
1523e17c57b1SJeff Roberson sched_bind(struct thread *td, int cpu)
1524e17c57b1SJeff Roberson {
1525ad1e7d28SJulian Elischer 	struct td_sched *ts;
1526e17c57b1SJeff Roberson 
15271d7830edSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
15281d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1529e17c57b1SJeff Roberson 
153093ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1531e17c57b1SJeff Roberson 
15329727e637SJeff Roberson 	td->td_flags |= TDF_BOUND;
1533e17c57b1SJeff Roberson #ifdef SMP
1534ad1e7d28SJulian Elischer 	ts->ts_runq = &runq_pcpu[cpu];
1535e17c57b1SJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
1536e17c57b1SJeff Roberson 		return;
1537e17c57b1SJeff Roberson 
1538*686bcb5cSJeff Roberson 	mi_switch(SW_VOL);
1539*686bcb5cSJeff Roberson 	thread_lock(td);
1540e17c57b1SJeff Roberson #endif
1541e17c57b1SJeff Roberson }
1542e17c57b1SJeff Roberson 
1543e17c57b1SJeff Roberson void
1544e17c57b1SJeff Roberson sched_unbind(struct thread* td)
1545e17c57b1SJeff Roberson {
15467b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
15471d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
15489727e637SJeff Roberson 	td->td_flags &= ~TDF_BOUND;
1549e17c57b1SJeff Roberson }
1550e17c57b1SJeff Roberson 
1551de028f5aSJeff Roberson int
1552ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
1553ebccf1e3SJoseph Koshy {
15547b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
15559727e637SJeff Roberson 	return (td->td_flags & TDF_BOUND);
1556ebccf1e3SJoseph Koshy }
1557ebccf1e3SJoseph Koshy 
155836ec198bSDavid Xu void
155936ec198bSDavid Xu sched_relinquish(struct thread *td)
156036ec198bSDavid Xu {
15617b20fb19SJeff Roberson 	thread_lock(td);
1562*686bcb5cSJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH);
156336ec198bSDavid Xu }
156436ec198bSDavid Xu 
1565ebccf1e3SJoseph Koshy int
1566ca59f152SJeff Roberson sched_load(void)
1567ca59f152SJeff Roberson {
1568ca59f152SJeff Roberson 	return (sched_tdcnt);
1569ca59f152SJeff Roberson }
1570ca59f152SJeff Roberson 
1571de028f5aSJeff Roberson int
1572de028f5aSJeff Roberson sched_sizeof_proc(void)
1573de028f5aSJeff Roberson {
1574de028f5aSJeff Roberson 	return (sizeof(struct proc));
1575de028f5aSJeff Roberson }
157636ec198bSDavid Xu 
1577de028f5aSJeff Roberson int
1578de028f5aSJeff Roberson sched_sizeof_thread(void)
1579de028f5aSJeff Roberson {
1580ad1e7d28SJulian Elischer 	return (sizeof(struct thread) + sizeof(struct td_sched));
1581de028f5aSJeff Roberson }
158279acfc49SJeff Roberson 
158379acfc49SJeff Roberson fixpt_t
15847cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
158579acfc49SJeff Roberson {
1586ad1e7d28SJulian Elischer 	struct td_sched *ts;
158755f2099aSJeff Roberson 
15883da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
158993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1590ad1e7d28SJulian Elischer 	return (ts->ts_pctcpu);
159179acfc49SJeff Roberson }
1592b41f1452SDavid Xu 
159336af9869SEdward Tomasz Napierala #ifdef RACCT
159436af9869SEdward Tomasz Napierala /*
159536af9869SEdward Tomasz Napierala  * Calculates the contribution to the thread cpu usage for the latest
159636af9869SEdward Tomasz Napierala  * (unfinished) second.
159736af9869SEdward Tomasz Napierala  */
159836af9869SEdward Tomasz Napierala fixpt_t
159936af9869SEdward Tomasz Napierala sched_pctcpu_delta(struct thread *td)
160036af9869SEdward Tomasz Napierala {
160136af9869SEdward Tomasz Napierala 	struct td_sched *ts;
160236af9869SEdward Tomasz Napierala 	fixpt_t delta;
160336af9869SEdward Tomasz Napierala 	int realstathz;
160436af9869SEdward Tomasz Napierala 
160536af9869SEdward Tomasz Napierala 	THREAD_LOCK_ASSERT(td, MA_OWNED);
160693ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
160736af9869SEdward Tomasz Napierala 	delta = 0;
160836af9869SEdward Tomasz Napierala 	realstathz = stathz ? stathz : hz;
160936af9869SEdward Tomasz Napierala 	if (ts->ts_cpticks != 0) {
161036af9869SEdward Tomasz Napierala #if	(FSHIFT >= CCPU_SHIFT)
161136af9869SEdward Tomasz Napierala 		delta = (realstathz == 100)
161236af9869SEdward Tomasz Napierala 		    ? ((fixpt_t) ts->ts_cpticks) <<
161336af9869SEdward Tomasz Napierala 		    (FSHIFT - CCPU_SHIFT) :
161436af9869SEdward Tomasz Napierala 		    100 * (((fixpt_t) ts->ts_cpticks)
161536af9869SEdward Tomasz Napierala 		    << (FSHIFT - CCPU_SHIFT)) / realstathz;
161636af9869SEdward Tomasz Napierala #else
161736af9869SEdward Tomasz Napierala 		delta = ((FSCALE - ccpu) *
161836af9869SEdward Tomasz Napierala 		    (ts->ts_cpticks *
161936af9869SEdward Tomasz Napierala 		    FSCALE / realstathz)) >> FSHIFT;
162036af9869SEdward Tomasz Napierala #endif
162136af9869SEdward Tomasz Napierala 	}
162236af9869SEdward Tomasz Napierala 
162336af9869SEdward Tomasz Napierala 	return (delta);
162436af9869SEdward Tomasz Napierala }
162536af9869SEdward Tomasz Napierala #endif
162636af9869SEdward Tomasz Napierala 
1627ccd0ec40SKonstantin Belousov u_int
1628ccd0ec40SKonstantin Belousov sched_estcpu(struct thread *td)
1629b41f1452SDavid Xu {
1630ccd0ec40SKonstantin Belousov 
163193ccd6bfSKonstantin Belousov 	return (td_get_sched(td)->ts_estcpu);
1632b41f1452SDavid Xu }
1633f0393f06SJeff Roberson 
1634f0393f06SJeff Roberson /*
1635f0393f06SJeff Roberson  * The actual idle process.
1636f0393f06SJeff Roberson  */
1637f0393f06SJeff Roberson void
1638f0393f06SJeff Roberson sched_idletd(void *dummy)
1639f0393f06SJeff Roberson {
1640b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
1641f0393f06SJeff Roberson 
1642ba96d2d8SJohn Baldwin 	THREAD_NO_SLEEPING();
1643b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
1644f0393f06SJeff Roberson 	for (;;) {
1645f0393f06SJeff Roberson 		mtx_assert(&Giant, MA_NOTOWNED);
1646f0393f06SJeff Roberson 
1647b722ad00SAlexander Motin 		while (sched_runnable() == 0) {
1648b722ad00SAlexander Motin 			cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1649b722ad00SAlexander Motin 			stat->idlecalls++;
1650b722ad00SAlexander Motin 		}
1651f0393f06SJeff Roberson 
1652f0393f06SJeff Roberson 		mtx_lock_spin(&sched_lock);
1653*686bcb5cSJeff Roberson 		mi_switch(SW_VOL | SWT_IDLE);
1654f0393f06SJeff Roberson 	}
1655f0393f06SJeff Roberson }
1656f0393f06SJeff Roberson 
16577b20fb19SJeff Roberson /*
16587b20fb19SJeff Roberson  * A CPU is entering for the first time or a thread is exiting.
16597b20fb19SJeff Roberson  */
16607b20fb19SJeff Roberson void
16617b20fb19SJeff Roberson sched_throw(struct thread *td)
16627b20fb19SJeff Roberson {
16637b20fb19SJeff Roberson 	/*
16647b20fb19SJeff Roberson 	 * Correct spinlock nesting.  The idle thread context that we are
16657b20fb19SJeff Roberson 	 * borrowing was created so that it would start out with a single
16667b20fb19SJeff Roberson 	 * spin lock (sched_lock) held in fork_trampoline().  Since we've
16677b20fb19SJeff Roberson 	 * explicitly acquired locks in this function, the nesting count
16687b20fb19SJeff Roberson 	 * is now 2 rather than 1.  Since we are nested, calling
16697b20fb19SJeff Roberson 	 * spinlock_exit() will simply adjust the counts without allowing
16707b20fb19SJeff Roberson 	 * spin lock using code to interrupt us.
16717b20fb19SJeff Roberson 	 */
16727b20fb19SJeff Roberson 	if (td == NULL) {
16737b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
16747b20fb19SJeff Roberson 		spinlock_exit();
16757e3a96eaSJohn Baldwin 		PCPU_SET(switchtime, cpu_ticks());
16767e3a96eaSJohn Baldwin 		PCPU_SET(switchticks, ticks);
16777b20fb19SJeff Roberson 	} else {
1678eea4f254SJeff Roberson 		lock_profile_release_lock(&sched_lock.lock_object);
16797b20fb19SJeff Roberson 		MPASS(td->td_lock == &sched_lock);
168092de34dfSJohn Baldwin 		td->td_lastcpu = td->td_oncpu;
168192de34dfSJohn Baldwin 		td->td_oncpu = NOCPU;
16827b20fb19SJeff Roberson 	}
16837b20fb19SJeff Roberson 	mtx_assert(&sched_lock, MA_OWNED);
16847b20fb19SJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
16857b20fb19SJeff Roberson 	cpu_throw(td, choosethread());	/* doesn't return */
16867b20fb19SJeff Roberson }
16877b20fb19SJeff Roberson 
16887b20fb19SJeff Roberson void
1689fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
16907b20fb19SJeff Roberson {
16917b20fb19SJeff Roberson 
16927b20fb19SJeff Roberson 	/*
16937b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
16947b20fb19SJeff Roberson 	 * non-nested critical section with sched_lock held but not recursed.
16957b20fb19SJeff Roberson 	 */
1696fe54587fSJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
1697fe54587fSJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
1698eea4f254SJeff Roberson 	lock_profile_obtain_lock_success(&sched_lock.lock_object,
1699eea4f254SJeff Roberson 	    0, 0, __FILE__, __LINE__);
1700fe54587fSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
170128ef18b8SAndriy Gapon 
170228ef18b8SAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
170328ef18b8SAndriy Gapon 	    "prio:%d", td->td_priority);
170428ef18b8SAndriy Gapon 	SDT_PROBE0(sched, , , on__cpu);
17057b20fb19SJeff Roberson }
17067b20fb19SJeff Roberson 
17078f51ad55SJeff Roberson char *
17088f51ad55SJeff Roberson sched_tdname(struct thread *td)
17098f51ad55SJeff Roberson {
17108f51ad55SJeff Roberson #ifdef KTR
17118f51ad55SJeff Roberson 	struct td_sched *ts;
17128f51ad55SJeff Roberson 
171393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
17148f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
17158f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
17168f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
17178f51ad55SJeff Roberson 	return (ts->ts_name);
17188f51ad55SJeff Roberson #else
17198f51ad55SJeff Roberson 	return (td->td_name);
17208f51ad55SJeff Roberson #endif
17218f51ad55SJeff Roberson }
17228f51ad55SJeff Roberson 
172344ad5475SJohn Baldwin #ifdef KTR
172444ad5475SJohn Baldwin void
172544ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
172644ad5475SJohn Baldwin {
172744ad5475SJohn Baldwin 	struct td_sched *ts;
172844ad5475SJohn Baldwin 
172993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
173044ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
173144ad5475SJohn Baldwin }
173244ad5475SJohn Baldwin #endif
173344ad5475SJohn Baldwin 
1734885d51a3SJeff Roberson void
1735885d51a3SJeff Roberson sched_affinity(struct thread *td)
1736885d51a3SJeff Roberson {
1737f200843bSJohn Baldwin #ifdef SMP
1738f200843bSJohn Baldwin 	struct td_sched *ts;
1739f200843bSJohn Baldwin 	int cpu;
1740f200843bSJohn Baldwin 
1741f200843bSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1742f200843bSJohn Baldwin 
1743f200843bSJohn Baldwin 	/*
1744f200843bSJohn Baldwin 	 * Set the TSF_AFFINITY flag if there is at least one CPU this
1745f200843bSJohn Baldwin 	 * thread can't run on.
1746f200843bSJohn Baldwin 	 */
174793ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1748f200843bSJohn Baldwin 	ts->ts_flags &= ~TSF_AFFINITY;
17493aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1750f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu)) {
1751f200843bSJohn Baldwin 			ts->ts_flags |= TSF_AFFINITY;
1752f200843bSJohn Baldwin 			break;
1753f200843bSJohn Baldwin 		}
1754f200843bSJohn Baldwin 	}
1755f200843bSJohn Baldwin 
1756f200843bSJohn Baldwin 	/*
1757f200843bSJohn Baldwin 	 * If this thread can run on all CPUs, nothing else to do.
1758f200843bSJohn Baldwin 	 */
1759f200843bSJohn Baldwin 	if (!(ts->ts_flags & TSF_AFFINITY))
1760f200843bSJohn Baldwin 		return;
1761f200843bSJohn Baldwin 
1762f200843bSJohn Baldwin 	/* Pinned threads and bound threads should be left alone. */
1763f200843bSJohn Baldwin 	if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1764f200843bSJohn Baldwin 		return;
1765f200843bSJohn Baldwin 
1766f200843bSJohn Baldwin 	switch (td->td_state) {
1767f200843bSJohn Baldwin 	case TDS_RUNQ:
1768f200843bSJohn Baldwin 		/*
1769f200843bSJohn Baldwin 		 * If we are on a per-CPU runqueue that is in the set,
1770f200843bSJohn Baldwin 		 * then nothing needs to be done.
1771f200843bSJohn Baldwin 		 */
1772f200843bSJohn Baldwin 		if (ts->ts_runq != &runq &&
1773f200843bSJohn Baldwin 		    THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1774f200843bSJohn Baldwin 			return;
1775f200843bSJohn Baldwin 
1776f200843bSJohn Baldwin 		/* Put this thread on a valid per-CPU runqueue. */
1777f200843bSJohn Baldwin 		sched_rem(td);
177861a74c5cSJeff Roberson 		sched_add(td, SRQ_HOLDTD | SRQ_BORING);
1779f200843bSJohn Baldwin 		break;
1780f200843bSJohn Baldwin 	case TDS_RUNNING:
1781f200843bSJohn Baldwin 		/*
1782f200843bSJohn Baldwin 		 * See if our current CPU is in the set.  If not, force a
1783f200843bSJohn Baldwin 		 * context switch.
1784f200843bSJohn Baldwin 		 */
1785f200843bSJohn Baldwin 		if (THREAD_CAN_SCHED(td, td->td_oncpu))
1786f200843bSJohn Baldwin 			return;
1787f200843bSJohn Baldwin 
1788f200843bSJohn Baldwin 		td->td_flags |= TDF_NEEDRESCHED;
1789f200843bSJohn Baldwin 		if (td != curthread)
1790d9d8d144SJohn Baldwin 			ipi_cpu(cpu, IPI_AST);
1791f200843bSJohn Baldwin 		break;
1792f200843bSJohn Baldwin 	default:
1793f200843bSJohn Baldwin 		break;
1794f200843bSJohn Baldwin 	}
1795f200843bSJohn Baldwin #endif
1796885d51a3SJeff Roberson }
1797