xref: /freebsd/sys/kern/sched_4bsd.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
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/mutex.h>
48 #include <sys/proc.h>
49 #include <sys/resourcevar.h>
50 #include <sys/sched.h>
51 #include <sys/smp.h>
52 #include <sys/sysctl.h>
53 #include <sys/sx.h>
54 
55 /*
56  * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
57  * the range 100-256 Hz (approximately).
58  */
59 #define	ESTCPULIM(e) \
60     min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
61     RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
62 #define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
63 #define	NICE_WEIGHT		1	/* Priorities per nice level. */
64 
65 struct ke_sched {
66 	int	ske_cpticks;	/* (j) Ticks of cpu time. */
67 };
68 
69 static struct ke_sched ke_sched;
70 
71 struct ke_sched *kse0_sched = &ke_sched;
72 struct kg_sched *ksegrp0_sched = NULL;
73 struct p_sched *proc0_sched = NULL;
74 struct td_sched *thread0_sched = NULL;
75 
76 static int	sched_quantum;	/* Roundrobin scheduling quantum in ticks. */
77 #define	SCHED_QUANTUM	(hz / 10)	/* Default sched quantum */
78 
79 static struct callout schedcpu_callout;
80 static struct callout roundrobin_callout;
81 
82 static void	roundrobin(void *arg);
83 static void	schedcpu(void *arg);
84 static void	sched_setup(void *dummy);
85 static void	maybe_resched(struct thread *td);
86 static void	updatepri(struct ksegrp *kg);
87 static void	resetpriority(struct ksegrp *kg);
88 
89 SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
90 
91 /*
92  * Global run queue.
93  */
94 static struct runq runq;
95 SYSINIT(runq, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, runq_init, &runq)
96 
97 static int
98 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
99 {
100 	int error, new_val;
101 
102 	new_val = sched_quantum * tick;
103 	error = sysctl_handle_int(oidp, &new_val, 0, req);
104         if (error != 0 || req->newptr == NULL)
105 		return (error);
106 	if (new_val < tick)
107 		return (EINVAL);
108 	sched_quantum = new_val / tick;
109 	hogticks = 2 * sched_quantum;
110 	return (0);
111 }
112 
113 SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
114 	0, sizeof sched_quantum, sysctl_kern_quantum, "I",
115 	"Roundrobin scheduling quantum in microseconds");
116 
117 /*
118  * Arrange to reschedule if necessary, taking the priorities and
119  * schedulers into account.
120  */
121 static void
122 maybe_resched(struct thread *td)
123 {
124 
125 	mtx_assert(&sched_lock, MA_OWNED);
126 	if (td->td_priority < curthread->td_priority && curthread->td_kse)
127 		curthread->td_flags |= TDF_NEEDRESCHED;
128 }
129 
130 /*
131  * Force switch among equal priority processes every 100ms.
132  * We don't actually need to force a context switch of the current process.
133  * The act of firing the event triggers a context switch to softclock() and
134  * then switching back out again which is equivalent to a preemption, thus
135  * no further work is needed on the local CPU.
136  */
137 /* ARGSUSED */
138 static void
139 roundrobin(void *arg)
140 {
141 
142 #ifdef SMP
143 	mtx_lock_spin(&sched_lock);
144 	forward_roundrobin();
145 	mtx_unlock_spin(&sched_lock);
146 #endif
147 
148 	callout_reset(&roundrobin_callout, sched_quantum, roundrobin, NULL);
149 }
150 
151 /*
152  * Constants for digital decay and forget:
153  *	90% of (kg_estcpu) usage in 5 * loadav time
154  *	95% of (ke_pctcpu) usage in 60 seconds (load insensitive)
155  *          Note that, as ps(1) mentions, this can let percentages
156  *          total over 100% (I've seen 137.9% for 3 processes).
157  *
158  * Note that schedclock() updates kg_estcpu and p_cpticks asynchronously.
159  *
160  * We wish to decay away 90% of kg_estcpu in (5 * loadavg) seconds.
161  * That is, the system wants to compute a value of decay such
162  * that the following for loop:
163  * 	for (i = 0; i < (5 * loadavg); i++)
164  * 		kg_estcpu *= decay;
165  * will compute
166  * 	kg_estcpu *= 0.1;
167  * for all values of loadavg:
168  *
169  * Mathematically this loop can be expressed by saying:
170  * 	decay ** (5 * loadavg) ~= .1
171  *
172  * The system computes decay as:
173  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
174  *
175  * We wish to prove that the system's computation of decay
176  * will always fulfill the equation:
177  * 	decay ** (5 * loadavg) ~= .1
178  *
179  * If we compute b as:
180  * 	b = 2 * loadavg
181  * then
182  * 	decay = b / (b + 1)
183  *
184  * We now need to prove two things:
185  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
186  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
187  *
188  * Facts:
189  *         For x close to zero, exp(x) =~ 1 + x, since
190  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
191  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
192  *         For x close to zero, ln(1+x) =~ x, since
193  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
194  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
195  *         ln(.1) =~ -2.30
196  *
197  * Proof of (1):
198  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
199  *	solving for factor,
200  *      ln(factor) =~ (-2.30/5*loadav), or
201  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
202  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
203  *
204  * Proof of (2):
205  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
206  *	solving for power,
207  *      power*ln(b/(b+1)) =~ -2.30, or
208  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
209  *
210  * Actual power values for the implemented algorithm are as follows:
211  *      loadav: 1       2       3       4
212  *      power:  5.68    10.32   14.94   19.55
213  */
214 
215 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
216 #define	loadfactor(loadav)	(2 * (loadav))
217 #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
218 
219 /* decay 95% of `ke_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
220 static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
221 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
222 
223 /*
224  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
225  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
226  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
227  *
228  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
229  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
230  *
231  * If you don't want to bother with the faster/more-accurate formula, you
232  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
233  * (more general) method of calculating the %age of CPU used by a process.
234  */
235 #define	CCPU_SHIFT	11
236 
237 /*
238  * Recompute process priorities, every hz ticks.
239  * MP-safe, called without the Giant mutex.
240  */
241 /* ARGSUSED */
242 static void
243 schedcpu(void *arg)
244 {
245 	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
246 	struct thread *td;
247 	struct proc *p;
248 	struct kse *ke;
249 	struct ksegrp *kg;
250 	int awake, realstathz;
251 
252 	realstathz = stathz ? stathz : hz;
253 	sx_slock(&allproc_lock);
254 	FOREACH_PROC_IN_SYSTEM(p) {
255 		/*
256 		 * Prevent state changes and protect run queue.
257 		 */
258 		mtx_lock_spin(&sched_lock);
259 		/*
260 		 * Increment time in/out of memory.  We ignore overflow; with
261 		 * 16-bit int's (remember them?) overflow takes 45 days.
262 		 */
263 		p->p_swtime++;
264 		FOREACH_KSEGRP_IN_PROC(p, kg) {
265 			awake = 0;
266 			FOREACH_KSE_IN_GROUP(kg, ke) {
267 				/*
268 				 * Increment sleep time (if sleeping).  We
269 				 * ignore overflow, as above.
270 				 */
271 				/*
272 				 * The kse slptimes are not touched in wakeup
273 				 * because the thread may not HAVE a KSE.
274 				 */
275 				if (ke->ke_state == KES_ONRUNQ) {
276 					awake = 1;
277 					ke->ke_flags &= ~KEF_DIDRUN;
278 				} else if ((ke->ke_state == KES_THREAD) &&
279 				    (TD_IS_RUNNING(ke->ke_thread))) {
280 					awake = 1;
281 					/* Do not clear KEF_DIDRUN */
282 				} else if (ke->ke_flags & KEF_DIDRUN) {
283 					awake = 1;
284 					ke->ke_flags &= ~KEF_DIDRUN;
285 				}
286 
287 				/*
288 				 * ke_pctcpu is only for ps and ttyinfo().
289 				 * Do it per kse, and add them up at the end?
290 				 * XXXKSE
291 				 */
292 				ke->ke_pctcpu = (ke->ke_pctcpu * ccpu) >>
293 				    FSHIFT;
294 				/*
295 				 * If the kse has been idle the entire second,
296 				 * stop recalculating its priority until
297 				 * it wakes up.
298 				 */
299 				if (ke->ke_sched->ske_cpticks == 0)
300 					continue;
301 #if	(FSHIFT >= CCPU_SHIFT)
302 				ke->ke_pctcpu += (realstathz == 100)
303 				    ? ((fixpt_t) ke->ke_sched->ske_cpticks) <<
304 				    (FSHIFT - CCPU_SHIFT) :
305 				    100 * (((fixpt_t) ke->ke_sched->ske_cpticks)
306 				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
307 #else
308 				ke->ke_pctcpu += ((FSCALE - ccpu) *
309 				    (ke->ke_sched->ske_cpticks *
310 				    FSCALE / realstathz)) >> FSHIFT;
311 #endif
312 				ke->ke_sched->ske_cpticks = 0;
313 			} /* end of kse loop */
314 			/*
315 			 * If there are ANY running threads in this KSEGRP,
316 			 * then don't count it as sleeping.
317 			 */
318 			if (awake) {
319 				if (kg->kg_slptime > 1) {
320 					/*
321 					 * In an ideal world, this should not
322 					 * happen, because whoever woke us
323 					 * up from the long sleep should have
324 					 * unwound the slptime and reset our
325 					 * priority before we run at the stale
326 					 * priority.  Should KASSERT at some
327 					 * point when all the cases are fixed.
328 					 */
329 					updatepri(kg);
330 				}
331 				kg->kg_slptime = 0;
332 			} else
333 				kg->kg_slptime++;
334 			if (kg->kg_slptime > 1)
335 				continue;
336 			kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu);
337 		      	resetpriority(kg);
338 			FOREACH_THREAD_IN_GROUP(kg, td) {
339 				if (td->td_priority >= PUSER) {
340 					sched_prio(td, kg->kg_user_pri);
341 				}
342 			}
343 		} /* end of ksegrp loop */
344 		mtx_unlock_spin(&sched_lock);
345 	} /* end of process loop */
346 	sx_sunlock(&allproc_lock);
347 	callout_reset(&schedcpu_callout, hz, schedcpu, NULL);
348 }
349 
350 /*
351  * Recalculate the priority of a process after it has slept for a while.
352  * For all load averages >= 1 and max kg_estcpu of 255, sleeping for at
353  * least six times the loadfactor will decay kg_estcpu to zero.
354  */
355 static void
356 updatepri(struct ksegrp *kg)
357 {
358 	register fixpt_t loadfac;
359 	register unsigned int newcpu;
360 
361 	loadfac = loadfactor(averunnable.ldavg[0]);
362 	if (kg->kg_slptime > 5 * loadfac)
363 		kg->kg_estcpu = 0;
364 	else {
365 		newcpu = kg->kg_estcpu;
366 		kg->kg_slptime--;	/* was incremented in schedcpu() */
367 		while (newcpu && --kg->kg_slptime)
368 			newcpu = decay_cpu(loadfac, newcpu);
369 		kg->kg_estcpu = newcpu;
370 	}
371 	resetpriority(kg);
372 }
373 
374 /*
375  * Compute the priority of a process when running in user mode.
376  * Arrange to reschedule if the resulting priority is better
377  * than that of the current process.
378  */
379 static void
380 resetpriority(struct ksegrp *kg)
381 {
382 	register unsigned int newpriority;
383 	struct thread *td;
384 
385 	if (kg->kg_pri_class == PRI_TIMESHARE) {
386 		newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT +
387 		    NICE_WEIGHT * (kg->kg_nice - PRIO_MIN);
388 		newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
389 		    PRI_MAX_TIMESHARE);
390 		kg->kg_user_pri = newpriority;
391 	}
392 	FOREACH_THREAD_IN_GROUP(kg, td) {
393 		maybe_resched(td);			/* XXXKSE silly */
394 	}
395 }
396 
397 /* ARGSUSED */
398 static void
399 sched_setup(void *dummy)
400 {
401 
402 	if (sched_quantum == 0)
403 		sched_quantum = SCHED_QUANTUM;
404 	hogticks = 2 * sched_quantum;
405 
406 	callout_init(&schedcpu_callout, CALLOUT_MPSAFE);
407 	callout_init(&roundrobin_callout, 0);
408 
409 	/* Kick off timeout driven events by calling first time. */
410 	roundrobin(NULL);
411 	schedcpu(NULL);
412 }
413 
414 /* External interfaces start here */
415 int
416 sched_runnable(void)
417 {
418         return runq_check(&runq);
419 }
420 
421 int
422 sched_rr_interval(void)
423 {
424 	if (sched_quantum == 0)
425 		sched_quantum = SCHED_QUANTUM;
426 	return (sched_quantum);
427 }
428 
429 /*
430  * We adjust the priority of the current process.  The priority of
431  * a process gets worse as it accumulates CPU time.  The cpu usage
432  * estimator (kg_estcpu) is increased here.  resetpriority() will
433  * compute a different priority each time kg_estcpu increases by
434  * INVERSE_ESTCPU_WEIGHT
435  * (until MAXPRI is reached).  The cpu usage estimator ramps up
436  * quite quickly when the process is running (linearly), and decays
437  * away exponentially, at a rate which is proportionally slower when
438  * the system is busy.  The basic principle is that the system will
439  * 90% forget that the process used a lot of CPU time in 5 * loadav
440  * seconds.  This causes the system to favor processes which haven't
441  * run much recently, and to round-robin among other processes.
442  */
443 void
444 sched_clock(struct kse *ke)
445 {
446 	struct ksegrp *kg;
447 	struct thread *td;
448 
449 	mtx_assert(&sched_lock, MA_OWNED);
450 	kg = ke->ke_ksegrp;
451 	td = ke->ke_thread;
452 
453 	ke->ke_sched->ske_cpticks++;
454 	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1);
455 	if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
456 		resetpriority(kg);
457 		if (td->td_priority >= PUSER)
458 			td->td_priority = kg->kg_user_pri;
459 	}
460 }
461 
462 /*
463  * charge childs scheduling cpu usage to parent.
464  *
465  * XXXKSE assume only one thread & kse & ksegrp keep estcpu in each ksegrp.
466  * Charge it to the ksegrp that did the wait since process estcpu is sum of
467  * all ksegrps, this is strictly as expected.  Assume that the child process
468  * aggregated all the estcpu into the 'built-in' ksegrp.
469  */
470 void
471 sched_exit(struct proc *p, struct proc *p1)
472 {
473 	sched_exit_kse(FIRST_KSE_IN_PROC(p), FIRST_KSE_IN_PROC(p1));
474 	sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), FIRST_KSEGRP_IN_PROC(p1));
475 	sched_exit_thread(FIRST_THREAD_IN_PROC(p), FIRST_THREAD_IN_PROC(p1));
476 }
477 
478 void
479 sched_exit_kse(struct kse *ke, struct kse *child)
480 {
481 }
482 
483 void
484 sched_exit_ksegrp(struct ksegrp *kg, struct ksegrp *child)
485 {
486 
487 	mtx_assert(&sched_lock, MA_OWNED);
488 	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + child->kg_estcpu);
489 }
490 
491 void
492 sched_exit_thread(struct thread *td, struct thread *child)
493 {
494 }
495 
496 void
497 sched_fork(struct proc *p, struct proc *p1)
498 {
499 	sched_fork_kse(FIRST_KSE_IN_PROC(p), FIRST_KSE_IN_PROC(p1));
500 	sched_fork_ksegrp(FIRST_KSEGRP_IN_PROC(p), FIRST_KSEGRP_IN_PROC(p1));
501 	sched_fork_thread(FIRST_THREAD_IN_PROC(p), FIRST_THREAD_IN_PROC(p1));
502 }
503 
504 void
505 sched_fork_kse(struct kse *ke, struct kse *child)
506 {
507 	child->ke_sched->ske_cpticks = 0;
508 }
509 
510 void
511 sched_fork_ksegrp(struct ksegrp *kg, struct ksegrp *child)
512 {
513 	mtx_assert(&sched_lock, MA_OWNED);
514 	child->kg_estcpu = kg->kg_estcpu;
515 }
516 
517 void
518 sched_fork_thread(struct thread *td, struct thread *child)
519 {
520 }
521 
522 void
523 sched_nice(struct ksegrp *kg, int nice)
524 {
525 
526 	PROC_LOCK_ASSERT(kg->kg_proc, MA_OWNED);
527 	mtx_assert(&sched_lock, MA_OWNED);
528 	kg->kg_nice = nice;
529 	resetpriority(kg);
530 }
531 
532 void
533 sched_class(struct ksegrp *kg, int class)
534 {
535 	mtx_assert(&sched_lock, MA_OWNED);
536 	kg->kg_pri_class = class;
537 }
538 
539 /*
540  * Adjust the priority of a thread.
541  * This may include moving the thread within the KSEGRP,
542  * changing the assignment of a kse to the thread,
543  * and moving a KSE in the system run queue.
544  */
545 void
546 sched_prio(struct thread *td, u_char prio)
547 {
548 
549 	mtx_assert(&sched_lock, MA_OWNED);
550 	if (TD_ON_RUNQ(td)) {
551 		adjustrunqueue(td, prio);
552 	} else {
553 		td->td_priority = prio;
554 	}
555 }
556 
557 void
558 sched_sleep(struct thread *td, u_char prio)
559 {
560 
561 	mtx_assert(&sched_lock, MA_OWNED);
562 	td->td_ksegrp->kg_slptime = 0;
563 	td->td_priority = prio;
564 }
565 
566 void
567 sched_switchin(struct thread *td)
568 {
569 
570 	mtx_assert(&sched_lock, MA_OWNED);
571 	td->td_oncpu = PCPU_GET(cpuid);
572 }
573 
574 void
575 sched_switchout(struct thread *td)
576 {
577 	struct kse *ke;
578 	struct proc *p;
579 
580 	ke = td->td_kse;
581 	p = td->td_proc;
582 
583 	mtx_assert(&sched_lock, MA_OWNED);
584 	KASSERT((ke->ke_state == KES_THREAD), ("mi_switch: kse state?"));
585 
586 	td->td_lastcpu = td->td_oncpu;
587 	td->td_last_kse = ke;
588 	td->td_oncpu = NOCPU;
589 	td->td_flags &= ~TDF_NEEDRESCHED;
590 	/*
591 	 * At the last moment, if this thread is still marked RUNNING,
592 	 * then put it back on the run queue as it has not been suspended
593 	 * or stopped or any thing else similar.
594 	 */
595 	if (TD_IS_RUNNING(td)) {
596 		/* Put us back on the run queue (kse and all). */
597 		setrunqueue(td);
598 	} else if (p->p_flag & P_SA) {
599 		/*
600 		 * We will not be on the run queue. So we must be
601 		 * sleeping or similar. As it's available,
602 		 * someone else can use the KSE if they need it.
603 		 */
604 		kse_reassign(ke);
605 	}
606 }
607 
608 void
609 sched_wakeup(struct thread *td)
610 {
611 	struct ksegrp *kg;
612 
613 	mtx_assert(&sched_lock, MA_OWNED);
614 	kg = td->td_ksegrp;
615 	if (kg->kg_slptime > 1)
616 		updatepri(kg);
617 	kg->kg_slptime = 0;
618 	setrunqueue(td);
619 	maybe_resched(td);
620 }
621 
622 void
623 sched_add(struct kse *ke)
624 {
625 	mtx_assert(&sched_lock, MA_OWNED);
626 	KASSERT((ke->ke_thread != NULL), ("runq_add: No thread on KSE"));
627 	KASSERT((ke->ke_thread->td_kse != NULL),
628 	    ("runq_add: No KSE on thread"));
629 	KASSERT(ke->ke_state != KES_ONRUNQ,
630 	    ("runq_add: kse %p (%s) already in run queue", ke,
631 	    ke->ke_proc->p_comm));
632 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
633 	    ("runq_add: process swapped out"));
634 	ke->ke_ksegrp->kg_runq_kses++;
635 	ke->ke_state = KES_ONRUNQ;
636 
637 	runq_add(&runq, ke);
638 }
639 
640 void
641 sched_rem(struct kse *ke)
642 {
643 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
644 	    ("runq_remove: process swapped out"));
645 	KASSERT((ke->ke_state == KES_ONRUNQ), ("KSE not on run queue"));
646 	mtx_assert(&sched_lock, MA_OWNED);
647 
648 	runq_remove(&runq, ke);
649 	ke->ke_state = KES_THREAD;
650 	ke->ke_ksegrp->kg_runq_kses--;
651 }
652 
653 struct kse *
654 sched_choose(void)
655 {
656 	struct kse *ke;
657 
658 	ke = runq_choose(&runq);
659 
660 	if (ke != NULL) {
661 		runq_remove(&runq, ke);
662 		ke->ke_state = KES_THREAD;
663 
664 		KASSERT((ke->ke_thread != NULL),
665 		    ("runq_choose: No thread on KSE"));
666 		KASSERT((ke->ke_thread->td_kse != NULL),
667 		    ("runq_choose: No KSE on thread"));
668 		KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
669 		    ("runq_choose: process swapped out"));
670 	}
671 	return (ke);
672 }
673 
674 void
675 sched_userret(struct thread *td)
676 {
677 	struct ksegrp *kg;
678 	/*
679 	 * XXX we cheat slightly on the locking here to avoid locking in
680 	 * the usual case.  Setting td_priority here is essentially an
681 	 * incomplete workaround for not setting it properly elsewhere.
682 	 * Now that some interrupt handlers are threads, not setting it
683 	 * properly elsewhere can clobber it in the window between setting
684 	 * it here and returning to user mode, so don't waste time setting
685 	 * it perfectly here.
686 	 */
687 	kg = td->td_ksegrp;
688 	if (td->td_priority != kg->kg_user_pri) {
689 		mtx_lock_spin(&sched_lock);
690 		td->td_priority = kg->kg_user_pri;
691 		mtx_unlock_spin(&sched_lock);
692 	}
693 }
694 
695 int
696 sched_sizeof_kse(void)
697 {
698 	return (sizeof(struct kse) + sizeof(struct ke_sched));
699 }
700 int
701 sched_sizeof_ksegrp(void)
702 {
703 	return (sizeof(struct ksegrp));
704 }
705 int
706 sched_sizeof_proc(void)
707 {
708 	return (sizeof(struct proc));
709 }
710 int
711 sched_sizeof_thread(void)
712 {
713 	return (sizeof(struct thread));
714 }
715 
716 fixpt_t
717 sched_pctcpu(struct kse *ke)
718 {
719 	return (ke->ke_pctcpu);
720 }
721