sched_4bsd.c revision 145109
1104964Sjeff/*-
2104964Sjeff * Copyright (c) 1982, 1986, 1990, 1991, 1993
3104964Sjeff *	The Regents of the University of California.  All rights reserved.
4104964Sjeff * (c) UNIX System Laboratories, Inc.
5104964Sjeff * All or some portions of this file are derived from material licensed
6104964Sjeff * to the University of California by American Telephone and Telegraph
7104964Sjeff * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8104964Sjeff * the permission of UNIX System Laboratories, Inc.
9104964Sjeff *
10104964Sjeff * Redistribution and use in source and binary forms, with or without
11104964Sjeff * modification, are permitted provided that the following conditions
12104964Sjeff * are met:
13104964Sjeff * 1. Redistributions of source code must retain the above copyright
14104964Sjeff *    notice, this list of conditions and the following disclaimer.
15104964Sjeff * 2. Redistributions in binary form must reproduce the above copyright
16104964Sjeff *    notice, this list of conditions and the following disclaimer in the
17104964Sjeff *    documentation and/or other materials provided with the distribution.
18104964Sjeff * 4. Neither the name of the University nor the names of its contributors
19104964Sjeff *    may be used to endorse or promote products derived from this software
20104964Sjeff *    without specific prior written permission.
21104964Sjeff *
22104964Sjeff * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23104964Sjeff * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24104964Sjeff * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25104964Sjeff * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26104964Sjeff * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27104964Sjeff * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28104964Sjeff * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29104964Sjeff * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30104964Sjeff * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31104964Sjeff * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32104964Sjeff * SUCH DAMAGE.
33104964Sjeff */
34104964Sjeff
35116182Sobrien#include <sys/cdefs.h>
36116182Sobrien__FBSDID("$FreeBSD: head/sys/kern/sched_4bsd.c 145109 2005-04-15 14:01:43Z maxim $");
37116182Sobrien
38134791Sjulian#define kse td_sched
39134791Sjulian
40104964Sjeff#include <sys/param.h>
41104964Sjeff#include <sys/systm.h>
42104964Sjeff#include <sys/kernel.h>
43104964Sjeff#include <sys/ktr.h>
44104964Sjeff#include <sys/lock.h>
45123871Sjhb#include <sys/kthread.h>
46104964Sjeff#include <sys/mutex.h>
47104964Sjeff#include <sys/proc.h>
48104964Sjeff#include <sys/resourcevar.h>
49104964Sjeff#include <sys/sched.h>
50104964Sjeff#include <sys/smp.h>
51104964Sjeff#include <sys/sysctl.h>
52104964Sjeff#include <sys/sx.h>
53139453Sjhb#include <sys/turnstile.h>
54134689Sjulian#include <machine/smp.h>
55104964Sjeff
56107135Sjeff/*
57107135Sjeff * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
58107135Sjeff * the range 100-256 Hz (approximately).
59107135Sjeff */
60107135Sjeff#define	ESTCPULIM(e) \
61107135Sjeff    min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
62107135Sjeff    RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
63122355Sbde#ifdef SMP
64122355Sbde#define	INVERSE_ESTCPU_WEIGHT	(8 * smp_cpus)
65122355Sbde#else
66107135Sjeff#define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
67122355Sbde#endif
68107135Sjeff#define	NICE_WEIGHT		1	/* Priorities per nice level. */
69107135Sjeff
70134791Sjulian/*
71134791Sjulian * The schedulable entity that can be given a context to run.
72134791Sjulian * A process may have several of these. Probably one per processor
73134791Sjulian * but posibly a few more. In this universe they are grouped
74134791Sjulian * with a KSEG that contains the priority and niceness
75134791Sjulian * for the group.
76134791Sjulian */
77134791Sjulianstruct kse {
78134791Sjulian	TAILQ_ENTRY(kse) ke_procq;	/* (j/z) Run queue. */
79134791Sjulian	struct thread	*ke_thread;	/* (*) Active associated thread. */
80134791Sjulian	fixpt_t		ke_pctcpu;	/* (j) %cpu during p_swtime. */
81134791Sjulian	char		ke_rqindex;	/* (j) Run queue index. */
82134791Sjulian	enum {
83134791Sjulian		KES_THREAD = 0x0,	/* slaved to thread state */
84134791Sjulian		KES_ONRUNQ
85134791Sjulian	} ke_state;			/* (j) KSE status. */
86134791Sjulian	int		ke_cpticks;	/* (j) Ticks of cpu time. */
87134791Sjulian	struct runq	*ke_runq;	/* runq the kse is currently on */
88109145Sjeff};
89109145Sjeff
90134791Sjulian#define ke_proc		ke_thread->td_proc
91134791Sjulian#define ke_ksegrp	ke_thread->td_ksegrp
92134791Sjulian
93134791Sjulian#define td_kse td_sched
94134791Sjulian
95134791Sjulian/* flags kept in td_flags */
96134791Sjulian#define TDF_DIDRUN	TDF_SCHED0	/* KSE actually ran. */
97134791Sjulian#define TDF_EXIT	TDF_SCHED1	/* KSE is being killed. */
98134791Sjulian#define TDF_BOUND	TDF_SCHED2
99134791Sjulian
100134791Sjulian#define ke_flags	ke_thread->td_flags
101134791Sjulian#define KEF_DIDRUN	TDF_DIDRUN /* KSE actually ran. */
102134791Sjulian#define KEF_EXIT	TDF_EXIT /* KSE is being killed. */
103134791Sjulian#define KEF_BOUND	TDF_BOUND /* stuck to one CPU */
104134791Sjulian
105124955Sjeff#define SKE_RUNQ_PCPU(ke)						\
106124955Sjeff    ((ke)->ke_runq != 0 && (ke)->ke_runq != &runq)
107124955Sjeff
108134791Sjulianstruct kg_sched {
109134791Sjulian	struct thread	*skg_last_assigned; /* (j) Last thread assigned to */
110134791Sjulian					   /* the system scheduler. */
111134791Sjulian	int	skg_avail_opennings;	/* (j) Num KSEs requested in group. */
112134791Sjulian	int	skg_concurrency;	/* (j) Num KSEs requested in group. */
113134791Sjulian};
114134791Sjulian#define kg_last_assigned	kg_sched->skg_last_assigned
115134791Sjulian#define kg_avail_opennings	kg_sched->skg_avail_opennings
116134791Sjulian#define kg_concurrency		kg_sched->skg_concurrency
117134791Sjulian
118136167Sjulian#define SLOT_RELEASE(kg)						\
119136167Sjuliando {									\
120136167Sjulian	kg->kg_avail_opennings++; 					\
121136167Sjulian	CTR3(KTR_RUNQ, "kg %p(%d) Slot released (->%d)",		\
122136167Sjulian	kg,								\
123136167Sjulian	kg->kg_concurrency,						\
124136167Sjulian	 kg->kg_avail_opennings);					\
125136167Sjulian/*	KASSERT((kg->kg_avail_opennings <= kg->kg_concurrency),		\
126136167Sjulian	    ("slots out of whack"));*/					\
127136167Sjulian} while (0)
128136167Sjulian
129136167Sjulian#define SLOT_USE(kg)							\
130136167Sjuliando {									\
131136167Sjulian	kg->kg_avail_opennings--; 					\
132136167Sjulian	CTR3(KTR_RUNQ, "kg %p(%d) Slot used (->%d)",			\
133136167Sjulian	kg,								\
134136167Sjulian	kg->kg_concurrency,						\
135136167Sjulian	 kg->kg_avail_opennings);					\
136136167Sjulian/*	KASSERT((kg->kg_avail_opennings >= 0),				\
137136167Sjulian	    ("slots out of whack"));*/					\
138136167Sjulian} while (0)
139136167Sjulian
140124955Sjeff/*
141124955Sjeff * KSE_CAN_MIGRATE macro returns true if the kse can migrate between
142125295Sjeff * cpus.
143124955Sjeff */
144124955Sjeff#define KSE_CAN_MIGRATE(ke)						\
145135076Sscottl    ((ke)->ke_thread->td_pinned == 0 && ((ke)->ke_flags & KEF_BOUND) == 0)
146109145Sjeff
147134791Sjulianstatic struct kse kse0;
148134791Sjulianstatic struct kg_sched kg_sched0;
149104964Sjeff
150125288Sjeffstatic int	sched_tdcnt;	/* Total runnable threads in the system. */
151104964Sjeffstatic int	sched_quantum;	/* Roundrobin scheduling quantum in ticks. */
152112535Smux#define	SCHED_QUANTUM	(hz / 10)	/* Default sched quantum */
153104964Sjeff
154104964Sjeffstatic struct callout roundrobin_callout;
155104964Sjeff
156134791Sjulianstatic void	slot_fill(struct ksegrp *kg);
157134791Sjulianstatic struct kse *sched_choose(void);		/* XXX Should be thread * */
158134791Sjulian
159124955Sjeffstatic void	setup_runqs(void);
160104964Sjeffstatic void	roundrobin(void *arg);
161123871Sjhbstatic void	schedcpu(void);
162124955Sjeffstatic void	schedcpu_thread(void);
163139453Sjhbstatic void	sched_priority(struct thread *td, u_char prio);
164104964Sjeffstatic void	sched_setup(void *dummy);
165104964Sjeffstatic void	maybe_resched(struct thread *td);
166104964Sjeffstatic void	updatepri(struct ksegrp *kg);
167104964Sjeffstatic void	resetpriority(struct ksegrp *kg);
168139453Sjhbstatic void	resetpriority_thread(struct thread *td, struct ksegrp *kg);
169134694Sjulian#ifdef SMP
170134688Sjulianstatic int	forward_wakeup(int  cpunum);
171134694Sjulian#endif
172104964Sjeff
173124955Sjeffstatic struct kproc_desc sched_kp = {
174124955Sjeff        "schedcpu",
175124955Sjeff        schedcpu_thread,
176124955Sjeff        NULL
177124955Sjeff};
178124955SjeffSYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start, &sched_kp)
179124955SjeffSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
180104964Sjeff
181104964Sjeff/*
182104964Sjeff * Global run queue.
183104964Sjeff */
184104964Sjeffstatic struct runq runq;
185104964Sjeff
186124955Sjeff#ifdef SMP
187124955Sjeff/*
188124955Sjeff * Per-CPU run queues
189124955Sjeff */
190124955Sjeffstatic struct runq runq_pcpu[MAXCPU];
191124955Sjeff#endif
192124955Sjeff
193124955Sjeffstatic void
194124955Sjeffsetup_runqs(void)
195124955Sjeff{
196124955Sjeff#ifdef SMP
197124955Sjeff	int i;
198124955Sjeff
199124955Sjeff	for (i = 0; i < MAXCPU; ++i)
200124955Sjeff		runq_init(&runq_pcpu[i]);
201124955Sjeff#endif
202124955Sjeff
203124955Sjeff	runq_init(&runq);
204124955Sjeff}
205124955Sjeff
206104964Sjeffstatic int
207104964Sjeffsysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
208104964Sjeff{
209104964Sjeff	int error, new_val;
210104964Sjeff
211104964Sjeff	new_val = sched_quantum * tick;
212104964Sjeff	error = sysctl_handle_int(oidp, &new_val, 0, req);
213104964Sjeff        if (error != 0 || req->newptr == NULL)
214104964Sjeff		return (error);
215104964Sjeff	if (new_val < tick)
216104964Sjeff		return (EINVAL);
217104964Sjeff	sched_quantum = new_val / tick;
218104964Sjeff	hogticks = 2 * sched_quantum;
219104964Sjeff	return (0);
220104964Sjeff}
221104964Sjeff
222132589SscottlSYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
223130881Sscottl
224132589SscottlSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
225132589Sscottl    "Scheduler name");
226130881Sscottl
227132589SscottlSYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
228132589Sscottl    0, sizeof sched_quantum, sysctl_kern_quantum, "I",
229132589Sscottl    "Roundrobin scheduling quantum in microseconds");
230104964Sjeff
231134693Sjulian#ifdef SMP
232134688Sjulian/* Enable forwarding of wakeups to all other cpus */
233134688SjulianSYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL, "Kernel SMP");
234134688Sjulian
235134792Sjulianstatic int forward_wakeup_enabled = 1;
236134688SjulianSYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
237134688Sjulian	   &forward_wakeup_enabled, 0,
238134688Sjulian	   "Forwarding of wakeup to idle CPUs");
239134688Sjulian
240134688Sjulianstatic int forward_wakeups_requested = 0;
241134688SjulianSYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
242134688Sjulian	   &forward_wakeups_requested, 0,
243134688Sjulian	   "Requests for Forwarding of wakeup to idle CPUs");
244134688Sjulian
245134688Sjulianstatic int forward_wakeups_delivered = 0;
246134688SjulianSYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
247134688Sjulian	   &forward_wakeups_delivered, 0,
248134688Sjulian	   "Completed Forwarding of wakeup to idle CPUs");
249134688Sjulian
250134792Sjulianstatic int forward_wakeup_use_mask = 1;
251134688SjulianSYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
252134688Sjulian	   &forward_wakeup_use_mask, 0,
253134688Sjulian	   "Use the mask of idle cpus");
254134688Sjulian
255134688Sjulianstatic int forward_wakeup_use_loop = 0;
256134688SjulianSYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
257134688Sjulian	   &forward_wakeup_use_loop, 0,
258134688Sjulian	   "Use a loop to find idle cpus");
259134688Sjulian
260134688Sjulianstatic int forward_wakeup_use_single = 0;
261134688SjulianSYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, onecpu, CTLFLAG_RW,
262134688Sjulian	   &forward_wakeup_use_single, 0,
263134688Sjulian	   "Only signal one idle cpu");
264134688Sjulian
265134688Sjulianstatic int forward_wakeup_use_htt = 0;
266134688SjulianSYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, htt2, CTLFLAG_RW,
267134688Sjulian	   &forward_wakeup_use_htt, 0,
268134688Sjulian	   "account for htt");
269135051Sjulian
270134693Sjulian#endif
271135051Sjulianstatic int sched_followon = 0;
272135051SjulianSYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
273135051Sjulian	   &sched_followon, 0,
274135051Sjulian	   "allow threads to share a quantum");
275134688Sjulian
276135051Sjulianstatic int sched_pfollowons = 0;
277135051SjulianSYSCTL_INT(_kern_sched, OID_AUTO, pfollowons, CTLFLAG_RD,
278135051Sjulian	   &sched_pfollowons, 0,
279135051Sjulian	   "number of followons done to a different ksegrp");
280135051Sjulian
281135051Sjulianstatic int sched_kgfollowons = 0;
282135051SjulianSYSCTL_INT(_kern_sched, OID_AUTO, kgfollowons, CTLFLAG_RD,
283135051Sjulian	   &sched_kgfollowons, 0,
284135051Sjulian	   "number of followons done in a ksegrp");
285135051Sjulian
286139317Sjeffstatic __inline void
287139317Sjeffsched_load_add(void)
288139317Sjeff{
289139317Sjeff	sched_tdcnt++;
290139317Sjeff	CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
291139317Sjeff}
292139317Sjeff
293139317Sjeffstatic __inline void
294139317Sjeffsched_load_rem(void)
295139317Sjeff{
296139317Sjeff	sched_tdcnt--;
297139317Sjeff	CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
298139317Sjeff}
299104964Sjeff/*
300104964Sjeff * Arrange to reschedule if necessary, taking the priorities and
301104964Sjeff * schedulers into account.
302104964Sjeff */
303104964Sjeffstatic void
304104964Sjeffmaybe_resched(struct thread *td)
305104964Sjeff{
306104964Sjeff
307104964Sjeff	mtx_assert(&sched_lock, MA_OWNED);
308134791Sjulian	if (td->td_priority < curthread->td_priority)
309111032Sjulian		curthread->td_flags |= TDF_NEEDRESCHED;
310104964Sjeff}
311104964Sjeff
312104964Sjeff/*
313104964Sjeff * Force switch among equal priority processes every 100ms.
314104964Sjeff * We don't actually need to force a context switch of the current process.
315104964Sjeff * The act of firing the event triggers a context switch to softclock() and
316104964Sjeff * then switching back out again which is equivalent to a preemption, thus
317104964Sjeff * no further work is needed on the local CPU.
318104964Sjeff */
319104964Sjeff/* ARGSUSED */
320104964Sjeffstatic void
321104964Sjeffroundrobin(void *arg)
322104964Sjeff{
323104964Sjeff
324104964Sjeff#ifdef SMP
325104964Sjeff	mtx_lock_spin(&sched_lock);
326104964Sjeff	forward_roundrobin();
327104964Sjeff	mtx_unlock_spin(&sched_lock);
328104964Sjeff#endif
329104964Sjeff
330104964Sjeff	callout_reset(&roundrobin_callout, sched_quantum, roundrobin, NULL);
331104964Sjeff}
332104964Sjeff
333104964Sjeff/*
334104964Sjeff * Constants for digital decay and forget:
335118972Sjhb *	90% of (kg_estcpu) usage in 5 * loadav time
336118972Sjhb *	95% of (ke_pctcpu) usage in 60 seconds (load insensitive)
337104964Sjeff *          Note that, as ps(1) mentions, this can let percentages
338104964Sjeff *          total over 100% (I've seen 137.9% for 3 processes).
339104964Sjeff *
340118972Sjhb * Note that schedclock() updates kg_estcpu and p_cpticks asynchronously.
341104964Sjeff *
342118972Sjhb * We wish to decay away 90% of kg_estcpu in (5 * loadavg) seconds.
343104964Sjeff * That is, the system wants to compute a value of decay such
344104964Sjeff * that the following for loop:
345104964Sjeff * 	for (i = 0; i < (5 * loadavg); i++)
346118972Sjhb * 		kg_estcpu *= decay;
347104964Sjeff * will compute
348118972Sjhb * 	kg_estcpu *= 0.1;
349104964Sjeff * for all values of loadavg:
350104964Sjeff *
351104964Sjeff * Mathematically this loop can be expressed by saying:
352104964Sjeff * 	decay ** (5 * loadavg) ~= .1
353104964Sjeff *
354104964Sjeff * The system computes decay as:
355104964Sjeff * 	decay = (2 * loadavg) / (2 * loadavg + 1)
356104964Sjeff *
357104964Sjeff * We wish to prove that the system's computation of decay
358104964Sjeff * will always fulfill the equation:
359104964Sjeff * 	decay ** (5 * loadavg) ~= .1
360104964Sjeff *
361104964Sjeff * If we compute b as:
362104964Sjeff * 	b = 2 * loadavg
363104964Sjeff * then
364104964Sjeff * 	decay = b / (b + 1)
365104964Sjeff *
366104964Sjeff * We now need to prove two things:
367104964Sjeff *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
368104964Sjeff *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
369104964Sjeff *
370104964Sjeff * Facts:
371104964Sjeff *         For x close to zero, exp(x) =~ 1 + x, since
372104964Sjeff *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
373104964Sjeff *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
374104964Sjeff *         For x close to zero, ln(1+x) =~ x, since
375104964Sjeff *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
376104964Sjeff *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
377104964Sjeff *         ln(.1) =~ -2.30
378104964Sjeff *
379104964Sjeff * Proof of (1):
380104964Sjeff *    Solve (factor)**(power) =~ .1 given power (5*loadav):
381104964Sjeff *	solving for factor,
382104964Sjeff *      ln(factor) =~ (-2.30/5*loadav), or
383104964Sjeff *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
384104964Sjeff *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
385104964Sjeff *
386104964Sjeff * Proof of (2):
387104964Sjeff *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
388104964Sjeff *	solving for power,
389104964Sjeff *      power*ln(b/(b+1)) =~ -2.30, or
390104964Sjeff *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
391104964Sjeff *
392104964Sjeff * Actual power values for the implemented algorithm are as follows:
393104964Sjeff *      loadav: 1       2       3       4
394104964Sjeff *      power:  5.68    10.32   14.94   19.55
395104964Sjeff */
396104964Sjeff
397104964Sjeff/* calculations for digital decay to forget 90% of usage in 5*loadav sec */
398104964Sjeff#define	loadfactor(loadav)	(2 * (loadav))
399104964Sjeff#define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
400104964Sjeff
401118972Sjhb/* decay 95% of `ke_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
402104964Sjeffstatic fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
403104964SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
404104964Sjeff
405104964Sjeff/*
406104964Sjeff * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
407104964Sjeff * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
408104964Sjeff * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
409104964Sjeff *
410104964Sjeff * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
411104964Sjeff *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
412104964Sjeff *
413104964Sjeff * If you don't want to bother with the faster/more-accurate formula, you
414104964Sjeff * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
415104964Sjeff * (more general) method of calculating the %age of CPU used by a process.
416104964Sjeff */
417104964Sjeff#define	CCPU_SHIFT	11
418104964Sjeff
419104964Sjeff/*
420104964Sjeff * Recompute process priorities, every hz ticks.
421104964Sjeff * MP-safe, called without the Giant mutex.
422104964Sjeff */
423104964Sjeff/* ARGSUSED */
424104964Sjeffstatic void
425123871Sjhbschedcpu(void)
426104964Sjeff{
427104964Sjeff	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
428104964Sjeff	struct thread *td;
429104964Sjeff	struct proc *p;
430104964Sjeff	struct kse *ke;
431104964Sjeff	struct ksegrp *kg;
432118972Sjhb	int awake, realstathz;
433104964Sjeff
434104964Sjeff	realstathz = stathz ? stathz : hz;
435104964Sjeff	sx_slock(&allproc_lock);
436104964Sjeff	FOREACH_PROC_IN_SYSTEM(p) {
437118972Sjhb		/*
438118972Sjhb		 * Prevent state changes and protect run queue.
439118972Sjhb		 */
440104964Sjeff		mtx_lock_spin(&sched_lock);
441118972Sjhb		/*
442118972Sjhb		 * Increment time in/out of memory.  We ignore overflow; with
443118972Sjhb		 * 16-bit int's (remember them?) overflow takes 45 days.
444118972Sjhb		 */
445104964Sjeff		p->p_swtime++;
446104964Sjeff		FOREACH_KSEGRP_IN_PROC(p, kg) {
447104964Sjeff			awake = 0;
448134791Sjulian			FOREACH_THREAD_IN_GROUP(kg, td) {
449134791Sjulian				ke = td->td_kse;
450104964Sjeff				/*
451118972Sjhb				 * Increment sleep time (if sleeping).  We
452118972Sjhb				 * ignore overflow, as above.
453104964Sjeff				 */
454104964Sjeff				/*
455104964Sjeff				 * The kse slptimes are not touched in wakeup
456104964Sjeff				 * because the thread may not HAVE a KSE.
457104964Sjeff				 */
458104964Sjeff				if (ke->ke_state == KES_ONRUNQ) {
459104964Sjeff					awake = 1;
460104964Sjeff					ke->ke_flags &= ~KEF_DIDRUN;
461104964Sjeff				} else if ((ke->ke_state == KES_THREAD) &&
462134791Sjulian				    (TD_IS_RUNNING(td))) {
463104964Sjeff					awake = 1;
464104964Sjeff					/* Do not clear KEF_DIDRUN */
465104964Sjeff				} else if (ke->ke_flags & KEF_DIDRUN) {
466104964Sjeff					awake = 1;
467104964Sjeff					ke->ke_flags &= ~KEF_DIDRUN;
468104964Sjeff				}
469104964Sjeff
470104964Sjeff				/*
471118972Sjhb				 * ke_pctcpu is only for ps and ttyinfo().
472118972Sjhb				 * Do it per kse, and add them up at the end?
473104964Sjeff				 * XXXKSE
474104964Sjeff				 */
475118972Sjhb				ke->ke_pctcpu = (ke->ke_pctcpu * ccpu) >>
476109145Sjeff				    FSHIFT;
477104964Sjeff				/*
478104964Sjeff				 * If the kse has been idle the entire second,
479104964Sjeff				 * stop recalculating its priority until
480104964Sjeff				 * it wakes up.
481104964Sjeff				 */
482134145Sjulian				if (ke->ke_cpticks == 0)
483104964Sjeff					continue;
484104964Sjeff#if	(FSHIFT >= CCPU_SHIFT)
485109157Sjeff				ke->ke_pctcpu += (realstathz == 100)
486134145Sjulian				    ? ((fixpt_t) ke->ke_cpticks) <<
487104964Sjeff				    (FSHIFT - CCPU_SHIFT) :
488134145Sjulian				    100 * (((fixpt_t) ke->ke_cpticks)
489109145Sjeff				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
490104964Sjeff#else
491109157Sjeff				ke->ke_pctcpu += ((FSCALE - ccpu) *
492134145Sjulian				    (ke->ke_cpticks *
493109145Sjeff				    FSCALE / realstathz)) >> FSHIFT;
494104964Sjeff#endif
495134145Sjulian				ke->ke_cpticks = 0;
496104964Sjeff			} /* end of kse loop */
497104964Sjeff			/*
498104964Sjeff			 * If there are ANY running threads in this KSEGRP,
499104964Sjeff			 * then don't count it as sleeping.
500104964Sjeff			 */
501104964Sjeff			if (awake) {
502104964Sjeff				if (kg->kg_slptime > 1) {
503104964Sjeff					/*
504104964Sjeff					 * In an ideal world, this should not
505104964Sjeff					 * happen, because whoever woke us
506104964Sjeff					 * up from the long sleep should have
507104964Sjeff					 * unwound the slptime and reset our
508104964Sjeff					 * priority before we run at the stale
509104964Sjeff					 * priority.  Should KASSERT at some
510104964Sjeff					 * point when all the cases are fixed.
511104964Sjeff					 */
512104964Sjeff					updatepri(kg);
513104964Sjeff				}
514104964Sjeff				kg->kg_slptime = 0;
515118972Sjhb			} else
516104964Sjeff				kg->kg_slptime++;
517104964Sjeff			if (kg->kg_slptime > 1)
518104964Sjeff				continue;
519104964Sjeff			kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu);
520104964Sjeff		      	resetpriority(kg);
521104964Sjeff			FOREACH_THREAD_IN_GROUP(kg, td) {
522139453Sjhb				resetpriority_thread(td, kg);
523104964Sjeff			}
524104964Sjeff		} /* end of ksegrp loop */
525104964Sjeff		mtx_unlock_spin(&sched_lock);
526104964Sjeff	} /* end of process loop */
527104964Sjeff	sx_sunlock(&allproc_lock);
528104964Sjeff}
529104964Sjeff
530104964Sjeff/*
531123871Sjhb * Main loop for a kthread that executes schedcpu once a second.
532123871Sjhb */
533123871Sjhbstatic void
534124955Sjeffschedcpu_thread(void)
535123871Sjhb{
536123871Sjhb	int nowake;
537123871Sjhb
538123871Sjhb	for (;;) {
539123871Sjhb		schedcpu();
540123871Sjhb		tsleep(&nowake, curthread->td_priority, "-", hz);
541123871Sjhb	}
542123871Sjhb}
543123871Sjhb
544123871Sjhb/*
545104964Sjeff * Recalculate the priority of a process after it has slept for a while.
546118972Sjhb * For all load averages >= 1 and max kg_estcpu of 255, sleeping for at
547118972Sjhb * least six times the loadfactor will decay kg_estcpu to zero.
548104964Sjeff */
549104964Sjeffstatic void
550104964Sjeffupdatepri(struct ksegrp *kg)
551104964Sjeff{
552118972Sjhb	register fixpt_t loadfac;
553104964Sjeff	register unsigned int newcpu;
554104964Sjeff
555118972Sjhb	loadfac = loadfactor(averunnable.ldavg[0]);
556104964Sjeff	if (kg->kg_slptime > 5 * loadfac)
557104964Sjeff		kg->kg_estcpu = 0;
558104964Sjeff	else {
559118972Sjhb		newcpu = kg->kg_estcpu;
560118972Sjhb		kg->kg_slptime--;	/* was incremented in schedcpu() */
561104964Sjeff		while (newcpu && --kg->kg_slptime)
562104964Sjeff			newcpu = decay_cpu(loadfac, newcpu);
563104964Sjeff		kg->kg_estcpu = newcpu;
564104964Sjeff	}
565104964Sjeff}
566104964Sjeff
567104964Sjeff/*
568104964Sjeff * Compute the priority of a process when running in user mode.
569104964Sjeff * Arrange to reschedule if the resulting priority is better
570104964Sjeff * than that of the current process.
571104964Sjeff */
572104964Sjeffstatic void
573104964Sjeffresetpriority(struct ksegrp *kg)
574104964Sjeff{
575104964Sjeff	register unsigned int newpriority;
576104964Sjeff
577104964Sjeff	if (kg->kg_pri_class == PRI_TIMESHARE) {
578104964Sjeff		newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT +
579130551Sjulian		    NICE_WEIGHT * (kg->kg_proc->p_nice - PRIO_MIN);
580104964Sjeff		newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
581104964Sjeff		    PRI_MAX_TIMESHARE);
582104964Sjeff		kg->kg_user_pri = newpriority;
583104964Sjeff	}
584104964Sjeff}
585104964Sjeff
586139453Sjhb/*
587139453Sjhb * Update the thread's priority when the associated ksegroup's user
588139453Sjhb * priority changes.
589139453Sjhb */
590139453Sjhbstatic void
591139453Sjhbresetpriority_thread(struct thread *td, struct ksegrp *kg)
592139453Sjhb{
593139453Sjhb
594139453Sjhb	/* Only change threads with a time sharing user priority. */
595139453Sjhb	if (td->td_priority < PRI_MIN_TIMESHARE ||
596139453Sjhb	    td->td_priority > PRI_MAX_TIMESHARE)
597139453Sjhb		return;
598139453Sjhb
599139453Sjhb	/* XXX the whole needresched thing is broken, but not silly. */
600139453Sjhb	maybe_resched(td);
601139453Sjhb
602139453Sjhb	sched_prio(td, kg->kg_user_pri);
603139453Sjhb}
604139453Sjhb
605104964Sjeff/* ARGSUSED */
606104964Sjeffstatic void
607104964Sjeffsched_setup(void *dummy)
608104964Sjeff{
609124955Sjeff	setup_runqs();
610118972Sjhb
611104964Sjeff	if (sched_quantum == 0)
612104964Sjeff		sched_quantum = SCHED_QUANTUM;
613104964Sjeff	hogticks = 2 * sched_quantum;
614104964Sjeff
615126665Srwatson	callout_init(&roundrobin_callout, CALLOUT_MPSAFE);
616104964Sjeff
617104964Sjeff	/* Kick off timeout driven events by calling first time. */
618104964Sjeff	roundrobin(NULL);
619125288Sjeff
620125288Sjeff	/* Account for thread0. */
621139317Sjeff	sched_load_add();
622104964Sjeff}
623104964Sjeff
624104964Sjeff/* External interfaces start here */
625134791Sjulian/*
626134791Sjulian * Very early in the boot some setup of scheduler-specific
627145109Smaxim * parts of proc0 and of some scheduler resources needs to be done.
628134791Sjulian * Called from:
629134791Sjulian *  proc0_init()
630134791Sjulian */
631134791Sjulianvoid
632134791Sjulianschedinit(void)
633134791Sjulian{
634134791Sjulian	/*
635134791Sjulian	 * Set up the scheduler specific parts of proc0.
636134791Sjulian	 */
637134791Sjulian	proc0.p_sched = NULL; /* XXX */
638134791Sjulian	ksegrp0.kg_sched = &kg_sched0;
639134791Sjulian	thread0.td_sched = &kse0;
640134791Sjulian	kse0.ke_thread = &thread0;
641134791Sjulian	kse0.ke_state = KES_THREAD;
642134791Sjulian	kg_sched0.skg_concurrency = 1;
643134791Sjulian	kg_sched0.skg_avail_opennings = 0; /* we are already running */
644134791Sjulian}
645134791Sjulian
646104964Sjeffint
647104964Sjeffsched_runnable(void)
648104964Sjeff{
649124955Sjeff#ifdef SMP
650124955Sjeff	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
651124955Sjeff#else
652124955Sjeff	return runq_check(&runq);
653124955Sjeff#endif
654104964Sjeff}
655104964Sjeff
656104964Sjeffint
657104964Sjeffsched_rr_interval(void)
658104964Sjeff{
659104964Sjeff	if (sched_quantum == 0)
660104964Sjeff		sched_quantum = SCHED_QUANTUM;
661104964Sjeff	return (sched_quantum);
662104964Sjeff}
663104964Sjeff
664104964Sjeff/*
665104964Sjeff * We adjust the priority of the current process.  The priority of
666104964Sjeff * a process gets worse as it accumulates CPU time.  The cpu usage
667118972Sjhb * estimator (kg_estcpu) is increased here.  resetpriority() will
668118972Sjhb * compute a different priority each time kg_estcpu increases by
669104964Sjeff * INVERSE_ESTCPU_WEIGHT
670104964Sjeff * (until MAXPRI is reached).  The cpu usage estimator ramps up
671104964Sjeff * quite quickly when the process is running (linearly), and decays
672104964Sjeff * away exponentially, at a rate which is proportionally slower when
673104964Sjeff * the system is busy.  The basic principle is that the system will
674104964Sjeff * 90% forget that the process used a lot of CPU time in 5 * loadav
675104964Sjeff * seconds.  This causes the system to favor processes which haven't
676104964Sjeff * run much recently, and to round-robin among other processes.
677104964Sjeff */
678104964Sjeffvoid
679121127Sjeffsched_clock(struct thread *td)
680104964Sjeff{
681104964Sjeff	struct ksegrp *kg;
682121127Sjeff	struct kse *ke;
683104964Sjeff
684113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
685121127Sjeff	kg = td->td_ksegrp;
686121127Sjeff	ke = td->td_kse;
687113356Sjeff
688134145Sjulian	ke->ke_cpticks++;
689104964Sjeff	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1);
690104964Sjeff	if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
691104964Sjeff		resetpriority(kg);
692139453Sjhb		resetpriority_thread(td, kg);
693104964Sjeff	}
694104964Sjeff}
695118972Sjhb
696104964Sjeff/*
697104964Sjeff * charge childs scheduling cpu usage to parent.
698104964Sjeff *
699104964Sjeff * XXXKSE assume only one thread & kse & ksegrp keep estcpu in each ksegrp.
700104964Sjeff * Charge it to the ksegrp that did the wait since process estcpu is sum of
701104964Sjeff * all ksegrps, this is strictly as expected.  Assume that the child process
702104964Sjeff * aggregated all the estcpu into the 'built-in' ksegrp.
703104964Sjeff */
704104964Sjeffvoid
705132372Sjuliansched_exit(struct proc *p, struct thread *td)
706104964Sjeff{
707132372Sjulian	sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), td);
708132372Sjulian	sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
709113356Sjeff}
710113356Sjeff
711113356Sjeffvoid
712132372Sjuliansched_exit_ksegrp(struct ksegrp *kg, struct thread *childtd)
713113356Sjeff{
714113923Sjhb
715113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
716132372Sjulian	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + childtd->td_ksegrp->kg_estcpu);
717104964Sjeff}
718104964Sjeff
719104964Sjeffvoid
720113356Sjeffsched_exit_thread(struct thread *td, struct thread *child)
721104964Sjeff{
722139317Sjeff	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
723139317Sjeff	    child, child->td_proc->p_comm, child->td_priority);
724127894Sdfr	if ((child->td_proc->p_flag & P_NOLOAD) == 0)
725139317Sjeff		sched_load_rem();
726113356Sjeff}
727109145Sjeff
728113356Sjeffvoid
729134791Sjuliansched_fork(struct thread *td, struct thread *childtd)
730113356Sjeff{
731134791Sjulian	sched_fork_ksegrp(td, childtd->td_ksegrp);
732134791Sjulian	sched_fork_thread(td, childtd);
733113356Sjeff}
734113356Sjeff
735113356Sjeffvoid
736132372Sjuliansched_fork_ksegrp(struct thread *td, struct ksegrp *child)
737113356Sjeff{
738113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
739132372Sjulian	child->kg_estcpu = td->td_ksegrp->kg_estcpu;
740113356Sjeff}
741109145Sjeff
742113356Sjeffvoid
743134791Sjuliansched_fork_thread(struct thread *td, struct thread *childtd)
744113356Sjeff{
745134791Sjulian	sched_newthread(childtd);
746104964Sjeff}
747104964Sjeff
748104964Sjeffvoid
749130551Sjuliansched_nice(struct proc *p, int nice)
750104964Sjeff{
751130551Sjulian	struct ksegrp *kg;
752139453Sjhb	struct thread *td;
753113873Sjhb
754130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
755113873Sjhb	mtx_assert(&sched_lock, MA_OWNED);
756130551Sjulian	p->p_nice = nice;
757130551Sjulian	FOREACH_KSEGRP_IN_PROC(p, kg) {
758130551Sjulian		resetpriority(kg);
759139453Sjhb		FOREACH_THREAD_IN_GROUP(kg, td) {
760139453Sjhb			resetpriority_thread(td, kg);
761139453Sjhb		}
762130551Sjulian	}
763104964Sjeff}
764104964Sjeff
765113356Sjeffvoid
766113356Sjeffsched_class(struct ksegrp *kg, int class)
767113356Sjeff{
768113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
769113356Sjeff	kg->kg_pri_class = class;
770113356Sjeff}
771113356Sjeff
772105127Sjulian/*
773105127Sjulian * Adjust the priority of a thread.
774105127Sjulian * This may include moving the thread within the KSEGRP,
775105127Sjulian * changing the assignment of a kse to the thread,
776105127Sjulian * and moving a KSE in the system run queue.
777105127Sjulian */
778139453Sjhbstatic void
779139453Sjhbsched_priority(struct thread *td, u_char prio)
780104964Sjeff{
781139317Sjeff	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
782139317Sjeff	    td, td->td_proc->p_comm, td->td_priority, prio, curthread,
783139317Sjeff	    curthread->td_proc->p_comm);
784104964Sjeff
785113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
786139453Sjhb	if (td->td_priority == prio)
787139453Sjhb		return;
788104964Sjeff	if (TD_ON_RUNQ(td)) {
789105127Sjulian		adjustrunqueue(td, prio);
790105127Sjulian	} else {
791105127Sjulian		td->td_priority = prio;
792104964Sjeff	}
793104964Sjeff}
794104964Sjeff
795139453Sjhb/*
796139453Sjhb * Update a thread's priority when it is lent another thread's
797139453Sjhb * priority.
798139453Sjhb */
799104964Sjeffvoid
800139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
801139453Sjhb{
802139453Sjhb
803139453Sjhb	td->td_flags |= TDF_BORROWING;
804139453Sjhb	sched_priority(td, prio);
805139453Sjhb}
806139453Sjhb
807139453Sjhb/*
808139453Sjhb * Restore a thread's priority when priority propagation is
809139453Sjhb * over.  The prio argument is the minimum priority the thread
810139453Sjhb * needs to have to satisfy other possible priority lending
811139453Sjhb * requests.  If the thread's regulary priority is less
812139453Sjhb * important than prio the thread will keep a priority boost
813139453Sjhb * of prio.
814139453Sjhb */
815139453Sjhbvoid
816139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
817139453Sjhb{
818139453Sjhb	u_char base_pri;
819139453Sjhb
820139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
821139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
822139453Sjhb		base_pri = td->td_ksegrp->kg_user_pri;
823139453Sjhb	else
824139453Sjhb		base_pri = td->td_base_pri;
825139453Sjhb	if (prio >= base_pri) {
826139453Sjhb		td->td_flags &= ~TDF_BORROWING;
827139453Sjhb		sched_prio(td, base_pri);
828139453Sjhb	} else
829139453Sjhb		sched_lend_prio(td, prio);
830139453Sjhb}
831139453Sjhb
832139453Sjhbvoid
833139453Sjhbsched_prio(struct thread *td, u_char prio)
834139453Sjhb{
835139453Sjhb	u_char oldprio;
836139453Sjhb
837139453Sjhb	/* First, update the base priority. */
838139453Sjhb	td->td_base_pri = prio;
839139453Sjhb
840139453Sjhb	/*
841139453Sjhb	 * If the thread is borrowing another thread's priority, don't ever
842139453Sjhb	 * lower the priority.
843139453Sjhb	 */
844139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
845139453Sjhb		return;
846139453Sjhb
847139453Sjhb	/* Change the real priority. */
848139453Sjhb	oldprio = td->td_priority;
849139453Sjhb	sched_priority(td, prio);
850139453Sjhb
851139453Sjhb	/*
852139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
853139453Sjhb	 * its state.
854139453Sjhb	 */
855139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
856139453Sjhb		turnstile_adjust(td, oldprio);
857139453Sjhb}
858139453Sjhb
859139453Sjhbvoid
860126326Sjhbsched_sleep(struct thread *td)
861104964Sjeff{
862113923Sjhb
863113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
864104964Sjeff	td->td_ksegrp->kg_slptime = 0;
865104964Sjeff}
866104964Sjeff
867135051Sjulianstatic void remrunqueue(struct thread *td);
868135051Sjulian
869104964Sjeffvoid
870135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
871104964Sjeff{
872104964Sjeff	struct kse *ke;
873135051Sjulian	struct ksegrp *kg;
874104964Sjeff	struct proc *p;
875104964Sjeff
876104964Sjeff	ke = td->td_kse;
877104964Sjeff	p = td->td_proc;
878104964Sjeff
879113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
880104964Sjeff
881125295Sjeff	if ((p->p_flag & P_NOLOAD) == 0)
882139317Sjeff		sched_load_rem();
883134791Sjulian	/*
884135051Sjulian	 * We are volunteering to switch out so we get to nominate
885135051Sjulian	 * a successor for the rest of our quantum
886135051Sjulian	 * First try another thread in our ksegrp, and then look for
887135051Sjulian	 * other ksegrps in our process.
888135051Sjulian	 */
889135051Sjulian	if (sched_followon &&
890135051Sjulian	    (p->p_flag & P_HADTHREADS) &&
891135051Sjulian	    (flags & SW_VOL) &&
892135051Sjulian	    newtd == NULL) {
893135051Sjulian		/* lets schedule another thread from this process */
894135051Sjulian		 kg = td->td_ksegrp;
895135051Sjulian		 if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
896135051Sjulian			remrunqueue(newtd);
897135051Sjulian			sched_kgfollowons++;
898135051Sjulian		 } else {
899135051Sjulian			FOREACH_KSEGRP_IN_PROC(p, kg) {
900135051Sjulian				if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
901135051Sjulian					sched_pfollowons++;
902135051Sjulian					remrunqueue(newtd);
903135051Sjulian					break;
904135051Sjulian				}
905135051Sjulian			}
906135051Sjulian		}
907135051Sjulian	}
908135051Sjulian
909138527Sups	if (newtd)
910138527Sups		newtd->td_flags |= (td->td_flags & TDF_NEEDRESCHED);
911138527Sups
912113339Sjulian	td->td_lastcpu = td->td_oncpu;
913132266Sjhb	td->td_flags &= ~TDF_NEEDRESCHED;
914144777Sups	td->td_owepreempt = 0;
915113339Sjulian	td->td_oncpu = NOCPU;
916104964Sjeff	/*
917104964Sjeff	 * At the last moment, if this thread is still marked RUNNING,
918104964Sjeff	 * then put it back on the run queue as it has not been suspended
919131473Sjhb	 * or stopped or any thing else similar.  We never put the idle
920131473Sjhb	 * threads on the run queue, however.
921104964Sjeff	 */
922131473Sjhb	if (td == PCPU_GET(idlethread))
923131473Sjhb		TD_SET_CAN_RUN(td);
924134791Sjulian	else {
925136170Sjulian		SLOT_RELEASE(td->td_ksegrp);
926134791Sjulian		if (TD_IS_RUNNING(td)) {
927134791Sjulian			/* Put us back on the run queue (kse and all). */
928136170Sjulian			setrunqueue(td, (flags & SW_PREEMPT) ?
929136170Sjulian			    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
930136170Sjulian			    SRQ_OURSELF|SRQ_YIELDING);
931134791Sjulian		} else if (p->p_flag & P_HADTHREADS) {
932134791Sjulian			/*
933134791Sjulian			 * We will not be on the run queue. So we must be
934134791Sjulian			 * sleeping or similar. As it's available,
935134791Sjulian			 * someone else can use the KSE if they need it.
936136170Sjulian			 * It's NOT available if we are about to need it
937134791Sjulian			 */
938136170Sjulian			if (newtd == NULL || newtd->td_ksegrp != td->td_ksegrp)
939136170Sjulian				slot_fill(td->td_ksegrp);
940134791Sjulian		}
941104964Sjeff	}
942136170Sjulian	if (newtd) {
943136170Sjulian		/*
944136170Sjulian		 * The thread we are about to run needs to be counted
945136170Sjulian		 * as if it had been added to the run queue and selected.
946136170Sjulian		 * It came from:
947136170Sjulian		 * * A preemption
948136170Sjulian		 * * An upcall
949136170Sjulian		 * * A followon
950136170Sjulian		 */
951136170Sjulian		KASSERT((newtd->td_inhibitors == 0),
952136170Sjulian			("trying to run inhibitted thread"));
953136170Sjulian		SLOT_USE(newtd->td_ksegrp);
954136170Sjulian		newtd->td_kse->ke_flags |= KEF_DIDRUN;
955136170Sjulian        	TD_SET_RUNNING(newtd);
956136170Sjulian		if ((newtd->td_proc->p_flag & P_NOLOAD) == 0)
957139317Sjeff			sched_load_add();
958136170Sjulian	} else {
959131473Sjhb		newtd = choosethread();
960136170Sjulian	}
961136170Sjulian
962121128Sjeff	if (td != newtd)
963121128Sjeff		cpu_switch(td, newtd);
964121128Sjeff	sched_lock.mtx_lock = (uintptr_t)td;
965121128Sjeff	td->td_oncpu = PCPU_GET(cpuid);
966104964Sjeff}
967104964Sjeff
968104964Sjeffvoid
969104964Sjeffsched_wakeup(struct thread *td)
970104964Sjeff{
971104964Sjeff	struct ksegrp *kg;
972104964Sjeff
973113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
974104964Sjeff	kg = td->td_ksegrp;
975139453Sjhb	if (kg->kg_slptime > 1) {
976104964Sjeff		updatepri(kg);
977139453Sjhb		resetpriority(kg);
978139453Sjhb	}
979104964Sjeff	kg->kg_slptime = 0;
980134586Sjulian	setrunqueue(td, SRQ_BORING);
981104964Sjeff}
982104964Sjeff
983134693Sjulian#ifdef SMP
984134688Sjulian/* enable HTT_2 if you have a 2-way HTT cpu.*/
985134688Sjulianstatic int
986134688Sjulianforward_wakeup(int  cpunum)
987134688Sjulian{
988134688Sjulian	cpumask_t map, me, dontuse;
989134688Sjulian	cpumask_t map2;
990134688Sjulian	struct pcpu *pc;
991134688Sjulian	cpumask_t id, map3;
992134688Sjulian
993134688Sjulian	mtx_assert(&sched_lock, MA_OWNED);
994134688Sjulian
995134791Sjulian	CTR0(KTR_RUNQ, "forward_wakeup()");
996134688Sjulian
997134688Sjulian	if ((!forward_wakeup_enabled) ||
998134688Sjulian	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
999134688Sjulian		return (0);
1000134688Sjulian	if (!smp_started || cold || panicstr)
1001134688Sjulian		return (0);
1002134688Sjulian
1003134688Sjulian	forward_wakeups_requested++;
1004134688Sjulian
1005134688Sjulian/*
1006134688Sjulian * check the idle mask we received against what we calculated before
1007134688Sjulian * in the old version.
1008134688Sjulian */
1009134688Sjulian	me = PCPU_GET(cpumask);
1010134688Sjulian	/*
1011134688Sjulian	 * don't bother if we should be doing it ourself..
1012134688Sjulian	 */
1013134688Sjulian	if ((me & idle_cpus_mask) && (cpunum == NOCPU || me == (1 << cpunum)))
1014134688Sjulian		return (0);
1015134688Sjulian
1016134688Sjulian	dontuse = me | stopped_cpus | hlt_cpus_mask;
1017134688Sjulian	map3 = 0;
1018134688Sjulian	if (forward_wakeup_use_loop) {
1019134688Sjulian		SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
1020134688Sjulian			id = pc->pc_cpumask;
1021134688Sjulian			if ( (id & dontuse) == 0 &&
1022134688Sjulian			    pc->pc_curthread == pc->pc_idlethread) {
1023134688Sjulian				map3 |= id;
1024134688Sjulian			}
1025134688Sjulian		}
1026134688Sjulian	}
1027134688Sjulian
1028134688Sjulian	if (forward_wakeup_use_mask) {
1029134688Sjulian		map = 0;
1030134688Sjulian		map = idle_cpus_mask & ~dontuse;
1031134688Sjulian
1032134688Sjulian		/* If they are both on, compare and use loop if different */
1033134688Sjulian		if (forward_wakeup_use_loop) {
1034134688Sjulian			if (map != map3) {
1035134688Sjulian				printf("map (%02X) != map3 (%02X)\n",
1036134688Sjulian						map, map3);
1037134688Sjulian				map = map3;
1038134688Sjulian			}
1039134688Sjulian		}
1040134688Sjulian	} else {
1041134688Sjulian		map = map3;
1042134688Sjulian	}
1043134688Sjulian	/* If we only allow a specific CPU, then mask off all the others */
1044134688Sjulian	if (cpunum != NOCPU) {
1045134688Sjulian		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1046134688Sjulian		map &= (1 << cpunum);
1047134688Sjulian	} else {
1048134688Sjulian		/* Try choose an idle die. */
1049134688Sjulian		if (forward_wakeup_use_htt) {
1050134688Sjulian			map2 =  (map & (map >> 1)) & 0x5555;
1051134688Sjulian			if (map2) {
1052134688Sjulian				map = map2;
1053134688Sjulian			}
1054134688Sjulian		}
1055134688Sjulian
1056134688Sjulian		/* set only one bit */
1057134688Sjulian		if (forward_wakeup_use_single) {
1058134688Sjulian			map = map & ((~map) + 1);
1059134688Sjulian		}
1060134688Sjulian	}
1061134688Sjulian	if (map) {
1062134688Sjulian		forward_wakeups_delivered++;
1063134688Sjulian		ipi_selected(map, IPI_AST);
1064134688Sjulian		return (1);
1065134688Sjulian	}
1066134688Sjulian	if (cpunum == NOCPU)
1067134688Sjulian		printf("forward_wakeup: Idle processor not found\n");
1068134688Sjulian	return (0);
1069134688Sjulian}
1070134693Sjulian#endif
1071134688Sjulian
1072104964Sjeffvoid
1073134586Sjuliansched_add(struct thread *td, int flags)
1074104964Sjeff{
1075121127Sjeff	struct kse *ke;
1076134591Sjulian#ifdef SMP
1077134591Sjulian	int forwarded = 0;
1078134591Sjulian	int cpu;
1079134591Sjulian#endif
1080121127Sjeff
1081121127Sjeff	ke = td->td_kse;
1082104964Sjeff	mtx_assert(&sched_lock, MA_OWNED);
1083104964Sjeff	KASSERT(ke->ke_state != KES_ONRUNQ,
1084124957Sjeff	    ("sched_add: kse %p (%s) already in run queue", ke,
1085104964Sjeff	    ke->ke_proc->p_comm));
1086104964Sjeff	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1087124957Sjeff	    ("sched_add: process swapped out"));
1088139317Sjeff	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1089139317Sjeff	    td, td->td_proc->p_comm, td->td_priority, curthread,
1090139317Sjeff	    curthread->td_proc->p_comm);
1091131481Sjhb
1092131481Sjhb#ifdef SMP
1093124955Sjeff	if (KSE_CAN_MIGRATE(ke)) {
1094134591Sjulian		CTR2(KTR_RUNQ,
1095134591Sjulian		    "sched_add: adding kse:%p (td:%p) to gbl runq", ke, td);
1096134591Sjulian		cpu = NOCPU;
1097124955Sjeff		ke->ke_runq = &runq;
1098124955Sjeff	} else {
1099124955Sjeff		if (!SKE_RUNQ_PCPU(ke))
1100134591Sjulian			ke->ke_runq = &runq_pcpu[(cpu = PCPU_GET(cpuid))];
1101134591Sjulian		else
1102134591Sjulian			cpu = td->td_lastcpu;
1103134591Sjulian		CTR3(KTR_RUNQ,
1104134591Sjulian		    "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
1105124955Sjeff	}
1106124955Sjeff#else
1107133396Sjulian	CTR2(KTR_RUNQ, "sched_add: adding kse:%p (td:%p) to runq", ke, td);
1108124955Sjeff	ke->ke_runq = &runq;
1109134591Sjulian
1110124955Sjeff#endif
1111134591Sjulian	/*
1112134591Sjulian	 * If we are yielding (on the way out anyhow)
1113134591Sjulian	 * or the thread being saved is US,
1114134591Sjulian	 * then don't try be smart about preemption
1115134591Sjulian	 * or kicking off another CPU
1116134591Sjulian	 * as it won't help and may hinder.
1117134591Sjulian	 * In the YIEDLING case, we are about to run whoever is
1118134591Sjulian	 * being put in the queue anyhow, and in the
1119134591Sjulian	 * OURSELF case, we are puting ourself on the run queue
1120134591Sjulian	 * which also only happens when we are about to yield.
1121134591Sjulian	 */
1122134591Sjulian	if((flags & SRQ_YIELDING) == 0) {
1123134591Sjulian#ifdef SMP
1124134591Sjulian		cpumask_t me = PCPU_GET(cpumask);
1125134591Sjulian		int idle = idle_cpus_mask & me;
1126134591Sjulian		/*
1127134591Sjulian		 * Only try to kick off another CPU if
1128134591Sjulian		 * the thread is unpinned
1129134591Sjulian		 * or pinned to another cpu,
1130134591Sjulian		 * and there are other available and idle CPUs.
1131134837Sjulian		 * if we are idle, or it's an interrupt,
1132134837Sjulian		 * then skip straight to preemption.
1133134591Sjulian		 */
1134134837Sjulian		if ( (! idle) && ((flags & SRQ_INTR) == 0) &&
1135134591Sjulian		    (idle_cpus_mask & ~(hlt_cpus_mask | me)) &&
1136134591Sjulian		    ( KSE_CAN_MIGRATE(ke) ||
1137134591Sjulian		      ke->ke_runq != &runq_pcpu[PCPU_GET(cpuid)])) {
1138134591Sjulian			forwarded = forward_wakeup(cpu);
1139134591Sjulian		}
1140134591Sjulian		/*
1141134591Sjulian		 * If we failed to kick off another cpu, then look to
1142134591Sjulian		 * see if we should preempt this CPU. Only allow this
1143134591Sjulian		 * if it is not pinned or IS pinned to this CPU.
1144134591Sjulian		 * If we are the idle thread, we also try do preempt.
1145134591Sjulian		 * as it will be quicker and being idle, we won't
1146134591Sjulian		 * lose in doing so..
1147134591Sjulian		 */
1148134591Sjulian		if ((!forwarded) &&
1149134591Sjulian		    (ke->ke_runq == &runq ||
1150134591Sjulian		     ke->ke_runq == &runq_pcpu[PCPU_GET(cpuid)]))
1151134591Sjulian#endif
1152134591Sjulian
1153134591Sjulian		{
1154134591Sjulian			if (maybe_preempt(td))
1155134591Sjulian				return;
1156134591Sjulian		}
1157134591Sjulian	}
1158125295Sjeff	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1159139317Sjeff		sched_load_add();
1160136170Sjulian	SLOT_USE(td->td_ksegrp);
1161136170Sjulian	runq_add(ke->ke_runq, ke, flags);
1162133520Sjulian	ke->ke_state = KES_ONRUNQ;
1163132118Sjhb	maybe_resched(td);
1164104964Sjeff}
1165104964Sjeff
1166104964Sjeffvoid
1167121127Sjeffsched_rem(struct thread *td)
1168104964Sjeff{
1169121127Sjeff	struct kse *ke;
1170121127Sjeff
1171121127Sjeff	ke = td->td_kse;
1172104964Sjeff	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1173124957Sjeff	    ("sched_rem: process swapped out"));
1174124957Sjeff	KASSERT((ke->ke_state == KES_ONRUNQ),
1175124957Sjeff	    ("sched_rem: KSE not on run queue"));
1176104964Sjeff	mtx_assert(&sched_lock, MA_OWNED);
1177139317Sjeff	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
1178139317Sjeff	    td, td->td_proc->p_comm, td->td_priority, curthread,
1179139317Sjeff	    curthread->td_proc->p_comm);
1180104964Sjeff
1181125295Sjeff	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1182139317Sjeff		sched_load_rem();
1183136167Sjulian	SLOT_RELEASE(td->td_ksegrp);
1184134145Sjulian	runq_remove(ke->ke_runq, ke);
1185124955Sjeff
1186104964Sjeff	ke->ke_state = KES_THREAD;
1187104964Sjeff}
1188104964Sjeff
1189135295Sjulian/*
1190135295Sjulian * Select threads to run.
1191135295Sjulian * Notice that the running threads still consume a slot.
1192135295Sjulian */
1193104964Sjeffstruct kse *
1194104964Sjeffsched_choose(void)
1195104964Sjeff{
1196104964Sjeff	struct kse *ke;
1197124955Sjeff	struct runq *rq;
1198104964Sjeff
1199124955Sjeff#ifdef SMP
1200124955Sjeff	struct kse *kecpu;
1201124955Sjeff
1202124955Sjeff	rq = &runq;
1203104964Sjeff	ke = runq_choose(&runq);
1204124955Sjeff	kecpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1205104964Sjeff
1206124955Sjeff	if (ke == NULL ||
1207124955Sjeff	    (kecpu != NULL &&
1208124955Sjeff	     kecpu->ke_thread->td_priority < ke->ke_thread->td_priority)) {
1209133396Sjulian		CTR2(KTR_RUNQ, "choosing kse %p from pcpu runq %d", kecpu,
1210124955Sjeff		     PCPU_GET(cpuid));
1211124955Sjeff		ke = kecpu;
1212124955Sjeff		rq = &runq_pcpu[PCPU_GET(cpuid)];
1213124955Sjeff	} else {
1214133396Sjulian		CTR1(KTR_RUNQ, "choosing kse %p from main runq", ke);
1215124955Sjeff	}
1216124955Sjeff
1217124955Sjeff#else
1218124955Sjeff	rq = &runq;
1219124955Sjeff	ke = runq_choose(&runq);
1220124955Sjeff#endif
1221124955Sjeff
1222104964Sjeff	if (ke != NULL) {
1223124955Sjeff		runq_remove(rq, ke);
1224104964Sjeff		ke->ke_state = KES_THREAD;
1225104964Sjeff
1226104964Sjeff		KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1227124957Sjeff		    ("sched_choose: process swapped out"));
1228104964Sjeff	}
1229104964Sjeff	return (ke);
1230104964Sjeff}
1231104964Sjeff
1232104964Sjeffvoid
1233104964Sjeffsched_userret(struct thread *td)
1234104964Sjeff{
1235104964Sjeff	struct ksegrp *kg;
1236104964Sjeff	/*
1237104964Sjeff	 * XXX we cheat slightly on the locking here to avoid locking in
1238104964Sjeff	 * the usual case.  Setting td_priority here is essentially an
1239104964Sjeff	 * incomplete workaround for not setting it properly elsewhere.
1240104964Sjeff	 * Now that some interrupt handlers are threads, not setting it
1241104964Sjeff	 * properly elsewhere can clobber it in the window between setting
1242104964Sjeff	 * it here and returning to user mode, so don't waste time setting
1243104964Sjeff	 * it perfectly here.
1244104964Sjeff	 */
1245139453Sjhb	KASSERT((td->td_flags & TDF_BORROWING) == 0,
1246139453Sjhb	    ("thread with borrowed priority returning to userland"));
1247104964Sjeff	kg = td->td_ksegrp;
1248104964Sjeff	if (td->td_priority != kg->kg_user_pri) {
1249104964Sjeff		mtx_lock_spin(&sched_lock);
1250104964Sjeff		td->td_priority = kg->kg_user_pri;
1251139453Sjhb		td->td_base_pri = kg->kg_user_pri;
1252104964Sjeff		mtx_unlock_spin(&sched_lock);
1253104964Sjeff	}
1254104964Sjeff}
1255107126Sjeff
1256124955Sjeffvoid
1257124955Sjeffsched_bind(struct thread *td, int cpu)
1258124955Sjeff{
1259124955Sjeff	struct kse *ke;
1260124955Sjeff
1261124955Sjeff	mtx_assert(&sched_lock, MA_OWNED);
1262124955Sjeff	KASSERT(TD_IS_RUNNING(td),
1263124955Sjeff	    ("sched_bind: cannot bind non-running thread"));
1264124955Sjeff
1265124955Sjeff	ke = td->td_kse;
1266124955Sjeff
1267124955Sjeff	ke->ke_flags |= KEF_BOUND;
1268124955Sjeff#ifdef SMP
1269124955Sjeff	ke->ke_runq = &runq_pcpu[cpu];
1270124955Sjeff	if (PCPU_GET(cpuid) == cpu)
1271124955Sjeff		return;
1272124955Sjeff
1273124955Sjeff	ke->ke_state = KES_THREAD;
1274124955Sjeff
1275131473Sjhb	mi_switch(SW_VOL, NULL);
1276124955Sjeff#endif
1277124955Sjeff}
1278124955Sjeff
1279124955Sjeffvoid
1280124955Sjeffsched_unbind(struct thread* td)
1281124955Sjeff{
1282124955Sjeff	mtx_assert(&sched_lock, MA_OWNED);
1283124955Sjeff	td->td_kse->ke_flags &= ~KEF_BOUND;
1284124955Sjeff}
1285124955Sjeff
1286107126Sjeffint
1287125288Sjeffsched_load(void)
1288125288Sjeff{
1289125288Sjeff	return (sched_tdcnt);
1290125288Sjeff}
1291125288Sjeff
1292125288Sjeffint
1293107126Sjeffsched_sizeof_ksegrp(void)
1294107126Sjeff{
1295134791Sjulian	return (sizeof(struct ksegrp) + sizeof(struct kg_sched));
1296107126Sjeff}
1297107126Sjeffint
1298107126Sjeffsched_sizeof_proc(void)
1299107126Sjeff{
1300107126Sjeff	return (sizeof(struct proc));
1301107126Sjeff}
1302107126Sjeffint
1303107126Sjeffsched_sizeof_thread(void)
1304107126Sjeff{
1305134791Sjulian	return (sizeof(struct thread) + sizeof(struct kse));
1306107126Sjeff}
1307107137Sjeff
1308107137Sjefffixpt_t
1309121127Sjeffsched_pctcpu(struct thread *td)
1310107137Sjeff{
1311121147Sjeff	struct kse *ke;
1312121147Sjeff
1313121147Sjeff	ke = td->td_kse;
1314134791Sjulian	return (ke->ke_pctcpu);
1315121147Sjeff
1316121147Sjeff	return (0);
1317107137Sjeff}
1318134791Sjulian#define KERN_SWITCH_INCLUDE 1
1319134791Sjulian#include "kern/kern_switch.c"
1320