xref: /freebsd/sys/kern/sched_4bsd.c (revision c2d27b0ec7000d28b4f31148005ccfe371f47db3)
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>
59af29f399SDmitry Chagin #include <sys/umtxvar.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 
2127029da5cSPawel Biernacki SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2137029da5cSPawel Biernacki     "Scheduler");
214dc095794SScott Long 
215e038d354SScott Long SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
216e038d354SScott Long     "Scheduler name");
2177029da5cSPawel Biernacki SYSCTL_PROC(_kern_sched, OID_AUTO, quantum,
2187029da5cSPawel Biernacki     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
2197029da5cSPawel Biernacki     sysctl_kern_quantum, "I",
22037f4e025SAlexander Motin     "Quantum for timeshare threads in microseconds");
22148317e9eSAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
22237f4e025SAlexander Motin     "Quantum for timeshare threads in stathz ticks");
22337c28a02SJulian Elischer #ifdef SMP
22482a1dfc1SJulian Elischer /* Enable forwarding of wakeups to all other cpus */
2257029da5cSPawel Biernacki static SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup,
2267029da5cSPawel Biernacki     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
2276472ac3dSEd Schouten     "Kernel SMP");
22882a1dfc1SJulian Elischer 
229a90f3f25SJeff Roberson static int runq_fuzz = 1;
230a90f3f25SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
231a90f3f25SJeff Roberson 
232bce73aedSJulian Elischer static int forward_wakeup_enabled = 1;
23382a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
23482a1dfc1SJulian Elischer 	   &forward_wakeup_enabled, 0,
23582a1dfc1SJulian Elischer 	   "Forwarding of wakeup to idle CPUs");
23682a1dfc1SJulian Elischer 
23782a1dfc1SJulian Elischer static int forward_wakeups_requested = 0;
23882a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
23982a1dfc1SJulian Elischer 	   &forward_wakeups_requested, 0,
24082a1dfc1SJulian Elischer 	   "Requests for Forwarding of wakeup to idle CPUs");
24182a1dfc1SJulian Elischer 
24282a1dfc1SJulian Elischer static int forward_wakeups_delivered = 0;
24382a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
24482a1dfc1SJulian Elischer 	   &forward_wakeups_delivered, 0,
24582a1dfc1SJulian Elischer 	   "Completed Forwarding of wakeup to idle CPUs");
24682a1dfc1SJulian Elischer 
247bce73aedSJulian Elischer static int forward_wakeup_use_mask = 1;
24882a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
24982a1dfc1SJulian Elischer 	   &forward_wakeup_use_mask, 0,
25082a1dfc1SJulian Elischer 	   "Use the mask of idle cpus");
25182a1dfc1SJulian Elischer 
25282a1dfc1SJulian Elischer static int forward_wakeup_use_loop = 0;
25382a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
25482a1dfc1SJulian Elischer 	   &forward_wakeup_use_loop, 0,
25582a1dfc1SJulian Elischer 	   "Use a loop to find idle cpus");
25682a1dfc1SJulian Elischer 
25737c28a02SJulian Elischer #endif
258ad1e7d28SJulian Elischer #if 0
2593389af30SJulian Elischer static int sched_followon = 0;
2603389af30SJulian Elischer SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
2613389af30SJulian Elischer 	   &sched_followon, 0,
2623389af30SJulian Elischer 	   "allow threads to share a quantum");
2638460a577SJohn Birrell #endif
26482a1dfc1SJulian Elischer 
265b3e9e682SRyan Stone SDT_PROVIDER_DEFINE(sched);
266b3e9e682SRyan Stone 
267d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
268b3e9e682SRyan Stone     "struct proc *", "uint8_t");
269d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
270b3e9e682SRyan Stone     "struct proc *", "void *");
271d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
272b3e9e682SRyan Stone     "struct proc *", "void *", "int");
273d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
274b3e9e682SRyan Stone     "struct proc *", "uint8_t", "struct thread *");
275d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
276d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
277b3e9e682SRyan Stone     "struct proc *");
278d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , on__cpu);
279d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , remain__cpu);
280d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
281b3e9e682SRyan Stone     "struct proc *");
282b3e9e682SRyan Stone 
283907bdbc2SJeff Roberson static __inline void
284907bdbc2SJeff Roberson sched_load_add(void)
285907bdbc2SJeff Roberson {
2868f51ad55SJeff Roberson 
287907bdbc2SJeff Roberson 	sched_tdcnt++;
2888f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
289d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
290907bdbc2SJeff Roberson }
291907bdbc2SJeff Roberson 
292907bdbc2SJeff Roberson static __inline void
293907bdbc2SJeff Roberson sched_load_rem(void)
294907bdbc2SJeff Roberson {
2958f51ad55SJeff Roberson 
296907bdbc2SJeff Roberson 	sched_tdcnt--;
2978f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
298d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
299907bdbc2SJeff Roberson }
300b43179fbSJeff Roberson /*
301b43179fbSJeff Roberson  * Arrange to reschedule if necessary, taking the priorities and
302b43179fbSJeff Roberson  * schedulers into account.
303b43179fbSJeff Roberson  */
304b43179fbSJeff Roberson static void
305b43179fbSJeff Roberson maybe_resched(struct thread *td)
306b43179fbSJeff Roberson {
307b43179fbSJeff Roberson 
3087b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
309ed062c8dSJulian Elischer 	if (td->td_priority < curthread->td_priority)
310c6d31b83SKonstantin Belousov 		ast_sched_locked(curthread, TDA_SCHED);
311b43179fbSJeff Roberson }
312b43179fbSJeff Roberson 
313b43179fbSJeff Roberson /*
314a90f3f25SJeff Roberson  * This function is called when a thread is about to be put on run queue
315a90f3f25SJeff Roberson  * because it has been made runnable or its priority has been adjusted.  It
316a6b91f0fSJohn Baldwin  * determines if the new thread should preempt the current thread.  If so,
317a6b91f0fSJohn Baldwin  * it sets td_owepreempt to request a preemption.
318a90f3f25SJeff Roberson  */
319a90f3f25SJeff Roberson int
320a90f3f25SJeff Roberson maybe_preempt(struct thread *td)
321a90f3f25SJeff Roberson {
322a90f3f25SJeff Roberson #ifdef PREEMPTION
323a90f3f25SJeff Roberson 	struct thread *ctd;
324a90f3f25SJeff Roberson 	int cpri, pri;
325a90f3f25SJeff Roberson 
326a90f3f25SJeff Roberson 	/*
327a90f3f25SJeff Roberson 	 * The new thread should not preempt the current thread if any of the
328a90f3f25SJeff Roberson 	 * following conditions are true:
329a90f3f25SJeff Roberson 	 *
330a90f3f25SJeff Roberson 	 *  - The kernel is in the throes of crashing (panicstr).
331a90f3f25SJeff Roberson 	 *  - The current thread has a higher (numerically lower) or
332a90f3f25SJeff Roberson 	 *    equivalent priority.  Note that this prevents curthread from
333a90f3f25SJeff Roberson 	 *    trying to preempt to itself.
334a90f3f25SJeff Roberson 	 *  - The current thread has an inhibitor set or is in the process of
335a90f3f25SJeff Roberson 	 *    exiting.  In this case, the current thread is about to switch
336a90f3f25SJeff Roberson 	 *    out anyways, so there's no point in preempting.  If we did,
337a90f3f25SJeff Roberson 	 *    the current thread would not be properly resumed as well, so
338a90f3f25SJeff Roberson 	 *    just avoid that whole landmine.
339a90f3f25SJeff Roberson 	 *  - If the new thread's priority is not a realtime priority and
340a90f3f25SJeff Roberson 	 *    the current thread's priority is not an idle priority and
341a90f3f25SJeff Roberson 	 *    FULL_PREEMPTION is disabled.
342a90f3f25SJeff Roberson 	 *
343a90f3f25SJeff Roberson 	 * If all of these conditions are false, but the current thread is in
344a90f3f25SJeff Roberson 	 * a nested critical section, then we have to defer the preemption
345a90f3f25SJeff Roberson 	 * until we exit the critical section.  Otherwise, switch immediately
346a90f3f25SJeff Roberson 	 * to the new thread.
347a90f3f25SJeff Roberson 	 */
348a90f3f25SJeff Roberson 	ctd = curthread;
349a90f3f25SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
350a90f3f25SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
351a90f3f25SJeff Roberson 			("maybe_preempt: trying to run inhibited thread"));
352a90f3f25SJeff Roberson 	pri = td->td_priority;
353a90f3f25SJeff Roberson 	cpri = ctd->td_priority;
354879e0604SMateusz Guzik 	if (KERNEL_PANICKED() || pri >= cpri /* || dumping */ ||
355a90f3f25SJeff Roberson 	    TD_IS_INHIBITED(ctd))
356a90f3f25SJeff Roberson 		return (0);
357a90f3f25SJeff Roberson #ifndef FULL_PREEMPTION
358a90f3f25SJeff Roberson 	if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
359a90f3f25SJeff Roberson 		return (0);
360a90f3f25SJeff Roberson #endif
361a90f3f25SJeff Roberson 
362a6b91f0fSJohn Baldwin 	CTR0(KTR_PROC, "maybe_preempt: scheduling preemption");
363a90f3f25SJeff Roberson 	ctd->td_owepreempt = 1;
364a90f3f25SJeff Roberson 	return (1);
365a90f3f25SJeff Roberson #else
366a90f3f25SJeff Roberson 	return (0);
367a90f3f25SJeff Roberson #endif
368a90f3f25SJeff Roberson }
369a90f3f25SJeff Roberson 
370a90f3f25SJeff Roberson /*
371b43179fbSJeff Roberson  * Constants for digital decay and forget:
372ccd0ec40SKonstantin Belousov  *	90% of (ts_estcpu) usage in 5 * loadav time
373ad1e7d28SJulian Elischer  *	95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
374b43179fbSJeff Roberson  *          Note that, as ps(1) mentions, this can let percentages
375b43179fbSJeff Roberson  *          total over 100% (I've seen 137.9% for 3 processes).
376b43179fbSJeff Roberson  *
377ccd0ec40SKonstantin Belousov  * Note that schedclock() updates ts_estcpu and p_cpticks asynchronously.
378b43179fbSJeff Roberson  *
379ccd0ec40SKonstantin Belousov  * We wish to decay away 90% of ts_estcpu in (5 * loadavg) seconds.
380b43179fbSJeff Roberson  * That is, the system wants to compute a value of decay such
381b43179fbSJeff Roberson  * that the following for loop:
382b43179fbSJeff Roberson  * 	for (i = 0; i < (5 * loadavg); i++)
383ccd0ec40SKonstantin Belousov  * 		ts_estcpu *= decay;
384b43179fbSJeff Roberson  * will compute
385ccd0ec40SKonstantin Belousov  * 	ts_estcpu *= 0.1;
386b43179fbSJeff Roberson  * for all values of loadavg:
387b43179fbSJeff Roberson  *
388b43179fbSJeff Roberson  * Mathematically this loop can be expressed by saying:
389b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
390b43179fbSJeff Roberson  *
391b43179fbSJeff Roberson  * The system computes decay as:
392b43179fbSJeff Roberson  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
393b43179fbSJeff Roberson  *
394b43179fbSJeff Roberson  * We wish to prove that the system's computation of decay
395b43179fbSJeff Roberson  * will always fulfill the equation:
396b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
397b43179fbSJeff Roberson  *
398b43179fbSJeff Roberson  * If we compute b as:
399b43179fbSJeff Roberson  * 	b = 2 * loadavg
400b43179fbSJeff Roberson  * then
401b43179fbSJeff Roberson  * 	decay = b / (b + 1)
402b43179fbSJeff Roberson  *
403b43179fbSJeff Roberson  * We now need to prove two things:
404b43179fbSJeff Roberson  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
405b43179fbSJeff Roberson  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
406b43179fbSJeff Roberson  *
407b43179fbSJeff Roberson  * Facts:
408b43179fbSJeff Roberson  *         For x close to zero, exp(x) =~ 1 + x, since
409b43179fbSJeff Roberson  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
410b43179fbSJeff Roberson  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
411b43179fbSJeff Roberson  *         For x close to zero, ln(1+x) =~ x, since
412b43179fbSJeff Roberson  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
413b43179fbSJeff Roberson  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
414b43179fbSJeff Roberson  *         ln(.1) =~ -2.30
415b43179fbSJeff Roberson  *
416b43179fbSJeff Roberson  * Proof of (1):
417b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
418b43179fbSJeff Roberson  *	solving for factor,
419b43179fbSJeff Roberson  *      ln(factor) =~ (-2.30/5*loadav), or
420b43179fbSJeff Roberson  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
421b43179fbSJeff Roberson  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
422b43179fbSJeff Roberson  *
423b43179fbSJeff Roberson  * Proof of (2):
424b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
425b43179fbSJeff Roberson  *	solving for power,
426b43179fbSJeff Roberson  *      power*ln(b/(b+1)) =~ -2.30, or
427b43179fbSJeff Roberson  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
428b43179fbSJeff Roberson  *
429b43179fbSJeff Roberson  * Actual power values for the implemented algorithm are as follows:
430b43179fbSJeff Roberson  *      loadav: 1       2       3       4
431b43179fbSJeff Roberson  *      power:  5.68    10.32   14.94   19.55
432b43179fbSJeff Roberson  */
433b43179fbSJeff Roberson 
434b43179fbSJeff Roberson /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
435b43179fbSJeff Roberson #define	loadfactor(loadav)	(2 * (loadav))
436b43179fbSJeff Roberson #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
437b43179fbSJeff Roberson 
438ad1e7d28SJulian Elischer /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
439b43179fbSJeff Roberson static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
440b05ca429SPawel Biernacki SYSCTL_UINT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0,
441b05ca429SPawel Biernacki     "Decay factor used for updating %CPU");
442b43179fbSJeff Roberson 
443b43179fbSJeff Roberson /*
444b43179fbSJeff Roberson  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
445b43179fbSJeff Roberson  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
446b43179fbSJeff Roberson  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
447b43179fbSJeff Roberson  *
448b43179fbSJeff Roberson  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
449b43179fbSJeff Roberson  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
450b43179fbSJeff Roberson  *
451b43179fbSJeff Roberson  * If you don't want to bother with the faster/more-accurate formula, you
452b43179fbSJeff Roberson  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
453b43179fbSJeff Roberson  * (more general) method of calculating the %age of CPU used by a process.
454b43179fbSJeff Roberson  */
455b43179fbSJeff Roberson #define	CCPU_SHIFT	11
456b43179fbSJeff Roberson 
457b43179fbSJeff Roberson /*
458b43179fbSJeff Roberson  * Recompute process priorities, every hz ticks.
459b43179fbSJeff Roberson  * MP-safe, called without the Giant mutex.
460b43179fbSJeff Roberson  */
461b43179fbSJeff Roberson /* ARGSUSED */
462b43179fbSJeff Roberson static void
463c55bbb6cSJohn Baldwin schedcpu(void)
464b43179fbSJeff Roberson {
4653e85b721SEd Maste 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
466b43179fbSJeff Roberson 	struct thread *td;
467b43179fbSJeff Roberson 	struct proc *p;
468ad1e7d28SJulian Elischer 	struct td_sched *ts;
46948317e9eSAlexander Motin 	int awake;
470b43179fbSJeff Roberson 
471b43179fbSJeff Roberson 	sx_slock(&allproc_lock);
472b43179fbSJeff Roberson 	FOREACH_PROC_IN_SYSTEM(p) {
473374ae2a3SJeff Roberson 		PROC_LOCK(p);
474e806d352SJohn Baldwin 		if (p->p_state == PRS_NEW) {
475e806d352SJohn Baldwin 			PROC_UNLOCK(p);
476e806d352SJohn Baldwin 			continue;
477e806d352SJohn Baldwin 		}
4788460a577SJohn Birrell 		FOREACH_THREAD_IN_PROC(p, td) {
479b43179fbSJeff Roberson 			awake = 0;
48093ccd6bfSKonstantin Belousov 			ts = td_get_sched(td);
4817b20fb19SJeff Roberson 			thread_lock(td);
482b43179fbSJeff Roberson 			/*
48370fca427SJohn Baldwin 			 * Increment sleep time (if sleeping).  We
48470fca427SJohn Baldwin 			 * ignore overflow, as above.
485b43179fbSJeff Roberson 			 */
486b43179fbSJeff Roberson 			/*
487ad1e7d28SJulian Elischer 			 * The td_sched slptimes are not touched in wakeup
488ad1e7d28SJulian Elischer 			 * because the thread may not HAVE everything in
489ad1e7d28SJulian Elischer 			 * memory? XXX I think this is out of date.
490b43179fbSJeff Roberson 			 */
491f0393f06SJeff Roberson 			if (TD_ON_RUNQ(td)) {
492b43179fbSJeff Roberson 				awake = 1;
4939727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
494f0393f06SJeff Roberson 			} else if (TD_IS_RUNNING(td)) {
495b43179fbSJeff Roberson 				awake = 1;
4969727e637SJeff Roberson 				/* Do not clear TDF_DIDRUN */
4979727e637SJeff Roberson 			} else if (td->td_flags & TDF_DIDRUN) {
498b43179fbSJeff Roberson 				awake = 1;
4999727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
500b43179fbSJeff Roberson 			}
501b43179fbSJeff Roberson 
502b43179fbSJeff Roberson 			/*
503ad1e7d28SJulian Elischer 			 * ts_pctcpu is only for ps and ttyinfo().
504b43179fbSJeff Roberson 			 */
505ad1e7d28SJulian Elischer 			ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
506b43179fbSJeff Roberson 			/*
507ad1e7d28SJulian Elischer 			 * If the td_sched has been idle the entire second,
508b43179fbSJeff Roberson 			 * stop recalculating its priority until
509b43179fbSJeff Roberson 			 * it wakes up.
510b43179fbSJeff Roberson 			 */
511ad1e7d28SJulian Elischer 			if (ts->ts_cpticks != 0) {
512b43179fbSJeff Roberson #if	(FSHIFT >= CCPU_SHIFT)
513ad1e7d28SJulian Elischer 				ts->ts_pctcpu += (realstathz == 100)
514ad1e7d28SJulian Elischer 				    ? ((fixpt_t) ts->ts_cpticks) <<
515b43179fbSJeff Roberson 				    (FSHIFT - CCPU_SHIFT) :
516ad1e7d28SJulian Elischer 				    100 * (((fixpt_t) ts->ts_cpticks)
517bcb06d59SJeff Roberson 				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
518b43179fbSJeff Roberson #else
519ad1e7d28SJulian Elischer 				ts->ts_pctcpu += ((FSCALE - ccpu) *
520ad1e7d28SJulian Elischer 				    (ts->ts_cpticks *
521bcb06d59SJeff Roberson 				    FSCALE / realstathz)) >> FSHIFT;
522b43179fbSJeff Roberson #endif
523ad1e7d28SJulian Elischer 				ts->ts_cpticks = 0;
5248460a577SJohn Birrell 			}
5258460a577SJohn Birrell 			/*
5268460a577SJohn Birrell 			 * If there are ANY running threads in this process,
527b43179fbSJeff Roberson 			 * then don't count it as sleeping.
5288aa3d7ffSJohn Baldwin 			 * XXX: this is broken.
529b43179fbSJeff Roberson 			 */
530b43179fbSJeff Roberson 			if (awake) {
53154b0e65fSJeff Roberson 				if (ts->ts_slptime > 1) {
532b43179fbSJeff Roberson 					/*
533b43179fbSJeff Roberson 					 * In an ideal world, this should not
534b43179fbSJeff Roberson 					 * happen, because whoever woke us
535b43179fbSJeff Roberson 					 * up from the long sleep should have
536b43179fbSJeff Roberson 					 * unwound the slptime and reset our
537b43179fbSJeff Roberson 					 * priority before we run at the stale
538b43179fbSJeff Roberson 					 * priority.  Should KASSERT at some
539b43179fbSJeff Roberson 					 * point when all the cases are fixed.
540b43179fbSJeff Roberson 					 */
5418460a577SJohn Birrell 					updatepri(td);
5428460a577SJohn Birrell 				}
54354b0e65fSJeff Roberson 				ts->ts_slptime = 0;
5448460a577SJohn Birrell 			} else
54554b0e65fSJeff Roberson 				ts->ts_slptime++;
54654b0e65fSJeff Roberson 			if (ts->ts_slptime > 1) {
5477b20fb19SJeff Roberson 				thread_unlock(td);
5488460a577SJohn Birrell 				continue;
5497b20fb19SJeff Roberson 			}
550ccd0ec40SKonstantin Belousov 			ts->ts_estcpu = decay_cpu(loadfac, ts->ts_estcpu);
5518460a577SJohn Birrell 		      	resetpriority(td);
5528460a577SJohn Birrell 			resetpriority_thread(td);
5537b20fb19SJeff Roberson 			thread_unlock(td);
5548aa3d7ffSJohn Baldwin 		}
555374ae2a3SJeff Roberson 		PROC_UNLOCK(p);
5568aa3d7ffSJohn Baldwin 	}
557b43179fbSJeff Roberson 	sx_sunlock(&allproc_lock);
558c55bbb6cSJohn Baldwin }
559c55bbb6cSJohn Baldwin 
560c55bbb6cSJohn Baldwin /*
561c55bbb6cSJohn Baldwin  * Main loop for a kthread that executes schedcpu once a second.
562c55bbb6cSJohn Baldwin  */
563c55bbb6cSJohn Baldwin static void
564e17c57b1SJeff Roberson schedcpu_thread(void)
565c55bbb6cSJohn Baldwin {
566c55bbb6cSJohn Baldwin 
567c55bbb6cSJohn Baldwin 	for (;;) {
568c55bbb6cSJohn Baldwin 		schedcpu();
5694d70511aSJohn Baldwin 		pause("-", hz);
570c55bbb6cSJohn Baldwin 	}
571b43179fbSJeff Roberson }
572b43179fbSJeff Roberson 
573b43179fbSJeff Roberson /*
574b43179fbSJeff Roberson  * Recalculate the priority of a process after it has slept for a while.
575ccd0ec40SKonstantin Belousov  * For all load averages >= 1 and max ts_estcpu of 255, sleeping for at
576ccd0ec40SKonstantin Belousov  * least six times the loadfactor will decay ts_estcpu to zero.
577b43179fbSJeff Roberson  */
578b43179fbSJeff Roberson static void
5798460a577SJohn Birrell updatepri(struct thread *td)
580b43179fbSJeff Roberson {
58154b0e65fSJeff Roberson 	struct td_sched *ts;
58254b0e65fSJeff Roberson 	fixpt_t loadfac;
58354b0e65fSJeff Roberson 	unsigned int newcpu;
584b43179fbSJeff Roberson 
58593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
58670fca427SJohn Baldwin 	loadfac = loadfactor(averunnable.ldavg[0]);
58754b0e65fSJeff Roberson 	if (ts->ts_slptime > 5 * loadfac)
588ccd0ec40SKonstantin Belousov 		ts->ts_estcpu = 0;
589b43179fbSJeff Roberson 	else {
590ccd0ec40SKonstantin Belousov 		newcpu = ts->ts_estcpu;
59154b0e65fSJeff Roberson 		ts->ts_slptime--;	/* was incremented in schedcpu() */
59254b0e65fSJeff Roberson 		while (newcpu && --ts->ts_slptime)
593b43179fbSJeff Roberson 			newcpu = decay_cpu(loadfac, newcpu);
594ccd0ec40SKonstantin Belousov 		ts->ts_estcpu = newcpu;
595b43179fbSJeff Roberson 	}
596b43179fbSJeff Roberson }
597b43179fbSJeff Roberson 
598b43179fbSJeff Roberson /*
599b43179fbSJeff Roberson  * Compute the priority of a process when running in user mode.
600b43179fbSJeff Roberson  * Arrange to reschedule if the resulting priority is better
601b43179fbSJeff Roberson  * than that of the current process.
602b43179fbSJeff Roberson  */
603b43179fbSJeff Roberson static void
6048460a577SJohn Birrell resetpriority(struct thread *td)
605b43179fbSJeff Roberson {
606ccd0ec40SKonstantin Belousov 	u_int newpriority;
607b43179fbSJeff Roberson 
608ccd0ec40SKonstantin Belousov 	if (td->td_pri_class != PRI_TIMESHARE)
609ccd0ec40SKonstantin Belousov 		return;
61093ccd6bfSKonstantin Belousov 	newpriority = PUSER +
61193ccd6bfSKonstantin Belousov 	    td_get_sched(td)->ts_estcpu / INVERSE_ESTCPU_WEIGHT +
6128460a577SJohn Birrell 	    NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
613b43179fbSJeff Roberson 	newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
614b43179fbSJeff Roberson 	    PRI_MAX_TIMESHARE);
6158460a577SJohn Birrell 	sched_user_prio(td, newpriority);
616b43179fbSJeff Roberson }
617f5c157d9SJohn Baldwin 
618f5c157d9SJohn Baldwin /*
619ad1e7d28SJulian Elischer  * Update the thread's priority when the associated process's user
620f5c157d9SJohn Baldwin  * priority changes.
621f5c157d9SJohn Baldwin  */
622f5c157d9SJohn Baldwin static void
6238460a577SJohn Birrell resetpriority_thread(struct thread *td)
624f5c157d9SJohn Baldwin {
625f5c157d9SJohn Baldwin 
626f5c157d9SJohn Baldwin 	/* Only change threads with a time sharing user priority. */
627f5c157d9SJohn Baldwin 	if (td->td_priority < PRI_MIN_TIMESHARE ||
628f5c157d9SJohn Baldwin 	    td->td_priority > PRI_MAX_TIMESHARE)
629f5c157d9SJohn Baldwin 		return;
630f5c157d9SJohn Baldwin 
631f5c157d9SJohn Baldwin 	/* XXX the whole needresched thing is broken, but not silly. */
632f5c157d9SJohn Baldwin 	maybe_resched(td);
633f5c157d9SJohn Baldwin 
6348460a577SJohn Birrell 	sched_prio(td, td->td_user_pri);
635b43179fbSJeff Roberson }
636b43179fbSJeff Roberson 
637b43179fbSJeff Roberson /* ARGSUSED */
638b43179fbSJeff Roberson static void
639b43179fbSJeff Roberson sched_setup(void *dummy)
640b43179fbSJeff Roberson {
64170fca427SJohn Baldwin 
642579895dfSAlexander Motin 	setup_runqs();
643b43179fbSJeff Roberson 
644ca59f152SJeff Roberson 	/* Account for thread0. */
645907bdbc2SJeff Roberson 	sched_load_add();
646b43179fbSJeff Roberson }
647b43179fbSJeff Roberson 
64848317e9eSAlexander Motin /*
649579895dfSAlexander Motin  * This routine determines time constants after stathz and hz are setup.
65048317e9eSAlexander Motin  */
65148317e9eSAlexander Motin static void
65248317e9eSAlexander Motin sched_initticks(void *dummy)
65348317e9eSAlexander Motin {
65448317e9eSAlexander Motin 
65548317e9eSAlexander Motin 	realstathz = stathz ? stathz : hz;
65648317e9eSAlexander Motin 	sched_slice = realstathz / 10;	/* ~100ms */
65737f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
65837f4e025SAlexander Motin 	    realstathz);
65948317e9eSAlexander Motin }
66048317e9eSAlexander Motin 
661b43179fbSJeff Roberson /* External interfaces start here */
6628aa3d7ffSJohn Baldwin 
663ed062c8dSJulian Elischer /*
664ed062c8dSJulian Elischer  * Very early in the boot some setup of scheduler-specific
665f3050486SMaxim Konovalov  * parts of proc0 and of some scheduler resources needs to be done.
666ed062c8dSJulian Elischer  * Called from:
667ed062c8dSJulian Elischer  *  proc0_init()
668ed062c8dSJulian Elischer  */
669ed062c8dSJulian Elischer void
670ed062c8dSJulian Elischer schedinit(void)
671ed062c8dSJulian Elischer {
67293ccd6bfSKonstantin Belousov 
673ed062c8dSJulian Elischer 	/*
67493ccd6bfSKonstantin Belousov 	 * Set up the scheduler specific parts of thread0.
675ed062c8dSJulian Elischer 	 */
6767b20fb19SJeff Roberson 	thread0.td_lock = &sched_lock;
67793ccd6bfSKonstantin Belousov 	td_get_sched(&thread0)->ts_slice = sched_slice;
678686bcb5cSJeff Roberson 	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN);
679ed062c8dSJulian Elischer }
680ed062c8dSJulian Elischer 
681589aed00SKyle Evans void
682589aed00SKyle Evans schedinit_ap(void)
683589aed00SKyle Evans {
684589aed00SKyle Evans 
685589aed00SKyle Evans 	/* Nothing needed. */
686589aed00SKyle Evans }
687589aed00SKyle Evans 
688b43179fbSJeff Roberson int
689b43179fbSJeff Roberson sched_runnable(void)
690b43179fbSJeff Roberson {
691e17c57b1SJeff Roberson #ifdef SMP
692e17c57b1SJeff Roberson 	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
693e17c57b1SJeff Roberson #else
694b43179fbSJeff Roberson 	return runq_check(&runq);
695e17c57b1SJeff Roberson #endif
696b43179fbSJeff Roberson }
697b43179fbSJeff Roberson 
698b43179fbSJeff Roberson int
699b43179fbSJeff Roberson sched_rr_interval(void)
700b43179fbSJeff Roberson {
70148317e9eSAlexander Motin 
70248317e9eSAlexander Motin 	/* Convert sched_slice from stathz to hz. */
70337f4e025SAlexander Motin 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
704b43179fbSJeff Roberson }
705b43179fbSJeff Roberson 
70640efe743SJohn Baldwin SCHED_STAT_DEFINE(ithread_demotions, "Interrupt thread priority demotions");
70740efe743SJohn Baldwin SCHED_STAT_DEFINE(ithread_preemptions,
70840efe743SJohn Baldwin     "Interrupt thread preemptions due to time-sharing");
70940efe743SJohn Baldwin 
710b43179fbSJeff Roberson /*
711ccd0ec40SKonstantin Belousov  * We adjust the priority of the current process.  The priority of a
712ccd0ec40SKonstantin Belousov  * process gets worse as it accumulates CPU time.  The cpu usage
713ccd0ec40SKonstantin Belousov  * estimator (ts_estcpu) is increased here.  resetpriority() will
714ccd0ec40SKonstantin Belousov  * compute a different priority each time ts_estcpu increases by
715ccd0ec40SKonstantin Belousov  * INVERSE_ESTCPU_WEIGHT (until PRI_MAX_TIMESHARE is reached).  The
716ccd0ec40SKonstantin Belousov  * cpu usage estimator ramps up quite quickly when the process is
717ccd0ec40SKonstantin Belousov  * running (linearly), and decays away exponentially, at a rate which
718ccd0ec40SKonstantin Belousov  * is proportionally slower when the system is busy.  The basic
719ccd0ec40SKonstantin Belousov  * principle is that the system will 90% forget that the process used
720ccd0ec40SKonstantin Belousov  * a lot of CPU time in 5 * loadav seconds.  This causes the system to
721ccd0ec40SKonstantin Belousov  * favor processes which haven't run much recently, and to round-robin
722ccd0ec40SKonstantin Belousov  * among other processes.
723b43179fbSJeff Roberson  */
724c3cccf95SJeff Roberson static void
725c3cccf95SJeff Roberson sched_clock_tick(struct thread *td)
726b43179fbSJeff Roberson {
727b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
728ad1e7d28SJulian Elischer 	struct td_sched *ts;
729b43179fbSJeff Roberson 
7307b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
73193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
732f7f9e7f3SJeff Roberson 
733ad1e7d28SJulian Elischer 	ts->ts_cpticks++;
734ccd0ec40SKonstantin Belousov 	ts->ts_estcpu = ESTCPULIM(ts->ts_estcpu + 1);
735ccd0ec40SKonstantin Belousov 	if ((ts->ts_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
7368460a577SJohn Birrell 		resetpriority(td);
7378460a577SJohn Birrell 		resetpriority_thread(td);
738b43179fbSJeff Roberson 	}
7399dddab6fSJohn Baldwin 
7409dddab6fSJohn Baldwin 	/*
7419dddab6fSJohn Baldwin 	 * Force a context switch if the current thread has used up a full
742579895dfSAlexander Motin 	 * time slice (default is 100ms).
7439dddab6fSJohn Baldwin 	 */
744579895dfSAlexander Motin 	if (!TD_IS_IDLETHREAD(td) && --ts->ts_slice <= 0) {
74548317e9eSAlexander Motin 		ts->ts_slice = sched_slice;
74640efe743SJohn Baldwin 
74740efe743SJohn Baldwin 		/*
74840efe743SJohn Baldwin 		 * If an ithread uses a full quantum, demote its
74940efe743SJohn Baldwin 		 * priority and preempt it.
75040efe743SJohn Baldwin 		 */
75140efe743SJohn Baldwin 		if (PRI_BASE(td->td_pri_class) == PRI_ITHD) {
75240efe743SJohn Baldwin 			SCHED_STAT_INC(ithread_preemptions);
75340efe743SJohn Baldwin 			td->td_owepreempt = 1;
75440efe743SJohn Baldwin 			if (td->td_base_pri + RQ_PPQ < PRI_MAX_ITHD) {
75540efe743SJohn Baldwin 				SCHED_STAT_INC(ithread_demotions);
75640efe743SJohn Baldwin 				sched_prio(td, td->td_base_pri + RQ_PPQ);
75740efe743SJohn Baldwin 			}
758c6d31b83SKonstantin Belousov 		} else {
759c6d31b83SKonstantin Belousov 			td->td_flags |= TDF_SLICEEND;
760c6d31b83SKonstantin Belousov 			ast_sched_locked(td, TDA_SCHED);
761c6d31b83SKonstantin Belousov 		}
76248317e9eSAlexander Motin 	}
763b722ad00SAlexander Motin 
764b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
765b722ad00SAlexander Motin 	stat->oldidlecalls = stat->idlecalls;
766b722ad00SAlexander Motin 	stat->idlecalls = 0;
767b43179fbSJeff Roberson }
76870fca427SJohn Baldwin 
769c3cccf95SJeff Roberson void
770c3cccf95SJeff Roberson sched_clock(struct thread *td, int cnt)
771c3cccf95SJeff Roberson {
772c3cccf95SJeff Roberson 
773c3cccf95SJeff Roberson 	for ( ; cnt > 0; cnt--)
774c3cccf95SJeff Roberson 		sched_clock_tick(td);
775c3cccf95SJeff Roberson }
776c3cccf95SJeff Roberson 
7778460a577SJohn Birrell /*
7788aa3d7ffSJohn Baldwin  * Charge child's scheduling CPU usage to parent.
7798460a577SJohn Birrell  */
780b43179fbSJeff Roberson void
78155d44f79SJulian Elischer sched_exit(struct proc *p, struct thread *td)
782f7f9e7f3SJeff Roberson {
7838460a577SJohn Birrell 
7848f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "proc exit",
785cd39bb09SXin LI 	    "prio:%d", td->td_priority);
7868f51ad55SJeff Roberson 
787374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
788ad1e7d28SJulian Elischer 	sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
789b43179fbSJeff Roberson }
790b43179fbSJeff Roberson 
791b43179fbSJeff Roberson void
792f7f9e7f3SJeff Roberson sched_exit_thread(struct thread *td, struct thread *child)
793b43179fbSJeff Roberson {
794ad1e7d28SJulian Elischer 
7958f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "exit",
796cd39bb09SXin LI 	    "prio:%d", child->td_priority);
7977b20fb19SJeff Roberson 	thread_lock(td);
79893ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_estcpu = ESTCPULIM(td_get_sched(td)->ts_estcpu +
79993ccd6bfSKonstantin Belousov 	    td_get_sched(child)->ts_estcpu);
8007b20fb19SJeff Roberson 	thread_unlock(td);
8011b9d701fSAttilio Rao 	thread_lock(child);
8021b9d701fSAttilio Rao 	if ((child->td_flags & TDF_NOLOAD) == 0)
803907bdbc2SJeff Roberson 		sched_load_rem();
8041b9d701fSAttilio Rao 	thread_unlock(child);
805f7f9e7f3SJeff Roberson }
806bcb06d59SJeff Roberson 
807f7f9e7f3SJeff Roberson void
808ed062c8dSJulian Elischer sched_fork(struct thread *td, struct thread *childtd)
809f7f9e7f3SJeff Roberson {
810ed062c8dSJulian Elischer 	sched_fork_thread(td, childtd);
811f7f9e7f3SJeff Roberson }
812bcb06d59SJeff Roberson 
813f7f9e7f3SJeff Roberson void
814ed062c8dSJulian Elischer sched_fork_thread(struct thread *td, struct thread *childtd)
815f7f9e7f3SJeff Roberson {
81693ccd6bfSKonstantin Belousov 	struct td_sched *ts, *tsc;
8178b16c208SJeff Roberson 
81892de34dfSJohn Baldwin 	childtd->td_oncpu = NOCPU;
81992de34dfSJohn Baldwin 	childtd->td_lastcpu = NOCPU;
8207b20fb19SJeff Roberson 	childtd->td_lock = &sched_lock;
821f5a3ef99SMarcel Moolenaar 	childtd->td_cpuset = cpuset_ref(td->td_cpuset);
8223f289c3fSJeff Roberson 	childtd->td_domain.dr_policy = td->td_cpuset->cs_domain;
82322d19207SJohn Baldwin 	childtd->td_priority = childtd->td_base_pri;
82493ccd6bfSKonstantin Belousov 	ts = td_get_sched(childtd);
8258b16c208SJeff Roberson 	bzero(ts, sizeof(*ts));
82693ccd6bfSKonstantin Belousov 	tsc = td_get_sched(td);
82793ccd6bfSKonstantin Belousov 	ts->ts_estcpu = tsc->ts_estcpu;
82893ccd6bfSKonstantin Belousov 	ts->ts_flags |= (tsc->ts_flags & TSF_AFFINITY);
82948317e9eSAlexander Motin 	ts->ts_slice = 1;
830b43179fbSJeff Roberson }
831b43179fbSJeff Roberson 
832b43179fbSJeff Roberson void
833fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
834b43179fbSJeff Roberson {
835f5c157d9SJohn Baldwin 	struct thread *td;
8360b5318c8SJohn Baldwin 
837fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
838fa885116SJulian Elischer 	p->p_nice = nice;
8398460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
8407b20fb19SJeff Roberson 		thread_lock(td);
8418460a577SJohn Birrell 		resetpriority(td);
8428460a577SJohn Birrell 		resetpriority_thread(td);
8437b20fb19SJeff Roberson 		thread_unlock(td);
8448460a577SJohn Birrell 	}
845fa885116SJulian Elischer }
846b43179fbSJeff Roberson 
847f7f9e7f3SJeff Roberson void
8488460a577SJohn Birrell sched_class(struct thread *td, int class)
849f7f9e7f3SJeff Roberson {
8507b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
8518460a577SJohn Birrell 	td->td_pri_class = class;
852f7f9e7f3SJeff Roberson }
853f7f9e7f3SJeff Roberson 
8548460a577SJohn Birrell /*
8558460a577SJohn Birrell  * Adjust the priority of a thread.
8568460a577SJohn Birrell  */
857f5c157d9SJohn Baldwin static void
858f5c157d9SJohn Baldwin sched_priority(struct thread *td, u_char prio)
859b43179fbSJeff Roberson {
86027ee18adSRyan Stone 
8618f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
8628f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
8638f51ad55SJeff Roberson 	    sched_tdname(curthread));
864d9fae5abSAndriy Gapon 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
8658f51ad55SJeff Roberson 	if (td != curthread && prio > td->td_priority) {
8668f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
8678f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
8688f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
869d9fae5abSAndriy Gapon 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
870b3e9e682SRyan Stone 		    curthread);
8718f51ad55SJeff Roberson 	}
8727b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
873f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
874f5c157d9SJohn Baldwin 		return;
8751f955e2dSJulian Elischer 	td->td_priority = prio;
8769727e637SJeff Roberson 	if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
877f0393f06SJeff Roberson 		sched_rem(td);
87861a74c5cSJeff Roberson 		sched_add(td, SRQ_BORING | SRQ_HOLDTD);
879b43179fbSJeff Roberson 	}
880b43179fbSJeff Roberson }
881b43179fbSJeff Roberson 
882f5c157d9SJohn Baldwin /*
883f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
884f5c157d9SJohn Baldwin  * priority.
885f5c157d9SJohn Baldwin  */
886f5c157d9SJohn Baldwin void
887f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
888f5c157d9SJohn Baldwin {
889f5c157d9SJohn Baldwin 
890f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
891f5c157d9SJohn Baldwin 	sched_priority(td, prio);
892f5c157d9SJohn Baldwin }
893f5c157d9SJohn Baldwin 
894f5c157d9SJohn Baldwin /*
895f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
896f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
897f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
898f5c157d9SJohn Baldwin  * requests.  If the thread's regulary priority is less
899f5c157d9SJohn Baldwin  * important than prio the thread will keep a priority boost
900f5c157d9SJohn Baldwin  * of prio.
901f5c157d9SJohn Baldwin  */
902f5c157d9SJohn Baldwin void
903f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
904f5c157d9SJohn Baldwin {
905f5c157d9SJohn Baldwin 	u_char base_pri;
906f5c157d9SJohn Baldwin 
907f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
908f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
9098460a577SJohn Birrell 		base_pri = td->td_user_pri;
910f5c157d9SJohn Baldwin 	else
911f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
912f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
913f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
914f5c157d9SJohn Baldwin 		sched_prio(td, base_pri);
915f5c157d9SJohn Baldwin 	} else
916f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
917f5c157d9SJohn Baldwin }
918f5c157d9SJohn Baldwin 
919f5c157d9SJohn Baldwin void
920f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
921f5c157d9SJohn Baldwin {
922f5c157d9SJohn Baldwin 	u_char oldprio;
923f5c157d9SJohn Baldwin 
924f5c157d9SJohn Baldwin 	/* First, update the base priority. */
925f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
926f5c157d9SJohn Baldwin 
927f5c157d9SJohn Baldwin 	/*
928f5c157d9SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't ever
929f5c157d9SJohn Baldwin 	 * lower the priority.
930f5c157d9SJohn Baldwin 	 */
931f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
932f5c157d9SJohn Baldwin 		return;
933f5c157d9SJohn Baldwin 
934f5c157d9SJohn Baldwin 	/* Change the real priority. */
935f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
936f5c157d9SJohn Baldwin 	sched_priority(td, prio);
937f5c157d9SJohn Baldwin 
938f5c157d9SJohn Baldwin 	/*
939f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
940f5c157d9SJohn Baldwin 	 * its state.
941f5c157d9SJohn Baldwin 	 */
942f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
943f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
944f5c157d9SJohn Baldwin }
945f5c157d9SJohn Baldwin 
946b43179fbSJeff Roberson void
947fea89a28SJohn Baldwin sched_ithread_prio(struct thread *td, u_char prio)
948fea89a28SJohn Baldwin {
949fea89a28SJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
950fea89a28SJohn Baldwin 	MPASS(td->td_pri_class == PRI_ITHD);
951fea89a28SJohn Baldwin 	td->td_base_ithread_pri = prio;
952fea89a28SJohn Baldwin 	sched_prio(td, prio);
953fea89a28SJohn Baldwin }
954fea89a28SJohn Baldwin 
955fea89a28SJohn Baldwin void
9568460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
9573db720fdSDavid Xu {
9583db720fdSDavid Xu 
959435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
9608460a577SJohn Birrell 	td->td_base_user_pri = prio;
961acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
9625a215147SDavid Xu 		return;
9638460a577SJohn Birrell 	td->td_user_pri = prio;
9643db720fdSDavid Xu }
9653db720fdSDavid Xu 
9663db720fdSDavid Xu void
9673db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
9683db720fdSDavid Xu {
9693db720fdSDavid Xu 
970435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
971acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
972c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
973c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
974c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
975c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
976c6d31b83SKonstantin Belousov 		ast_sched_locked(td, TDA_SCHED);
977435806d3SDavid Xu }
9783db720fdSDavid Xu 
979ac97da9aSMateusz Guzik /*
980ac97da9aSMateusz Guzik  * Like the above but first check if there is anything to do.
981ac97da9aSMateusz Guzik  */
982ac97da9aSMateusz Guzik void
983ac97da9aSMateusz Guzik sched_lend_user_prio_cond(struct thread *td, u_char prio)
984ac97da9aSMateusz Guzik {
985ac97da9aSMateusz Guzik 
986ac97da9aSMateusz Guzik 	if (td->td_lend_user_pri != prio)
987ac97da9aSMateusz Guzik 		goto lend;
988ac97da9aSMateusz Guzik 	if (td->td_user_pri != min(prio, td->td_base_user_pri))
989ac97da9aSMateusz Guzik 		goto lend;
990b77594bbSMateusz Guzik 	if (td->td_priority != td->td_user_pri)
991ac97da9aSMateusz Guzik 		goto lend;
992ac97da9aSMateusz Guzik 	return;
993ac97da9aSMateusz Guzik 
994ac97da9aSMateusz Guzik lend:
995ac97da9aSMateusz Guzik 	thread_lock(td);
996ac97da9aSMateusz Guzik 	sched_lend_user_prio(td, prio);
997ac97da9aSMateusz Guzik 	thread_unlock(td);
998ac97da9aSMateusz Guzik }
999ac97da9aSMateusz Guzik 
10003db720fdSDavid Xu void
1001c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int pri)
1002b43179fbSJeff Roberson {
10032056d0a1SJohn Baldwin 
10047b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
100554b0e65fSJeff Roberson 	td->td_slptick = ticks;
100693ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_slptime = 0;
10072dc29adbSJohn Baldwin 	if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
1008c5aa6b58SJeff Roberson 		sched_prio(td, pri);
100917c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
1010c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
1011b43179fbSJeff Roberson }
1012b43179fbSJeff Roberson 
1013b43179fbSJeff Roberson void
1014686bcb5cSJeff Roberson sched_switch(struct thread *td, int flags)
1015b43179fbSJeff Roberson {
1016686bcb5cSJeff Roberson 	struct thread *newtd;
1017b0b9dee5SAttilio Rao 	struct mtx *tmtx;
10183d7f4117SAlexander Motin 	int preempted;
1019b43179fbSJeff Roberson 
102061a74c5cSJeff Roberson 	tmtx = &sched_lock;
1021b43179fbSJeff Roberson 
10227b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
10238aa3d7ffSJohn Baldwin 
1024060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
1025ad9dadc4SAndriy Gapon 	preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
1026ad9dadc4SAndriy Gapon 	    (flags & SW_PREEMPT) != 0;
1027c6d31b83SKonstantin Belousov 	td->td_flags &= ~TDF_SLICEEND;
1028c6d31b83SKonstantin Belousov 	ast_unsched_locked(td, TDA_SCHED);
102977918643SStephan Uphoff 	td->td_owepreempt = 0;
1030ca59f152SJeff Roberson 	td->td_oncpu = NOCPU;
10318aa3d7ffSJohn Baldwin 
1032b43179fbSJeff Roberson 	/*
1033b43179fbSJeff Roberson 	 * At the last moment, if this thread is still marked RUNNING,
1034b43179fbSJeff Roberson 	 * then put it back on the run queue as it has not been suspended
1035bf0acc27SJohn Baldwin 	 * or stopped or any thing else similar.  We never put the idle
1036bf0acc27SJohn Baldwin 	 * threads on the run queue, however.
1037b43179fbSJeff Roberson 	 */
1038c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD) {
1039bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
1040c6226eeaSJulian Elischer #ifdef SMP
1041a38f1f26SAttilio Rao 		CPU_CLR(PCPU_GET(cpuid), &idle_cpus_mask);
1042c6226eeaSJulian Elischer #endif
1043c6226eeaSJulian Elischer 	} else {
1044ed062c8dSJulian Elischer 		if (TD_IS_RUNNING(td)) {
1045ad1e7d28SJulian Elischer 			/* Put us back on the run queue. */
10463d7f4117SAlexander Motin 			sched_add(td, preempted ?
104761a74c5cSJeff Roberson 			    SRQ_HOLDTD|SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
104861a74c5cSJeff Roberson 			    SRQ_HOLDTD|SRQ_OURSELF|SRQ_YIELDING);
1049ed062c8dSJulian Elischer 		}
1050b43179fbSJeff Roberson 	}
105161a74c5cSJeff Roberson 
105261a74c5cSJeff Roberson 	/*
105361a74c5cSJeff Roberson 	 * Switch to the sched lock to fix things up and pick
105461a74c5cSJeff Roberson 	 * a new thread.  Block the td_lock in order to avoid
105561a74c5cSJeff Roberson 	 * breaking the critical path.
105661a74c5cSJeff Roberson 	 */
105761a74c5cSJeff Roberson 	if (td->td_lock != &sched_lock) {
105861a74c5cSJeff Roberson 		mtx_lock_spin(&sched_lock);
105961a74c5cSJeff Roberson 		tmtx = thread_lock_block(td);
106061a74c5cSJeff Roberson 		mtx_unlock_spin(tmtx);
106161a74c5cSJeff Roberson 	}
106261a74c5cSJeff Roberson 
106361a74c5cSJeff Roberson 	if ((td->td_flags & TDF_NOLOAD) == 0)
106461a74c5cSJeff Roberson 		sched_load_rem();
106561a74c5cSJeff Roberson 
1066ae53b483SJeff Roberson 	newtd = choosethread();
106761a74c5cSJeff Roberson 	MPASS(newtd->td_lock == &sched_lock);
106861a74c5cSJeff Roberson 
1069afa0a46cSAndriy Gapon #if (KTR_COMPILE & KTR_SCHED) != 0
1070afa0a46cSAndriy Gapon 	if (TD_IS_IDLETHREAD(td))
1071afa0a46cSAndriy Gapon 		KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
1072afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority);
1073afa0a46cSAndriy Gapon 	else
1074afa0a46cSAndriy Gapon 		KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
1075afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
1076afa0a46cSAndriy Gapon 		    "lockname:\"%s\"", td->td_lockname);
1077afa0a46cSAndriy Gapon #endif
1078afa0a46cSAndriy Gapon 
1079ebccf1e3SJoseph Koshy 	if (td != newtd) {
1080ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1081ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1082ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1083ebccf1e3SJoseph Koshy #endif
1084b3e9e682SRyan Stone 
10857dba7849SMark Johnston 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1086b3e9e682SRyan Stone 
1087c6226eeaSJulian Elischer                 /* I feel sleepy */
10886a467cc5SMateusz Guzik 		lock_profile_release_lock(&sched_lock.lock_object, true);
10896f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
10906f5f25e5SJohn Birrell 		/*
10916f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
10926f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
10936f5f25e5SJohn Birrell 		 * function to call.
10946f5f25e5SJohn Birrell 		 */
10956f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
10966f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
10976f5f25e5SJohn Birrell #endif
10986f5f25e5SJohn Birrell 
109961a74c5cSJeff Roberson 		cpu_switch(td, newtd, tmtx);
11006a467cc5SMateusz Guzik 		lock_profile_obtain_lock_success(&sched_lock.lock_object, true,
1101eea4f254SJeff Roberson 		    0, 0, __FILE__, __LINE__);
1102c6226eeaSJulian Elischer 		/*
1103c6226eeaSJulian Elischer 		 * Where am I?  What year is it?
1104c6226eeaSJulian Elischer 		 * We are in the same thread that went to sleep above,
11058aa3d7ffSJohn Baldwin 		 * but any amount of time may have passed. All our context
1106c6226eeaSJulian Elischer 		 * will still be available as will local variables.
1107c6226eeaSJulian Elischer 		 * PCPU values however may have changed as we may have
1108c6226eeaSJulian Elischer 		 * changed CPU so don't trust cached values of them.
1109c6226eeaSJulian Elischer 		 * New threads will go to fork_exit() instead of here
1110c6226eeaSJulian Elischer 		 * so if you change things here you may need to change
1111c6226eeaSJulian Elischer 		 * things there too.
11128aa3d7ffSJohn Baldwin 		 *
1113c6226eeaSJulian Elischer 		 * If the thread above was exiting it will never wake
1114c6226eeaSJulian Elischer 		 * up again here, so either it has saved everything it
1115c6226eeaSJulian Elischer 		 * needed to, or the thread_wait() or wait() will
1116c6226eeaSJulian Elischer 		 * need to reap it.
1117c6226eeaSJulian Elischer 		 */
1118b3e9e682SRyan Stone 
1119d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , on__cpu);
1120ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1121ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1122ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1123ebccf1e3SJoseph Koshy #endif
112461a74c5cSJeff Roberson 	} else {
112561a74c5cSJeff Roberson 		td->td_lock = &sched_lock;
1126d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , remain__cpu);
112761a74c5cSJeff Roberson 	}
1128ebccf1e3SJoseph Koshy 
1129afa0a46cSAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
1130afa0a46cSAndriy Gapon 	    "prio:%d", td->td_priority);
1131afa0a46cSAndriy Gapon 
1132c6226eeaSJulian Elischer #ifdef SMP
1133c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD)
1134a38f1f26SAttilio Rao 		CPU_SET(PCPU_GET(cpuid), &idle_cpus_mask);
1135c6226eeaSJulian Elischer #endif
1136ae53b483SJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
1137ae53b483SJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
1138686bcb5cSJeff Roberson 	spinlock_enter();
1139686bcb5cSJeff Roberson 	mtx_unlock_spin(&sched_lock);
1140b43179fbSJeff Roberson }
1141b43179fbSJeff Roberson 
1142b43179fbSJeff Roberson void
114361a74c5cSJeff Roberson sched_wakeup(struct thread *td, int srqflags)
1144b43179fbSJeff Roberson {
114554b0e65fSJeff Roberson 	struct td_sched *ts;
114654b0e65fSJeff Roberson 
11477b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
114893ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1149c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
115054b0e65fSJeff Roberson 	if (ts->ts_slptime > 1) {
11518460a577SJohn Birrell 		updatepri(td);
11528460a577SJohn Birrell 		resetpriority(td);
11538460a577SJohn Birrell 	}
11546eac7e57SAttilio Rao 	td->td_slptick = 0;
115554b0e65fSJeff Roberson 	ts->ts_slptime = 0;
115648317e9eSAlexander Motin 	ts->ts_slice = sched_slice;
115740efe743SJohn Baldwin 
115840efe743SJohn Baldwin 	/*
115940efe743SJohn Baldwin 	 * When resuming an idle ithread, restore its base ithread
116040efe743SJohn Baldwin 	 * priority.
116140efe743SJohn Baldwin 	 */
116240efe743SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) == PRI_ITHD &&
116340efe743SJohn Baldwin 	    td->td_base_pri != td->td_base_ithread_pri)
116440efe743SJohn Baldwin 		sched_prio(td, td->td_base_ithread_pri);
116540efe743SJohn Baldwin 
116661a74c5cSJeff Roberson 	sched_add(td, srqflags);
1167b43179fbSJeff Roberson }
1168b43179fbSJeff Roberson 
116937c28a02SJulian Elischer #ifdef SMP
117082a1dfc1SJulian Elischer static int
117182a1dfc1SJulian Elischer forward_wakeup(int cpunum)
117282a1dfc1SJulian Elischer {
117382a1dfc1SJulian Elischer 	struct pcpu *pc;
1174a38f1f26SAttilio Rao 	cpuset_t dontuse, map, map2;
1175a38f1f26SAttilio Rao 	u_int id, me;
117671a19bdcSAttilio Rao 	int iscpuset;
117782a1dfc1SJulian Elischer 
117882a1dfc1SJulian Elischer 	mtx_assert(&sched_lock, MA_OWNED);
117982a1dfc1SJulian Elischer 
1180ed062c8dSJulian Elischer 	CTR0(KTR_RUNQ, "forward_wakeup()");
118182a1dfc1SJulian Elischer 
118282a1dfc1SJulian Elischer 	if ((!forward_wakeup_enabled) ||
118382a1dfc1SJulian Elischer 	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
118482a1dfc1SJulian Elischer 		return (0);
1185879e0604SMateusz Guzik 	if (!smp_started || KERNEL_PANICKED())
118682a1dfc1SJulian Elischer 		return (0);
118782a1dfc1SJulian Elischer 
118882a1dfc1SJulian Elischer 	forward_wakeups_requested++;
118982a1dfc1SJulian Elischer 
119082a1dfc1SJulian Elischer 	/*
11918aa3d7ffSJohn Baldwin 	 * Check the idle mask we received against what we calculated
11928aa3d7ffSJohn Baldwin 	 * before in the old version.
119382a1dfc1SJulian Elischer 	 */
1194a38f1f26SAttilio Rao 	me = PCPU_GET(cpuid);
11958aa3d7ffSJohn Baldwin 
11968aa3d7ffSJohn Baldwin 	/* Don't bother if we should be doing it ourself. */
1197a38f1f26SAttilio Rao 	if (CPU_ISSET(me, &idle_cpus_mask) &&
1198a38f1f26SAttilio Rao 	    (cpunum == NOCPU || me == cpunum))
119982a1dfc1SJulian Elischer 		return (0);
120082a1dfc1SJulian Elischer 
1201a38f1f26SAttilio Rao 	CPU_SETOF(me, &dontuse);
1202e2650af1SStefan Eßer 	CPU_OR(&dontuse, &dontuse, &stopped_cpus);
1203e2650af1SStefan Eßer 	CPU_OR(&dontuse, &dontuse, &hlt_cpus_mask);
120471a19bdcSAttilio Rao 	CPU_ZERO(&map2);
120582a1dfc1SJulian Elischer 	if (forward_wakeup_use_loop) {
1206d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1207a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1208a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &dontuse) &&
120982a1dfc1SJulian Elischer 			    pc->pc_curthread == pc->pc_idlethread) {
1210a38f1f26SAttilio Rao 				CPU_SET(id, &map2);
121182a1dfc1SJulian Elischer 			}
121282a1dfc1SJulian Elischer 		}
121382a1dfc1SJulian Elischer 	}
121482a1dfc1SJulian Elischer 
121582a1dfc1SJulian Elischer 	if (forward_wakeup_use_mask) {
1216ec3af9d0SStefan Eßer 		map = idle_cpus_mask;
1217a19bd8e3SStefan Eßer 		CPU_ANDNOT(&map, &map, &dontuse);
121882a1dfc1SJulian Elischer 
12198aa3d7ffSJohn Baldwin 		/* If they are both on, compare and use loop if different. */
122082a1dfc1SJulian Elischer 		if (forward_wakeup_use_loop) {
122171a19bdcSAttilio Rao 			if (CPU_CMP(&map, &map2)) {
1222f0283a73SAttilio Rao 				printf("map != map2, loop method preferred\n");
1223f0283a73SAttilio Rao 				map = map2;
122482a1dfc1SJulian Elischer 			}
122582a1dfc1SJulian Elischer 		}
122682a1dfc1SJulian Elischer 	} else {
1227f0283a73SAttilio Rao 		map = map2;
122882a1dfc1SJulian Elischer 	}
12298aa3d7ffSJohn Baldwin 
12308aa3d7ffSJohn Baldwin 	/* If we only allow a specific CPU, then mask off all the others. */
123182a1dfc1SJulian Elischer 	if (cpunum != NOCPU) {
123282a1dfc1SJulian Elischer 		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
123371a19bdcSAttilio Rao 		iscpuset = CPU_ISSET(cpunum, &map);
123471a19bdcSAttilio Rao 		if (iscpuset == 0)
123571a19bdcSAttilio Rao 			CPU_ZERO(&map);
123671a19bdcSAttilio Rao 		else
123771a19bdcSAttilio Rao 			CPU_SETOF(cpunum, &map);
123882a1dfc1SJulian Elischer 	}
123971a19bdcSAttilio Rao 	if (!CPU_EMPTY(&map)) {
124082a1dfc1SJulian Elischer 		forward_wakeups_delivered++;
1241d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1242a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1243a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &map))
1244b722ad00SAlexander Motin 				continue;
1245b722ad00SAlexander Motin 			if (cpu_idle_wakeup(pc->pc_cpuid))
1246a38f1f26SAttilio Rao 				CPU_CLR(id, &map);
1247b722ad00SAlexander Motin 		}
124871a19bdcSAttilio Rao 		if (!CPU_EMPTY(&map))
124982a1dfc1SJulian Elischer 			ipi_selected(map, IPI_AST);
125082a1dfc1SJulian Elischer 		return (1);
125182a1dfc1SJulian Elischer 	}
125282a1dfc1SJulian Elischer 	if (cpunum == NOCPU)
125382a1dfc1SJulian Elischer 		printf("forward_wakeup: Idle processor not found\n");
125482a1dfc1SJulian Elischer 	return (0);
125582a1dfc1SJulian Elischer }
1256f3a0f873SStephan Uphoff 
1257f3a0f873SStephan Uphoff static void
1258f3a0f873SStephan Uphoff kick_other_cpu(int pri, int cpuid)
1259f3a0f873SStephan Uphoff {
12608aa3d7ffSJohn Baldwin 	struct pcpu *pcpu;
12618aa3d7ffSJohn Baldwin 	int cpri;
1262f3a0f873SStephan Uphoff 
12638aa3d7ffSJohn Baldwin 	pcpu = pcpu_find(cpuid);
1264a38f1f26SAttilio Rao 	if (CPU_ISSET(cpuid, &idle_cpus_mask)) {
1265f3a0f873SStephan Uphoff 		forward_wakeups_delivered++;
1266b722ad00SAlexander Motin 		if (!cpu_idle_wakeup(cpuid))
1267d9d8d144SJohn Baldwin 			ipi_cpu(cpuid, IPI_AST);
1268f3a0f873SStephan Uphoff 		return;
1269f3a0f873SStephan Uphoff 	}
1270f3a0f873SStephan Uphoff 
12718aa3d7ffSJohn Baldwin 	cpri = pcpu->pc_curthread->td_priority;
1272f3a0f873SStephan Uphoff 	if (pri >= cpri)
1273f3a0f873SStephan Uphoff 		return;
1274f3a0f873SStephan Uphoff 
1275f3a0f873SStephan Uphoff #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1276f3a0f873SStephan Uphoff #if !defined(FULL_PREEMPTION)
1277f3a0f873SStephan Uphoff 	if (pri <= PRI_MAX_ITHD)
1278f3a0f873SStephan Uphoff #endif /* ! FULL_PREEMPTION */
1279f3a0f873SStephan Uphoff 	{
1280d9d8d144SJohn Baldwin 		ipi_cpu(cpuid, IPI_PREEMPT);
1281f3a0f873SStephan Uphoff 		return;
1282f3a0f873SStephan Uphoff 	}
1283f3a0f873SStephan Uphoff #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1284f3a0f873SStephan Uphoff 
1285*c2d27b0eSMark Johnston 	if (pcpu->pc_curthread->td_lock == &sched_lock) {
1286c6d31b83SKonstantin Belousov 		ast_sched_locked(pcpu->pc_curthread, TDA_SCHED);
1287d9d8d144SJohn Baldwin 		ipi_cpu(cpuid, IPI_AST);
1288*c2d27b0eSMark Johnston 	}
1289f3a0f873SStephan Uphoff }
1290f3a0f873SStephan Uphoff #endif /* SMP */
1291f3a0f873SStephan Uphoff 
1292f200843bSJohn Baldwin #ifdef SMP
1293f200843bSJohn Baldwin static int
1294f200843bSJohn Baldwin sched_pickcpu(struct thread *td)
1295f200843bSJohn Baldwin {
1296f200843bSJohn Baldwin 	int best, cpu;
1297f200843bSJohn Baldwin 
1298f200843bSJohn Baldwin 	mtx_assert(&sched_lock, MA_OWNED);
1299f200843bSJohn Baldwin 
1300e2325d82SJohn Baldwin 	if (td->td_lastcpu != NOCPU && THREAD_CAN_SCHED(td, td->td_lastcpu))
1301c3ea3378SJohn Baldwin 		best = td->td_lastcpu;
1302c3ea3378SJohn Baldwin 	else
1303f200843bSJohn Baldwin 		best = NOCPU;
13043aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1305f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu))
1306f200843bSJohn Baldwin 			continue;
1307f200843bSJohn Baldwin 
1308f200843bSJohn Baldwin 		if (best == NOCPU)
1309f200843bSJohn Baldwin 			best = cpu;
1310f200843bSJohn Baldwin 		else if (runq_length[cpu] < runq_length[best])
1311f200843bSJohn Baldwin 			best = cpu;
1312f200843bSJohn Baldwin 	}
1313f200843bSJohn Baldwin 	KASSERT(best != NOCPU, ("no valid CPUs"));
1314f200843bSJohn Baldwin 
1315f200843bSJohn Baldwin 	return (best);
1316f200843bSJohn Baldwin }
1317f200843bSJohn Baldwin #endif
1318f200843bSJohn Baldwin 
1319b43179fbSJeff Roberson void
13202630e4c9SJulian Elischer sched_add(struct thread *td, int flags)
13216804a3abSJulian Elischer #ifdef SMP
1322f3a0f873SStephan Uphoff {
1323a38f1f26SAttilio Rao 	cpuset_t tidlemsk;
1324ad1e7d28SJulian Elischer 	struct td_sched *ts;
1325a38f1f26SAttilio Rao 	u_int cpu, cpuid;
13266804a3abSJulian Elischer 	int forwarded = 0;
1327f3a0f873SStephan Uphoff 	int single_cpu = 0;
13287cf90fb3SJeff Roberson 
132993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
13307b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1331f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1332f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1333f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1334f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1335b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1336b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
13378f51ad55SJeff Roberson 
13388f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
13398f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
13408f51ad55SJeff Roberson 	    sched_tdname(curthread));
13418f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
13428f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
1343b3e9e682SRyan Stone 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1344b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
13458f51ad55SJeff Roberson 
13467b20fb19SJeff Roberson 	/*
13477b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
13487b20fb19SJeff Roberson 	 * to the scheduler's lock.
13497b20fb19SJeff Roberson 	 */
13507b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
13517b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
135261a74c5cSJeff Roberson 		if ((flags & SRQ_HOLD) != 0)
135361a74c5cSJeff Roberson 			td->td_lock = &sched_lock;
135461a74c5cSJeff Roberson 		else
13557b20fb19SJeff Roberson 			thread_lock_set(td, &sched_lock);
13567b20fb19SJeff Roberson 	}
1357f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1358f3a0f873SStephan Uphoff 
135960dd73b7SRyan Stone 	/*
136060dd73b7SRyan Stone 	 * If SMP is started and the thread is pinned or otherwise limited to
136160dd73b7SRyan Stone 	 * a specific set of CPUs, queue the thread to a per-CPU run queue.
136260dd73b7SRyan Stone 	 * Otherwise, queue the thread to the global run queue.
136360dd73b7SRyan Stone 	 *
136460dd73b7SRyan Stone 	 * If SMP has not yet been started we must use the global run queue
136560dd73b7SRyan Stone 	 * as per-CPU state may not be initialized yet and we may crash if we
136660dd73b7SRyan Stone 	 * try to access the per-CPU run queues.
136760dd73b7SRyan Stone 	 */
136860dd73b7SRyan Stone 	if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
136960dd73b7SRyan Stone 	    ts->ts_flags & TSF_AFFINITY)) {
137060dd73b7SRyan Stone 		if (td->td_pinned != 0)
1371f3a0f873SStephan Uphoff 			cpu = td->td_lastcpu;
137260dd73b7SRyan Stone 		else if (td->td_flags & TDF_BOUND) {
13738aa3d7ffSJohn Baldwin 			/* Find CPU from bound runq. */
13748aa3d7ffSJohn Baldwin 			KASSERT(SKE_RUNQ_PCPU(ts),
13758aa3d7ffSJohn Baldwin 			    ("sched_add: bound td_sched not on cpu runq"));
1376ad1e7d28SJulian Elischer 			cpu = ts->ts_runq - &runq_pcpu[0];
137760dd73b7SRyan Stone 		} else
1378f200843bSJohn Baldwin 			/* Find a valid CPU for our cpuset */
1379f200843bSJohn Baldwin 			cpu = sched_pickcpu(td);
1380f200843bSJohn Baldwin 		ts->ts_runq = &runq_pcpu[cpu];
1381f200843bSJohn Baldwin 		single_cpu = 1;
1382f200843bSJohn Baldwin 		CTR3(KTR_RUNQ,
1383f200843bSJohn Baldwin 		    "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1384f200843bSJohn Baldwin 		    cpu);
1385f3a0f873SStephan Uphoff 	} else {
13866804a3abSJulian Elischer 		CTR2(KTR_RUNQ,
13878aa3d7ffSJohn Baldwin 		    "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
13888aa3d7ffSJohn Baldwin 		    td);
13896804a3abSJulian Elischer 		cpu = NOCPU;
1390ad1e7d28SJulian Elischer 		ts->ts_runq = &runq;
1391e17c57b1SJeff Roberson 	}
1392f3a0f873SStephan Uphoff 
1393a6b91f0fSJohn Baldwin 	if ((td->td_flags & TDF_NOLOAD) == 0)
1394a6b91f0fSJohn Baldwin 		sched_load_add();
1395a6b91f0fSJohn Baldwin 	runq_add(ts->ts_runq, td, flags);
1396a6b91f0fSJohn Baldwin 	if (cpu != NOCPU)
1397a6b91f0fSJohn Baldwin 		runq_length[cpu]++;
1398a6b91f0fSJohn Baldwin 
1399a38f1f26SAttilio Rao 	cpuid = PCPU_GET(cpuid);
1400a38f1f26SAttilio Rao 	if (single_cpu && cpu != cpuid) {
1401f3a0f873SStephan Uphoff 	        kick_other_cpu(td->td_priority, cpu);
1402f3a0f873SStephan Uphoff 	} else {
1403f3a0f873SStephan Uphoff 		if (!single_cpu) {
1404a19bd8e3SStefan Eßer 			tidlemsk = idle_cpus_mask;
1405a19bd8e3SStefan Eßer 			CPU_ANDNOT(&tidlemsk, &tidlemsk, &hlt_cpus_mask);
1406a38f1f26SAttilio Rao 			CPU_CLR(cpuid, &tidlemsk);
1407f3a0f873SStephan Uphoff 
1408a38f1f26SAttilio Rao 			if (!CPU_ISSET(cpuid, &idle_cpus_mask) &&
1409a38f1f26SAttilio Rao 			    ((flags & SRQ_INTR) == 0) &&
141071a19bdcSAttilio Rao 			    !CPU_EMPTY(&tidlemsk))
1411f3a0f873SStephan Uphoff 				forwarded = forward_wakeup(cpu);
1412f3a0f873SStephan Uphoff 		}
1413f3a0f873SStephan Uphoff 
1414f3a0f873SStephan Uphoff 		if (!forwarded) {
1415a6b91f0fSJohn Baldwin 			if (!maybe_preempt(td))
1416f3a0f873SStephan Uphoff 				maybe_resched(td);
1417f3a0f873SStephan Uphoff 		}
1418f3a0f873SStephan Uphoff 	}
141961a74c5cSJeff Roberson 	if ((flags & SRQ_HOLDTD) == 0)
142061a74c5cSJeff Roberson 		thread_unlock(td);
1421f3a0f873SStephan Uphoff }
1422f3a0f873SStephan Uphoff #else /* SMP */
1423f3a0f873SStephan Uphoff {
1424ad1e7d28SJulian Elischer 	struct td_sched *ts;
1425f200843bSJohn Baldwin 
142693ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
14277b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1428f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1429f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1430f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1431f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1432b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1433b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
14348f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
14358f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
14368f51ad55SJeff Roberson 	    sched_tdname(curthread));
14378f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
14388f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
14392aaae99dSSergey Kandaurov 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1440b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
14418aa3d7ffSJohn Baldwin 
14427b20fb19SJeff Roberson 	/*
14437b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
14447b20fb19SJeff Roberson 	 * to the scheduler's lock.
14457b20fb19SJeff Roberson 	 */
14467b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
14477b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
144861a74c5cSJeff Roberson 		if ((flags & SRQ_HOLD) != 0)
144961a74c5cSJeff Roberson 			td->td_lock = &sched_lock;
145061a74c5cSJeff Roberson 		else
14517b20fb19SJeff Roberson 			thread_lock_set(td, &sched_lock);
14527b20fb19SJeff Roberson 	}
1453f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1454ad1e7d28SJulian Elischer 	CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1455ad1e7d28SJulian Elischer 	ts->ts_runq = &runq;
14566804a3abSJulian Elischer 
14571b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1458907bdbc2SJeff Roberson 		sched_load_add();
14599727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
1460a6b91f0fSJohn Baldwin 	if (!maybe_preempt(td))
14616942d433SJohn Baldwin 		maybe_resched(td);
146261a74c5cSJeff Roberson 	if ((flags & SRQ_HOLDTD) == 0)
146361a74c5cSJeff Roberson 		thread_unlock(td);
1464b43179fbSJeff Roberson }
1465f3a0f873SStephan Uphoff #endif /* SMP */
1466f3a0f873SStephan Uphoff 
1467b43179fbSJeff Roberson void
14687cf90fb3SJeff Roberson sched_rem(struct thread *td)
1469b43179fbSJeff Roberson {
1470ad1e7d28SJulian Elischer 	struct td_sched *ts;
14717cf90fb3SJeff Roberson 
147293ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1473b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1474b61ce5b0SJeff Roberson 	    ("sched_rem: thread swapped out"));
1475f0393f06SJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
1476ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
1477b43179fbSJeff Roberson 	mtx_assert(&sched_lock, MA_OWNED);
14788f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
14798f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
14808f51ad55SJeff Roberson 	    sched_tdname(curthread));
1481b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
1482b43179fbSJeff Roberson 
14831b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1484907bdbc2SJeff Roberson 		sched_load_rem();
1485f200843bSJohn Baldwin #ifdef SMP
1486f200843bSJohn Baldwin 	if (ts->ts_runq != &runq)
1487f200843bSJohn Baldwin 		runq_length[ts->ts_runq - runq_pcpu]--;
1488f200843bSJohn Baldwin #endif
14899727e637SJeff Roberson 	runq_remove(ts->ts_runq, td);
1490f0393f06SJeff Roberson 	TD_SET_CAN_RUN(td);
1491b43179fbSJeff Roberson }
1492b43179fbSJeff Roberson 
149314f0e2e9SJulian Elischer /*
14948aa3d7ffSJohn Baldwin  * Select threads to run.  Note that running threads still consume a
14958aa3d7ffSJohn Baldwin  * slot.
149614f0e2e9SJulian Elischer  */
1497f0393f06SJeff Roberson struct thread *
1498b43179fbSJeff Roberson sched_choose(void)
1499b43179fbSJeff Roberson {
15009727e637SJeff Roberson 	struct thread *td;
1501e17c57b1SJeff Roberson 	struct runq *rq;
1502b43179fbSJeff Roberson 
15037b20fb19SJeff Roberson 	mtx_assert(&sched_lock,  MA_OWNED);
1504e17c57b1SJeff Roberson #ifdef SMP
15059727e637SJeff Roberson 	struct thread *tdcpu;
1506e17c57b1SJeff Roberson 
1507e17c57b1SJeff Roberson 	rq = &runq;
15089727e637SJeff Roberson 	td = runq_choose_fuzz(&runq, runq_fuzz);
15099727e637SJeff Roberson 	tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1510e17c57b1SJeff Roberson 
15119727e637SJeff Roberson 	if (td == NULL ||
15129727e637SJeff Roberson 	    (tdcpu != NULL &&
15139727e637SJeff Roberson 	     tdcpu->td_priority < td->td_priority)) {
15149727e637SJeff Roberson 		CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1515e17c57b1SJeff Roberson 		     PCPU_GET(cpuid));
15169727e637SJeff Roberson 		td = tdcpu;
1517e17c57b1SJeff Roberson 		rq = &runq_pcpu[PCPU_GET(cpuid)];
1518e17c57b1SJeff Roberson 	} else {
15199727e637SJeff Roberson 		CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1520e17c57b1SJeff Roberson 	}
1521e17c57b1SJeff Roberson 
1522e17c57b1SJeff Roberson #else
1523e17c57b1SJeff Roberson 	rq = &runq;
15249727e637SJeff Roberson 	td = runq_choose(&runq);
1525e17c57b1SJeff Roberson #endif
1526b43179fbSJeff Roberson 
15279727e637SJeff Roberson 	if (td) {
1528f200843bSJohn Baldwin #ifdef SMP
1529f200843bSJohn Baldwin 		if (td == tdcpu)
1530f200843bSJohn Baldwin 			runq_length[PCPU_GET(cpuid)]--;
1531f200843bSJohn Baldwin #endif
15329727e637SJeff Roberson 		runq_remove(rq, td);
15339727e637SJeff Roberson 		td->td_flags |= TDF_DIDRUN;
1534b43179fbSJeff Roberson 
15359727e637SJeff Roberson 		KASSERT(td->td_flags & TDF_INMEM,
1536b61ce5b0SJeff Roberson 		    ("sched_choose: thread swapped out"));
15379727e637SJeff Roberson 		return (td);
1538b43179fbSJeff Roberson 	}
1539f0393f06SJeff Roberson 	return (PCPU_GET(idlethread));
1540b43179fbSJeff Roberson }
1541b43179fbSJeff Roberson 
1542b43179fbSJeff Roberson void
15431e24c28fSJeff Roberson sched_preempt(struct thread *td)
15441e24c28fSJeff Roberson {
1545b3e9e682SRyan Stone 
1546b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
1547686bcb5cSJeff Roberson 	if (td->td_critnest > 1) {
15481e24c28fSJeff Roberson 		td->td_owepreempt = 1;
1549686bcb5cSJeff Roberson 	} else {
1550686bcb5cSJeff Roberson 		thread_lock(td);
1551686bcb5cSJeff Roberson 		mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT);
1552686bcb5cSJeff Roberson 	}
15531e24c28fSJeff Roberson }
15541e24c28fSJeff Roberson 
15551e24c28fSJeff Roberson void
155628240885SMateusz Guzik sched_userret_slowpath(struct thread *td)
1557b43179fbSJeff Roberson {
155828240885SMateusz Guzik 
15597b20fb19SJeff Roberson 	thread_lock(td);
15608460a577SJohn Birrell 	td->td_priority = td->td_user_pri;
15618460a577SJohn Birrell 	td->td_base_pri = td->td_user_pri;
15627b20fb19SJeff Roberson 	thread_unlock(td);
15638460a577SJohn Birrell }
1564de028f5aSJeff Roberson 
1565e17c57b1SJeff Roberson void
1566e17c57b1SJeff Roberson sched_bind(struct thread *td, int cpu)
1567e17c57b1SJeff Roberson {
15688758ac75SJohn Baldwin #ifdef SMP
15698758ac75SJohn Baldwin 	struct td_sched *ts = td_get_sched(td);
15708758ac75SJohn Baldwin #endif
1571e17c57b1SJeff Roberson 
15721d7830edSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
15731d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1574e17c57b1SJeff Roberson 
15759727e637SJeff Roberson 	td->td_flags |= TDF_BOUND;
1576e17c57b1SJeff Roberson #ifdef SMP
1577ad1e7d28SJulian Elischer 	ts->ts_runq = &runq_pcpu[cpu];
1578e17c57b1SJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
1579e17c57b1SJeff Roberson 		return;
1580e17c57b1SJeff Roberson 
1581686bcb5cSJeff Roberson 	mi_switch(SW_VOL);
1582686bcb5cSJeff Roberson 	thread_lock(td);
1583e17c57b1SJeff Roberson #endif
1584e17c57b1SJeff Roberson }
1585e17c57b1SJeff Roberson 
1586e17c57b1SJeff Roberson void
1587e17c57b1SJeff Roberson sched_unbind(struct thread* td)
1588e17c57b1SJeff Roberson {
15897b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
15901d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
15919727e637SJeff Roberson 	td->td_flags &= ~TDF_BOUND;
1592e17c57b1SJeff Roberson }
1593e17c57b1SJeff Roberson 
1594de028f5aSJeff Roberson int
1595ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
1596ebccf1e3SJoseph Koshy {
15977b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
15989727e637SJeff Roberson 	return (td->td_flags & TDF_BOUND);
1599ebccf1e3SJoseph Koshy }
1600ebccf1e3SJoseph Koshy 
160136ec198bSDavid Xu void
160236ec198bSDavid Xu sched_relinquish(struct thread *td)
160336ec198bSDavid Xu {
16047b20fb19SJeff Roberson 	thread_lock(td);
1605686bcb5cSJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH);
160636ec198bSDavid Xu }
160736ec198bSDavid Xu 
1608ebccf1e3SJoseph Koshy int
1609ca59f152SJeff Roberson sched_load(void)
1610ca59f152SJeff Roberson {
1611ca59f152SJeff Roberson 	return (sched_tdcnt);
1612ca59f152SJeff Roberson }
1613ca59f152SJeff Roberson 
1614de028f5aSJeff Roberson int
1615de028f5aSJeff Roberson sched_sizeof_proc(void)
1616de028f5aSJeff Roberson {
1617de028f5aSJeff Roberson 	return (sizeof(struct proc));
1618de028f5aSJeff Roberson }
161936ec198bSDavid Xu 
1620de028f5aSJeff Roberson int
1621de028f5aSJeff Roberson sched_sizeof_thread(void)
1622de028f5aSJeff Roberson {
1623ad1e7d28SJulian Elischer 	return (sizeof(struct thread) + sizeof(struct td_sched));
1624de028f5aSJeff Roberson }
162579acfc49SJeff Roberson 
162679acfc49SJeff Roberson fixpt_t
16277cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
162879acfc49SJeff Roberson {
1629ad1e7d28SJulian Elischer 	struct td_sched *ts;
163055f2099aSJeff Roberson 
16313da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
163293ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1633ad1e7d28SJulian Elischer 	return (ts->ts_pctcpu);
163479acfc49SJeff Roberson }
1635b41f1452SDavid Xu 
163636af9869SEdward Tomasz Napierala #ifdef RACCT
163736af9869SEdward Tomasz Napierala /*
163836af9869SEdward Tomasz Napierala  * Calculates the contribution to the thread cpu usage for the latest
163936af9869SEdward Tomasz Napierala  * (unfinished) second.
164036af9869SEdward Tomasz Napierala  */
164136af9869SEdward Tomasz Napierala fixpt_t
164236af9869SEdward Tomasz Napierala sched_pctcpu_delta(struct thread *td)
164336af9869SEdward Tomasz Napierala {
164436af9869SEdward Tomasz Napierala 	struct td_sched *ts;
164536af9869SEdward Tomasz Napierala 	fixpt_t delta;
164636af9869SEdward Tomasz Napierala 	int realstathz;
164736af9869SEdward Tomasz Napierala 
164836af9869SEdward Tomasz Napierala 	THREAD_LOCK_ASSERT(td, MA_OWNED);
164993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
165036af9869SEdward Tomasz Napierala 	delta = 0;
165136af9869SEdward Tomasz Napierala 	realstathz = stathz ? stathz : hz;
165236af9869SEdward Tomasz Napierala 	if (ts->ts_cpticks != 0) {
165336af9869SEdward Tomasz Napierala #if	(FSHIFT >= CCPU_SHIFT)
165436af9869SEdward Tomasz Napierala 		delta = (realstathz == 100)
165536af9869SEdward Tomasz Napierala 		    ? ((fixpt_t) ts->ts_cpticks) <<
165636af9869SEdward Tomasz Napierala 		    (FSHIFT - CCPU_SHIFT) :
165736af9869SEdward Tomasz Napierala 		    100 * (((fixpt_t) ts->ts_cpticks)
165836af9869SEdward Tomasz Napierala 		    << (FSHIFT - CCPU_SHIFT)) / realstathz;
165936af9869SEdward Tomasz Napierala #else
166036af9869SEdward Tomasz Napierala 		delta = ((FSCALE - ccpu) *
166136af9869SEdward Tomasz Napierala 		    (ts->ts_cpticks *
166236af9869SEdward Tomasz Napierala 		    FSCALE / realstathz)) >> FSHIFT;
166336af9869SEdward Tomasz Napierala #endif
166436af9869SEdward Tomasz Napierala 	}
166536af9869SEdward Tomasz Napierala 
166636af9869SEdward Tomasz Napierala 	return (delta);
166736af9869SEdward Tomasz Napierala }
166836af9869SEdward Tomasz Napierala #endif
166936af9869SEdward Tomasz Napierala 
1670ccd0ec40SKonstantin Belousov u_int
1671ccd0ec40SKonstantin Belousov sched_estcpu(struct thread *td)
1672b41f1452SDavid Xu {
1673ccd0ec40SKonstantin Belousov 
167493ccd6bfSKonstantin Belousov 	return (td_get_sched(td)->ts_estcpu);
1675b41f1452SDavid Xu }
1676f0393f06SJeff Roberson 
1677f0393f06SJeff Roberson /*
1678f0393f06SJeff Roberson  * The actual idle process.
1679f0393f06SJeff Roberson  */
1680f0393f06SJeff Roberson void
1681f0393f06SJeff Roberson sched_idletd(void *dummy)
1682f0393f06SJeff Roberson {
1683b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
1684f0393f06SJeff Roberson 
1685ba96d2d8SJohn Baldwin 	THREAD_NO_SLEEPING();
1686b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
1687f0393f06SJeff Roberson 	for (;;) {
1688f0393f06SJeff Roberson 		mtx_assert(&Giant, MA_NOTOWNED);
1689f0393f06SJeff Roberson 
1690b722ad00SAlexander Motin 		while (sched_runnable() == 0) {
1691b722ad00SAlexander Motin 			cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1692b722ad00SAlexander Motin 			stat->idlecalls++;
1693b722ad00SAlexander Motin 		}
1694f0393f06SJeff Roberson 
1695f0393f06SJeff Roberson 		mtx_lock_spin(&sched_lock);
1696686bcb5cSJeff Roberson 		mi_switch(SW_VOL | SWT_IDLE);
1697f0393f06SJeff Roberson 	}
1698f0393f06SJeff Roberson }
1699f0393f06SJeff Roberson 
17006a8ea6d1SKyle Evans static void
17016a8ea6d1SKyle Evans sched_throw_tail(struct thread *td)
17026a8ea6d1SKyle Evans {
17036a8ea6d1SKyle Evans 
17046a8ea6d1SKyle Evans 	mtx_assert(&sched_lock, MA_OWNED);
17056a8ea6d1SKyle Evans 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
17066a8ea6d1SKyle Evans 	cpu_throw(td, choosethread());	/* doesn't return */
17076a8ea6d1SKyle Evans }
17086a8ea6d1SKyle Evans 
17097b20fb19SJeff Roberson /*
17106a8ea6d1SKyle Evans  * A CPU is entering for the first time.
17117b20fb19SJeff Roberson  */
17127b20fb19SJeff Roberson void
17136a8ea6d1SKyle Evans sched_ap_entry(void)
17147b20fb19SJeff Roberson {
17156a8ea6d1SKyle Evans 
17167b20fb19SJeff Roberson 	/*
17177b20fb19SJeff Roberson 	 * Correct spinlock nesting.  The idle thread context that we are
17187b20fb19SJeff Roberson 	 * borrowing was created so that it would start out with a single
17197b20fb19SJeff Roberson 	 * spin lock (sched_lock) held in fork_trampoline().  Since we've
17207b20fb19SJeff Roberson 	 * explicitly acquired locks in this function, the nesting count
17217b20fb19SJeff Roberson 	 * is now 2 rather than 1.  Since we are nested, calling
17227b20fb19SJeff Roberson 	 * spinlock_exit() will simply adjust the counts without allowing
17237b20fb19SJeff Roberson 	 * spin lock using code to interrupt us.
17247b20fb19SJeff Roberson 	 */
17257b20fb19SJeff Roberson 	mtx_lock_spin(&sched_lock);
17267b20fb19SJeff Roberson 	spinlock_exit();
17277e3a96eaSJohn Baldwin 	PCPU_SET(switchtime, cpu_ticks());
17287e3a96eaSJohn Baldwin 	PCPU_SET(switchticks, ticks);
17296a8ea6d1SKyle Evans 
17306a8ea6d1SKyle Evans 	sched_throw_tail(NULL);
17316a8ea6d1SKyle Evans }
17326a8ea6d1SKyle Evans 
17336a8ea6d1SKyle Evans /*
17346a8ea6d1SKyle Evans  * A thread is exiting.
17356a8ea6d1SKyle Evans  */
17366a8ea6d1SKyle Evans void
17376a8ea6d1SKyle Evans sched_throw(struct thread *td)
17386a8ea6d1SKyle Evans {
17396a8ea6d1SKyle Evans 
17406a8ea6d1SKyle Evans 	MPASS(td != NULL);
17417b20fb19SJeff Roberson 	MPASS(td->td_lock == &sched_lock);
17426a8ea6d1SKyle Evans 
17436a8ea6d1SKyle Evans 	lock_profile_release_lock(&sched_lock.lock_object, true);
174492de34dfSJohn Baldwin 	td->td_lastcpu = td->td_oncpu;
174592de34dfSJohn Baldwin 	td->td_oncpu = NOCPU;
17466a8ea6d1SKyle Evans 
17476a8ea6d1SKyle Evans 	sched_throw_tail(td);
17487b20fb19SJeff Roberson }
17497b20fb19SJeff Roberson 
17507b20fb19SJeff Roberson void
1751fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
17527b20fb19SJeff Roberson {
17537b20fb19SJeff Roberson 
17547b20fb19SJeff Roberson 	/*
17557b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
17567b20fb19SJeff Roberson 	 * non-nested critical section with sched_lock held but not recursed.
17577b20fb19SJeff Roberson 	 */
1758fe54587fSJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
1759fe54587fSJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
17606a467cc5SMateusz Guzik 	lock_profile_obtain_lock_success(&sched_lock.lock_object, true,
1761eea4f254SJeff Roberson 	    0, 0, __FILE__, __LINE__);
1762fe54587fSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
176328ef18b8SAndriy Gapon 
176428ef18b8SAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
176528ef18b8SAndriy Gapon 	    "prio:%d", td->td_priority);
176628ef18b8SAndriy Gapon 	SDT_PROBE0(sched, , , on__cpu);
17677b20fb19SJeff Roberson }
17687b20fb19SJeff Roberson 
17698f51ad55SJeff Roberson char *
17708f51ad55SJeff Roberson sched_tdname(struct thread *td)
17718f51ad55SJeff Roberson {
17728f51ad55SJeff Roberson #ifdef KTR
17738f51ad55SJeff Roberson 	struct td_sched *ts;
17748f51ad55SJeff Roberson 
177593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
17768f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
17778f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
17788f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
17798f51ad55SJeff Roberson 	return (ts->ts_name);
17808f51ad55SJeff Roberson #else
17818f51ad55SJeff Roberson 	return (td->td_name);
17828f51ad55SJeff Roberson #endif
17838f51ad55SJeff Roberson }
17848f51ad55SJeff Roberson 
178544ad5475SJohn Baldwin #ifdef KTR
178644ad5475SJohn Baldwin void
178744ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
178844ad5475SJohn Baldwin {
178944ad5475SJohn Baldwin 	struct td_sched *ts;
179044ad5475SJohn Baldwin 
179193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
179244ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
179344ad5475SJohn Baldwin }
179444ad5475SJohn Baldwin #endif
179544ad5475SJohn Baldwin 
1796885d51a3SJeff Roberson void
1797885d51a3SJeff Roberson sched_affinity(struct thread *td)
1798885d51a3SJeff Roberson {
1799f200843bSJohn Baldwin #ifdef SMP
1800f200843bSJohn Baldwin 	struct td_sched *ts;
1801f200843bSJohn Baldwin 	int cpu;
1802f200843bSJohn Baldwin 
1803f200843bSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1804f200843bSJohn Baldwin 
1805f200843bSJohn Baldwin 	/*
1806f200843bSJohn Baldwin 	 * Set the TSF_AFFINITY flag if there is at least one CPU this
1807f200843bSJohn Baldwin 	 * thread can't run on.
1808f200843bSJohn Baldwin 	 */
180993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1810f200843bSJohn Baldwin 	ts->ts_flags &= ~TSF_AFFINITY;
18113aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1812f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu)) {
1813f200843bSJohn Baldwin 			ts->ts_flags |= TSF_AFFINITY;
1814f200843bSJohn Baldwin 			break;
1815f200843bSJohn Baldwin 		}
1816f200843bSJohn Baldwin 	}
1817f200843bSJohn Baldwin 
1818f200843bSJohn Baldwin 	/*
1819f200843bSJohn Baldwin 	 * If this thread can run on all CPUs, nothing else to do.
1820f200843bSJohn Baldwin 	 */
1821f200843bSJohn Baldwin 	if (!(ts->ts_flags & TSF_AFFINITY))
1822f200843bSJohn Baldwin 		return;
1823f200843bSJohn Baldwin 
1824f200843bSJohn Baldwin 	/* Pinned threads and bound threads should be left alone. */
1825f200843bSJohn Baldwin 	if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1826f200843bSJohn Baldwin 		return;
1827f200843bSJohn Baldwin 
1828fa2528acSAlex Richardson 	switch (TD_GET_STATE(td)) {
1829f200843bSJohn Baldwin 	case TDS_RUNQ:
1830f200843bSJohn Baldwin 		/*
1831f200843bSJohn Baldwin 		 * If we are on a per-CPU runqueue that is in the set,
1832f200843bSJohn Baldwin 		 * then nothing needs to be done.
1833f200843bSJohn Baldwin 		 */
1834f200843bSJohn Baldwin 		if (ts->ts_runq != &runq &&
1835f200843bSJohn Baldwin 		    THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1836f200843bSJohn Baldwin 			return;
1837f200843bSJohn Baldwin 
1838f200843bSJohn Baldwin 		/* Put this thread on a valid per-CPU runqueue. */
1839f200843bSJohn Baldwin 		sched_rem(td);
184061a74c5cSJeff Roberson 		sched_add(td, SRQ_HOLDTD | SRQ_BORING);
1841f200843bSJohn Baldwin 		break;
1842f200843bSJohn Baldwin 	case TDS_RUNNING:
1843f200843bSJohn Baldwin 		/*
1844f200843bSJohn Baldwin 		 * See if our current CPU is in the set.  If not, force a
1845f200843bSJohn Baldwin 		 * context switch.
1846f200843bSJohn Baldwin 		 */
1847f200843bSJohn Baldwin 		if (THREAD_CAN_SCHED(td, td->td_oncpu))
1848f200843bSJohn Baldwin 			return;
1849f200843bSJohn Baldwin 
1850c6d31b83SKonstantin Belousov 		ast_sched_locked(td, TDA_SCHED);
1851f200843bSJohn Baldwin 		if (td != curthread)
1852d9d8d144SJohn Baldwin 			ipi_cpu(cpu, IPI_AST);
1853f200843bSJohn Baldwin 		break;
1854f200843bSJohn Baldwin 	default:
1855f200843bSJohn Baldwin 		break;
1856f200843bSJohn Baldwin 	}
1857f200843bSJohn Baldwin #endif
1858885d51a3SJeff Roberson }
1859