xref: /freebsd/sys/kern/sched_4bsd.c (revision 84ee9401a3fc8d3c22424266f421a928989cd692)
1 /*-
2  * Copyright (c) 1982, 1986, 1990, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_hwpmc_hooks.h"
39 
40 #define kse td_sched
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/ktr.h>
46 #include <sys/lock.h>
47 #include <sys/kthread.h>
48 #include <sys/mutex.h>
49 #include <sys/proc.h>
50 #include <sys/resourcevar.h>
51 #include <sys/sched.h>
52 #include <sys/smp.h>
53 #include <sys/sysctl.h>
54 #include <sys/sx.h>
55 #include <sys/turnstile.h>
56 #include <sys/umtx.h>
57 #include <machine/pcb.h>
58 #include <machine/smp.h>
59 
60 #ifdef HWPMC_HOOKS
61 #include <sys/pmckern.h>
62 #endif
63 
64 /*
65  * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
66  * the range 100-256 Hz (approximately).
67  */
68 #define	ESTCPULIM(e) \
69     min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
70     RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
71 #ifdef SMP
72 #define	INVERSE_ESTCPU_WEIGHT	(8 * smp_cpus)
73 #else
74 #define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
75 #endif
76 #define	NICE_WEIGHT		1	/* Priorities per nice level. */
77 
78 /*
79  * The schedulable entity that can be given a context to run.
80  * A process may have several of these. Probably one per processor
81  * but possibly a few more. In this universe they are grouped
82  * with a KSEG that contains the priority and niceness
83  * for the group.
84  */
85 struct kse {
86 	TAILQ_ENTRY(kse) ke_procq;	/* (j/z) Run queue. */
87 	struct thread	*ke_thread;	/* (*) Active associated thread. */
88 	fixpt_t		ke_pctcpu;	/* (j) %cpu during p_swtime. */
89 	u_char		ke_rqindex;	/* (j) Run queue index. */
90 	enum {
91 		KES_THREAD = 0x0,	/* slaved to thread state */
92 		KES_ONRUNQ
93 	} ke_state;			/* (j) KSE status. */
94 	int		ke_cpticks;	/* (j) Ticks of cpu time. */
95 	struct runq	*ke_runq;	/* runq the kse is currently on */
96 };
97 
98 #define ke_proc		ke_thread->td_proc
99 #define ke_ksegrp	ke_thread->td_ksegrp
100 
101 #define td_kse td_sched
102 
103 /* flags kept in td_flags */
104 #define TDF_DIDRUN	TDF_SCHED0	/* KSE actually ran. */
105 #define TDF_EXIT	TDF_SCHED1	/* KSE is being killed. */
106 #define TDF_BOUND	TDF_SCHED2
107 
108 #define ke_flags	ke_thread->td_flags
109 #define KEF_DIDRUN	TDF_DIDRUN /* KSE actually ran. */
110 #define KEF_EXIT	TDF_EXIT /* KSE is being killed. */
111 #define KEF_BOUND	TDF_BOUND /* stuck to one CPU */
112 
113 #define SKE_RUNQ_PCPU(ke)						\
114     ((ke)->ke_runq != 0 && (ke)->ke_runq != &runq)
115 
116 struct kg_sched {
117 	struct thread	*skg_last_assigned; /* (j) Last thread assigned to */
118 					   /* the system scheduler. */
119 	int	skg_avail_opennings;	/* (j) Num KSEs requested in group. */
120 	int	skg_concurrency;	/* (j) Num KSEs requested in group. */
121 };
122 #define kg_last_assigned	kg_sched->skg_last_assigned
123 #define kg_avail_opennings	kg_sched->skg_avail_opennings
124 #define kg_concurrency		kg_sched->skg_concurrency
125 
126 #define SLOT_RELEASE(kg)						\
127 do {									\
128 	kg->kg_avail_opennings++; 					\
129 	CTR3(KTR_RUNQ, "kg %p(%d) Slot released (->%d)",		\
130 	    kg,								\
131 	    kg->kg_concurrency,						\
132 	    kg->kg_avail_opennings);					\
133 /*	KASSERT((kg->kg_avail_opennings <= kg->kg_concurrency),		\
134 	    ("slots out of whack"));*/					\
135 } while (0)
136 
137 #define SLOT_USE(kg)							\
138 do {									\
139 	kg->kg_avail_opennings--; 					\
140 	CTR3(KTR_RUNQ, "kg %p(%d) Slot used (->%d)",			\
141 	    kg,								\
142 	    kg->kg_concurrency,						\
143 	    kg->kg_avail_opennings);					\
144 /*	KASSERT((kg->kg_avail_opennings >= 0),				\
145 	    ("slots out of whack"));*/					\
146 } while (0)
147 
148 /*
149  * KSE_CAN_MIGRATE macro returns true if the kse can migrate between
150  * cpus.
151  */
152 #define KSE_CAN_MIGRATE(ke)						\
153     ((ke)->ke_thread->td_pinned == 0 && ((ke)->ke_flags & KEF_BOUND) == 0)
154 
155 static struct kse kse0;
156 static struct kg_sched kg_sched0;
157 
158 static int	sched_tdcnt;	/* Total runnable threads in the system. */
159 static int	sched_quantum;	/* Roundrobin scheduling quantum in ticks. */
160 #define	SCHED_QUANTUM	(hz / 10)	/* Default sched quantum */
161 
162 static struct callout roundrobin_callout;
163 
164 static void	slot_fill(struct ksegrp *kg);
165 static struct kse *sched_choose(void);		/* XXX Should be thread * */
166 
167 static void	setup_runqs(void);
168 static void	roundrobin(void *arg);
169 static void	schedcpu(void);
170 static void	schedcpu_thread(void);
171 static void	sched_priority(struct thread *td, u_char prio);
172 static void	sched_setup(void *dummy);
173 static void	maybe_resched(struct thread *td);
174 static void	updatepri(struct ksegrp *kg);
175 static void	resetpriority(struct ksegrp *kg);
176 static void	resetpriority_thread(struct thread *td, struct ksegrp *kg);
177 #ifdef SMP
178 static int	forward_wakeup(int  cpunum);
179 #endif
180 
181 static struct kproc_desc sched_kp = {
182         "schedcpu",
183         schedcpu_thread,
184         NULL
185 };
186 SYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start, &sched_kp)
187 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
188 
189 /*
190  * Global run queue.
191  */
192 static struct runq runq;
193 
194 #ifdef SMP
195 /*
196  * Per-CPU run queues
197  */
198 static struct runq runq_pcpu[MAXCPU];
199 #endif
200 
201 static void
202 setup_runqs(void)
203 {
204 #ifdef SMP
205 	int i;
206 
207 	for (i = 0; i < MAXCPU; ++i)
208 		runq_init(&runq_pcpu[i]);
209 #endif
210 
211 	runq_init(&runq);
212 }
213 
214 static int
215 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
216 {
217 	int error, new_val;
218 
219 	new_val = sched_quantum * tick;
220 	error = sysctl_handle_int(oidp, &new_val, 0, req);
221         if (error != 0 || req->newptr == NULL)
222 		return (error);
223 	if (new_val < tick)
224 		return (EINVAL);
225 	sched_quantum = new_val / tick;
226 	hogticks = 2 * sched_quantum;
227 	return (0);
228 }
229 
230 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
231 
232 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
233     "Scheduler name");
234 
235 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
236     0, sizeof sched_quantum, sysctl_kern_quantum, "I",
237     "Roundrobin scheduling quantum in microseconds");
238 
239 #ifdef SMP
240 /* Enable forwarding of wakeups to all other cpus */
241 SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL, "Kernel SMP");
242 
243 static int forward_wakeup_enabled = 1;
244 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
245 	   &forward_wakeup_enabled, 0,
246 	   "Forwarding of wakeup to idle CPUs");
247 
248 static int forward_wakeups_requested = 0;
249 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
250 	   &forward_wakeups_requested, 0,
251 	   "Requests for Forwarding of wakeup to idle CPUs");
252 
253 static int forward_wakeups_delivered = 0;
254 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
255 	   &forward_wakeups_delivered, 0,
256 	   "Completed Forwarding of wakeup to idle CPUs");
257 
258 static int forward_wakeup_use_mask = 1;
259 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
260 	   &forward_wakeup_use_mask, 0,
261 	   "Use the mask of idle cpus");
262 
263 static int forward_wakeup_use_loop = 0;
264 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
265 	   &forward_wakeup_use_loop, 0,
266 	   "Use a loop to find idle cpus");
267 
268 static int forward_wakeup_use_single = 0;
269 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, onecpu, CTLFLAG_RW,
270 	   &forward_wakeup_use_single, 0,
271 	   "Only signal one idle cpu");
272 
273 static int forward_wakeup_use_htt = 0;
274 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, htt2, CTLFLAG_RW,
275 	   &forward_wakeup_use_htt, 0,
276 	   "account for htt");
277 
278 #endif
279 static int sched_followon = 0;
280 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
281 	   &sched_followon, 0,
282 	   "allow threads to share a quantum");
283 
284 static int sched_pfollowons = 0;
285 SYSCTL_INT(_kern_sched, OID_AUTO, pfollowons, CTLFLAG_RD,
286 	   &sched_pfollowons, 0,
287 	   "number of followons done to a different ksegrp");
288 
289 static int sched_kgfollowons = 0;
290 SYSCTL_INT(_kern_sched, OID_AUTO, kgfollowons, CTLFLAG_RD,
291 	   &sched_kgfollowons, 0,
292 	   "number of followons done in a ksegrp");
293 
294 static __inline void
295 sched_load_add(void)
296 {
297 	sched_tdcnt++;
298 	CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
299 }
300 
301 static __inline void
302 sched_load_rem(void)
303 {
304 	sched_tdcnt--;
305 	CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
306 }
307 /*
308  * Arrange to reschedule if necessary, taking the priorities and
309  * schedulers into account.
310  */
311 static void
312 maybe_resched(struct thread *td)
313 {
314 
315 	mtx_assert(&sched_lock, MA_OWNED);
316 	if (td->td_priority < curthread->td_priority)
317 		curthread->td_flags |= TDF_NEEDRESCHED;
318 }
319 
320 /*
321  * Force switch among equal priority processes every 100ms.
322  * We don't actually need to force a context switch of the current process.
323  * The act of firing the event triggers a context switch to softclock() and
324  * then switching back out again which is equivalent to a preemption, thus
325  * no further work is needed on the local CPU.
326  */
327 /* ARGSUSED */
328 static void
329 roundrobin(void *arg)
330 {
331 
332 #ifdef SMP
333 	mtx_lock_spin(&sched_lock);
334 	forward_roundrobin();
335 	mtx_unlock_spin(&sched_lock);
336 #endif
337 
338 	callout_reset(&roundrobin_callout, sched_quantum, roundrobin, NULL);
339 }
340 
341 /*
342  * Constants for digital decay and forget:
343  *	90% of (kg_estcpu) usage in 5 * loadav time
344  *	95% of (ke_pctcpu) usage in 60 seconds (load insensitive)
345  *          Note that, as ps(1) mentions, this can let percentages
346  *          total over 100% (I've seen 137.9% for 3 processes).
347  *
348  * Note that schedclock() updates kg_estcpu and p_cpticks asynchronously.
349  *
350  * We wish to decay away 90% of kg_estcpu in (5 * loadavg) seconds.
351  * That is, the system wants to compute a value of decay such
352  * that the following for loop:
353  * 	for (i = 0; i < (5 * loadavg); i++)
354  * 		kg_estcpu *= decay;
355  * will compute
356  * 	kg_estcpu *= 0.1;
357  * for all values of loadavg:
358  *
359  * Mathematically this loop can be expressed by saying:
360  * 	decay ** (5 * loadavg) ~= .1
361  *
362  * The system computes decay as:
363  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
364  *
365  * We wish to prove that the system's computation of decay
366  * will always fulfill the equation:
367  * 	decay ** (5 * loadavg) ~= .1
368  *
369  * If we compute b as:
370  * 	b = 2 * loadavg
371  * then
372  * 	decay = b / (b + 1)
373  *
374  * We now need to prove two things:
375  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
376  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
377  *
378  * Facts:
379  *         For x close to zero, exp(x) =~ 1 + x, since
380  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
381  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
382  *         For x close to zero, ln(1+x) =~ x, since
383  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
384  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
385  *         ln(.1) =~ -2.30
386  *
387  * Proof of (1):
388  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
389  *	solving for factor,
390  *      ln(factor) =~ (-2.30/5*loadav), or
391  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
392  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
393  *
394  * Proof of (2):
395  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
396  *	solving for power,
397  *      power*ln(b/(b+1)) =~ -2.30, or
398  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
399  *
400  * Actual power values for the implemented algorithm are as follows:
401  *      loadav: 1       2       3       4
402  *      power:  5.68    10.32   14.94   19.55
403  */
404 
405 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
406 #define	loadfactor(loadav)	(2 * (loadav))
407 #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
408 
409 /* decay 95% of `ke_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
410 static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
411 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
412 
413 /*
414  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
415  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
416  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
417  *
418  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
419  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
420  *
421  * If you don't want to bother with the faster/more-accurate formula, you
422  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
423  * (more general) method of calculating the %age of CPU used by a process.
424  */
425 #define	CCPU_SHIFT	11
426 
427 /*
428  * Recompute process priorities, every hz ticks.
429  * MP-safe, called without the Giant mutex.
430  */
431 /* ARGSUSED */
432 static void
433 schedcpu(void)
434 {
435 	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
436 	struct thread *td;
437 	struct proc *p;
438 	struct kse *ke;
439 	struct ksegrp *kg;
440 	int awake, realstathz;
441 
442 	realstathz = stathz ? stathz : hz;
443 	sx_slock(&allproc_lock);
444 	FOREACH_PROC_IN_SYSTEM(p) {
445 		/*
446 		 * Prevent state changes and protect run queue.
447 		 */
448 		mtx_lock_spin(&sched_lock);
449 		/*
450 		 * Increment time in/out of memory.  We ignore overflow; with
451 		 * 16-bit int's (remember them?) overflow takes 45 days.
452 		 */
453 		p->p_swtime++;
454 		FOREACH_KSEGRP_IN_PROC(p, kg) {
455 			awake = 0;
456 			FOREACH_THREAD_IN_GROUP(kg, td) {
457 				ke = td->td_kse;
458 				/*
459 				 * Increment sleep time (if sleeping).  We
460 				 * ignore overflow, as above.
461 				 */
462 				/*
463 				 * The kse slptimes are not touched in wakeup
464 				 * because the thread may not HAVE a KSE.
465 				 */
466 				if (ke->ke_state == KES_ONRUNQ) {
467 					awake = 1;
468 					ke->ke_flags &= ~KEF_DIDRUN;
469 				} else if ((ke->ke_state == KES_THREAD) &&
470 				    (TD_IS_RUNNING(td))) {
471 					awake = 1;
472 					/* Do not clear KEF_DIDRUN */
473 				} else if (ke->ke_flags & KEF_DIDRUN) {
474 					awake = 1;
475 					ke->ke_flags &= ~KEF_DIDRUN;
476 				}
477 
478 				/*
479 				 * ke_pctcpu is only for ps and ttyinfo().
480 				 * Do it per kse, and add them up at the end?
481 				 * XXXKSE
482 				 */
483 				ke->ke_pctcpu = (ke->ke_pctcpu * ccpu) >>
484 				    FSHIFT;
485 				/*
486 				 * If the kse has been idle the entire second,
487 				 * stop recalculating its priority until
488 				 * it wakes up.
489 				 */
490 				if (ke->ke_cpticks == 0)
491 					continue;
492 #if	(FSHIFT >= CCPU_SHIFT)
493 				ke->ke_pctcpu += (realstathz == 100)
494 				    ? ((fixpt_t) ke->ke_cpticks) <<
495 				    (FSHIFT - CCPU_SHIFT) :
496 				    100 * (((fixpt_t) ke->ke_cpticks)
497 				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
498 #else
499 				ke->ke_pctcpu += ((FSCALE - ccpu) *
500 				    (ke->ke_cpticks *
501 				    FSCALE / realstathz)) >> FSHIFT;
502 #endif
503 				ke->ke_cpticks = 0;
504 			} /* end of kse loop */
505 			/*
506 			 * If there are ANY running threads in this KSEGRP,
507 			 * then don't count it as sleeping.
508 			 */
509 			if (awake) {
510 				if (kg->kg_slptime > 1) {
511 					/*
512 					 * In an ideal world, this should not
513 					 * happen, because whoever woke us
514 					 * up from the long sleep should have
515 					 * unwound the slptime and reset our
516 					 * priority before we run at the stale
517 					 * priority.  Should KASSERT at some
518 					 * point when all the cases are fixed.
519 					 */
520 					updatepri(kg);
521 				}
522 				kg->kg_slptime = 0;
523 			} else
524 				kg->kg_slptime++;
525 			if (kg->kg_slptime > 1)
526 				continue;
527 			kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu);
528 		      	resetpriority(kg);
529 			FOREACH_THREAD_IN_GROUP(kg, td) {
530 				resetpriority_thread(td, kg);
531 			}
532 		} /* end of ksegrp loop */
533 		mtx_unlock_spin(&sched_lock);
534 	} /* end of process loop */
535 	sx_sunlock(&allproc_lock);
536 }
537 
538 /*
539  * Main loop for a kthread that executes schedcpu once a second.
540  */
541 static void
542 schedcpu_thread(void)
543 {
544 	int nowake;
545 
546 	for (;;) {
547 		schedcpu();
548 		tsleep(&nowake, 0, "-", hz);
549 	}
550 }
551 
552 /*
553  * Recalculate the priority of a process after it has slept for a while.
554  * For all load averages >= 1 and max kg_estcpu of 255, sleeping for at
555  * least six times the loadfactor will decay kg_estcpu to zero.
556  */
557 static void
558 updatepri(struct ksegrp *kg)
559 {
560 	register fixpt_t loadfac;
561 	register unsigned int newcpu;
562 
563 	loadfac = loadfactor(averunnable.ldavg[0]);
564 	if (kg->kg_slptime > 5 * loadfac)
565 		kg->kg_estcpu = 0;
566 	else {
567 		newcpu = kg->kg_estcpu;
568 		kg->kg_slptime--;	/* was incremented in schedcpu() */
569 		while (newcpu && --kg->kg_slptime)
570 			newcpu = decay_cpu(loadfac, newcpu);
571 		kg->kg_estcpu = newcpu;
572 	}
573 }
574 
575 /*
576  * Compute the priority of a process when running in user mode.
577  * Arrange to reschedule if the resulting priority is better
578  * than that of the current process.
579  */
580 static void
581 resetpriority(struct ksegrp *kg)
582 {
583 	register unsigned int newpriority;
584 
585 	if (kg->kg_pri_class == PRI_TIMESHARE) {
586 		newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT +
587 		    NICE_WEIGHT * (kg->kg_proc->p_nice - PRIO_MIN);
588 		newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
589 		    PRI_MAX_TIMESHARE);
590 		sched_user_prio(kg, newpriority);
591 	}
592 }
593 
594 /*
595  * Update the thread's priority when the associated ksegroup's user
596  * priority changes.
597  */
598 static void
599 resetpriority_thread(struct thread *td, struct ksegrp *kg)
600 {
601 
602 	/* Only change threads with a time sharing user priority. */
603 	if (td->td_priority < PRI_MIN_TIMESHARE ||
604 	    td->td_priority > PRI_MAX_TIMESHARE)
605 		return;
606 
607 	/* XXX the whole needresched thing is broken, but not silly. */
608 	maybe_resched(td);
609 
610 	sched_prio(td, kg->kg_user_pri);
611 }
612 
613 /* ARGSUSED */
614 static void
615 sched_setup(void *dummy)
616 {
617 	setup_runqs();
618 
619 	if (sched_quantum == 0)
620 		sched_quantum = SCHED_QUANTUM;
621 	hogticks = 2 * sched_quantum;
622 
623 	callout_init(&roundrobin_callout, CALLOUT_MPSAFE);
624 
625 	/* Kick off timeout driven events by calling first time. */
626 	roundrobin(NULL);
627 
628 	/* Account for thread0. */
629 	sched_load_add();
630 }
631 
632 /* External interfaces start here */
633 /*
634  * Very early in the boot some setup of scheduler-specific
635  * parts of proc0 and of some scheduler resources needs to be done.
636  * Called from:
637  *  proc0_init()
638  */
639 void
640 schedinit(void)
641 {
642 	/*
643 	 * Set up the scheduler specific parts of proc0.
644 	 */
645 	proc0.p_sched = NULL; /* XXX */
646 	ksegrp0.kg_sched = &kg_sched0;
647 	thread0.td_sched = &kse0;
648 	kse0.ke_thread = &thread0;
649 	kse0.ke_state = KES_THREAD;
650 	kg_sched0.skg_concurrency = 1;
651 	kg_sched0.skg_avail_opennings = 0; /* we are already running */
652 }
653 
654 int
655 sched_runnable(void)
656 {
657 #ifdef SMP
658 	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
659 #else
660 	return runq_check(&runq);
661 #endif
662 }
663 
664 int
665 sched_rr_interval(void)
666 {
667 	if (sched_quantum == 0)
668 		sched_quantum = SCHED_QUANTUM;
669 	return (sched_quantum);
670 }
671 
672 /*
673  * We adjust the priority of the current process.  The priority of
674  * a process gets worse as it accumulates CPU time.  The cpu usage
675  * estimator (kg_estcpu) is increased here.  resetpriority() will
676  * compute a different priority each time kg_estcpu increases by
677  * INVERSE_ESTCPU_WEIGHT
678  * (until MAXPRI is reached).  The cpu usage estimator ramps up
679  * quite quickly when the process is running (linearly), and decays
680  * away exponentially, at a rate which is proportionally slower when
681  * the system is busy.  The basic principle is that the system will
682  * 90% forget that the process used a lot of CPU time in 5 * loadav
683  * seconds.  This causes the system to favor processes which haven't
684  * run much recently, and to round-robin among other processes.
685  */
686 void
687 sched_clock(struct thread *td)
688 {
689 	struct ksegrp *kg;
690 	struct kse *ke;
691 
692 	mtx_assert(&sched_lock, MA_OWNED);
693 	kg = td->td_ksegrp;
694 	ke = td->td_kse;
695 
696 	ke->ke_cpticks++;
697 	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1);
698 	if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
699 		resetpriority(kg);
700 		resetpriority_thread(td, kg);
701 	}
702 }
703 
704 /*
705  * charge childs scheduling cpu usage to parent.
706  *
707  * XXXKSE assume only one thread & kse & ksegrp keep estcpu in each ksegrp.
708  * Charge it to the ksegrp that did the wait since process estcpu is sum of
709  * all ksegrps, this is strictly as expected.  Assume that the child process
710  * aggregated all the estcpu into the 'built-in' ksegrp.
711  */
712 void
713 sched_exit(struct proc *p, struct thread *td)
714 {
715 	sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), td);
716 	sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
717 }
718 
719 void
720 sched_exit_ksegrp(struct ksegrp *kg, struct thread *childtd)
721 {
722 
723 	mtx_assert(&sched_lock, MA_OWNED);
724 	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + childtd->td_ksegrp->kg_estcpu);
725 }
726 
727 void
728 sched_exit_thread(struct thread *td, struct thread *child)
729 {
730 	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
731 	    child, child->td_proc->p_comm, child->td_priority);
732 	if ((child->td_proc->p_flag & P_NOLOAD) == 0)
733 		sched_load_rem();
734 }
735 
736 void
737 sched_fork(struct thread *td, struct thread *childtd)
738 {
739 	sched_fork_ksegrp(td, childtd->td_ksegrp);
740 	sched_fork_thread(td, childtd);
741 }
742 
743 void
744 sched_fork_ksegrp(struct thread *td, struct ksegrp *child)
745 {
746 	mtx_assert(&sched_lock, MA_OWNED);
747 	child->kg_estcpu = td->td_ksegrp->kg_estcpu;
748 }
749 
750 void
751 sched_fork_thread(struct thread *td, struct thread *childtd)
752 {
753 	sched_newthread(childtd);
754 }
755 
756 void
757 sched_nice(struct proc *p, int nice)
758 {
759 	struct ksegrp *kg;
760 	struct thread *td;
761 
762 	PROC_LOCK_ASSERT(p, MA_OWNED);
763 	mtx_assert(&sched_lock, MA_OWNED);
764 	p->p_nice = nice;
765 	FOREACH_KSEGRP_IN_PROC(p, kg) {
766 		resetpriority(kg);
767 		FOREACH_THREAD_IN_GROUP(kg, td) {
768 			resetpriority_thread(td, kg);
769 		}
770 	}
771 }
772 
773 void
774 sched_class(struct ksegrp *kg, int class)
775 {
776 	mtx_assert(&sched_lock, MA_OWNED);
777 	kg->kg_pri_class = class;
778 }
779 
780 /*
781  * Adjust the priority of a thread.
782  * This may include moving the thread within the KSEGRP,
783  * changing the assignment of a kse to the thread,
784  * and moving a KSE in the system run queue.
785  */
786 static void
787 sched_priority(struct thread *td, u_char prio)
788 {
789 	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
790 	    td, td->td_proc->p_comm, td->td_priority, prio, curthread,
791 	    curthread->td_proc->p_comm);
792 
793 	mtx_assert(&sched_lock, MA_OWNED);
794 	if (td->td_priority == prio)
795 		return;
796 	if (TD_ON_RUNQ(td)) {
797 		adjustrunqueue(td, prio);
798 	} else {
799 		td->td_priority = prio;
800 	}
801 }
802 
803 /*
804  * Update a thread's priority when it is lent another thread's
805  * priority.
806  */
807 void
808 sched_lend_prio(struct thread *td, u_char prio)
809 {
810 
811 	td->td_flags |= TDF_BORROWING;
812 	sched_priority(td, prio);
813 }
814 
815 /*
816  * Restore a thread's priority when priority propagation is
817  * over.  The prio argument is the minimum priority the thread
818  * needs to have to satisfy other possible priority lending
819  * requests.  If the thread's regulary priority is less
820  * important than prio the thread will keep a priority boost
821  * of prio.
822  */
823 void
824 sched_unlend_prio(struct thread *td, u_char prio)
825 {
826 	u_char base_pri;
827 
828 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
829 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
830 		base_pri = td->td_ksegrp->kg_user_pri;
831 	else
832 		base_pri = td->td_base_pri;
833 	if (prio >= base_pri) {
834 		td->td_flags &= ~TDF_BORROWING;
835 		sched_prio(td, base_pri);
836 	} else
837 		sched_lend_prio(td, prio);
838 }
839 
840 void
841 sched_prio(struct thread *td, u_char prio)
842 {
843 	u_char oldprio;
844 
845 	/* First, update the base priority. */
846 	td->td_base_pri = prio;
847 
848 	/*
849 	 * If the thread is borrowing another thread's priority, don't ever
850 	 * lower the priority.
851 	 */
852 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
853 		return;
854 
855 	/* Change the real priority. */
856 	oldprio = td->td_priority;
857 	sched_priority(td, prio);
858 
859 	/*
860 	 * If the thread is on a turnstile, then let the turnstile update
861 	 * its state.
862 	 */
863 	if (TD_ON_LOCK(td) && oldprio != prio)
864 		turnstile_adjust(td, oldprio);
865 }
866 
867 void
868 sched_user_prio(struct ksegrp *kg, u_char prio)
869 {
870 	struct thread *td;
871 	u_char oldprio;
872 
873 	kg->kg_base_user_pri = prio;
874 
875 	/* XXXKSE only for 1:1 */
876 
877 	td = TAILQ_FIRST(&kg->kg_threads);
878 	if (td == NULL) {
879 		kg->kg_user_pri = prio;
880 		return;
881 	}
882 
883 	if (td->td_flags & TDF_UBORROWING && kg->kg_user_pri <= prio)
884 		return;
885 
886 	oldprio = kg->kg_user_pri;
887 	kg->kg_user_pri = prio;
888 
889 	if (TD_ON_UPILOCK(td) && oldprio != prio)
890 		umtx_pi_adjust(td, oldprio);
891 }
892 
893 void
894 sched_lend_user_prio(struct thread *td, u_char prio)
895 {
896 	u_char oldprio;
897 
898 	td->td_flags |= TDF_UBORROWING;
899 
900 	oldprio = td->td_ksegrp->kg_user_pri;
901 	td->td_ksegrp->kg_user_pri = prio;
902 
903 	if (TD_ON_UPILOCK(td) && oldprio != prio)
904 		umtx_pi_adjust(td, oldprio);
905 }
906 
907 void
908 sched_unlend_user_prio(struct thread *td, u_char prio)
909 {
910 	struct ksegrp *kg = td->td_ksegrp;
911 	u_char base_pri;
912 
913 	base_pri = kg->kg_base_user_pri;
914 	if (prio >= base_pri) {
915 		td->td_flags &= ~TDF_UBORROWING;
916 		sched_user_prio(kg, base_pri);
917 	} else
918 		sched_lend_user_prio(td, prio);
919 }
920 
921 void
922 sched_sleep(struct thread *td)
923 {
924 
925 	mtx_assert(&sched_lock, MA_OWNED);
926 	td->td_ksegrp->kg_slptime = 0;
927 }
928 
929 static void remrunqueue(struct thread *td);
930 
931 void
932 sched_switch(struct thread *td, struct thread *newtd, int flags)
933 {
934 	struct kse *ke;
935 	struct ksegrp *kg;
936 	struct proc *p;
937 
938 	ke = td->td_kse;
939 	p = td->td_proc;
940 
941 	mtx_assert(&sched_lock, MA_OWNED);
942 
943 	if ((p->p_flag & P_NOLOAD) == 0)
944 		sched_load_rem();
945 	/*
946 	 * We are volunteering to switch out so we get to nominate
947 	 * a successor for the rest of our quantum
948 	 * First try another thread in our ksegrp, and then look for
949 	 * other ksegrps in our process.
950 	 */
951 	if (sched_followon &&
952 	    (p->p_flag & P_HADTHREADS) &&
953 	    (flags & SW_VOL) &&
954 	    newtd == NULL) {
955 		/* lets schedule another thread from this process */
956 		 kg = td->td_ksegrp;
957 		 if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
958 			remrunqueue(newtd);
959 			sched_kgfollowons++;
960 		 } else {
961 			FOREACH_KSEGRP_IN_PROC(p, kg) {
962 				if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
963 					sched_pfollowons++;
964 					remrunqueue(newtd);
965 					break;
966 				}
967 			}
968 		}
969 	}
970 
971 	if (newtd)
972 		newtd->td_flags |= (td->td_flags & TDF_NEEDRESCHED);
973 
974 	td->td_lastcpu = td->td_oncpu;
975 	td->td_flags &= ~TDF_NEEDRESCHED;
976 	td->td_owepreempt = 0;
977 	td->td_oncpu = NOCPU;
978 	/*
979 	 * At the last moment, if this thread is still marked RUNNING,
980 	 * then put it back on the run queue as it has not been suspended
981 	 * or stopped or any thing else similar.  We never put the idle
982 	 * threads on the run queue, however.
983 	 */
984 	if (td == PCPU_GET(idlethread))
985 		TD_SET_CAN_RUN(td);
986 	else {
987 		SLOT_RELEASE(td->td_ksegrp);
988 		if (TD_IS_RUNNING(td)) {
989 			/* Put us back on the run queue (kse and all). */
990 			setrunqueue(td, (flags & SW_PREEMPT) ?
991 			    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
992 			    SRQ_OURSELF|SRQ_YIELDING);
993 		} else if (p->p_flag & P_HADTHREADS) {
994 			/*
995 			 * We will not be on the run queue. So we must be
996 			 * sleeping or similar. As it's available,
997 			 * someone else can use the KSE if they need it.
998 			 * It's NOT available if we are about to need it
999 			 */
1000 			if (newtd == NULL || newtd->td_ksegrp != td->td_ksegrp)
1001 				slot_fill(td->td_ksegrp);
1002 		}
1003 	}
1004 	if (newtd) {
1005 		/*
1006 		 * The thread we are about to run needs to be counted
1007 		 * as if it had been added to the run queue and selected.
1008 		 * It came from:
1009 		 * * A preemption
1010 		 * * An upcall
1011 		 * * A followon
1012 		 */
1013 		KASSERT((newtd->td_inhibitors == 0),
1014 			("trying to run inhibitted thread"));
1015 		SLOT_USE(newtd->td_ksegrp);
1016 		newtd->td_kse->ke_flags |= KEF_DIDRUN;
1017         	TD_SET_RUNNING(newtd);
1018 		if ((newtd->td_proc->p_flag & P_NOLOAD) == 0)
1019 			sched_load_add();
1020 	} else {
1021 		newtd = choosethread();
1022 	}
1023 
1024 	if (td != newtd) {
1025 #ifdef	HWPMC_HOOKS
1026 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1027 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1028 #endif
1029 		cpu_switch(td, newtd);
1030 #ifdef	HWPMC_HOOKS
1031 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1032 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1033 #endif
1034 	}
1035 
1036 	sched_lock.mtx_lock = (uintptr_t)td;
1037 	td->td_oncpu = PCPU_GET(cpuid);
1038 }
1039 
1040 void
1041 sched_wakeup(struct thread *td)
1042 {
1043 	struct ksegrp *kg;
1044 
1045 	mtx_assert(&sched_lock, MA_OWNED);
1046 	kg = td->td_ksegrp;
1047 	if (kg->kg_slptime > 1) {
1048 		updatepri(kg);
1049 		resetpriority(kg);
1050 	}
1051 	kg->kg_slptime = 0;
1052 	setrunqueue(td, SRQ_BORING);
1053 }
1054 
1055 #ifdef SMP
1056 /* enable HTT_2 if you have a 2-way HTT cpu.*/
1057 static int
1058 forward_wakeup(int  cpunum)
1059 {
1060 	cpumask_t map, me, dontuse;
1061 	cpumask_t map2;
1062 	struct pcpu *pc;
1063 	cpumask_t id, map3;
1064 
1065 	mtx_assert(&sched_lock, MA_OWNED);
1066 
1067 	CTR0(KTR_RUNQ, "forward_wakeup()");
1068 
1069 	if ((!forward_wakeup_enabled) ||
1070 	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
1071 		return (0);
1072 	if (!smp_started || cold || panicstr)
1073 		return (0);
1074 
1075 	forward_wakeups_requested++;
1076 
1077 /*
1078  * check the idle mask we received against what we calculated before
1079  * in the old version.
1080  */
1081 	me = PCPU_GET(cpumask);
1082 	/*
1083 	 * don't bother if we should be doing it ourself..
1084 	 */
1085 	if ((me & idle_cpus_mask) && (cpunum == NOCPU || me == (1 << cpunum)))
1086 		return (0);
1087 
1088 	dontuse = me | stopped_cpus | hlt_cpus_mask;
1089 	map3 = 0;
1090 	if (forward_wakeup_use_loop) {
1091 		SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
1092 			id = pc->pc_cpumask;
1093 			if ( (id & dontuse) == 0 &&
1094 			    pc->pc_curthread == pc->pc_idlethread) {
1095 				map3 |= id;
1096 			}
1097 		}
1098 	}
1099 
1100 	if (forward_wakeup_use_mask) {
1101 		map = 0;
1102 		map = idle_cpus_mask & ~dontuse;
1103 
1104 		/* If they are both on, compare and use loop if different */
1105 		if (forward_wakeup_use_loop) {
1106 			if (map != map3) {
1107 				printf("map (%02X) != map3 (%02X)\n",
1108 						map, map3);
1109 				map = map3;
1110 			}
1111 		}
1112 	} else {
1113 		map = map3;
1114 	}
1115 	/* If we only allow a specific CPU, then mask off all the others */
1116 	if (cpunum != NOCPU) {
1117 		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1118 		map &= (1 << cpunum);
1119 	} else {
1120 		/* Try choose an idle die. */
1121 		if (forward_wakeup_use_htt) {
1122 			map2 =  (map & (map >> 1)) & 0x5555;
1123 			if (map2) {
1124 				map = map2;
1125 			}
1126 		}
1127 
1128 		/* set only one bit */
1129 		if (forward_wakeup_use_single) {
1130 			map = map & ((~map) + 1);
1131 		}
1132 	}
1133 	if (map) {
1134 		forward_wakeups_delivered++;
1135 		ipi_selected(map, IPI_AST);
1136 		return (1);
1137 	}
1138 	if (cpunum == NOCPU)
1139 		printf("forward_wakeup: Idle processor not found\n");
1140 	return (0);
1141 }
1142 #endif
1143 
1144 #ifdef SMP
1145 static void kick_other_cpu(int pri,int cpuid);
1146 
1147 static void
1148 kick_other_cpu(int pri,int cpuid)
1149 {
1150 	struct pcpu * pcpu = pcpu_find(cpuid);
1151 	int cpri = pcpu->pc_curthread->td_priority;
1152 
1153 	if (idle_cpus_mask & pcpu->pc_cpumask) {
1154 		forward_wakeups_delivered++;
1155 		ipi_selected(pcpu->pc_cpumask, IPI_AST);
1156 		return;
1157 	}
1158 
1159 	if (pri >= cpri)
1160 		return;
1161 
1162 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1163 #if !defined(FULL_PREEMPTION)
1164 	if (pri <= PRI_MAX_ITHD)
1165 #endif /* ! FULL_PREEMPTION */
1166 	{
1167 		ipi_selected(pcpu->pc_cpumask, IPI_PREEMPT);
1168 		return;
1169 	}
1170 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1171 
1172 	pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1173 	ipi_selected( pcpu->pc_cpumask , IPI_AST);
1174 	return;
1175 }
1176 #endif /* SMP */
1177 
1178 void
1179 sched_add(struct thread *td, int flags)
1180 #ifdef SMP
1181 {
1182 	struct kse *ke;
1183 	int forwarded = 0;
1184 	int cpu;
1185 	int single_cpu = 0;
1186 
1187 	ke = td->td_kse;
1188 	mtx_assert(&sched_lock, MA_OWNED);
1189 	KASSERT(ke->ke_state != KES_ONRUNQ,
1190 	    ("sched_add: kse %p (%s) already in run queue", ke,
1191 	    ke->ke_proc->p_comm));
1192 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1193 	    ("sched_add: process swapped out"));
1194 	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1195 	    td, td->td_proc->p_comm, td->td_priority, curthread,
1196 	    curthread->td_proc->p_comm);
1197 
1198 
1199 	if (td->td_pinned != 0) {
1200 		cpu = td->td_lastcpu;
1201 		ke->ke_runq = &runq_pcpu[cpu];
1202 		single_cpu = 1;
1203 		CTR3(KTR_RUNQ,
1204 		    "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
1205 	} else if ((ke)->ke_flags & KEF_BOUND) {
1206 		/* Find CPU from bound runq */
1207 		KASSERT(SKE_RUNQ_PCPU(ke),("sched_add: bound kse not on cpu runq"));
1208 		cpu = ke->ke_runq - &runq_pcpu[0];
1209 		single_cpu = 1;
1210 		CTR3(KTR_RUNQ,
1211 		    "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
1212 	} else {
1213 		CTR2(KTR_RUNQ,
1214 		    "sched_add: adding kse:%p (td:%p) to gbl runq", ke, td);
1215 		cpu = NOCPU;
1216 		ke->ke_runq = &runq;
1217 	}
1218 
1219 	if (single_cpu && (cpu != PCPU_GET(cpuid))) {
1220 	        kick_other_cpu(td->td_priority,cpu);
1221 	} else {
1222 
1223 		if (!single_cpu) {
1224 			cpumask_t me = PCPU_GET(cpumask);
1225 			int idle = idle_cpus_mask & me;
1226 
1227 			if (!idle && ((flags & SRQ_INTR) == 0) &&
1228 			    (idle_cpus_mask & ~(hlt_cpus_mask | me)))
1229 				forwarded = forward_wakeup(cpu);
1230 		}
1231 
1232 		if (!forwarded) {
1233 			if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1234 				return;
1235 			else
1236 				maybe_resched(td);
1237 		}
1238 	}
1239 
1240 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1241 		sched_load_add();
1242 	SLOT_USE(td->td_ksegrp);
1243 	runq_add(ke->ke_runq, ke, flags);
1244 	ke->ke_state = KES_ONRUNQ;
1245 }
1246 #else /* SMP */
1247 {
1248 	struct kse *ke;
1249 	ke = td->td_kse;
1250 	mtx_assert(&sched_lock, MA_OWNED);
1251 	KASSERT(ke->ke_state != KES_ONRUNQ,
1252 	    ("sched_add: kse %p (%s) already in run queue", ke,
1253 	    ke->ke_proc->p_comm));
1254 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1255 	    ("sched_add: process swapped out"));
1256 	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1257 	    td, td->td_proc->p_comm, td->td_priority, curthread,
1258 	    curthread->td_proc->p_comm);
1259 	CTR2(KTR_RUNQ, "sched_add: adding kse:%p (td:%p) to runq", ke, td);
1260 	ke->ke_runq = &runq;
1261 
1262 	/*
1263 	 * If we are yielding (on the way out anyhow)
1264 	 * or the thread being saved is US,
1265 	 * then don't try be smart about preemption
1266 	 * or kicking off another CPU
1267 	 * as it won't help and may hinder.
1268 	 * In the YIEDLING case, we are about to run whoever is
1269 	 * being put in the queue anyhow, and in the
1270 	 * OURSELF case, we are puting ourself on the run queue
1271 	 * which also only happens when we are about to yield.
1272 	 */
1273 	if((flags & SRQ_YIELDING) == 0) {
1274 		if (maybe_preempt(td))
1275 			return;
1276 	}
1277 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1278 		sched_load_add();
1279 	SLOT_USE(td->td_ksegrp);
1280 	runq_add(ke->ke_runq, ke, flags);
1281 	ke->ke_state = KES_ONRUNQ;
1282 	maybe_resched(td);
1283 }
1284 #endif /* SMP */
1285 
1286 void
1287 sched_rem(struct thread *td)
1288 {
1289 	struct kse *ke;
1290 
1291 	ke = td->td_kse;
1292 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1293 	    ("sched_rem: process swapped out"));
1294 	KASSERT((ke->ke_state == KES_ONRUNQ),
1295 	    ("sched_rem: KSE not on run queue"));
1296 	mtx_assert(&sched_lock, MA_OWNED);
1297 	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
1298 	    td, td->td_proc->p_comm, td->td_priority, curthread,
1299 	    curthread->td_proc->p_comm);
1300 
1301 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1302 		sched_load_rem();
1303 	SLOT_RELEASE(td->td_ksegrp);
1304 	runq_remove(ke->ke_runq, ke);
1305 
1306 	ke->ke_state = KES_THREAD;
1307 }
1308 
1309 /*
1310  * Select threads to run.
1311  * Notice that the running threads still consume a slot.
1312  */
1313 struct kse *
1314 sched_choose(void)
1315 {
1316 	struct kse *ke;
1317 	struct runq *rq;
1318 
1319 #ifdef SMP
1320 	struct kse *kecpu;
1321 
1322 	rq = &runq;
1323 	ke = runq_choose(&runq);
1324 	kecpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1325 
1326 	if (ke == NULL ||
1327 	    (kecpu != NULL &&
1328 	     kecpu->ke_thread->td_priority < ke->ke_thread->td_priority)) {
1329 		CTR2(KTR_RUNQ, "choosing kse %p from pcpu runq %d", kecpu,
1330 		     PCPU_GET(cpuid));
1331 		ke = kecpu;
1332 		rq = &runq_pcpu[PCPU_GET(cpuid)];
1333 	} else {
1334 		CTR1(KTR_RUNQ, "choosing kse %p from main runq", ke);
1335 	}
1336 
1337 #else
1338 	rq = &runq;
1339 	ke = runq_choose(&runq);
1340 #endif
1341 
1342 	if (ke != NULL) {
1343 		runq_remove(rq, ke);
1344 		ke->ke_state = KES_THREAD;
1345 
1346 		KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1347 		    ("sched_choose: process swapped out"));
1348 	}
1349 	return (ke);
1350 }
1351 
1352 void
1353 sched_userret(struct thread *td)
1354 {
1355 	struct ksegrp *kg;
1356 	/*
1357 	 * XXX we cheat slightly on the locking here to avoid locking in
1358 	 * the usual case.  Setting td_priority here is essentially an
1359 	 * incomplete workaround for not setting it properly elsewhere.
1360 	 * Now that some interrupt handlers are threads, not setting it
1361 	 * properly elsewhere can clobber it in the window between setting
1362 	 * it here and returning to user mode, so don't waste time setting
1363 	 * it perfectly here.
1364 	 */
1365 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
1366 	    ("thread with borrowed priority returning to userland"));
1367 	kg = td->td_ksegrp;
1368 	if (td->td_priority != kg->kg_user_pri) {
1369 		mtx_lock_spin(&sched_lock);
1370 		td->td_priority = kg->kg_user_pri;
1371 		td->td_base_pri = kg->kg_user_pri;
1372 		mtx_unlock_spin(&sched_lock);
1373 	}
1374 }
1375 
1376 void
1377 sched_bind(struct thread *td, int cpu)
1378 {
1379 	struct kse *ke;
1380 
1381 	mtx_assert(&sched_lock, MA_OWNED);
1382 	KASSERT(TD_IS_RUNNING(td),
1383 	    ("sched_bind: cannot bind non-running thread"));
1384 
1385 	ke = td->td_kse;
1386 
1387 	ke->ke_flags |= KEF_BOUND;
1388 #ifdef SMP
1389 	ke->ke_runq = &runq_pcpu[cpu];
1390 	if (PCPU_GET(cpuid) == cpu)
1391 		return;
1392 
1393 	ke->ke_state = KES_THREAD;
1394 
1395 	mi_switch(SW_VOL, NULL);
1396 #endif
1397 }
1398 
1399 void
1400 sched_unbind(struct thread* td)
1401 {
1402 	mtx_assert(&sched_lock, MA_OWNED);
1403 	td->td_kse->ke_flags &= ~KEF_BOUND;
1404 }
1405 
1406 int
1407 sched_is_bound(struct thread *td)
1408 {
1409 	mtx_assert(&sched_lock, MA_OWNED);
1410 	return (td->td_kse->ke_flags & KEF_BOUND);
1411 }
1412 
1413 void
1414 sched_relinquish(struct thread *td)
1415 {
1416 	struct ksegrp *kg;
1417 
1418 	kg = td->td_ksegrp;
1419 	mtx_lock_spin(&sched_lock);
1420 	if (kg->kg_pri_class == PRI_TIMESHARE)
1421 		sched_prio(td, PRI_MAX_TIMESHARE);
1422 	mi_switch(SW_VOL, NULL);
1423 	mtx_unlock_spin(&sched_lock);
1424 }
1425 
1426 int
1427 sched_load(void)
1428 {
1429 	return (sched_tdcnt);
1430 }
1431 
1432 int
1433 sched_sizeof_ksegrp(void)
1434 {
1435 	return (sizeof(struct ksegrp) + sizeof(struct kg_sched));
1436 }
1437 
1438 int
1439 sched_sizeof_proc(void)
1440 {
1441 	return (sizeof(struct proc));
1442 }
1443 
1444 int
1445 sched_sizeof_thread(void)
1446 {
1447 	return (sizeof(struct thread) + sizeof(struct kse));
1448 }
1449 
1450 fixpt_t
1451 sched_pctcpu(struct thread *td)
1452 {
1453 	struct kse *ke;
1454 
1455 	ke = td->td_kse;
1456 	return (ke->ke_pctcpu);
1457 }
1458 
1459 void
1460 sched_tick(void)
1461 {
1462 }
1463 #define KERN_SWITCH_INCLUDE 1
1464 #include "kern/kern_switch.c"
1465