xref: /freebsd/sys/kern/sched_4bsd.c (revision 6472ac3d8a86336899b6cfb789a4cd9897e3fab5)
1b43179fbSJeff Roberson /*-
2b43179fbSJeff Roberson  * Copyright (c) 1982, 1986, 1990, 1991, 1993
3b43179fbSJeff Roberson  *	The Regents of the University of California.  All rights reserved.
4b43179fbSJeff Roberson  * (c) UNIX System Laboratories, Inc.
5b43179fbSJeff Roberson  * All or some portions of this file are derived from material licensed
6b43179fbSJeff Roberson  * to the University of California by American Telephone and Telegraph
7b43179fbSJeff Roberson  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8b43179fbSJeff Roberson  * the permission of UNIX System Laboratories, Inc.
9b43179fbSJeff Roberson  *
10b43179fbSJeff Roberson  * Redistribution and use in source and binary forms, with or without
11b43179fbSJeff Roberson  * modification, are permitted provided that the following conditions
12b43179fbSJeff Roberson  * are met:
13b43179fbSJeff Roberson  * 1. Redistributions of source code must retain the above copyright
14b43179fbSJeff Roberson  *    notice, this list of conditions and the following disclaimer.
15b43179fbSJeff Roberson  * 2. Redistributions in binary form must reproduce the above copyright
16b43179fbSJeff Roberson  *    notice, this list of conditions and the following disclaimer in the
17b43179fbSJeff Roberson  *    documentation and/or other materials provided with the distribution.
18b43179fbSJeff Roberson  * 4. Neither the name of the University nor the names of its contributors
19b43179fbSJeff Roberson  *    may be used to endorse or promote products derived from this software
20b43179fbSJeff Roberson  *    without specific prior written permission.
21b43179fbSJeff Roberson  *
22b43179fbSJeff Roberson  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23b43179fbSJeff Roberson  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24b43179fbSJeff Roberson  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25b43179fbSJeff Roberson  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26b43179fbSJeff Roberson  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27b43179fbSJeff Roberson  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28b43179fbSJeff Roberson  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29b43179fbSJeff Roberson  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30b43179fbSJeff Roberson  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31b43179fbSJeff Roberson  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32b43179fbSJeff Roberson  * SUCH DAMAGE.
33b43179fbSJeff Roberson  */
34b43179fbSJeff Roberson 
35677b542eSDavid E. O'Brien #include <sys/cdefs.h>
36677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
37677b542eSDavid E. O'Brien 
384da0d332SPeter Wemm #include "opt_hwpmc_hooks.h"
39a564bfc7SJeff Roberson #include "opt_sched.h"
406f5f25e5SJohn Birrell #include "opt_kdtrace.h"
414da0d332SPeter Wemm 
42b43179fbSJeff Roberson #include <sys/param.h>
43b43179fbSJeff Roberson #include <sys/systm.h>
44f5a3ef99SMarcel Moolenaar #include <sys/cpuset.h>
45b43179fbSJeff Roberson #include <sys/kernel.h>
46b43179fbSJeff Roberson #include <sys/ktr.h>
47b43179fbSJeff Roberson #include <sys/lock.h>
48c55bbb6cSJohn Baldwin #include <sys/kthread.h>
49b43179fbSJeff Roberson #include <sys/mutex.h>
50b43179fbSJeff Roberson #include <sys/proc.h>
51b43179fbSJeff Roberson #include <sys/resourcevar.h>
52b43179fbSJeff Roberson #include <sys/sched.h>
53b43179fbSJeff Roberson #include <sys/smp.h>
54b43179fbSJeff Roberson #include <sys/sysctl.h>
55b43179fbSJeff Roberson #include <sys/sx.h>
56f5c157d9SJohn Baldwin #include <sys/turnstile.h>
573db720fdSDavid Xu #include <sys/umtx.h>
582e4db89cSDavid E. O'Brien #include <machine/pcb.h>
59293968d8SJulian Elischer #include <machine/smp.h>
60b43179fbSJeff Roberson 
61ebccf1e3SJoseph Koshy #ifdef HWPMC_HOOKS
62ebccf1e3SJoseph Koshy #include <sys/pmckern.h>
63ebccf1e3SJoseph Koshy #endif
64ebccf1e3SJoseph Koshy 
656f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
666f5f25e5SJohn Birrell #include <sys/dtrace_bsd.h>
676f5f25e5SJohn Birrell int				dtrace_vtime_active;
686f5f25e5SJohn Birrell dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
696f5f25e5SJohn Birrell #endif
706f5f25e5SJohn Birrell 
7106439a04SJeff Roberson /*
7206439a04SJeff Roberson  * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
7306439a04SJeff Roberson  * the range 100-256 Hz (approximately).
7406439a04SJeff Roberson  */
7506439a04SJeff Roberson #define	ESTCPULIM(e) \
7606439a04SJeff Roberson     min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
7706439a04SJeff Roberson     RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
78b698380fSBruce Evans #ifdef SMP
79b698380fSBruce Evans #define	INVERSE_ESTCPU_WEIGHT	(8 * smp_cpus)
80b698380fSBruce Evans #else
8106439a04SJeff Roberson #define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
82b698380fSBruce Evans #endif
8306439a04SJeff Roberson #define	NICE_WEIGHT		1	/* Priorities per nice level. */
8406439a04SJeff Roberson 
850d2cf837SJeff Roberson #define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
868f51ad55SJeff Roberson 
878460a577SJohn Birrell /*
888460a577SJohn Birrell  * The schedulable entity that runs a context.
89ad1e7d28SJulian Elischer  * This is  an extension to the thread structure and is tailored to
90ad1e7d28SJulian Elischer  * the requirements of this scheduler
918460a577SJohn Birrell  */
92ad1e7d28SJulian Elischer struct td_sched {
93ad1e7d28SJulian Elischer 	fixpt_t		ts_pctcpu;	/* (j) %cpu during p_swtime. */
94ad1e7d28SJulian Elischer 	int		ts_cpticks;	/* (j) Ticks of cpu time. */
9554b0e65fSJeff Roberson 	int		ts_slptime;	/* (j) Seconds !RUNNING. */
96f200843bSJohn Baldwin 	int		ts_flags;
97ad1e7d28SJulian Elischer 	struct runq	*ts_runq;	/* runq the thread is currently on */
988f51ad55SJeff Roberson #ifdef KTR
998f51ad55SJeff Roberson 	char		ts_name[TS_NAME_LEN];
1008f51ad55SJeff Roberson #endif
101bcb06d59SJeff Roberson };
102ed062c8dSJulian Elischer 
103ed062c8dSJulian Elischer /* flags kept in td_flags */
104ad1e7d28SJulian Elischer #define TDF_DIDRUN	TDF_SCHED0	/* thread actually ran. */
1059727e637SJeff Roberson #define TDF_BOUND	TDF_SCHED1	/* Bound to one CPU. */
106bcb06d59SJeff Roberson 
107f200843bSJohn Baldwin /* flags kept in ts_flags */
108f200843bSJohn Baldwin #define	TSF_AFFINITY	0x0001		/* Has a non-"full" CPU set. */
109f200843bSJohn Baldwin 
110ad1e7d28SJulian Elischer #define SKE_RUNQ_PCPU(ts)						\
111ad1e7d28SJulian Elischer     ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
112e17c57b1SJeff Roberson 
113f200843bSJohn Baldwin #define	THREAD_CAN_SCHED(td, cpu)	\
114f200843bSJohn Baldwin     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
115f200843bSJohn Baldwin 
116ad1e7d28SJulian Elischer static struct td_sched td_sched0;
1176ea38de8SJeff Roberson struct mtx sched_lock;
118b43179fbSJeff Roberson 
119ca59f152SJeff Roberson static int	sched_tdcnt;	/* Total runnable threads in the system. */
120b43179fbSJeff Roberson static int	sched_quantum;	/* Roundrobin scheduling quantum in ticks. */
1214974b53eSMaxime Henrion #define	SCHED_QUANTUM	(hz / 10)	/* Default sched quantum */
122b43179fbSJeff Roberson 
123e17c57b1SJeff Roberson static void	setup_runqs(void);
124c55bbb6cSJohn Baldwin static void	schedcpu(void);
125e17c57b1SJeff Roberson static void	schedcpu_thread(void);
126f5c157d9SJohn Baldwin static void	sched_priority(struct thread *td, u_char prio);
127b43179fbSJeff Roberson static void	sched_setup(void *dummy);
128b43179fbSJeff Roberson static void	maybe_resched(struct thread *td);
1298460a577SJohn Birrell static void	updatepri(struct thread *td);
1308460a577SJohn Birrell static void	resetpriority(struct thread *td);
1318460a577SJohn Birrell static void	resetpriority_thread(struct thread *td);
13200b0483dSJulian Elischer #ifdef SMP
133f200843bSJohn Baldwin static int	sched_pickcpu(struct thread *td);
13482a1dfc1SJulian Elischer static int	forward_wakeup(int cpunum);
1358aa3d7ffSJohn Baldwin static void	kick_other_cpu(int pri, int cpuid);
13600b0483dSJulian Elischer #endif
137b43179fbSJeff Roberson 
138e17c57b1SJeff Roberson static struct kproc_desc sched_kp = {
139e17c57b1SJeff Roberson         "schedcpu",
140e17c57b1SJeff Roberson         schedcpu_thread,
141e17c57b1SJeff Roberson         NULL
142e17c57b1SJeff Roberson };
143237fdd78SRobert Watson SYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start,
144237fdd78SRobert Watson     &sched_kp);
145237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
146b43179fbSJeff Roberson 
147b43179fbSJeff Roberson /*
148b43179fbSJeff Roberson  * Global run queue.
149b43179fbSJeff Roberson  */
150b43179fbSJeff Roberson static struct runq runq;
151e17c57b1SJeff Roberson 
152e17c57b1SJeff Roberson #ifdef SMP
153e17c57b1SJeff Roberson /*
154e17c57b1SJeff Roberson  * Per-CPU run queues
155e17c57b1SJeff Roberson  */
156e17c57b1SJeff Roberson static struct runq runq_pcpu[MAXCPU];
157f200843bSJohn Baldwin long runq_length[MAXCPU];
1583121f534SAttilio Rao 
15971a19bdcSAttilio Rao static cpuset_t idle_cpus_mask;
160e17c57b1SJeff Roberson #endif
161e17c57b1SJeff Roberson 
162b722ad00SAlexander Motin struct pcpuidlestat {
163b722ad00SAlexander Motin 	u_int idlecalls;
164b722ad00SAlexander Motin 	u_int oldidlecalls;
165b722ad00SAlexander Motin };
1663e288e62SDimitry Andric static DPCPU_DEFINE(struct pcpuidlestat, idlestat);
167b722ad00SAlexander Motin 
168e17c57b1SJeff Roberson static void
169e17c57b1SJeff Roberson setup_runqs(void)
170e17c57b1SJeff Roberson {
171e17c57b1SJeff Roberson #ifdef SMP
172e17c57b1SJeff Roberson 	int i;
173e17c57b1SJeff Roberson 
174e17c57b1SJeff Roberson 	for (i = 0; i < MAXCPU; ++i)
175e17c57b1SJeff Roberson 		runq_init(&runq_pcpu[i]);
176e17c57b1SJeff Roberson #endif
177e17c57b1SJeff Roberson 
178e17c57b1SJeff Roberson 	runq_init(&runq);
179e17c57b1SJeff Roberson }
180b43179fbSJeff Roberson 
181b43179fbSJeff Roberson static int
182b43179fbSJeff Roberson sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
183b43179fbSJeff Roberson {
184b43179fbSJeff Roberson 	int error, new_val;
185b43179fbSJeff Roberson 
186b43179fbSJeff Roberson 	new_val = sched_quantum * tick;
187b43179fbSJeff Roberson 	error = sysctl_handle_int(oidp, &new_val, 0, req);
188b43179fbSJeff Roberson         if (error != 0 || req->newptr == NULL)
189b43179fbSJeff Roberson 		return (error);
190b43179fbSJeff Roberson 	if (new_val < tick)
191b43179fbSJeff Roberson 		return (EINVAL);
192b43179fbSJeff Roberson 	sched_quantum = new_val / tick;
193b43179fbSJeff Roberson 	hogticks = 2 * sched_quantum;
194b43179fbSJeff Roberson 	return (0);
195b43179fbSJeff Roberson }
196b43179fbSJeff Roberson 
197e038d354SScott Long SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
198dc095794SScott Long 
199e038d354SScott Long SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
200e038d354SScott Long     "Scheduler name");
201dc095794SScott Long 
202dc095794SScott Long SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
203b43179fbSJeff Roberson     0, sizeof sched_quantum, sysctl_kern_quantum, "I",
204b43179fbSJeff Roberson     "Roundrobin scheduling quantum in microseconds");
205b43179fbSJeff Roberson 
20637c28a02SJulian Elischer #ifdef SMP
20782a1dfc1SJulian Elischer /* Enable forwarding of wakeups to all other cpus */
208*6472ac3dSEd Schouten static SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL,
209*6472ac3dSEd Schouten     "Kernel SMP");
21082a1dfc1SJulian Elischer 
211a90f3f25SJeff Roberson static int runq_fuzz = 1;
212a90f3f25SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
213a90f3f25SJeff Roberson 
214bce73aedSJulian Elischer static int forward_wakeup_enabled = 1;
21582a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
21682a1dfc1SJulian Elischer 	   &forward_wakeup_enabled, 0,
21782a1dfc1SJulian Elischer 	   "Forwarding of wakeup to idle CPUs");
21882a1dfc1SJulian Elischer 
21982a1dfc1SJulian Elischer static int forward_wakeups_requested = 0;
22082a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
22182a1dfc1SJulian Elischer 	   &forward_wakeups_requested, 0,
22282a1dfc1SJulian Elischer 	   "Requests for Forwarding of wakeup to idle CPUs");
22382a1dfc1SJulian Elischer 
22482a1dfc1SJulian Elischer static int forward_wakeups_delivered = 0;
22582a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
22682a1dfc1SJulian Elischer 	   &forward_wakeups_delivered, 0,
22782a1dfc1SJulian Elischer 	   "Completed Forwarding of wakeup to idle CPUs");
22882a1dfc1SJulian Elischer 
229bce73aedSJulian Elischer static int forward_wakeup_use_mask = 1;
23082a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
23182a1dfc1SJulian Elischer 	   &forward_wakeup_use_mask, 0,
23282a1dfc1SJulian Elischer 	   "Use the mask of idle cpus");
23382a1dfc1SJulian Elischer 
23482a1dfc1SJulian Elischer static int forward_wakeup_use_loop = 0;
23582a1dfc1SJulian Elischer SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
23682a1dfc1SJulian Elischer 	   &forward_wakeup_use_loop, 0,
23782a1dfc1SJulian Elischer 	   "Use a loop to find idle cpus");
23882a1dfc1SJulian Elischer 
23937c28a02SJulian Elischer #endif
240ad1e7d28SJulian Elischer #if 0
2413389af30SJulian Elischer static int sched_followon = 0;
2423389af30SJulian Elischer SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
2433389af30SJulian Elischer 	   &sched_followon, 0,
2443389af30SJulian Elischer 	   "allow threads to share a quantum");
2458460a577SJohn Birrell #endif
24682a1dfc1SJulian Elischer 
247907bdbc2SJeff Roberson static __inline void
248907bdbc2SJeff Roberson sched_load_add(void)
249907bdbc2SJeff Roberson {
2508f51ad55SJeff Roberson 
251907bdbc2SJeff Roberson 	sched_tdcnt++;
2528f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
253907bdbc2SJeff Roberson }
254907bdbc2SJeff Roberson 
255907bdbc2SJeff Roberson static __inline void
256907bdbc2SJeff Roberson sched_load_rem(void)
257907bdbc2SJeff Roberson {
2588f51ad55SJeff Roberson 
259907bdbc2SJeff Roberson 	sched_tdcnt--;
2608f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
261907bdbc2SJeff Roberson }
262b43179fbSJeff Roberson /*
263b43179fbSJeff Roberson  * Arrange to reschedule if necessary, taking the priorities and
264b43179fbSJeff Roberson  * schedulers into account.
265b43179fbSJeff Roberson  */
266b43179fbSJeff Roberson static void
267b43179fbSJeff Roberson maybe_resched(struct thread *td)
268b43179fbSJeff Roberson {
269b43179fbSJeff Roberson 
2707b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
271ed062c8dSJulian Elischer 	if (td->td_priority < curthread->td_priority)
2724a338afdSJulian Elischer 		curthread->td_flags |= TDF_NEEDRESCHED;
273b43179fbSJeff Roberson }
274b43179fbSJeff Roberson 
275b43179fbSJeff Roberson /*
276a90f3f25SJeff Roberson  * This function is called when a thread is about to be put on run queue
277a90f3f25SJeff Roberson  * because it has been made runnable or its priority has been adjusted.  It
278a90f3f25SJeff Roberson  * determines if the new thread should be immediately preempted to.  If so,
279a90f3f25SJeff Roberson  * it switches to it and eventually returns true.  If not, it returns false
280a90f3f25SJeff Roberson  * so that the caller may place the thread on an appropriate run queue.
281a90f3f25SJeff Roberson  */
282a90f3f25SJeff Roberson int
283a90f3f25SJeff Roberson maybe_preempt(struct thread *td)
284a90f3f25SJeff Roberson {
285a90f3f25SJeff Roberson #ifdef PREEMPTION
286a90f3f25SJeff Roberson 	struct thread *ctd;
287a90f3f25SJeff Roberson 	int cpri, pri;
288a90f3f25SJeff Roberson 
289a90f3f25SJeff Roberson 	/*
290a90f3f25SJeff Roberson 	 * The new thread should not preempt the current thread if any of the
291a90f3f25SJeff Roberson 	 * following conditions are true:
292a90f3f25SJeff Roberson 	 *
293a90f3f25SJeff Roberson 	 *  - The kernel is in the throes of crashing (panicstr).
294a90f3f25SJeff Roberson 	 *  - The current thread has a higher (numerically lower) or
295a90f3f25SJeff Roberson 	 *    equivalent priority.  Note that this prevents curthread from
296a90f3f25SJeff Roberson 	 *    trying to preempt to itself.
297a90f3f25SJeff Roberson 	 *  - It is too early in the boot for context switches (cold is set).
298a90f3f25SJeff Roberson 	 *  - The current thread has an inhibitor set or is in the process of
299a90f3f25SJeff Roberson 	 *    exiting.  In this case, the current thread is about to switch
300a90f3f25SJeff Roberson 	 *    out anyways, so there's no point in preempting.  If we did,
301a90f3f25SJeff Roberson 	 *    the current thread would not be properly resumed as well, so
302a90f3f25SJeff Roberson 	 *    just avoid that whole landmine.
303a90f3f25SJeff Roberson 	 *  - If the new thread's priority is not a realtime priority and
304a90f3f25SJeff Roberson 	 *    the current thread's priority is not an idle priority and
305a90f3f25SJeff Roberson 	 *    FULL_PREEMPTION is disabled.
306a90f3f25SJeff Roberson 	 *
307a90f3f25SJeff Roberson 	 * If all of these conditions are false, but the current thread is in
308a90f3f25SJeff Roberson 	 * a nested critical section, then we have to defer the preemption
309a90f3f25SJeff Roberson 	 * until we exit the critical section.  Otherwise, switch immediately
310a90f3f25SJeff Roberson 	 * to the new thread.
311a90f3f25SJeff Roberson 	 */
312a90f3f25SJeff Roberson 	ctd = curthread;
313a90f3f25SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
314a90f3f25SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
315a90f3f25SJeff Roberson 			("maybe_preempt: trying to run inhibited thread"));
316a90f3f25SJeff Roberson 	pri = td->td_priority;
317a90f3f25SJeff Roberson 	cpri = ctd->td_priority;
318a90f3f25SJeff Roberson 	if (panicstr != NULL || pri >= cpri || cold /* || dumping */ ||
319a90f3f25SJeff Roberson 	    TD_IS_INHIBITED(ctd))
320a90f3f25SJeff Roberson 		return (0);
321a90f3f25SJeff Roberson #ifndef FULL_PREEMPTION
322a90f3f25SJeff Roberson 	if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
323a90f3f25SJeff Roberson 		return (0);
324a90f3f25SJeff Roberson #endif
325a90f3f25SJeff Roberson 
326a90f3f25SJeff Roberson 	if (ctd->td_critnest > 1) {
327a90f3f25SJeff Roberson 		CTR1(KTR_PROC, "maybe_preempt: in critical section %d",
328a90f3f25SJeff Roberson 		    ctd->td_critnest);
329a90f3f25SJeff Roberson 		ctd->td_owepreempt = 1;
330a90f3f25SJeff Roberson 		return (0);
331a90f3f25SJeff Roberson 	}
332a90f3f25SJeff Roberson 	/*
333a90f3f25SJeff Roberson 	 * Thread is runnable but not yet put on system run queue.
334a90f3f25SJeff Roberson 	 */
335a90f3f25SJeff Roberson 	MPASS(ctd->td_lock == td->td_lock);
336a90f3f25SJeff Roberson 	MPASS(TD_ON_RUNQ(td));
337a90f3f25SJeff Roberson 	TD_SET_RUNNING(td);
338a90f3f25SJeff Roberson 	CTR3(KTR_PROC, "preempting to thread %p (pid %d, %s)\n", td,
339a90f3f25SJeff Roberson 	    td->td_proc->p_pid, td->td_name);
3408df78c41SJeff Roberson 	mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, td);
341a90f3f25SJeff Roberson 	/*
342a90f3f25SJeff Roberson 	 * td's lock pointer may have changed.  We have to return with it
343a90f3f25SJeff Roberson 	 * locked.
344a90f3f25SJeff Roberson 	 */
345a90f3f25SJeff Roberson 	spinlock_enter();
346a90f3f25SJeff Roberson 	thread_unlock(ctd);
347a90f3f25SJeff Roberson 	thread_lock(td);
348a90f3f25SJeff Roberson 	spinlock_exit();
349a90f3f25SJeff Roberson 	return (1);
350a90f3f25SJeff Roberson #else
351a90f3f25SJeff Roberson 	return (0);
352a90f3f25SJeff Roberson #endif
353a90f3f25SJeff Roberson }
354a90f3f25SJeff Roberson 
355a90f3f25SJeff Roberson /*
356b43179fbSJeff Roberson  * Constants for digital decay and forget:
3578460a577SJohn Birrell  *	90% of (td_estcpu) usage in 5 * loadav time
358ad1e7d28SJulian Elischer  *	95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
359b43179fbSJeff Roberson  *          Note that, as ps(1) mentions, this can let percentages
360b43179fbSJeff Roberson  *          total over 100% (I've seen 137.9% for 3 processes).
361b43179fbSJeff Roberson  *
3628460a577SJohn Birrell  * Note that schedclock() updates td_estcpu and p_cpticks asynchronously.
363b43179fbSJeff Roberson  *
3648460a577SJohn Birrell  * We wish to decay away 90% of td_estcpu in (5 * loadavg) seconds.
365b43179fbSJeff Roberson  * That is, the system wants to compute a value of decay such
366b43179fbSJeff Roberson  * that the following for loop:
367b43179fbSJeff Roberson  * 	for (i = 0; i < (5 * loadavg); i++)
3688460a577SJohn Birrell  * 		td_estcpu *= decay;
369b43179fbSJeff Roberson  * will compute
3708460a577SJohn Birrell  * 	td_estcpu *= 0.1;
371b43179fbSJeff Roberson  * for all values of loadavg:
372b43179fbSJeff Roberson  *
373b43179fbSJeff Roberson  * Mathematically this loop can be expressed by saying:
374b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
375b43179fbSJeff Roberson  *
376b43179fbSJeff Roberson  * The system computes decay as:
377b43179fbSJeff Roberson  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
378b43179fbSJeff Roberson  *
379b43179fbSJeff Roberson  * We wish to prove that the system's computation of decay
380b43179fbSJeff Roberson  * will always fulfill the equation:
381b43179fbSJeff Roberson  * 	decay ** (5 * loadavg) ~= .1
382b43179fbSJeff Roberson  *
383b43179fbSJeff Roberson  * If we compute b as:
384b43179fbSJeff Roberson  * 	b = 2 * loadavg
385b43179fbSJeff Roberson  * then
386b43179fbSJeff Roberson  * 	decay = b / (b + 1)
387b43179fbSJeff Roberson  *
388b43179fbSJeff Roberson  * We now need to prove two things:
389b43179fbSJeff Roberson  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
390b43179fbSJeff Roberson  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
391b43179fbSJeff Roberson  *
392b43179fbSJeff Roberson  * Facts:
393b43179fbSJeff Roberson  *         For x close to zero, exp(x) =~ 1 + x, since
394b43179fbSJeff Roberson  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
395b43179fbSJeff Roberson  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
396b43179fbSJeff Roberson  *         For x close to zero, ln(1+x) =~ x, since
397b43179fbSJeff Roberson  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
398b43179fbSJeff Roberson  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
399b43179fbSJeff Roberson  *         ln(.1) =~ -2.30
400b43179fbSJeff Roberson  *
401b43179fbSJeff Roberson  * Proof of (1):
402b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
403b43179fbSJeff Roberson  *	solving for factor,
404b43179fbSJeff Roberson  *      ln(factor) =~ (-2.30/5*loadav), or
405b43179fbSJeff Roberson  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
406b43179fbSJeff Roberson  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
407b43179fbSJeff Roberson  *
408b43179fbSJeff Roberson  * Proof of (2):
409b43179fbSJeff Roberson  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
410b43179fbSJeff Roberson  *	solving for power,
411b43179fbSJeff Roberson  *      power*ln(b/(b+1)) =~ -2.30, or
412b43179fbSJeff Roberson  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
413b43179fbSJeff Roberson  *
414b43179fbSJeff Roberson  * Actual power values for the implemented algorithm are as follows:
415b43179fbSJeff Roberson  *      loadav: 1       2       3       4
416b43179fbSJeff Roberson  *      power:  5.68    10.32   14.94   19.55
417b43179fbSJeff Roberson  */
418b43179fbSJeff Roberson 
419b43179fbSJeff Roberson /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
420b43179fbSJeff Roberson #define	loadfactor(loadav)	(2 * (loadav))
421b43179fbSJeff Roberson #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
422b43179fbSJeff Roberson 
423ad1e7d28SJulian Elischer /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
424b43179fbSJeff Roberson static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
42552c0b557SMatthew D Fleming SYSCTL_UINT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
426b43179fbSJeff Roberson 
427b43179fbSJeff Roberson /*
428b43179fbSJeff Roberson  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
429b43179fbSJeff Roberson  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
430b43179fbSJeff Roberson  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
431b43179fbSJeff Roberson  *
432b43179fbSJeff Roberson  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
433b43179fbSJeff Roberson  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
434b43179fbSJeff Roberson  *
435b43179fbSJeff Roberson  * If you don't want to bother with the faster/more-accurate formula, you
436b43179fbSJeff Roberson  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
437b43179fbSJeff Roberson  * (more general) method of calculating the %age of CPU used by a process.
438b43179fbSJeff Roberson  */
439b43179fbSJeff Roberson #define	CCPU_SHIFT	11
440b43179fbSJeff Roberson 
441b43179fbSJeff Roberson /*
442b43179fbSJeff Roberson  * Recompute process priorities, every hz ticks.
443b43179fbSJeff Roberson  * MP-safe, called without the Giant mutex.
444b43179fbSJeff Roberson  */
445b43179fbSJeff Roberson /* ARGSUSED */
446b43179fbSJeff Roberson static void
447c55bbb6cSJohn Baldwin schedcpu(void)
448b43179fbSJeff Roberson {
449b43179fbSJeff Roberson 	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
450b43179fbSJeff Roberson 	struct thread *td;
451b43179fbSJeff Roberson 	struct proc *p;
452ad1e7d28SJulian Elischer 	struct td_sched *ts;
45370fca427SJohn Baldwin 	int awake, realstathz;
454b43179fbSJeff Roberson 
455b43179fbSJeff Roberson 	realstathz = stathz ? stathz : hz;
456b43179fbSJeff Roberson 	sx_slock(&allproc_lock);
457b43179fbSJeff Roberson 	FOREACH_PROC_IN_SYSTEM(p) {
458374ae2a3SJeff Roberson 		PROC_LOCK(p);
459e806d352SJohn Baldwin 		if (p->p_state == PRS_NEW) {
460e806d352SJohn Baldwin 			PROC_UNLOCK(p);
461e806d352SJohn Baldwin 			continue;
462e806d352SJohn Baldwin 		}
4638460a577SJohn Birrell 		FOREACH_THREAD_IN_PROC(p, td) {
464b43179fbSJeff Roberson 			awake = 0;
4657b20fb19SJeff Roberson 			thread_lock(td);
466ad1e7d28SJulian Elischer 			ts = td->td_sched;
467b43179fbSJeff Roberson 			/*
46870fca427SJohn Baldwin 			 * Increment sleep time (if sleeping).  We
46970fca427SJohn Baldwin 			 * ignore overflow, as above.
470b43179fbSJeff Roberson 			 */
471b43179fbSJeff Roberson 			/*
472ad1e7d28SJulian Elischer 			 * The td_sched slptimes are not touched in wakeup
473ad1e7d28SJulian Elischer 			 * because the thread may not HAVE everything in
474ad1e7d28SJulian Elischer 			 * memory? XXX I think this is out of date.
475b43179fbSJeff Roberson 			 */
476f0393f06SJeff Roberson 			if (TD_ON_RUNQ(td)) {
477b43179fbSJeff Roberson 				awake = 1;
4789727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
479f0393f06SJeff Roberson 			} else if (TD_IS_RUNNING(td)) {
480b43179fbSJeff Roberson 				awake = 1;
4819727e637SJeff Roberson 				/* Do not clear TDF_DIDRUN */
4829727e637SJeff Roberson 			} else if (td->td_flags & TDF_DIDRUN) {
483b43179fbSJeff Roberson 				awake = 1;
4849727e637SJeff Roberson 				td->td_flags &= ~TDF_DIDRUN;
485b43179fbSJeff Roberson 			}
486b43179fbSJeff Roberson 
487b43179fbSJeff Roberson 			/*
488ad1e7d28SJulian Elischer 			 * ts_pctcpu is only for ps and ttyinfo().
489b43179fbSJeff Roberson 			 */
490ad1e7d28SJulian Elischer 			ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
491b43179fbSJeff Roberson 			/*
492ad1e7d28SJulian Elischer 			 * If the td_sched has been idle the entire second,
493b43179fbSJeff Roberson 			 * stop recalculating its priority until
494b43179fbSJeff Roberson 			 * it wakes up.
495b43179fbSJeff Roberson 			 */
496ad1e7d28SJulian Elischer 			if (ts->ts_cpticks != 0) {
497b43179fbSJeff Roberson #if	(FSHIFT >= CCPU_SHIFT)
498ad1e7d28SJulian Elischer 				ts->ts_pctcpu += (realstathz == 100)
499ad1e7d28SJulian Elischer 				    ? ((fixpt_t) ts->ts_cpticks) <<
500b43179fbSJeff Roberson 				    (FSHIFT - CCPU_SHIFT) :
501ad1e7d28SJulian Elischer 				    100 * (((fixpt_t) ts->ts_cpticks)
502bcb06d59SJeff Roberson 				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
503b43179fbSJeff Roberson #else
504ad1e7d28SJulian Elischer 				ts->ts_pctcpu += ((FSCALE - ccpu) *
505ad1e7d28SJulian Elischer 				    (ts->ts_cpticks *
506bcb06d59SJeff Roberson 				    FSCALE / realstathz)) >> FSHIFT;
507b43179fbSJeff Roberson #endif
508ad1e7d28SJulian Elischer 				ts->ts_cpticks = 0;
5098460a577SJohn Birrell 			}
5108460a577SJohn Birrell 			/*
5118460a577SJohn Birrell 			 * If there are ANY running threads in this process,
512b43179fbSJeff Roberson 			 * then don't count it as sleeping.
5138aa3d7ffSJohn Baldwin 			 * XXX: this is broken.
514b43179fbSJeff Roberson 			 */
515b43179fbSJeff Roberson 			if (awake) {
51654b0e65fSJeff Roberson 				if (ts->ts_slptime > 1) {
517b43179fbSJeff Roberson 					/*
518b43179fbSJeff Roberson 					 * In an ideal world, this should not
519b43179fbSJeff Roberson 					 * happen, because whoever woke us
520b43179fbSJeff Roberson 					 * up from the long sleep should have
521b43179fbSJeff Roberson 					 * unwound the slptime and reset our
522b43179fbSJeff Roberson 					 * priority before we run at the stale
523b43179fbSJeff Roberson 					 * priority.  Should KASSERT at some
524b43179fbSJeff Roberson 					 * point when all the cases are fixed.
525b43179fbSJeff Roberson 					 */
5268460a577SJohn Birrell 					updatepri(td);
5278460a577SJohn Birrell 				}
52854b0e65fSJeff Roberson 				ts->ts_slptime = 0;
5298460a577SJohn Birrell 			} else
53054b0e65fSJeff Roberson 				ts->ts_slptime++;
53154b0e65fSJeff Roberson 			if (ts->ts_slptime > 1) {
5327b20fb19SJeff Roberson 				thread_unlock(td);
5338460a577SJohn Birrell 				continue;
5347b20fb19SJeff Roberson 			}
5358460a577SJohn Birrell 			td->td_estcpu = decay_cpu(loadfac, td->td_estcpu);
5368460a577SJohn Birrell 		      	resetpriority(td);
5378460a577SJohn Birrell 			resetpriority_thread(td);
5387b20fb19SJeff Roberson 			thread_unlock(td);
5398aa3d7ffSJohn Baldwin 		}
540374ae2a3SJeff Roberson 		PROC_UNLOCK(p);
5418aa3d7ffSJohn Baldwin 	}
542b43179fbSJeff Roberson 	sx_sunlock(&allproc_lock);
543c55bbb6cSJohn Baldwin }
544c55bbb6cSJohn Baldwin 
545c55bbb6cSJohn Baldwin /*
546c55bbb6cSJohn Baldwin  * Main loop for a kthread that executes schedcpu once a second.
547c55bbb6cSJohn Baldwin  */
548c55bbb6cSJohn Baldwin static void
549e17c57b1SJeff Roberson schedcpu_thread(void)
550c55bbb6cSJohn Baldwin {
551c55bbb6cSJohn Baldwin 
552c55bbb6cSJohn Baldwin 	for (;;) {
553c55bbb6cSJohn Baldwin 		schedcpu();
5544d70511aSJohn Baldwin 		pause("-", hz);
555c55bbb6cSJohn Baldwin 	}
556b43179fbSJeff Roberson }
557b43179fbSJeff Roberson 
558b43179fbSJeff Roberson /*
559b43179fbSJeff Roberson  * Recalculate the priority of a process after it has slept for a while.
5608460a577SJohn Birrell  * For all load averages >= 1 and max td_estcpu of 255, sleeping for at
5618460a577SJohn Birrell  * least six times the loadfactor will decay td_estcpu to zero.
562b43179fbSJeff Roberson  */
563b43179fbSJeff Roberson static void
5648460a577SJohn Birrell updatepri(struct thread *td)
565b43179fbSJeff Roberson {
56654b0e65fSJeff Roberson 	struct td_sched *ts;
56754b0e65fSJeff Roberson 	fixpt_t loadfac;
56854b0e65fSJeff Roberson 	unsigned int newcpu;
569b43179fbSJeff Roberson 
57054b0e65fSJeff Roberson 	ts = td->td_sched;
57170fca427SJohn Baldwin 	loadfac = loadfactor(averunnable.ldavg[0]);
57254b0e65fSJeff Roberson 	if (ts->ts_slptime > 5 * loadfac)
5738460a577SJohn Birrell 		td->td_estcpu = 0;
574b43179fbSJeff Roberson 	else {
5758460a577SJohn Birrell 		newcpu = td->td_estcpu;
57654b0e65fSJeff Roberson 		ts->ts_slptime--;	/* was incremented in schedcpu() */
57754b0e65fSJeff Roberson 		while (newcpu && --ts->ts_slptime)
578b43179fbSJeff Roberson 			newcpu = decay_cpu(loadfac, newcpu);
5798460a577SJohn Birrell 		td->td_estcpu = newcpu;
580b43179fbSJeff Roberson 	}
581b43179fbSJeff Roberson }
582b43179fbSJeff Roberson 
583b43179fbSJeff Roberson /*
584b43179fbSJeff Roberson  * Compute the priority of a process when running in user mode.
585b43179fbSJeff Roberson  * Arrange to reschedule if the resulting priority is better
586b43179fbSJeff Roberson  * than that of the current process.
587b43179fbSJeff Roberson  */
588b43179fbSJeff Roberson static void
5898460a577SJohn Birrell resetpriority(struct thread *td)
590b43179fbSJeff Roberson {
591b43179fbSJeff Roberson 	register unsigned int newpriority;
592b43179fbSJeff Roberson 
5938460a577SJohn Birrell 	if (td->td_pri_class == PRI_TIMESHARE) {
5948460a577SJohn Birrell 		newpriority = PUSER + td->td_estcpu / INVERSE_ESTCPU_WEIGHT +
5958460a577SJohn Birrell 		    NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
596b43179fbSJeff Roberson 		newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
597b43179fbSJeff Roberson 		    PRI_MAX_TIMESHARE);
5988460a577SJohn Birrell 		sched_user_prio(td, newpriority);
599b43179fbSJeff Roberson 	}
600b43179fbSJeff Roberson }
601f5c157d9SJohn Baldwin 
602f5c157d9SJohn Baldwin /*
603ad1e7d28SJulian Elischer  * Update the thread's priority when the associated process's user
604f5c157d9SJohn Baldwin  * priority changes.
605f5c157d9SJohn Baldwin  */
606f5c157d9SJohn Baldwin static void
6078460a577SJohn Birrell resetpriority_thread(struct thread *td)
608f5c157d9SJohn Baldwin {
609f5c157d9SJohn Baldwin 
610f5c157d9SJohn Baldwin 	/* Only change threads with a time sharing user priority. */
611f5c157d9SJohn Baldwin 	if (td->td_priority < PRI_MIN_TIMESHARE ||
612f5c157d9SJohn Baldwin 	    td->td_priority > PRI_MAX_TIMESHARE)
613f5c157d9SJohn Baldwin 		return;
614f5c157d9SJohn Baldwin 
615f5c157d9SJohn Baldwin 	/* XXX the whole needresched thing is broken, but not silly. */
616f5c157d9SJohn Baldwin 	maybe_resched(td);
617f5c157d9SJohn Baldwin 
6188460a577SJohn Birrell 	sched_prio(td, td->td_user_pri);
619b43179fbSJeff Roberson }
620b43179fbSJeff Roberson 
621b43179fbSJeff Roberson /* ARGSUSED */
622b43179fbSJeff Roberson static void
623b43179fbSJeff Roberson sched_setup(void *dummy)
624b43179fbSJeff Roberson {
625e17c57b1SJeff Roberson 	setup_runqs();
62670fca427SJohn Baldwin 
627b43179fbSJeff Roberson 	if (sched_quantum == 0)
628b43179fbSJeff Roberson 		sched_quantum = SCHED_QUANTUM;
629b43179fbSJeff Roberson 	hogticks = 2 * sched_quantum;
630b43179fbSJeff Roberson 
631ca59f152SJeff Roberson 	/* Account for thread0. */
632907bdbc2SJeff Roberson 	sched_load_add();
633b43179fbSJeff Roberson }
634b43179fbSJeff Roberson 
635b43179fbSJeff Roberson /* External interfaces start here */
6368aa3d7ffSJohn Baldwin 
637ed062c8dSJulian Elischer /*
638ed062c8dSJulian Elischer  * Very early in the boot some setup of scheduler-specific
639f3050486SMaxim Konovalov  * parts of proc0 and of some scheduler resources needs to be done.
640ed062c8dSJulian Elischer  * Called from:
641ed062c8dSJulian Elischer  *  proc0_init()
642ed062c8dSJulian Elischer  */
643ed062c8dSJulian Elischer void
644ed062c8dSJulian Elischer schedinit(void)
645ed062c8dSJulian Elischer {
646ed062c8dSJulian Elischer 	/*
647ed062c8dSJulian Elischer 	 * Set up the scheduler specific parts of proc0.
648ed062c8dSJulian Elischer 	 */
649ed062c8dSJulian Elischer 	proc0.p_sched = NULL; /* XXX */
650ad1e7d28SJulian Elischer 	thread0.td_sched = &td_sched0;
6517b20fb19SJeff Roberson 	thread0.td_lock = &sched_lock;
6526ea38de8SJeff Roberson 	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
653ed062c8dSJulian Elischer }
654ed062c8dSJulian Elischer 
655b43179fbSJeff Roberson int
656b43179fbSJeff Roberson sched_runnable(void)
657b43179fbSJeff Roberson {
658e17c57b1SJeff Roberson #ifdef SMP
659e17c57b1SJeff Roberson 	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
660e17c57b1SJeff Roberson #else
661b43179fbSJeff Roberson 	return runq_check(&runq);
662e17c57b1SJeff Roberson #endif
663b43179fbSJeff Roberson }
664b43179fbSJeff Roberson 
665b43179fbSJeff Roberson int
666b43179fbSJeff Roberson sched_rr_interval(void)
667b43179fbSJeff Roberson {
668b43179fbSJeff Roberson 	if (sched_quantum == 0)
669b43179fbSJeff Roberson 		sched_quantum = SCHED_QUANTUM;
670b43179fbSJeff Roberson 	return (sched_quantum);
671b43179fbSJeff Roberson }
672b43179fbSJeff Roberson 
673b43179fbSJeff Roberson /*
674b43179fbSJeff Roberson  * We adjust the priority of the current process.  The priority of
675b43179fbSJeff Roberson  * a process gets worse as it accumulates CPU time.  The cpu usage
6768460a577SJohn Birrell  * estimator (td_estcpu) is increased here.  resetpriority() will
6778460a577SJohn Birrell  * compute a different priority each time td_estcpu increases by
678b43179fbSJeff Roberson  * INVERSE_ESTCPU_WEIGHT
679b43179fbSJeff Roberson  * (until MAXPRI is reached).  The cpu usage estimator ramps up
680b43179fbSJeff Roberson  * quite quickly when the process is running (linearly), and decays
681b43179fbSJeff Roberson  * away exponentially, at a rate which is proportionally slower when
682b43179fbSJeff Roberson  * the system is busy.  The basic principle is that the system will
683b43179fbSJeff Roberson  * 90% forget that the process used a lot of CPU time in 5 * loadav
684b43179fbSJeff Roberson  * seconds.  This causes the system to favor processes which haven't
685b43179fbSJeff Roberson  * run much recently, and to round-robin among other processes.
686b43179fbSJeff Roberson  */
687b43179fbSJeff Roberson void
6887cf90fb3SJeff Roberson sched_clock(struct thread *td)
689b43179fbSJeff Roberson {
690b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
691ad1e7d28SJulian Elischer 	struct td_sched *ts;
692b43179fbSJeff Roberson 
6937b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
694ad1e7d28SJulian Elischer 	ts = td->td_sched;
695f7f9e7f3SJeff Roberson 
696ad1e7d28SJulian Elischer 	ts->ts_cpticks++;
6978460a577SJohn Birrell 	td->td_estcpu = ESTCPULIM(td->td_estcpu + 1);
6988460a577SJohn Birrell 	if ((td->td_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
6998460a577SJohn Birrell 		resetpriority(td);
7008460a577SJohn Birrell 		resetpriority_thread(td);
701b43179fbSJeff Roberson 	}
7029dddab6fSJohn Baldwin 
7039dddab6fSJohn Baldwin 	/*
7049dddab6fSJohn Baldwin 	 * Force a context switch if the current thread has used up a full
7059dddab6fSJohn Baldwin 	 * quantum (default quantum is 100ms).
7069dddab6fSJohn Baldwin 	 */
7079dddab6fSJohn Baldwin 	if (!TD_IS_IDLETHREAD(td) &&
7089dddab6fSJohn Baldwin 	    ticks - PCPU_GET(switchticks) >= sched_quantum)
7099dddab6fSJohn Baldwin 		td->td_flags |= TDF_NEEDRESCHED;
710b722ad00SAlexander Motin 
711b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
712b722ad00SAlexander Motin 	stat->oldidlecalls = stat->idlecalls;
713b722ad00SAlexander Motin 	stat->idlecalls = 0;
714b43179fbSJeff Roberson }
71570fca427SJohn Baldwin 
7168460a577SJohn Birrell /*
7178aa3d7ffSJohn Baldwin  * Charge child's scheduling CPU usage to parent.
7188460a577SJohn Birrell  */
719b43179fbSJeff Roberson void
72055d44f79SJulian Elischer sched_exit(struct proc *p, struct thread *td)
721f7f9e7f3SJeff Roberson {
7228460a577SJohn Birrell 
7238f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "proc exit",
724cd39bb09SXin LI 	    "prio:%d", td->td_priority);
7258f51ad55SJeff Roberson 
726374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
727ad1e7d28SJulian Elischer 	sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
728b43179fbSJeff Roberson }
729b43179fbSJeff Roberson 
730b43179fbSJeff Roberson void
731f7f9e7f3SJeff Roberson sched_exit_thread(struct thread *td, struct thread *child)
732b43179fbSJeff Roberson {
733ad1e7d28SJulian Elischer 
7348f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "exit",
735cd39bb09SXin LI 	    "prio:%d", child->td_priority);
7367b20fb19SJeff Roberson 	thread_lock(td);
737ad1e7d28SJulian Elischer 	td->td_estcpu = ESTCPULIM(td->td_estcpu + child->td_estcpu);
7387b20fb19SJeff Roberson 	thread_unlock(td);
7391b9d701fSAttilio Rao 	thread_lock(child);
7401b9d701fSAttilio Rao 	if ((child->td_flags & TDF_NOLOAD) == 0)
741907bdbc2SJeff Roberson 		sched_load_rem();
7421b9d701fSAttilio Rao 	thread_unlock(child);
743f7f9e7f3SJeff Roberson }
744bcb06d59SJeff Roberson 
745f7f9e7f3SJeff Roberson void
746ed062c8dSJulian Elischer sched_fork(struct thread *td, struct thread *childtd)
747f7f9e7f3SJeff Roberson {
748ed062c8dSJulian Elischer 	sched_fork_thread(td, childtd);
749f7f9e7f3SJeff Roberson }
750bcb06d59SJeff Roberson 
751f7f9e7f3SJeff Roberson void
752ed062c8dSJulian Elischer sched_fork_thread(struct thread *td, struct thread *childtd)
753f7f9e7f3SJeff Roberson {
7548b16c208SJeff Roberson 	struct td_sched *ts;
7558b16c208SJeff Roberson 
756ad1e7d28SJulian Elischer 	childtd->td_estcpu = td->td_estcpu;
7577b20fb19SJeff Roberson 	childtd->td_lock = &sched_lock;
758f5a3ef99SMarcel Moolenaar 	childtd->td_cpuset = cpuset_ref(td->td_cpuset);
75922d19207SJohn Baldwin 	childtd->td_priority = childtd->td_base_pri;
7608b16c208SJeff Roberson 	ts = childtd->td_sched;
7618b16c208SJeff Roberson 	bzero(ts, sizeof(*ts));
762f200843bSJohn Baldwin 	ts->ts_flags |= (td->td_sched->ts_flags & TSF_AFFINITY);
763b43179fbSJeff Roberson }
764b43179fbSJeff Roberson 
765b43179fbSJeff Roberson void
766fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
767b43179fbSJeff Roberson {
768f5c157d9SJohn Baldwin 	struct thread *td;
7690b5318c8SJohn Baldwin 
770fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
771fa885116SJulian Elischer 	p->p_nice = nice;
7728460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
7737b20fb19SJeff Roberson 		thread_lock(td);
7748460a577SJohn Birrell 		resetpriority(td);
7758460a577SJohn Birrell 		resetpriority_thread(td);
7767b20fb19SJeff Roberson 		thread_unlock(td);
7778460a577SJohn Birrell 	}
778fa885116SJulian Elischer }
779b43179fbSJeff Roberson 
780f7f9e7f3SJeff Roberson void
7818460a577SJohn Birrell sched_class(struct thread *td, int class)
782f7f9e7f3SJeff Roberson {
7837b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
7848460a577SJohn Birrell 	td->td_pri_class = class;
785f7f9e7f3SJeff Roberson }
786f7f9e7f3SJeff Roberson 
7878460a577SJohn Birrell /*
7888460a577SJohn Birrell  * Adjust the priority of a thread.
7898460a577SJohn Birrell  */
790f5c157d9SJohn Baldwin static void
791f5c157d9SJohn Baldwin sched_priority(struct thread *td, u_char prio)
792b43179fbSJeff Roberson {
793b43179fbSJeff Roberson 
7948f51ad55SJeff Roberson 
7958f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
7968f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
7978f51ad55SJeff Roberson 	    sched_tdname(curthread));
7988f51ad55SJeff Roberson 	if (td != curthread && prio > td->td_priority) {
7998f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
8008f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
8018f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
8028f51ad55SJeff Roberson 	}
8037b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
804f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
805f5c157d9SJohn Baldwin 		return;
8061f955e2dSJulian Elischer 	td->td_priority = prio;
8079727e637SJeff Roberson 	if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
808f0393f06SJeff Roberson 		sched_rem(td);
809f0393f06SJeff Roberson 		sched_add(td, SRQ_BORING);
810b43179fbSJeff Roberson 	}
811b43179fbSJeff Roberson }
812b43179fbSJeff Roberson 
813f5c157d9SJohn Baldwin /*
814f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
815f5c157d9SJohn Baldwin  * priority.
816f5c157d9SJohn Baldwin  */
817f5c157d9SJohn Baldwin void
818f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
819f5c157d9SJohn Baldwin {
820f5c157d9SJohn Baldwin 
821f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
822f5c157d9SJohn Baldwin 	sched_priority(td, prio);
823f5c157d9SJohn Baldwin }
824f5c157d9SJohn Baldwin 
825f5c157d9SJohn Baldwin /*
826f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
827f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
828f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
829f5c157d9SJohn Baldwin  * requests.  If the thread's regulary priority is less
830f5c157d9SJohn Baldwin  * important than prio the thread will keep a priority boost
831f5c157d9SJohn Baldwin  * of prio.
832f5c157d9SJohn Baldwin  */
833f5c157d9SJohn Baldwin void
834f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
835f5c157d9SJohn Baldwin {
836f5c157d9SJohn Baldwin 	u_char base_pri;
837f5c157d9SJohn Baldwin 
838f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
839f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
8408460a577SJohn Birrell 		base_pri = td->td_user_pri;
841f5c157d9SJohn Baldwin 	else
842f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
843f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
844f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
845f5c157d9SJohn Baldwin 		sched_prio(td, base_pri);
846f5c157d9SJohn Baldwin 	} else
847f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
848f5c157d9SJohn Baldwin }
849f5c157d9SJohn Baldwin 
850f5c157d9SJohn Baldwin void
851f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
852f5c157d9SJohn Baldwin {
853f5c157d9SJohn Baldwin 	u_char oldprio;
854f5c157d9SJohn Baldwin 
855f5c157d9SJohn Baldwin 	/* First, update the base priority. */
856f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
857f5c157d9SJohn Baldwin 
858f5c157d9SJohn Baldwin 	/*
859f5c157d9SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't ever
860f5c157d9SJohn Baldwin 	 * lower the priority.
861f5c157d9SJohn Baldwin 	 */
862f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
863f5c157d9SJohn Baldwin 		return;
864f5c157d9SJohn Baldwin 
865f5c157d9SJohn Baldwin 	/* Change the real priority. */
866f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
867f5c157d9SJohn Baldwin 	sched_priority(td, prio);
868f5c157d9SJohn Baldwin 
869f5c157d9SJohn Baldwin 	/*
870f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
871f5c157d9SJohn Baldwin 	 * its state.
872f5c157d9SJohn Baldwin 	 */
873f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
874f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
875f5c157d9SJohn Baldwin }
876f5c157d9SJohn Baldwin 
877b43179fbSJeff Roberson void
8788460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
8793db720fdSDavid Xu {
8803db720fdSDavid Xu 
881435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
8828460a577SJohn Birrell 	td->td_base_user_pri = prio;
883acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
8845a215147SDavid Xu 		return;
8858460a577SJohn Birrell 	td->td_user_pri = prio;
8863db720fdSDavid Xu }
8873db720fdSDavid Xu 
8883db720fdSDavid Xu void
8893db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
8903db720fdSDavid Xu {
8913db720fdSDavid Xu 
892435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
893acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
894c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
895c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
896c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
897c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
898c8e368a9SDavid Xu 		td->td_flags |= TDF_NEEDRESCHED;
899435806d3SDavid Xu }
9003db720fdSDavid Xu 
9013db720fdSDavid Xu void
902c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int pri)
903b43179fbSJeff Roberson {
9042056d0a1SJohn Baldwin 
9057b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
90654b0e65fSJeff Roberson 	td->td_slptick = ticks;
90754b0e65fSJeff Roberson 	td->td_sched->ts_slptime = 0;
9082dc29adbSJohn Baldwin 	if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
909c5aa6b58SJeff Roberson 		sched_prio(td, pri);
91017c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
911c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
912b43179fbSJeff Roberson }
913b43179fbSJeff Roberson 
914b43179fbSJeff Roberson void
9153389af30SJulian Elischer sched_switch(struct thread *td, struct thread *newtd, int flags)
916b43179fbSJeff Roberson {
917b0b9dee5SAttilio Rao 	struct mtx *tmtx;
918ad1e7d28SJulian Elischer 	struct td_sched *ts;
919b43179fbSJeff Roberson 	struct proc *p;
920b43179fbSJeff Roberson 
921b0b9dee5SAttilio Rao 	tmtx = NULL;
922ad1e7d28SJulian Elischer 	ts = td->td_sched;
923b43179fbSJeff Roberson 	p = td->td_proc;
924b43179fbSJeff Roberson 
9257b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
9268aa3d7ffSJohn Baldwin 
9277b20fb19SJeff Roberson 	/*
9287b20fb19SJeff Roberson 	 * Switch to the sched lock to fix things up and pick
9297b20fb19SJeff Roberson 	 * a new thread.
930b0b9dee5SAttilio Rao 	 * Block the td_lock in order to avoid breaking the critical path.
9317b20fb19SJeff Roberson 	 */
9327b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
9337b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
934b0b9dee5SAttilio Rao 		tmtx = thread_lock_block(td);
9357b20fb19SJeff Roberson 	}
936b43179fbSJeff Roberson 
9371b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
938907bdbc2SJeff Roberson 		sched_load_rem();
9393389af30SJulian Elischer 
940060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
941586cb6ecSFabien Thomas 	if (!(flags & SW_PREEMPT))
94252eb8464SJohn Baldwin 		td->td_flags &= ~TDF_NEEDRESCHED;
94377918643SStephan Uphoff 	td->td_owepreempt = 0;
944ca59f152SJeff Roberson 	td->td_oncpu = NOCPU;
9458aa3d7ffSJohn Baldwin 
946b43179fbSJeff Roberson 	/*
947b43179fbSJeff Roberson 	 * At the last moment, if this thread is still marked RUNNING,
948b43179fbSJeff Roberson 	 * then put it back on the run queue as it has not been suspended
949bf0acc27SJohn Baldwin 	 * or stopped or any thing else similar.  We never put the idle
950bf0acc27SJohn Baldwin 	 * threads on the run queue, however.
951b43179fbSJeff Roberson 	 */
952c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD) {
953bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
954c6226eeaSJulian Elischer #ifdef SMP
955a38f1f26SAttilio Rao 		CPU_CLR(PCPU_GET(cpuid), &idle_cpus_mask);
956c6226eeaSJulian Elischer #endif
957c6226eeaSJulian Elischer 	} else {
958ed062c8dSJulian Elischer 		if (TD_IS_RUNNING(td)) {
959ad1e7d28SJulian Elischer 			/* Put us back on the run queue. */
960f0393f06SJeff Roberson 			sched_add(td, (flags & SW_PREEMPT) ?
961c20c691bSJulian Elischer 			    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
962c20c691bSJulian Elischer 			    SRQ_OURSELF|SRQ_YIELDING);
963ed062c8dSJulian Elischer 		}
964b43179fbSJeff Roberson 	}
965c20c691bSJulian Elischer 	if (newtd) {
966c20c691bSJulian Elischer 		/*
967c20c691bSJulian Elischer 		 * The thread we are about to run needs to be counted
968c20c691bSJulian Elischer 		 * as if it had been added to the run queue and selected.
969c20c691bSJulian Elischer 		 * It came from:
970c20c691bSJulian Elischer 		 * * A preemption
971c20c691bSJulian Elischer 		 * * An upcall
972c20c691bSJulian Elischer 		 * * A followon
973c20c691bSJulian Elischer 		 */
974c20c691bSJulian Elischer 		KASSERT((newtd->td_inhibitors == 0),
9752da78e38SRobert Watson 			("trying to run inhibited thread"));
9769727e637SJeff Roberson 		newtd->td_flags |= TDF_DIDRUN;
977c20c691bSJulian Elischer         	TD_SET_RUNNING(newtd);
9781b9d701fSAttilio Rao 		if ((newtd->td_flags & TDF_NOLOAD) == 0)
979907bdbc2SJeff Roberson 			sched_load_add();
980c20c691bSJulian Elischer 	} else {
981ae53b483SJeff Roberson 		newtd = choosethread();
9827b20fb19SJeff Roberson 		MPASS(newtd->td_lock == &sched_lock);
98358060789SAttilio Rao 	}
984c20c691bSJulian Elischer 
985ebccf1e3SJoseph Koshy 	if (td != newtd) {
986ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
987ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
988ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
989ebccf1e3SJoseph Koshy #endif
990c6226eeaSJulian Elischer                 /* I feel sleepy */
991eea4f254SJeff Roberson 		lock_profile_release_lock(&sched_lock.lock_object);
9926f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
9936f5f25e5SJohn Birrell 		/*
9946f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
9956f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
9966f5f25e5SJohn Birrell 		 * function to call.
9976f5f25e5SJohn Birrell 		 */
9986f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
9996f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
10006f5f25e5SJohn Birrell #endif
10016f5f25e5SJohn Birrell 
1002b0b9dee5SAttilio Rao 		cpu_switch(td, newtd, tmtx != NULL ? tmtx : td->td_lock);
1003eea4f254SJeff Roberson 		lock_profile_obtain_lock_success(&sched_lock.lock_object,
1004eea4f254SJeff Roberson 		    0, 0, __FILE__, __LINE__);
1005c6226eeaSJulian Elischer 		/*
1006c6226eeaSJulian Elischer 		 * Where am I?  What year is it?
1007c6226eeaSJulian Elischer 		 * We are in the same thread that went to sleep above,
10088aa3d7ffSJohn Baldwin 		 * but any amount of time may have passed. All our context
1009c6226eeaSJulian Elischer 		 * will still be available as will local variables.
1010c6226eeaSJulian Elischer 		 * PCPU values however may have changed as we may have
1011c6226eeaSJulian Elischer 		 * changed CPU so don't trust cached values of them.
1012c6226eeaSJulian Elischer 		 * New threads will go to fork_exit() instead of here
1013c6226eeaSJulian Elischer 		 * so if you change things here you may need to change
1014c6226eeaSJulian Elischer 		 * things there too.
10158aa3d7ffSJohn Baldwin 		 *
1016c6226eeaSJulian Elischer 		 * If the thread above was exiting it will never wake
1017c6226eeaSJulian Elischer 		 * up again here, so either it has saved everything it
1018c6226eeaSJulian Elischer 		 * needed to, or the thread_wait() or wait() will
1019c6226eeaSJulian Elischer 		 * need to reap it.
1020c6226eeaSJulian Elischer 		 */
1021ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1022ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1023ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1024ebccf1e3SJoseph Koshy #endif
1025ebccf1e3SJoseph Koshy 	}
1026ebccf1e3SJoseph Koshy 
1027c6226eeaSJulian Elischer #ifdef SMP
1028c6226eeaSJulian Elischer 	if (td->td_flags & TDF_IDLETD)
1029a38f1f26SAttilio Rao 		CPU_SET(PCPU_GET(cpuid), &idle_cpus_mask);
1030c6226eeaSJulian Elischer #endif
1031ae53b483SJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
1032ae53b483SJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
10337b20fb19SJeff Roberson 	MPASS(td->td_lock == &sched_lock);
1034b43179fbSJeff Roberson }
1035b43179fbSJeff Roberson 
1036b43179fbSJeff Roberson void
1037b43179fbSJeff Roberson sched_wakeup(struct thread *td)
1038b43179fbSJeff Roberson {
103954b0e65fSJeff Roberson 	struct td_sched *ts;
104054b0e65fSJeff Roberson 
10417b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
104254b0e65fSJeff Roberson 	ts = td->td_sched;
1043c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
104454b0e65fSJeff Roberson 	if (ts->ts_slptime > 1) {
10458460a577SJohn Birrell 		updatepri(td);
10468460a577SJohn Birrell 		resetpriority(td);
10478460a577SJohn Birrell 	}
10486eac7e57SAttilio Rao 	td->td_slptick = 0;
104954b0e65fSJeff Roberson 	ts->ts_slptime = 0;
1050f0393f06SJeff Roberson 	sched_add(td, SRQ_BORING);
1051b43179fbSJeff Roberson }
1052b43179fbSJeff Roberson 
105337c28a02SJulian Elischer #ifdef SMP
105482a1dfc1SJulian Elischer static int
105582a1dfc1SJulian Elischer forward_wakeup(int cpunum)
105682a1dfc1SJulian Elischer {
105782a1dfc1SJulian Elischer 	struct pcpu *pc;
1058a38f1f26SAttilio Rao 	cpuset_t dontuse, map, map2;
1059a38f1f26SAttilio Rao 	u_int id, me;
106071a19bdcSAttilio Rao 	int iscpuset;
106182a1dfc1SJulian Elischer 
106282a1dfc1SJulian Elischer 	mtx_assert(&sched_lock, MA_OWNED);
106382a1dfc1SJulian Elischer 
1064ed062c8dSJulian Elischer 	CTR0(KTR_RUNQ, "forward_wakeup()");
106582a1dfc1SJulian Elischer 
106682a1dfc1SJulian Elischer 	if ((!forward_wakeup_enabled) ||
106782a1dfc1SJulian Elischer 	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
106882a1dfc1SJulian Elischer 		return (0);
106982a1dfc1SJulian Elischer 	if (!smp_started || cold || panicstr)
107082a1dfc1SJulian Elischer 		return (0);
107182a1dfc1SJulian Elischer 
107282a1dfc1SJulian Elischer 	forward_wakeups_requested++;
107382a1dfc1SJulian Elischer 
107482a1dfc1SJulian Elischer 	/*
10758aa3d7ffSJohn Baldwin 	 * Check the idle mask we received against what we calculated
10768aa3d7ffSJohn Baldwin 	 * before in the old version.
107782a1dfc1SJulian Elischer 	 */
1078a38f1f26SAttilio Rao 	me = PCPU_GET(cpuid);
10798aa3d7ffSJohn Baldwin 
10808aa3d7ffSJohn Baldwin 	/* Don't bother if we should be doing it ourself. */
1081a38f1f26SAttilio Rao 	if (CPU_ISSET(me, &idle_cpus_mask) &&
1082a38f1f26SAttilio Rao 	    (cpunum == NOCPU || me == cpunum))
108382a1dfc1SJulian Elischer 		return (0);
108482a1dfc1SJulian Elischer 
1085a38f1f26SAttilio Rao 	CPU_SETOF(me, &dontuse);
108671a19bdcSAttilio Rao 	CPU_OR(&dontuse, &stopped_cpus);
108771a19bdcSAttilio Rao 	CPU_OR(&dontuse, &hlt_cpus_mask);
108871a19bdcSAttilio Rao 	CPU_ZERO(&map2);
108982a1dfc1SJulian Elischer 	if (forward_wakeup_use_loop) {
1090d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1091a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1092a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &dontuse) &&
109382a1dfc1SJulian Elischer 			    pc->pc_curthread == pc->pc_idlethread) {
1094a38f1f26SAttilio Rao 				CPU_SET(id, &map2);
109582a1dfc1SJulian Elischer 			}
109682a1dfc1SJulian Elischer 		}
109782a1dfc1SJulian Elischer 	}
109882a1dfc1SJulian Elischer 
109982a1dfc1SJulian Elischer 	if (forward_wakeup_use_mask) {
110071a19bdcSAttilio Rao 		map = idle_cpus_mask;
110171a19bdcSAttilio Rao 		CPU_NAND(&map, &dontuse);
110282a1dfc1SJulian Elischer 
11038aa3d7ffSJohn Baldwin 		/* If they are both on, compare and use loop if different. */
110482a1dfc1SJulian Elischer 		if (forward_wakeup_use_loop) {
110571a19bdcSAttilio Rao 			if (CPU_CMP(&map, &map2)) {
1106f0283a73SAttilio Rao 				printf("map != map2, loop method preferred\n");
1107f0283a73SAttilio Rao 				map = map2;
110882a1dfc1SJulian Elischer 			}
110982a1dfc1SJulian Elischer 		}
111082a1dfc1SJulian Elischer 	} else {
1111f0283a73SAttilio Rao 		map = map2;
111282a1dfc1SJulian Elischer 	}
11138aa3d7ffSJohn Baldwin 
11148aa3d7ffSJohn Baldwin 	/* If we only allow a specific CPU, then mask off all the others. */
111582a1dfc1SJulian Elischer 	if (cpunum != NOCPU) {
111682a1dfc1SJulian Elischer 		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
111771a19bdcSAttilio Rao 		iscpuset = CPU_ISSET(cpunum, &map);
111871a19bdcSAttilio Rao 		if (iscpuset == 0)
111971a19bdcSAttilio Rao 			CPU_ZERO(&map);
112071a19bdcSAttilio Rao 		else
112171a19bdcSAttilio Rao 			CPU_SETOF(cpunum, &map);
112282a1dfc1SJulian Elischer 	}
112371a19bdcSAttilio Rao 	if (!CPU_EMPTY(&map)) {
112482a1dfc1SJulian Elischer 		forward_wakeups_delivered++;
1125d098f930SNathan Whitehorn 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1126a38f1f26SAttilio Rao 			id = pc->pc_cpuid;
1127a38f1f26SAttilio Rao 			if (!CPU_ISSET(id, &map))
1128b722ad00SAlexander Motin 				continue;
1129b722ad00SAlexander Motin 			if (cpu_idle_wakeup(pc->pc_cpuid))
1130a38f1f26SAttilio Rao 				CPU_CLR(id, &map);
1131b722ad00SAlexander Motin 		}
113271a19bdcSAttilio Rao 		if (!CPU_EMPTY(&map))
113382a1dfc1SJulian Elischer 			ipi_selected(map, IPI_AST);
113482a1dfc1SJulian Elischer 		return (1);
113582a1dfc1SJulian Elischer 	}
113682a1dfc1SJulian Elischer 	if (cpunum == NOCPU)
113782a1dfc1SJulian Elischer 		printf("forward_wakeup: Idle processor not found\n");
113882a1dfc1SJulian Elischer 	return (0);
113982a1dfc1SJulian Elischer }
1140f3a0f873SStephan Uphoff 
1141f3a0f873SStephan Uphoff static void
1142f3a0f873SStephan Uphoff kick_other_cpu(int pri, int cpuid)
1143f3a0f873SStephan Uphoff {
11448aa3d7ffSJohn Baldwin 	struct pcpu *pcpu;
11458aa3d7ffSJohn Baldwin 	int cpri;
1146f3a0f873SStephan Uphoff 
11478aa3d7ffSJohn Baldwin 	pcpu = pcpu_find(cpuid);
1148a38f1f26SAttilio Rao 	if (CPU_ISSET(cpuid, &idle_cpus_mask)) {
1149f3a0f873SStephan Uphoff 		forward_wakeups_delivered++;
1150b722ad00SAlexander Motin 		if (!cpu_idle_wakeup(cpuid))
1151d9d8d144SJohn Baldwin 			ipi_cpu(cpuid, IPI_AST);
1152f3a0f873SStephan Uphoff 		return;
1153f3a0f873SStephan Uphoff 	}
1154f3a0f873SStephan Uphoff 
11558aa3d7ffSJohn Baldwin 	cpri = pcpu->pc_curthread->td_priority;
1156f3a0f873SStephan Uphoff 	if (pri >= cpri)
1157f3a0f873SStephan Uphoff 		return;
1158f3a0f873SStephan Uphoff 
1159f3a0f873SStephan Uphoff #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1160f3a0f873SStephan Uphoff #if !defined(FULL_PREEMPTION)
1161f3a0f873SStephan Uphoff 	if (pri <= PRI_MAX_ITHD)
1162f3a0f873SStephan Uphoff #endif /* ! FULL_PREEMPTION */
1163f3a0f873SStephan Uphoff 	{
1164d9d8d144SJohn Baldwin 		ipi_cpu(cpuid, IPI_PREEMPT);
1165f3a0f873SStephan Uphoff 		return;
1166f3a0f873SStephan Uphoff 	}
1167f3a0f873SStephan Uphoff #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1168f3a0f873SStephan Uphoff 
1169f3a0f873SStephan Uphoff 	pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1170d9d8d144SJohn Baldwin 	ipi_cpu(cpuid, IPI_AST);
1171f3a0f873SStephan Uphoff 	return;
1172f3a0f873SStephan Uphoff }
1173f3a0f873SStephan Uphoff #endif /* SMP */
1174f3a0f873SStephan Uphoff 
1175f200843bSJohn Baldwin #ifdef SMP
1176f200843bSJohn Baldwin static int
1177f200843bSJohn Baldwin sched_pickcpu(struct thread *td)
1178f200843bSJohn Baldwin {
1179f200843bSJohn Baldwin 	int best, cpu;
1180f200843bSJohn Baldwin 
1181f200843bSJohn Baldwin 	mtx_assert(&sched_lock, MA_OWNED);
1182f200843bSJohn Baldwin 
1183c3ea3378SJohn Baldwin 	if (THREAD_CAN_SCHED(td, td->td_lastcpu))
1184c3ea3378SJohn Baldwin 		best = td->td_lastcpu;
1185c3ea3378SJohn Baldwin 	else
1186f200843bSJohn Baldwin 		best = NOCPU;
11873aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1188f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu))
1189f200843bSJohn Baldwin 			continue;
1190f200843bSJohn Baldwin 
1191f200843bSJohn Baldwin 		if (best == NOCPU)
1192f200843bSJohn Baldwin 			best = cpu;
1193f200843bSJohn Baldwin 		else if (runq_length[cpu] < runq_length[best])
1194f200843bSJohn Baldwin 			best = cpu;
1195f200843bSJohn Baldwin 	}
1196f200843bSJohn Baldwin 	KASSERT(best != NOCPU, ("no valid CPUs"));
1197f200843bSJohn Baldwin 
1198f200843bSJohn Baldwin 	return (best);
1199f200843bSJohn Baldwin }
1200f200843bSJohn Baldwin #endif
1201f200843bSJohn Baldwin 
1202b43179fbSJeff Roberson void
12032630e4c9SJulian Elischer sched_add(struct thread *td, int flags)
12046804a3abSJulian Elischer #ifdef SMP
1205f3a0f873SStephan Uphoff {
1206a38f1f26SAttilio Rao 	cpuset_t tidlemsk;
1207ad1e7d28SJulian Elischer 	struct td_sched *ts;
1208a38f1f26SAttilio Rao 	u_int cpu, cpuid;
12096804a3abSJulian Elischer 	int forwarded = 0;
1210f3a0f873SStephan Uphoff 	int single_cpu = 0;
12117cf90fb3SJeff Roberson 
1212ad1e7d28SJulian Elischer 	ts = td->td_sched;
12137b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1214f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1215f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1216f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1217f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1218b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1219b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
12208f51ad55SJeff Roberson 
12218f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
12228f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
12238f51ad55SJeff Roberson 	    sched_tdname(curthread));
12248f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
12258f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
12268f51ad55SJeff Roberson 
12278aa3d7ffSJohn Baldwin 
12287b20fb19SJeff Roberson 	/*
12297b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
12307b20fb19SJeff Roberson 	 * to the scheduler's lock.
12317b20fb19SJeff Roberson 	 */
12327b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
12337b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
12347b20fb19SJeff Roberson 		thread_lock_set(td, &sched_lock);
12357b20fb19SJeff Roberson 	}
1236f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1237f3a0f873SStephan Uphoff 
123860dd73b7SRyan Stone 	/*
123960dd73b7SRyan Stone 	 * If SMP is started and the thread is pinned or otherwise limited to
124060dd73b7SRyan Stone 	 * a specific set of CPUs, queue the thread to a per-CPU run queue.
124160dd73b7SRyan Stone 	 * Otherwise, queue the thread to the global run queue.
124260dd73b7SRyan Stone 	 *
124360dd73b7SRyan Stone 	 * If SMP has not yet been started we must use the global run queue
124460dd73b7SRyan Stone 	 * as per-CPU state may not be initialized yet and we may crash if we
124560dd73b7SRyan Stone 	 * try to access the per-CPU run queues.
124660dd73b7SRyan Stone 	 */
124760dd73b7SRyan Stone 	if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
124860dd73b7SRyan Stone 	    ts->ts_flags & TSF_AFFINITY)) {
124960dd73b7SRyan Stone 		if (td->td_pinned != 0)
1250f3a0f873SStephan Uphoff 			cpu = td->td_lastcpu;
125160dd73b7SRyan Stone 		else if (td->td_flags & TDF_BOUND) {
12528aa3d7ffSJohn Baldwin 			/* Find CPU from bound runq. */
12538aa3d7ffSJohn Baldwin 			KASSERT(SKE_RUNQ_PCPU(ts),
12548aa3d7ffSJohn Baldwin 			    ("sched_add: bound td_sched not on cpu runq"));
1255ad1e7d28SJulian Elischer 			cpu = ts->ts_runq - &runq_pcpu[0];
125660dd73b7SRyan Stone 		} else
1257f200843bSJohn Baldwin 			/* Find a valid CPU for our cpuset */
1258f200843bSJohn Baldwin 			cpu = sched_pickcpu(td);
1259f200843bSJohn Baldwin 		ts->ts_runq = &runq_pcpu[cpu];
1260f200843bSJohn Baldwin 		single_cpu = 1;
1261f200843bSJohn Baldwin 		CTR3(KTR_RUNQ,
1262f200843bSJohn Baldwin 		    "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1263f200843bSJohn Baldwin 		    cpu);
1264f3a0f873SStephan Uphoff 	} else {
12656804a3abSJulian Elischer 		CTR2(KTR_RUNQ,
12668aa3d7ffSJohn Baldwin 		    "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
12678aa3d7ffSJohn Baldwin 		    td);
12686804a3abSJulian Elischer 		cpu = NOCPU;
1269ad1e7d28SJulian Elischer 		ts->ts_runq = &runq;
1270e17c57b1SJeff Roberson 	}
1271f3a0f873SStephan Uphoff 
1272a38f1f26SAttilio Rao 	cpuid = PCPU_GET(cpuid);
1273a38f1f26SAttilio Rao 	if (single_cpu && cpu != cpuid) {
1274f3a0f873SStephan Uphoff 	        kick_other_cpu(td->td_priority, cpu);
1275f3a0f873SStephan Uphoff 	} else {
1276f3a0f873SStephan Uphoff 		if (!single_cpu) {
1277a38f1f26SAttilio Rao 			tidlemsk = idle_cpus_mask;
1278a38f1f26SAttilio Rao 			CPU_NAND(&tidlemsk, &hlt_cpus_mask);
1279a38f1f26SAttilio Rao 			CPU_CLR(cpuid, &tidlemsk);
1280f3a0f873SStephan Uphoff 
1281a38f1f26SAttilio Rao 			if (!CPU_ISSET(cpuid, &idle_cpus_mask) &&
1282a38f1f26SAttilio Rao 			    ((flags & SRQ_INTR) == 0) &&
128371a19bdcSAttilio Rao 			    !CPU_EMPTY(&tidlemsk))
1284f3a0f873SStephan Uphoff 				forwarded = forward_wakeup(cpu);
1285f3a0f873SStephan Uphoff 		}
1286f3a0f873SStephan Uphoff 
1287f3a0f873SStephan Uphoff 		if (!forwarded) {
1288a3f2d842SStephan Uphoff 			if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1289f3a0f873SStephan Uphoff 				return;
1290f3a0f873SStephan Uphoff 			else
1291f3a0f873SStephan Uphoff 				maybe_resched(td);
1292f3a0f873SStephan Uphoff 		}
1293f3a0f873SStephan Uphoff 	}
1294f3a0f873SStephan Uphoff 
12951b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1296f3a0f873SStephan Uphoff 		sched_load_add();
12979727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
1298f200843bSJohn Baldwin 	if (cpu != NOCPU)
1299f200843bSJohn Baldwin 		runq_length[cpu]++;
1300f3a0f873SStephan Uphoff }
1301f3a0f873SStephan Uphoff #else /* SMP */
1302f3a0f873SStephan Uphoff {
1303ad1e7d28SJulian Elischer 	struct td_sched *ts;
1304f200843bSJohn Baldwin 
1305ad1e7d28SJulian Elischer 	ts = td->td_sched;
13067b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1307f0393f06SJeff Roberson 	KASSERT((td->td_inhibitors == 0),
1308f0393f06SJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
1309f0393f06SJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1310f0393f06SJeff Roberson 	    ("sched_add: bad thread state"));
1311b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1312b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
13138f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
13148f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
13158f51ad55SJeff Roberson 	    sched_tdname(curthread));
13168f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
13178f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
13188aa3d7ffSJohn Baldwin 
13197b20fb19SJeff Roberson 	/*
13207b20fb19SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
13217b20fb19SJeff Roberson 	 * to the scheduler's lock.
13227b20fb19SJeff Roberson 	 */
13237b20fb19SJeff Roberson 	if (td->td_lock != &sched_lock) {
13247b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
13257b20fb19SJeff Roberson 		thread_lock_set(td, &sched_lock);
13267b20fb19SJeff Roberson 	}
1327f0393f06SJeff Roberson 	TD_SET_RUNQ(td);
1328ad1e7d28SJulian Elischer 	CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1329ad1e7d28SJulian Elischer 	ts->ts_runq = &runq;
13306804a3abSJulian Elischer 
13316804a3abSJulian Elischer 	/*
13328aa3d7ffSJohn Baldwin 	 * If we are yielding (on the way out anyhow) or the thread
13338aa3d7ffSJohn Baldwin 	 * being saved is US, then don't try be smart about preemption
13348aa3d7ffSJohn Baldwin 	 * or kicking off another CPU as it won't help and may hinder.
13358aa3d7ffSJohn Baldwin 	 * In the YIEDLING case, we are about to run whoever is being
13368aa3d7ffSJohn Baldwin 	 * put in the queue anyhow, and in the OURSELF case, we are
13378aa3d7ffSJohn Baldwin 	 * puting ourself on the run queue which also only happens
13388aa3d7ffSJohn Baldwin 	 * when we are about to yield.
13396804a3abSJulian Elischer 	 */
13406804a3abSJulian Elischer 	if ((flags & SRQ_YIELDING) == 0) {
13416804a3abSJulian Elischer 		if (maybe_preempt(td))
13426804a3abSJulian Elischer 			return;
13436804a3abSJulian Elischer 	}
13441b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1345907bdbc2SJeff Roberson 		sched_load_add();
13469727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
13476942d433SJohn Baldwin 	maybe_resched(td);
1348b43179fbSJeff Roberson }
1349f3a0f873SStephan Uphoff #endif /* SMP */
1350f3a0f873SStephan Uphoff 
1351b43179fbSJeff Roberson void
13527cf90fb3SJeff Roberson sched_rem(struct thread *td)
1353b43179fbSJeff Roberson {
1354ad1e7d28SJulian Elischer 	struct td_sched *ts;
13557cf90fb3SJeff Roberson 
1356ad1e7d28SJulian Elischer 	ts = td->td_sched;
1357b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
1358b61ce5b0SJeff Roberson 	    ("sched_rem: thread swapped out"));
1359f0393f06SJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
1360ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
1361b43179fbSJeff Roberson 	mtx_assert(&sched_lock, MA_OWNED);
13628f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
13638f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
13648f51ad55SJeff Roberson 	    sched_tdname(curthread));
1365b43179fbSJeff Roberson 
13661b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
1367907bdbc2SJeff Roberson 		sched_load_rem();
1368f200843bSJohn Baldwin #ifdef SMP
1369f200843bSJohn Baldwin 	if (ts->ts_runq != &runq)
1370f200843bSJohn Baldwin 		runq_length[ts->ts_runq - runq_pcpu]--;
1371f200843bSJohn Baldwin #endif
13729727e637SJeff Roberson 	runq_remove(ts->ts_runq, td);
1373f0393f06SJeff Roberson 	TD_SET_CAN_RUN(td);
1374b43179fbSJeff Roberson }
1375b43179fbSJeff Roberson 
137614f0e2e9SJulian Elischer /*
13778aa3d7ffSJohn Baldwin  * Select threads to run.  Note that running threads still consume a
13788aa3d7ffSJohn Baldwin  * slot.
137914f0e2e9SJulian Elischer  */
1380f0393f06SJeff Roberson struct thread *
1381b43179fbSJeff Roberson sched_choose(void)
1382b43179fbSJeff Roberson {
13839727e637SJeff Roberson 	struct thread *td;
1384e17c57b1SJeff Roberson 	struct runq *rq;
1385b43179fbSJeff Roberson 
13867b20fb19SJeff Roberson 	mtx_assert(&sched_lock,  MA_OWNED);
1387e17c57b1SJeff Roberson #ifdef SMP
13889727e637SJeff Roberson 	struct thread *tdcpu;
1389e17c57b1SJeff Roberson 
1390e17c57b1SJeff Roberson 	rq = &runq;
13919727e637SJeff Roberson 	td = runq_choose_fuzz(&runq, runq_fuzz);
13929727e637SJeff Roberson 	tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1393e17c57b1SJeff Roberson 
13949727e637SJeff Roberson 	if (td == NULL ||
13959727e637SJeff Roberson 	    (tdcpu != NULL &&
13969727e637SJeff Roberson 	     tdcpu->td_priority < td->td_priority)) {
13979727e637SJeff Roberson 		CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1398e17c57b1SJeff Roberson 		     PCPU_GET(cpuid));
13999727e637SJeff Roberson 		td = tdcpu;
1400e17c57b1SJeff Roberson 		rq = &runq_pcpu[PCPU_GET(cpuid)];
1401e17c57b1SJeff Roberson 	} else {
14029727e637SJeff Roberson 		CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1403e17c57b1SJeff Roberson 	}
1404e17c57b1SJeff Roberson 
1405e17c57b1SJeff Roberson #else
1406e17c57b1SJeff Roberson 	rq = &runq;
14079727e637SJeff Roberson 	td = runq_choose(&runq);
1408e17c57b1SJeff Roberson #endif
1409b43179fbSJeff Roberson 
14109727e637SJeff Roberson 	if (td) {
1411f200843bSJohn Baldwin #ifdef SMP
1412f200843bSJohn Baldwin 		if (td == tdcpu)
1413f200843bSJohn Baldwin 			runq_length[PCPU_GET(cpuid)]--;
1414f200843bSJohn Baldwin #endif
14159727e637SJeff Roberson 		runq_remove(rq, td);
14169727e637SJeff Roberson 		td->td_flags |= TDF_DIDRUN;
1417b43179fbSJeff Roberson 
14189727e637SJeff Roberson 		KASSERT(td->td_flags & TDF_INMEM,
1419b61ce5b0SJeff Roberson 		    ("sched_choose: thread swapped out"));
14209727e637SJeff Roberson 		return (td);
1421b43179fbSJeff Roberson 	}
1422f0393f06SJeff Roberson 	return (PCPU_GET(idlethread));
1423b43179fbSJeff Roberson }
1424b43179fbSJeff Roberson 
1425b43179fbSJeff Roberson void
14261e24c28fSJeff Roberson sched_preempt(struct thread *td)
14271e24c28fSJeff Roberson {
14281e24c28fSJeff Roberson 	thread_lock(td);
14291e24c28fSJeff Roberson 	if (td->td_critnest > 1)
14301e24c28fSJeff Roberson 		td->td_owepreempt = 1;
14311e24c28fSJeff Roberson 	else
14328df78c41SJeff Roberson 		mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, NULL);
14331e24c28fSJeff Roberson 	thread_unlock(td);
14341e24c28fSJeff Roberson }
14351e24c28fSJeff Roberson 
14361e24c28fSJeff Roberson void
1437b43179fbSJeff Roberson sched_userret(struct thread *td)
1438b43179fbSJeff Roberson {
1439b43179fbSJeff Roberson 	/*
1440b43179fbSJeff Roberson 	 * XXX we cheat slightly on the locking here to avoid locking in
1441b43179fbSJeff Roberson 	 * the usual case.  Setting td_priority here is essentially an
1442b43179fbSJeff Roberson 	 * incomplete workaround for not setting it properly elsewhere.
1443b43179fbSJeff Roberson 	 * Now that some interrupt handlers are threads, not setting it
1444b43179fbSJeff Roberson 	 * properly elsewhere can clobber it in the window between setting
1445b43179fbSJeff Roberson 	 * it here and returning to user mode, so don't waste time setting
1446b43179fbSJeff Roberson 	 * it perfectly here.
1447b43179fbSJeff Roberson 	 */
1448f5c157d9SJohn Baldwin 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
1449f5c157d9SJohn Baldwin 	    ("thread with borrowed priority returning to userland"));
14508460a577SJohn Birrell 	if (td->td_priority != td->td_user_pri) {
14517b20fb19SJeff Roberson 		thread_lock(td);
14528460a577SJohn Birrell 		td->td_priority = td->td_user_pri;
14538460a577SJohn Birrell 		td->td_base_pri = td->td_user_pri;
14547b20fb19SJeff Roberson 		thread_unlock(td);
14558460a577SJohn Birrell 	}
1456b43179fbSJeff Roberson }
1457de028f5aSJeff Roberson 
1458e17c57b1SJeff Roberson void
1459e17c57b1SJeff Roberson sched_bind(struct thread *td, int cpu)
1460e17c57b1SJeff Roberson {
1461ad1e7d28SJulian Elischer 	struct td_sched *ts;
1462e17c57b1SJeff Roberson 
14631d7830edSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
14641d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1465e17c57b1SJeff Roberson 
1466ad1e7d28SJulian Elischer 	ts = td->td_sched;
1467e17c57b1SJeff Roberson 
14689727e637SJeff Roberson 	td->td_flags |= TDF_BOUND;
1469e17c57b1SJeff Roberson #ifdef SMP
1470ad1e7d28SJulian Elischer 	ts->ts_runq = &runq_pcpu[cpu];
1471e17c57b1SJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
1472e17c57b1SJeff Roberson 		return;
1473e17c57b1SJeff Roberson 
1474bf0acc27SJohn Baldwin 	mi_switch(SW_VOL, NULL);
1475e17c57b1SJeff Roberson #endif
1476e17c57b1SJeff Roberson }
1477e17c57b1SJeff Roberson 
1478e17c57b1SJeff Roberson void
1479e17c57b1SJeff Roberson sched_unbind(struct thread* td)
1480e17c57b1SJeff Roberson {
14817b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
14821d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
14839727e637SJeff Roberson 	td->td_flags &= ~TDF_BOUND;
1484e17c57b1SJeff Roberson }
1485e17c57b1SJeff Roberson 
1486de028f5aSJeff Roberson int
1487ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
1488ebccf1e3SJoseph Koshy {
14897b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
14909727e637SJeff Roberson 	return (td->td_flags & TDF_BOUND);
1491ebccf1e3SJoseph Koshy }
1492ebccf1e3SJoseph Koshy 
149336ec198bSDavid Xu void
149436ec198bSDavid Xu sched_relinquish(struct thread *td)
149536ec198bSDavid Xu {
14967b20fb19SJeff Roberson 	thread_lock(td);
14978df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
14987b20fb19SJeff Roberson 	thread_unlock(td);
149936ec198bSDavid Xu }
150036ec198bSDavid Xu 
1501ebccf1e3SJoseph Koshy int
1502ca59f152SJeff Roberson sched_load(void)
1503ca59f152SJeff Roberson {
1504ca59f152SJeff Roberson 	return (sched_tdcnt);
1505ca59f152SJeff Roberson }
1506ca59f152SJeff Roberson 
1507de028f5aSJeff Roberson int
1508de028f5aSJeff Roberson sched_sizeof_proc(void)
1509de028f5aSJeff Roberson {
1510de028f5aSJeff Roberson 	return (sizeof(struct proc));
1511de028f5aSJeff Roberson }
151236ec198bSDavid Xu 
1513de028f5aSJeff Roberson int
1514de028f5aSJeff Roberson sched_sizeof_thread(void)
1515de028f5aSJeff Roberson {
1516ad1e7d28SJulian Elischer 	return (sizeof(struct thread) + sizeof(struct td_sched));
1517de028f5aSJeff Roberson }
151879acfc49SJeff Roberson 
151979acfc49SJeff Roberson fixpt_t
15207cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
152179acfc49SJeff Roberson {
1522ad1e7d28SJulian Elischer 	struct td_sched *ts;
152355f2099aSJeff Roberson 
15243da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1525ad1e7d28SJulian Elischer 	ts = td->td_sched;
1526ad1e7d28SJulian Elischer 	return (ts->ts_pctcpu);
152779acfc49SJeff Roberson }
1528b41f1452SDavid Xu 
1529b41f1452SDavid Xu void
1530a157e425SAlexander Motin sched_tick(int cnt)
1531b41f1452SDavid Xu {
1532b41f1452SDavid Xu }
1533f0393f06SJeff Roberson 
1534f0393f06SJeff Roberson /*
1535f0393f06SJeff Roberson  * The actual idle process.
1536f0393f06SJeff Roberson  */
1537f0393f06SJeff Roberson void
1538f0393f06SJeff Roberson sched_idletd(void *dummy)
1539f0393f06SJeff Roberson {
1540b722ad00SAlexander Motin 	struct pcpuidlestat *stat;
1541f0393f06SJeff Roberson 
1542b722ad00SAlexander Motin 	stat = DPCPU_PTR(idlestat);
1543f0393f06SJeff Roberson 	for (;;) {
1544f0393f06SJeff Roberson 		mtx_assert(&Giant, MA_NOTOWNED);
1545f0393f06SJeff Roberson 
1546b722ad00SAlexander Motin 		while (sched_runnable() == 0) {
1547b722ad00SAlexander Motin 			cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1548b722ad00SAlexander Motin 			stat->idlecalls++;
1549b722ad00SAlexander Motin 		}
1550f0393f06SJeff Roberson 
1551f0393f06SJeff Roberson 		mtx_lock_spin(&sched_lock);
15528df78c41SJeff Roberson 		mi_switch(SW_VOL | SWT_IDLE, NULL);
1553f0393f06SJeff Roberson 		mtx_unlock_spin(&sched_lock);
1554f0393f06SJeff Roberson 	}
1555f0393f06SJeff Roberson }
1556f0393f06SJeff Roberson 
15577b20fb19SJeff Roberson /*
15587b20fb19SJeff Roberson  * A CPU is entering for the first time or a thread is exiting.
15597b20fb19SJeff Roberson  */
15607b20fb19SJeff Roberson void
15617b20fb19SJeff Roberson sched_throw(struct thread *td)
15627b20fb19SJeff Roberson {
15637b20fb19SJeff Roberson 	/*
15647b20fb19SJeff Roberson 	 * Correct spinlock nesting.  The idle thread context that we are
15657b20fb19SJeff Roberson 	 * borrowing was created so that it would start out with a single
15667b20fb19SJeff Roberson 	 * spin lock (sched_lock) held in fork_trampoline().  Since we've
15677b20fb19SJeff Roberson 	 * explicitly acquired locks in this function, the nesting count
15687b20fb19SJeff Roberson 	 * is now 2 rather than 1.  Since we are nested, calling
15697b20fb19SJeff Roberson 	 * spinlock_exit() will simply adjust the counts without allowing
15707b20fb19SJeff Roberson 	 * spin lock using code to interrupt us.
15717b20fb19SJeff Roberson 	 */
15727b20fb19SJeff Roberson 	if (td == NULL) {
15737b20fb19SJeff Roberson 		mtx_lock_spin(&sched_lock);
15747b20fb19SJeff Roberson 		spinlock_exit();
15757b20fb19SJeff Roberson 	} else {
1576eea4f254SJeff Roberson 		lock_profile_release_lock(&sched_lock.lock_object);
15777b20fb19SJeff Roberson 		MPASS(td->td_lock == &sched_lock);
15787b20fb19SJeff Roberson 	}
15797b20fb19SJeff Roberson 	mtx_assert(&sched_lock, MA_OWNED);
15807b20fb19SJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
15817b20fb19SJeff Roberson 	PCPU_SET(switchtime, cpu_ticks());
15827b20fb19SJeff Roberson 	PCPU_SET(switchticks, ticks);
15837b20fb19SJeff Roberson 	cpu_throw(td, choosethread());	/* doesn't return */
15847b20fb19SJeff Roberson }
15857b20fb19SJeff Roberson 
15867b20fb19SJeff Roberson void
1587fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
15887b20fb19SJeff Roberson {
15897b20fb19SJeff Roberson 
15907b20fb19SJeff Roberson 	/*
15917b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
15927b20fb19SJeff Roberson 	 * non-nested critical section with sched_lock held but not recursed.
15937b20fb19SJeff Roberson 	 */
1594fe54587fSJeff Roberson 	td->td_oncpu = PCPU_GET(cpuid);
1595fe54587fSJeff Roberson 	sched_lock.mtx_lock = (uintptr_t)td;
1596eea4f254SJeff Roberson 	lock_profile_obtain_lock_success(&sched_lock.lock_object,
1597eea4f254SJeff Roberson 	    0, 0, __FILE__, __LINE__);
1598fe54587fSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
15997b20fb19SJeff Roberson }
16007b20fb19SJeff Roberson 
16018f51ad55SJeff Roberson char *
16028f51ad55SJeff Roberson sched_tdname(struct thread *td)
16038f51ad55SJeff Roberson {
16048f51ad55SJeff Roberson #ifdef KTR
16058f51ad55SJeff Roberson 	struct td_sched *ts;
16068f51ad55SJeff Roberson 
16078f51ad55SJeff Roberson 	ts = td->td_sched;
16088f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
16098f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
16108f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
16118f51ad55SJeff Roberson 	return (ts->ts_name);
16128f51ad55SJeff Roberson #else
16138f51ad55SJeff Roberson 	return (td->td_name);
16148f51ad55SJeff Roberson #endif
16158f51ad55SJeff Roberson }
16168f51ad55SJeff Roberson 
1617885d51a3SJeff Roberson void
1618885d51a3SJeff Roberson sched_affinity(struct thread *td)
1619885d51a3SJeff Roberson {
1620f200843bSJohn Baldwin #ifdef SMP
1621f200843bSJohn Baldwin 	struct td_sched *ts;
1622f200843bSJohn Baldwin 	int cpu;
1623f200843bSJohn Baldwin 
1624f200843bSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1625f200843bSJohn Baldwin 
1626f200843bSJohn Baldwin 	/*
1627f200843bSJohn Baldwin 	 * Set the TSF_AFFINITY flag if there is at least one CPU this
1628f200843bSJohn Baldwin 	 * thread can't run on.
1629f200843bSJohn Baldwin 	 */
1630f200843bSJohn Baldwin 	ts = td->td_sched;
1631f200843bSJohn Baldwin 	ts->ts_flags &= ~TSF_AFFINITY;
16323aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
1633f200843bSJohn Baldwin 		if (!THREAD_CAN_SCHED(td, cpu)) {
1634f200843bSJohn Baldwin 			ts->ts_flags |= TSF_AFFINITY;
1635f200843bSJohn Baldwin 			break;
1636f200843bSJohn Baldwin 		}
1637f200843bSJohn Baldwin 	}
1638f200843bSJohn Baldwin 
1639f200843bSJohn Baldwin 	/*
1640f200843bSJohn Baldwin 	 * If this thread can run on all CPUs, nothing else to do.
1641f200843bSJohn Baldwin 	 */
1642f200843bSJohn Baldwin 	if (!(ts->ts_flags & TSF_AFFINITY))
1643f200843bSJohn Baldwin 		return;
1644f200843bSJohn Baldwin 
1645f200843bSJohn Baldwin 	/* Pinned threads and bound threads should be left alone. */
1646f200843bSJohn Baldwin 	if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1647f200843bSJohn Baldwin 		return;
1648f200843bSJohn Baldwin 
1649f200843bSJohn Baldwin 	switch (td->td_state) {
1650f200843bSJohn Baldwin 	case TDS_RUNQ:
1651f200843bSJohn Baldwin 		/*
1652f200843bSJohn Baldwin 		 * If we are on a per-CPU runqueue that is in the set,
1653f200843bSJohn Baldwin 		 * then nothing needs to be done.
1654f200843bSJohn Baldwin 		 */
1655f200843bSJohn Baldwin 		if (ts->ts_runq != &runq &&
1656f200843bSJohn Baldwin 		    THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1657f200843bSJohn Baldwin 			return;
1658f200843bSJohn Baldwin 
1659f200843bSJohn Baldwin 		/* Put this thread on a valid per-CPU runqueue. */
1660f200843bSJohn Baldwin 		sched_rem(td);
1661f200843bSJohn Baldwin 		sched_add(td, SRQ_BORING);
1662f200843bSJohn Baldwin 		break;
1663f200843bSJohn Baldwin 	case TDS_RUNNING:
1664f200843bSJohn Baldwin 		/*
1665f200843bSJohn Baldwin 		 * See if our current CPU is in the set.  If not, force a
1666f200843bSJohn Baldwin 		 * context switch.
1667f200843bSJohn Baldwin 		 */
1668f200843bSJohn Baldwin 		if (THREAD_CAN_SCHED(td, td->td_oncpu))
1669f200843bSJohn Baldwin 			return;
1670f200843bSJohn Baldwin 
1671f200843bSJohn Baldwin 		td->td_flags |= TDF_NEEDRESCHED;
1672f200843bSJohn Baldwin 		if (td != curthread)
1673d9d8d144SJohn Baldwin 			ipi_cpu(cpu, IPI_AST);
1674f200843bSJohn Baldwin 		break;
1675f200843bSJohn Baldwin 	default:
1676f200843bSJohn Baldwin 		break;
1677f200843bSJohn Baldwin 	}
1678f200843bSJohn Baldwin #endif
1679885d51a3SJeff Roberson }
1680