xref: /freebsd/sys/kern/sched_4bsd.c (revision b8aa2713423518bc3d708a08b52433096de96e9b)
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 #if	(FSHIFT >= CCPU_SHIFT)
594 				ke->ke_pctcpu += (realstathz == 100)
595 			    	? ((fixpt_t) ke->ke_cpticks) <<
596 			    	(FSHIFT - CCPU_SHIFT) :
597 			    	100 * (((fixpt_t) ke->ke_cpticks)
598 			    	<< (FSHIFT - CCPU_SHIFT)) / realstathz;
599 #else
600 				ke->ke_pctcpu += ((FSCALE - ccpu) *
601 			    	(ke->ke_cpticks *
602 			    	FSCALE / realstathz)) >> FSHIFT;
603 #endif
604 				ke->ke_cpticks = 0;
605 			}
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 	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1142 		return;
1143 	oldprio = td->td_user_pri;
1144 	td->td_user_pri = prio;
1145 #endif
1146 
1147 	if (TD_ON_UPILOCK(td) && oldprio != prio)
1148 		umtx_pi_adjust(td, oldprio);
1149 }
1150 
1151 void
1152 sched_lend_user_prio(struct thread *td, u_char prio)
1153 {
1154 	u_char oldprio;
1155 
1156 	td->td_flags |= TDF_UBORROWING;
1157 
1158 #ifdef KSE
1159 	oldprio = td->td_ksegrp->kg_user_pri;
1160 	td->td_ksegrp->kg_user_pri = prio;
1161 #else
1162 	oldprio = td->td_user_pri;
1163 	td->td_user_pri = prio;
1164 #endif
1165 
1166 	if (TD_ON_UPILOCK(td) && oldprio != prio)
1167 		umtx_pi_adjust(td, oldprio);
1168 }
1169 
1170 void
1171 sched_unlend_user_prio(struct thread *td, u_char prio)
1172 {
1173 #ifdef KSE
1174 	struct ksegrp *kg = td->td_ksegrp;
1175 #endif
1176 	u_char base_pri;
1177 
1178 #ifdef KSE
1179 	base_pri = kg->kg_base_user_pri;
1180 #else
1181 	base_pri = td->td_base_user_pri;
1182 #endif
1183 	if (prio >= base_pri) {
1184 		td->td_flags &= ~TDF_UBORROWING;
1185 #ifdef KSE
1186 		sched_user_prio(kg, base_pri);
1187 #else
1188 		sched_user_prio(td, base_pri);
1189 #endif
1190 	} else
1191 		sched_lend_user_prio(td, prio);
1192 }
1193 
1194 void
1195 sched_sleep(struct thread *td)
1196 {
1197 
1198 	mtx_assert(&sched_lock, MA_OWNED);
1199 #ifdef KSE
1200 	td->td_ksegrp->kg_slptime = 0;
1201 #else
1202 	td->td_slptime = 0;
1203 #endif
1204 }
1205 
1206 #ifdef KSE
1207 static void remrunqueue(struct thread *td);
1208 #endif
1209 
1210 void
1211 sched_switch(struct thread *td, struct thread *newtd, int flags)
1212 {
1213 	struct kse *ke;
1214 #ifdef KSE
1215 	struct ksegrp *kg;
1216 #endif
1217 	struct proc *p;
1218 
1219 	ke = td->td_kse;
1220 	p = td->td_proc;
1221 
1222 	mtx_assert(&sched_lock, MA_OWNED);
1223 
1224 	if ((p->p_flag & P_NOLOAD) == 0)
1225 		sched_load_rem();
1226 #ifdef KSE
1227 	/*
1228 	 * We are volunteering to switch out so we get to nominate
1229 	 * a successor for the rest of our quantum
1230 	 * First try another thread in our ksegrp, and then look for
1231 	 * other ksegrps in our process.
1232 	 */
1233 	if (sched_followon &&
1234 	    (p->p_flag & P_HADTHREADS) &&
1235 	    (flags & SW_VOL) &&
1236 	    newtd == NULL) {
1237 		/* lets schedule another thread from this process */
1238 		 kg = td->td_ksegrp;
1239 		 if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
1240 			remrunqueue(newtd);
1241 			sched_kgfollowons++;
1242 		 } else {
1243 			FOREACH_KSEGRP_IN_PROC(p, kg) {
1244 				if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
1245 					sched_pfollowons++;
1246 					remrunqueue(newtd);
1247 					break;
1248 				}
1249 			}
1250 		}
1251 	}
1252 #endif
1253 
1254 	if (newtd)
1255 		newtd->td_flags |= (td->td_flags & TDF_NEEDRESCHED);
1256 
1257 	td->td_lastcpu = td->td_oncpu;
1258 	td->td_flags &= ~TDF_NEEDRESCHED;
1259 	td->td_owepreempt = 0;
1260 	td->td_oncpu = NOCPU;
1261 	/*
1262 	 * At the last moment, if this thread is still marked RUNNING,
1263 	 * then put it back on the run queue as it has not been suspended
1264 	 * or stopped or any thing else similar.  We never put the idle
1265 	 * threads on the run queue, however.
1266 	 */
1267 	if (td == PCPU_GET(idlethread))
1268 		TD_SET_CAN_RUN(td);
1269 	else {
1270 #ifdef KSE
1271 		SLOT_RELEASE(td->td_ksegrp);
1272 #endif
1273 		if (TD_IS_RUNNING(td)) {
1274 			/* Put us back on the run queue (kse and all). */
1275 			setrunqueue(td, (flags & SW_PREEMPT) ?
1276 			    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1277 			    SRQ_OURSELF|SRQ_YIELDING);
1278 #ifdef KSE
1279 		} else if (p->p_flag & P_HADTHREADS) {
1280 			/*
1281 			 * We will not be on the run queue. So we must be
1282 			 * sleeping or similar. As it's available,
1283 			 * someone else can use the KSE if they need it.
1284 			 * It's NOT available if we are about to need it
1285 			 */
1286 			if (newtd == NULL || newtd->td_ksegrp != td->td_ksegrp)
1287 				slot_fill(td->td_ksegrp);
1288 #endif
1289 		}
1290 	}
1291 	if (newtd) {
1292 		/*
1293 		 * The thread we are about to run needs to be counted
1294 		 * as if it had been added to the run queue and selected.
1295 		 * It came from:
1296 		 * * A preemption
1297 		 * ifdef KSE
1298 		 * * An upcall
1299 		 * endif
1300 		 * * A followon
1301 		 */
1302 		KASSERT((newtd->td_inhibitors == 0),
1303 			("trying to run inhibitted thread"));
1304 #ifdef KSE
1305 		SLOT_USE(newtd->td_ksegrp);
1306 #endif
1307 		newtd->td_kse->ke_flags |= KEF_DIDRUN;
1308         	TD_SET_RUNNING(newtd);
1309 		if ((newtd->td_proc->p_flag & P_NOLOAD) == 0)
1310 			sched_load_add();
1311 	} else {
1312 		newtd = choosethread();
1313 	}
1314 
1315 	if (td != newtd) {
1316 #ifdef	HWPMC_HOOKS
1317 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1318 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1319 #endif
1320 
1321 		cpu_switch(td, newtd);
1322 #ifdef	HWPMC_HOOKS
1323 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1324 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1325 #endif
1326 	}
1327 
1328 	sched_lock.mtx_lock = (uintptr_t)td;
1329 	td->td_oncpu = PCPU_GET(cpuid);
1330 }
1331 
1332 void
1333 sched_wakeup(struct thread *td)
1334 {
1335 #ifdef KSE
1336 	struct ksegrp *kg;
1337 #endif
1338 
1339 	mtx_assert(&sched_lock, MA_OWNED);
1340 #ifdef KSE
1341 	kg = td->td_ksegrp;
1342 	if (kg->kg_slptime > 1) {
1343 		updatepri(kg);
1344 		resetpriority(kg);
1345 	}
1346 	kg->kg_slptime = 0;
1347 #else
1348 	if (td->td_slptime > 1) {
1349 		updatepri(td);
1350 		resetpriority(td);
1351 	}
1352 	td->td_slptime = 0;
1353 #endif
1354 	setrunqueue(td, SRQ_BORING);
1355 }
1356 
1357 #ifdef SMP
1358 /* enable HTT_2 if you have a 2-way HTT cpu.*/
1359 static int
1360 forward_wakeup(int  cpunum)
1361 {
1362 	cpumask_t map, me, dontuse;
1363 	cpumask_t map2;
1364 	struct pcpu *pc;
1365 	cpumask_t id, map3;
1366 
1367 	mtx_assert(&sched_lock, MA_OWNED);
1368 
1369 	CTR0(KTR_RUNQ, "forward_wakeup()");
1370 
1371 	if ((!forward_wakeup_enabled) ||
1372 	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
1373 		return (0);
1374 	if (!smp_started || cold || panicstr)
1375 		return (0);
1376 
1377 	forward_wakeups_requested++;
1378 
1379 /*
1380  * check the idle mask we received against what we calculated before
1381  * in the old version.
1382  */
1383 	me = PCPU_GET(cpumask);
1384 	/*
1385 	 * don't bother if we should be doing it ourself..
1386 	 */
1387 	if ((me & idle_cpus_mask) && (cpunum == NOCPU || me == (1 << cpunum)))
1388 		return (0);
1389 
1390 	dontuse = me | stopped_cpus | hlt_cpus_mask;
1391 	map3 = 0;
1392 	if (forward_wakeup_use_loop) {
1393 		SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
1394 			id = pc->pc_cpumask;
1395 			if ( (id & dontuse) == 0 &&
1396 			    pc->pc_curthread == pc->pc_idlethread) {
1397 				map3 |= id;
1398 			}
1399 		}
1400 	}
1401 
1402 	if (forward_wakeup_use_mask) {
1403 		map = 0;
1404 		map = idle_cpus_mask & ~dontuse;
1405 
1406 		/* If they are both on, compare and use loop if different */
1407 		if (forward_wakeup_use_loop) {
1408 			if (map != map3) {
1409 				printf("map (%02X) != map3 (%02X)\n",
1410 						map, map3);
1411 				map = map3;
1412 			}
1413 		}
1414 	} else {
1415 		map = map3;
1416 	}
1417 	/* If we only allow a specific CPU, then mask off all the others */
1418 	if (cpunum != NOCPU) {
1419 		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1420 		map &= (1 << cpunum);
1421 	} else {
1422 		/* Try choose an idle die. */
1423 		if (forward_wakeup_use_htt) {
1424 			map2 =  (map & (map >> 1)) & 0x5555;
1425 			if (map2) {
1426 				map = map2;
1427 			}
1428 		}
1429 
1430 		/* set only one bit */
1431 		if (forward_wakeup_use_single) {
1432 			map = map & ((~map) + 1);
1433 		}
1434 	}
1435 	if (map) {
1436 		forward_wakeups_delivered++;
1437 		ipi_selected(map, IPI_AST);
1438 		return (1);
1439 	}
1440 	if (cpunum == NOCPU)
1441 		printf("forward_wakeup: Idle processor not found\n");
1442 	return (0);
1443 }
1444 #endif
1445 
1446 #ifdef SMP
1447 static void kick_other_cpu(int pri,int cpuid);
1448 
1449 static void
1450 kick_other_cpu(int pri,int cpuid)
1451 {
1452 	struct pcpu * pcpu = pcpu_find(cpuid);
1453 	int cpri = pcpu->pc_curthread->td_priority;
1454 
1455 	if (idle_cpus_mask & pcpu->pc_cpumask) {
1456 		forward_wakeups_delivered++;
1457 		ipi_selected(pcpu->pc_cpumask, IPI_AST);
1458 		return;
1459 	}
1460 
1461 	if (pri >= cpri)
1462 		return;
1463 
1464 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1465 #if !defined(FULL_PREEMPTION)
1466 	if (pri <= PRI_MAX_ITHD)
1467 #endif /* ! FULL_PREEMPTION */
1468 	{
1469 		ipi_selected(pcpu->pc_cpumask, IPI_PREEMPT);
1470 		return;
1471 	}
1472 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1473 
1474 	pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1475 	ipi_selected( pcpu->pc_cpumask , IPI_AST);
1476 	return;
1477 }
1478 #endif /* SMP */
1479 
1480 void
1481 sched_add(struct thread *td, int flags)
1482 #ifdef SMP
1483 {
1484 	struct kse *ke;
1485 	int forwarded = 0;
1486 	int cpu;
1487 	int single_cpu = 0;
1488 
1489 	ke = td->td_kse;
1490 	mtx_assert(&sched_lock, MA_OWNED);
1491 	KASSERT(ke->ke_state != KES_ONRUNQ,
1492 	    ("sched_add: kse %p (%s) already in run queue", ke,
1493 #ifdef KSE
1494 	    ke->ke_proc->p_comm));
1495 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1496 #else
1497 	    td->td_proc->p_comm));
1498 	KASSERT(td->td_proc->p_sflag & PS_INMEM,
1499 #endif
1500 	    ("sched_add: process swapped out"));
1501 	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1502 	    td, td->td_proc->p_comm, td->td_priority, curthread,
1503 	    curthread->td_proc->p_comm);
1504 
1505 
1506 	if (td->td_pinned != 0) {
1507 		cpu = td->td_lastcpu;
1508 		ke->ke_runq = &runq_pcpu[cpu];
1509 		single_cpu = 1;
1510 		CTR3(KTR_RUNQ,
1511 		    "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
1512 	} else if ((ke)->ke_flags & KEF_BOUND) {
1513 		/* Find CPU from bound runq */
1514 		KASSERT(SKE_RUNQ_PCPU(ke),("sched_add: bound kse not on cpu runq"));
1515 		cpu = ke->ke_runq - &runq_pcpu[0];
1516 		single_cpu = 1;
1517 		CTR3(KTR_RUNQ,
1518 		    "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
1519 	} else {
1520 		CTR2(KTR_RUNQ,
1521 		    "sched_add: adding kse:%p (td:%p) to gbl runq", ke, td);
1522 		cpu = NOCPU;
1523 		ke->ke_runq = &runq;
1524 	}
1525 
1526 	if (single_cpu && (cpu != PCPU_GET(cpuid))) {
1527 	        kick_other_cpu(td->td_priority,cpu);
1528 	} else {
1529 
1530 		if (!single_cpu) {
1531 			cpumask_t me = PCPU_GET(cpumask);
1532 			int idle = idle_cpus_mask & me;
1533 
1534 			if (!idle && ((flags & SRQ_INTR) == 0) &&
1535 			    (idle_cpus_mask & ~(hlt_cpus_mask | me)))
1536 				forwarded = forward_wakeup(cpu);
1537 		}
1538 
1539 		if (!forwarded) {
1540 			if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1541 				return;
1542 			else
1543 				maybe_resched(td);
1544 		}
1545 	}
1546 
1547 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1548 		sched_load_add();
1549 #ifdef KSE
1550 	SLOT_USE(td->td_ksegrp);
1551 #endif
1552 	runq_add(ke->ke_runq, ke, flags);
1553 	ke->ke_state = KES_ONRUNQ;
1554 }
1555 #else /* SMP */
1556 {
1557 	struct kse *ke;
1558 	ke = td->td_kse;
1559 	mtx_assert(&sched_lock, MA_OWNED);
1560 	KASSERT(ke->ke_state != KES_ONRUNQ,
1561 	    ("sched_add: kse %p (%s) already in run queue", ke,
1562 #ifdef KSE
1563 	    ke->ke_proc->p_comm));
1564 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1565 #else
1566 	    td->td_proc->p_comm));
1567 	KASSERT(td->td_proc->p_sflag & PS_INMEM,
1568 #endif
1569 	    ("sched_add: process swapped out"));
1570 	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1571 	    td, td->td_proc->p_comm, td->td_priority, curthread,
1572 	    curthread->td_proc->p_comm);
1573 	CTR2(KTR_RUNQ, "sched_add: adding kse:%p (td:%p) to runq", ke, td);
1574 	ke->ke_runq = &runq;
1575 
1576 	/*
1577 	 * If we are yielding (on the way out anyhow)
1578 	 * or the thread being saved is US,
1579 	 * then don't try be smart about preemption
1580 	 * or kicking off another CPU
1581 	 * as it won't help and may hinder.
1582 	 * In the YIEDLING case, we are about to run whoever is
1583 	 * being put in the queue anyhow, and in the
1584 	 * OURSELF case, we are puting ourself on the run queue
1585 	 * which also only happens when we are about to yield.
1586 	 */
1587 	if((flags & SRQ_YIELDING) == 0) {
1588 		if (maybe_preempt(td))
1589 			return;
1590 	}
1591 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1592 		sched_load_add();
1593 #ifdef KSE
1594 	SLOT_USE(td->td_ksegrp);
1595 #endif
1596 	runq_add(ke->ke_runq, ke, flags);
1597 	ke->ke_state = KES_ONRUNQ;
1598 	maybe_resched(td);
1599 }
1600 #endif /* SMP */
1601 
1602 void
1603 sched_rem(struct thread *td)
1604 {
1605 	struct kse *ke;
1606 
1607 	ke = td->td_kse;
1608 #ifdef KSE
1609 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1610 #else
1611 	KASSERT(td->td_proc->p_sflag & PS_INMEM,
1612 #endif
1613 	    ("sched_rem: process swapped out"));
1614 	KASSERT((ke->ke_state == KES_ONRUNQ),
1615 	    ("sched_rem: KSE not on run queue"));
1616 	mtx_assert(&sched_lock, MA_OWNED);
1617 	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
1618 	    td, td->td_proc->p_comm, td->td_priority, curthread,
1619 	    curthread->td_proc->p_comm);
1620 
1621 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1622 		sched_load_rem();
1623 #ifdef KSE
1624 	SLOT_RELEASE(td->td_ksegrp);
1625 #endif
1626 	runq_remove(ke->ke_runq, ke);
1627 
1628 	ke->ke_state = KES_THREAD;
1629 }
1630 
1631 /*
1632  * Select threads to run.
1633  * Notice that the running threads still consume a slot.
1634  */
1635 #ifdef KSE
1636 struct kse *
1637 #else
1638 struct thread *
1639 #endif
1640 sched_choose(void)
1641 {
1642 	struct kse *ke;
1643 	struct runq *rq;
1644 
1645 #ifdef SMP
1646 	struct kse *kecpu;
1647 
1648 	rq = &runq;
1649 	ke = runq_choose(&runq);
1650 	kecpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1651 
1652 	if (ke == NULL ||
1653 	    (kecpu != NULL &&
1654 	     kecpu->ke_thread->td_priority < ke->ke_thread->td_priority)) {
1655 		CTR2(KTR_RUNQ, "choosing kse %p from pcpu runq %d", kecpu,
1656 		     PCPU_GET(cpuid));
1657 		ke = kecpu;
1658 		rq = &runq_pcpu[PCPU_GET(cpuid)];
1659 	} else {
1660 		CTR1(KTR_RUNQ, "choosing kse %p from main runq", ke);
1661 	}
1662 
1663 #else
1664 	rq = &runq;
1665 	ke = runq_choose(&runq);
1666 #endif
1667 
1668 #ifdef KSE
1669 	if (ke != NULL) {
1670 #else
1671 	if (ke) {
1672 #endif
1673 		runq_remove(rq, ke);
1674 		ke->ke_state = KES_THREAD;
1675 
1676 #ifdef KSE
1677 		KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1678 		    ("sched_choose: process swapped out"));
1679 #else
1680 		KASSERT(ke->ke_thread->td_proc->p_sflag & PS_INMEM,
1681 		    ("sched_choose: process swapped out"));
1682 		return (ke->ke_thread);
1683 #endif
1684 	}
1685 #ifdef KSE
1686 	return (ke);
1687 #else
1688 	return (NULL);
1689 #endif
1690 }
1691 
1692 void
1693 sched_userret(struct thread *td)
1694 {
1695 #ifdef KSE
1696 	struct ksegrp *kg;
1697 #endif
1698 	/*
1699 	 * XXX we cheat slightly on the locking here to avoid locking in
1700 	 * the usual case.  Setting td_priority here is essentially an
1701 	 * incomplete workaround for not setting it properly elsewhere.
1702 	 * Now that some interrupt handlers are threads, not setting it
1703 	 * properly elsewhere can clobber it in the window between setting
1704 	 * it here and returning to user mode, so don't waste time setting
1705 	 * it perfectly here.
1706 	 */
1707 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
1708 	    ("thread with borrowed priority returning to userland"));
1709 #ifdef KSE
1710 	kg = td->td_ksegrp;
1711 	if (td->td_priority != kg->kg_user_pri) {
1712 		mtx_lock_spin(&sched_lock);
1713 		td->td_priority = kg->kg_user_pri;
1714 		td->td_base_pri = kg->kg_user_pri;
1715 		mtx_unlock_spin(&sched_lock);
1716 	}
1717 #else
1718 	if (td->td_priority != td->td_user_pri) {
1719 		mtx_lock_spin(&sched_lock);
1720 		td->td_priority = td->td_user_pri;
1721 		td->td_base_pri = td->td_user_pri;
1722 		mtx_unlock_spin(&sched_lock);
1723 	}
1724 #endif
1725 }
1726 
1727 void
1728 sched_bind(struct thread *td, int cpu)
1729 {
1730 	struct kse *ke;
1731 
1732 	mtx_assert(&sched_lock, MA_OWNED);
1733 	KASSERT(TD_IS_RUNNING(td),
1734 	    ("sched_bind: cannot bind non-running thread"));
1735 
1736 	ke = td->td_kse;
1737 
1738 	ke->ke_flags |= KEF_BOUND;
1739 #ifdef SMP
1740 	ke->ke_runq = &runq_pcpu[cpu];
1741 	if (PCPU_GET(cpuid) == cpu)
1742 		return;
1743 
1744 	ke->ke_state = KES_THREAD;
1745 
1746 	mi_switch(SW_VOL, NULL);
1747 #endif
1748 }
1749 
1750 void
1751 sched_unbind(struct thread* td)
1752 {
1753 	mtx_assert(&sched_lock, MA_OWNED);
1754 	td->td_kse->ke_flags &= ~KEF_BOUND;
1755 }
1756 
1757 int
1758 sched_is_bound(struct thread *td)
1759 {
1760 	mtx_assert(&sched_lock, MA_OWNED);
1761 	return (td->td_kse->ke_flags & KEF_BOUND);
1762 }
1763 
1764 void
1765 sched_relinquish(struct thread *td)
1766 {
1767 #ifdef KSE
1768 	struct ksegrp *kg;
1769 
1770 	kg = td->td_ksegrp;
1771 #endif
1772 	mtx_lock_spin(&sched_lock);
1773 #ifdef KSE
1774 	if (kg->kg_pri_class == PRI_TIMESHARE)
1775 #else
1776 	if (td->td_pri_class == PRI_TIMESHARE)
1777 #endif
1778 		sched_prio(td, PRI_MAX_TIMESHARE);
1779 	mi_switch(SW_VOL, NULL);
1780 	mtx_unlock_spin(&sched_lock);
1781 }
1782 
1783 int
1784 sched_load(void)
1785 {
1786 	return (sched_tdcnt);
1787 }
1788 
1789 #ifdef KSE
1790 int
1791 sched_sizeof_ksegrp(void)
1792 {
1793 	return (sizeof(struct ksegrp) + sizeof(struct kg_sched));
1794 }
1795 #endif
1796 
1797 int
1798 sched_sizeof_proc(void)
1799 {
1800 	return (sizeof(struct proc));
1801 }
1802 
1803 int
1804 sched_sizeof_thread(void)
1805 {
1806 	return (sizeof(struct thread) + sizeof(struct kse));
1807 }
1808 
1809 fixpt_t
1810 sched_pctcpu(struct thread *td)
1811 {
1812 	struct kse *ke;
1813 
1814 	ke = td->td_kse;
1815 	return (ke->ke_pctcpu);
1816 }
1817 
1818 void
1819 sched_tick(void)
1820 {
1821 }
1822 #define KERN_SWITCH_INCLUDE 1
1823 #include "kern/kern_switch.c"
1824