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