xref: /freebsd/sys/kern/sched_4bsd.c (revision 6fd05b64b5b65dd4ba9b86482a0634a5f0b96c29)
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 <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/ktr.h>
42 #include <sys/lock.h>
43 #include <sys/kthread.h>
44 #include <sys/mutex.h>
45 #include <sys/proc.h>
46 #include <sys/resourcevar.h>
47 #include <sys/sched.h>
48 #include <sys/smp.h>
49 #include <sys/sysctl.h>
50 #include <sys/sx.h>
51 
52 #define KTR_4BSD	0x0
53 
54 /*
55  * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
56  * the range 100-256 Hz (approximately).
57  */
58 #define	ESTCPULIM(e) \
59     min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
60     RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
61 #ifdef SMP
62 #define	INVERSE_ESTCPU_WEIGHT	(8 * smp_cpus)
63 #else
64 #define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
65 #endif
66 #define	NICE_WEIGHT		1	/* Priorities per nice level. */
67 
68 struct ke_sched {
69 	int		ske_cpticks;	/* (j) Ticks of cpu time. */
70 	struct runq	*ske_runq;	/* runq the kse is currently on */
71 };
72 #define ke_runq 	ke_sched->ske_runq
73 #define KEF_BOUND	KEF_SCHED1
74 
75 #define SKE_RUNQ_PCPU(ke)						\
76     ((ke)->ke_runq != 0 && (ke)->ke_runq != &runq)
77 
78 /*
79  * KSE_CAN_MIGRATE macro returns true if the kse can migrate between
80  * cpus.
81  */
82 #define KSE_CAN_MIGRATE(ke)						\
83     ((ke)->ke_thread->td_pinned == 0 && ((ke)->ke_flags & KEF_BOUND) == 0)
84 static struct ke_sched ke_sched;
85 
86 struct ke_sched *kse0_sched = &ke_sched;
87 struct kg_sched *ksegrp0_sched = NULL;
88 struct p_sched *proc0_sched = NULL;
89 struct td_sched *thread0_sched = NULL;
90 
91 static int	sched_tdcnt;	/* Total runnable threads in the system. */
92 static int	sched_quantum;	/* Roundrobin scheduling quantum in ticks. */
93 #define	SCHED_QUANTUM	(hz / 10)	/* Default sched quantum */
94 
95 static struct callout roundrobin_callout;
96 
97 static void	setup_runqs(void);
98 static void	roundrobin(void *arg);
99 static void	schedcpu(void);
100 static void	schedcpu_thread(void);
101 static void	sched_setup(void *dummy);
102 static void	maybe_resched(struct thread *td);
103 static void	updatepri(struct ksegrp *kg);
104 static void	resetpriority(struct ksegrp *kg);
105 
106 static struct kproc_desc sched_kp = {
107         "schedcpu",
108         schedcpu_thread,
109         NULL
110 };
111 SYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start, &sched_kp)
112 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
113 
114 /*
115  * Global run queue.
116  */
117 static struct runq runq;
118 
119 #ifdef SMP
120 /*
121  * Per-CPU run queues
122  */
123 static struct runq runq_pcpu[MAXCPU];
124 #endif
125 
126 static void
127 setup_runqs(void)
128 {
129 #ifdef SMP
130 	int i;
131 
132 	for (i = 0; i < MAXCPU; ++i)
133 		runq_init(&runq_pcpu[i]);
134 #endif
135 
136 	runq_init(&runq);
137 }
138 
139 static int
140 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
141 {
142 	int error, new_val;
143 
144 	new_val = sched_quantum * tick;
145 	error = sysctl_handle_int(oidp, &new_val, 0, req);
146         if (error != 0 || req->newptr == NULL)
147 		return (error);
148 	if (new_val < tick)
149 		return (EINVAL);
150 	sched_quantum = new_val / tick;
151 	hogticks = 2 * sched_quantum;
152 	return (0);
153 }
154 
155 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "SCHED");
156 
157 #define SCHD_NAME	"4bsd"
158 #define SCHD_NAME_LEN	4
159 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, SCHD_NAME, SCHD_NAME_LEN,
160 	      "System is using the 4BSD scheduler");
161 
162 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
163 	0, sizeof sched_quantum, sysctl_kern_quantum, "I",
164 	"Roundrobin scheduling quantum in microseconds");
165 
166 /*
167  * Arrange to reschedule if necessary, taking the priorities and
168  * schedulers into account.
169  */
170 static void
171 maybe_resched(struct thread *td)
172 {
173 
174 	mtx_assert(&sched_lock, MA_OWNED);
175 	if (td->td_priority < curthread->td_priority && curthread->td_kse)
176 		curthread->td_flags |= TDF_NEEDRESCHED;
177 }
178 
179 /*
180  * Force switch among equal priority processes every 100ms.
181  * We don't actually need to force a context switch of the current process.
182  * The act of firing the event triggers a context switch to softclock() and
183  * then switching back out again which is equivalent to a preemption, thus
184  * no further work is needed on the local CPU.
185  */
186 /* ARGSUSED */
187 static void
188 roundrobin(void *arg)
189 {
190 
191 #ifdef SMP
192 	mtx_lock_spin(&sched_lock);
193 	forward_roundrobin();
194 	mtx_unlock_spin(&sched_lock);
195 #endif
196 
197 	callout_reset(&roundrobin_callout, sched_quantum, roundrobin, NULL);
198 }
199 
200 /*
201  * Constants for digital decay and forget:
202  *	90% of (kg_estcpu) usage in 5 * loadav time
203  *	95% of (ke_pctcpu) usage in 60 seconds (load insensitive)
204  *          Note that, as ps(1) mentions, this can let percentages
205  *          total over 100% (I've seen 137.9% for 3 processes).
206  *
207  * Note that schedclock() updates kg_estcpu and p_cpticks asynchronously.
208  *
209  * We wish to decay away 90% of kg_estcpu in (5 * loadavg) seconds.
210  * That is, the system wants to compute a value of decay such
211  * that the following for loop:
212  * 	for (i = 0; i < (5 * loadavg); i++)
213  * 		kg_estcpu *= decay;
214  * will compute
215  * 	kg_estcpu *= 0.1;
216  * for all values of loadavg:
217  *
218  * Mathematically this loop can be expressed by saying:
219  * 	decay ** (5 * loadavg) ~= .1
220  *
221  * The system computes decay as:
222  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
223  *
224  * We wish to prove that the system's computation of decay
225  * will always fulfill the equation:
226  * 	decay ** (5 * loadavg) ~= .1
227  *
228  * If we compute b as:
229  * 	b = 2 * loadavg
230  * then
231  * 	decay = b / (b + 1)
232  *
233  * We now need to prove two things:
234  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
235  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
236  *
237  * Facts:
238  *         For x close to zero, exp(x) =~ 1 + x, since
239  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
240  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
241  *         For x close to zero, ln(1+x) =~ x, since
242  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
243  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
244  *         ln(.1) =~ -2.30
245  *
246  * Proof of (1):
247  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
248  *	solving for factor,
249  *      ln(factor) =~ (-2.30/5*loadav), or
250  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
251  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
252  *
253  * Proof of (2):
254  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
255  *	solving for power,
256  *      power*ln(b/(b+1)) =~ -2.30, or
257  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
258  *
259  * Actual power values for the implemented algorithm are as follows:
260  *      loadav: 1       2       3       4
261  *      power:  5.68    10.32   14.94   19.55
262  */
263 
264 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
265 #define	loadfactor(loadav)	(2 * (loadav))
266 #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
267 
268 /* decay 95% of `ke_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
269 static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
270 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
271 
272 /*
273  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
274  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
275  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
276  *
277  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
278  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
279  *
280  * If you don't want to bother with the faster/more-accurate formula, you
281  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
282  * (more general) method of calculating the %age of CPU used by a process.
283  */
284 #define	CCPU_SHIFT	11
285 
286 /*
287  * Recompute process priorities, every hz ticks.
288  * MP-safe, called without the Giant mutex.
289  */
290 /* ARGSUSED */
291 static void
292 schedcpu(void)
293 {
294 	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
295 	struct thread *td;
296 	struct proc *p;
297 	struct kse *ke;
298 	struct ksegrp *kg;
299 	int awake, realstathz;
300 
301 	realstathz = stathz ? stathz : hz;
302 	sx_slock(&allproc_lock);
303 	FOREACH_PROC_IN_SYSTEM(p) {
304 		/*
305 		 * Prevent state changes and protect run queue.
306 		 */
307 		mtx_lock_spin(&sched_lock);
308 		/*
309 		 * Increment time in/out of memory.  We ignore overflow; with
310 		 * 16-bit int's (remember them?) overflow takes 45 days.
311 		 */
312 		p->p_swtime++;
313 		FOREACH_KSEGRP_IN_PROC(p, kg) {
314 			awake = 0;
315 			FOREACH_KSE_IN_GROUP(kg, ke) {
316 				/*
317 				 * Increment sleep time (if sleeping).  We
318 				 * ignore overflow, as above.
319 				 */
320 				/*
321 				 * The kse slptimes are not touched in wakeup
322 				 * because the thread may not HAVE a KSE.
323 				 */
324 				if (ke->ke_state == KES_ONRUNQ) {
325 					awake = 1;
326 					ke->ke_flags &= ~KEF_DIDRUN;
327 				} else if ((ke->ke_state == KES_THREAD) &&
328 				    (TD_IS_RUNNING(ke->ke_thread))) {
329 					awake = 1;
330 					/* Do not clear KEF_DIDRUN */
331 				} else if (ke->ke_flags & KEF_DIDRUN) {
332 					awake = 1;
333 					ke->ke_flags &= ~KEF_DIDRUN;
334 				}
335 
336 				/*
337 				 * ke_pctcpu is only for ps and ttyinfo().
338 				 * Do it per kse, and add them up at the end?
339 				 * XXXKSE
340 				 */
341 				ke->ke_pctcpu = (ke->ke_pctcpu * ccpu) >>
342 				    FSHIFT;
343 				/*
344 				 * If the kse has been idle the entire second,
345 				 * stop recalculating its priority until
346 				 * it wakes up.
347 				 */
348 				if (ke->ke_sched->ske_cpticks == 0)
349 					continue;
350 #if	(FSHIFT >= CCPU_SHIFT)
351 				ke->ke_pctcpu += (realstathz == 100)
352 				    ? ((fixpt_t) ke->ke_sched->ske_cpticks) <<
353 				    (FSHIFT - CCPU_SHIFT) :
354 				    100 * (((fixpt_t) ke->ke_sched->ske_cpticks)
355 				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
356 #else
357 				ke->ke_pctcpu += ((FSCALE - ccpu) *
358 				    (ke->ke_sched->ske_cpticks *
359 				    FSCALE / realstathz)) >> FSHIFT;
360 #endif
361 				ke->ke_sched->ske_cpticks = 0;
362 			} /* end of kse loop */
363 			/*
364 			 * If there are ANY running threads in this KSEGRP,
365 			 * then don't count it as sleeping.
366 			 */
367 			if (awake) {
368 				if (kg->kg_slptime > 1) {
369 					/*
370 					 * In an ideal world, this should not
371 					 * happen, because whoever woke us
372 					 * up from the long sleep should have
373 					 * unwound the slptime and reset our
374 					 * priority before we run at the stale
375 					 * priority.  Should KASSERT at some
376 					 * point when all the cases are fixed.
377 					 */
378 					updatepri(kg);
379 				}
380 				kg->kg_slptime = 0;
381 			} else
382 				kg->kg_slptime++;
383 			if (kg->kg_slptime > 1)
384 				continue;
385 			kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu);
386 		      	resetpriority(kg);
387 			FOREACH_THREAD_IN_GROUP(kg, td) {
388 				if (td->td_priority >= PUSER) {
389 					sched_prio(td, kg->kg_user_pri);
390 				}
391 			}
392 		} /* end of ksegrp loop */
393 		mtx_unlock_spin(&sched_lock);
394 	} /* end of process loop */
395 	sx_sunlock(&allproc_lock);
396 }
397 
398 /*
399  * Main loop for a kthread that executes schedcpu once a second.
400  */
401 static void
402 schedcpu_thread(void)
403 {
404 	int nowake;
405 
406 	for (;;) {
407 		schedcpu();
408 		tsleep(&nowake, curthread->td_priority, "-", hz);
409 	}
410 }
411 
412 /*
413  * Recalculate the priority of a process after it has slept for a while.
414  * For all load averages >= 1 and max kg_estcpu of 255, sleeping for at
415  * least six times the loadfactor will decay kg_estcpu to zero.
416  */
417 static void
418 updatepri(struct ksegrp *kg)
419 {
420 	register fixpt_t loadfac;
421 	register unsigned int newcpu;
422 
423 	loadfac = loadfactor(averunnable.ldavg[0]);
424 	if (kg->kg_slptime > 5 * loadfac)
425 		kg->kg_estcpu = 0;
426 	else {
427 		newcpu = kg->kg_estcpu;
428 		kg->kg_slptime--;	/* was incremented in schedcpu() */
429 		while (newcpu && --kg->kg_slptime)
430 			newcpu = decay_cpu(loadfac, newcpu);
431 		kg->kg_estcpu = newcpu;
432 	}
433 	resetpriority(kg);
434 }
435 
436 /*
437  * Compute the priority of a process when running in user mode.
438  * Arrange to reschedule if the resulting priority is better
439  * than that of the current process.
440  */
441 static void
442 resetpriority(struct ksegrp *kg)
443 {
444 	register unsigned int newpriority;
445 	struct thread *td;
446 
447 	if (kg->kg_pri_class == PRI_TIMESHARE) {
448 		newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT +
449 		    NICE_WEIGHT * (kg->kg_proc->p_nice - PRIO_MIN);
450 		newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
451 		    PRI_MAX_TIMESHARE);
452 		kg->kg_user_pri = newpriority;
453 	}
454 	FOREACH_THREAD_IN_GROUP(kg, td) {
455 		maybe_resched(td);			/* XXXKSE silly */
456 	}
457 }
458 
459 /* ARGSUSED */
460 static void
461 sched_setup(void *dummy)
462 {
463 	setup_runqs();
464 
465 	if (sched_quantum == 0)
466 		sched_quantum = SCHED_QUANTUM;
467 	hogticks = 2 * sched_quantum;
468 
469 	callout_init(&roundrobin_callout, CALLOUT_MPSAFE);
470 
471 	/* Kick off timeout driven events by calling first time. */
472 	roundrobin(NULL);
473 
474 	/* Account for thread0. */
475 	sched_tdcnt++;
476 }
477 
478 /* External interfaces start here */
479 int
480 sched_runnable(void)
481 {
482 #ifdef SMP
483 	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
484 #else
485 	return runq_check(&runq);
486 #endif
487 }
488 
489 int
490 sched_rr_interval(void)
491 {
492 	if (sched_quantum == 0)
493 		sched_quantum = SCHED_QUANTUM;
494 	return (sched_quantum);
495 }
496 
497 /*
498  * We adjust the priority of the current process.  The priority of
499  * a process gets worse as it accumulates CPU time.  The cpu usage
500  * estimator (kg_estcpu) is increased here.  resetpriority() will
501  * compute a different priority each time kg_estcpu increases by
502  * INVERSE_ESTCPU_WEIGHT
503  * (until MAXPRI is reached).  The cpu usage estimator ramps up
504  * quite quickly when the process is running (linearly), and decays
505  * away exponentially, at a rate which is proportionally slower when
506  * the system is busy.  The basic principle is that the system will
507  * 90% forget that the process used a lot of CPU time in 5 * loadav
508  * seconds.  This causes the system to favor processes which haven't
509  * run much recently, and to round-robin among other processes.
510  */
511 void
512 sched_clock(struct thread *td)
513 {
514 	struct ksegrp *kg;
515 	struct kse *ke;
516 
517 	mtx_assert(&sched_lock, MA_OWNED);
518 	kg = td->td_ksegrp;
519 	ke = td->td_kse;
520 
521 	ke->ke_sched->ske_cpticks++;
522 	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1);
523 	if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
524 		resetpriority(kg);
525 		if (td->td_priority >= PUSER)
526 			td->td_priority = kg->kg_user_pri;
527 	}
528 }
529 
530 /*
531  * charge childs scheduling cpu usage to parent.
532  *
533  * XXXKSE assume only one thread & kse & ksegrp keep estcpu in each ksegrp.
534  * Charge it to the ksegrp that did the wait since process estcpu is sum of
535  * all ksegrps, this is strictly as expected.  Assume that the child process
536  * aggregated all the estcpu into the 'built-in' ksegrp.
537  */
538 void
539 sched_exit(struct proc *p, struct proc *p1)
540 {
541 	sched_exit_kse(FIRST_KSE_IN_PROC(p), FIRST_KSE_IN_PROC(p1));
542 	sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), FIRST_KSEGRP_IN_PROC(p1));
543 	sched_exit_thread(FIRST_THREAD_IN_PROC(p), FIRST_THREAD_IN_PROC(p1));
544 }
545 
546 void
547 sched_exit_kse(struct kse *ke, struct kse *child)
548 {
549 }
550 
551 void
552 sched_exit_ksegrp(struct ksegrp *kg, struct ksegrp *child)
553 {
554 
555 	mtx_assert(&sched_lock, MA_OWNED);
556 	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + child->kg_estcpu);
557 }
558 
559 void
560 sched_exit_thread(struct thread *td, struct thread *child)
561 {
562 	if ((child->td_proc->p_flag & P_NOLOAD) == 0)
563 		sched_tdcnt--;
564 }
565 
566 void
567 sched_fork(struct proc *p, struct proc *p1)
568 {
569 	sched_fork_kse(FIRST_KSE_IN_PROC(p), FIRST_KSE_IN_PROC(p1));
570 	sched_fork_ksegrp(FIRST_KSEGRP_IN_PROC(p), FIRST_KSEGRP_IN_PROC(p1));
571 	sched_fork_thread(FIRST_THREAD_IN_PROC(p), FIRST_THREAD_IN_PROC(p1));
572 }
573 
574 void
575 sched_fork_kse(struct kse *ke, struct kse *child)
576 {
577 	child->ke_sched->ske_cpticks = 0;
578 }
579 
580 void
581 sched_fork_ksegrp(struct ksegrp *kg, struct ksegrp *child)
582 {
583 	mtx_assert(&sched_lock, MA_OWNED);
584 	child->kg_estcpu = kg->kg_estcpu;
585 }
586 
587 void
588 sched_fork_thread(struct thread *td, struct thread *child)
589 {
590 }
591 
592 void
593 sched_nice(struct proc *p, int nice)
594 {
595 	struct ksegrp *kg;
596 
597 	PROC_LOCK_ASSERT(p, MA_OWNED);
598 	mtx_assert(&sched_lock, MA_OWNED);
599 	p->p_nice = nice;
600 	FOREACH_KSEGRP_IN_PROC(p, kg) {
601 		resetpriority(kg);
602 	}
603 }
604 
605 void
606 sched_class(struct ksegrp *kg, int class)
607 {
608 	mtx_assert(&sched_lock, MA_OWNED);
609 	kg->kg_pri_class = class;
610 }
611 
612 /*
613  * Adjust the priority of a thread.
614  * This may include moving the thread within the KSEGRP,
615  * changing the assignment of a kse to the thread,
616  * and moving a KSE in the system run queue.
617  */
618 void
619 sched_prio(struct thread *td, u_char prio)
620 {
621 
622 	mtx_assert(&sched_lock, MA_OWNED);
623 	if (TD_ON_RUNQ(td)) {
624 		adjustrunqueue(td, prio);
625 	} else {
626 		td->td_priority = prio;
627 	}
628 }
629 
630 void
631 sched_sleep(struct thread *td)
632 {
633 
634 	mtx_assert(&sched_lock, MA_OWNED);
635 	td->td_ksegrp->kg_slptime = 0;
636 	td->td_base_pri = td->td_priority;
637 }
638 
639 void
640 sched_switch(struct thread *td, struct thread *newtd)
641 {
642 	struct kse *ke;
643 	struct proc *p;
644 
645 	ke = td->td_kse;
646 	p = td->td_proc;
647 
648 	mtx_assert(&sched_lock, MA_OWNED);
649 	KASSERT((ke->ke_state == KES_THREAD), ("sched_switch: kse state?"));
650 
651 	if ((p->p_flag & P_NOLOAD) == 0)
652 		sched_tdcnt--;
653 	if (newtd != NULL && (newtd->td_proc->p_flag & P_NOLOAD) == 0)
654 		sched_tdcnt++;
655 	td->td_lastcpu = td->td_oncpu;
656 	td->td_last_kse = ke;
657 	td->td_flags &= ~TDF_NEEDRESCHED;
658 	td->td_pflags &= ~TDP_OWEPREEMPT;
659 	td->td_oncpu = NOCPU;
660 	/*
661 	 * At the last moment, if this thread is still marked RUNNING,
662 	 * then put it back on the run queue as it has not been suspended
663 	 * or stopped or any thing else similar.  We never put the idle
664 	 * threads on the run queue, however.
665 	 */
666 	if (td == PCPU_GET(idlethread))
667 		TD_SET_CAN_RUN(td);
668 	else if (TD_IS_RUNNING(td)) {
669 		/* Put us back on the run queue (kse and all). */
670 		setrunqueue(td);
671 	} else if (p->p_flag & P_SA) {
672 		/*
673 		 * We will not be on the run queue. So we must be
674 		 * sleeping or similar. As it's available,
675 		 * someone else can use the KSE if they need it.
676 		 */
677 		kse_reassign(ke);
678 	}
679 	if (newtd == NULL)
680 		newtd = choosethread();
681 	if (td != newtd)
682 		cpu_switch(td, newtd);
683 	sched_lock.mtx_lock = (uintptr_t)td;
684 	td->td_oncpu = PCPU_GET(cpuid);
685 }
686 
687 void
688 sched_wakeup(struct thread *td)
689 {
690 	struct ksegrp *kg;
691 
692 	mtx_assert(&sched_lock, MA_OWNED);
693 	kg = td->td_ksegrp;
694 	if (kg->kg_slptime > 1)
695 		updatepri(kg);
696 	kg->kg_slptime = 0;
697 	setrunqueue(td);
698 }
699 
700 void
701 sched_add(struct thread *td)
702 {
703 	struct kse *ke;
704 
705 	ke = td->td_kse;
706 	mtx_assert(&sched_lock, MA_OWNED);
707 	KASSERT((ke->ke_thread != NULL), ("sched_add: No thread on KSE"));
708 	KASSERT((ke->ke_thread->td_kse != NULL),
709 	    ("sched_add: No KSE on thread"));
710 	KASSERT(ke->ke_state != KES_ONRUNQ,
711 	    ("sched_add: kse %p (%s) already in run queue", ke,
712 	    ke->ke_proc->p_comm));
713 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
714 	    ("sched_add: process swapped out"));
715 
716 #ifdef SMP
717 	/*
718 	 * Only try to preempt if the thread is unpinned or pinned to the
719 	 * current CPU.
720 	 */
721 	if (KSE_CAN_MIGRATE(ke) || ke->ke_runq == &runq_pcpu[PCPU_GET(cpuid)])
722 #endif
723 	if (maybe_preempt(td))
724 		return;
725 	ke->ke_ksegrp->kg_runq_kses++;
726 	ke->ke_state = KES_ONRUNQ;
727 
728 #ifdef SMP
729 	if (KSE_CAN_MIGRATE(ke)) {
730 		CTR1(KTR_4BSD, "adding kse:%p to gbl runq", ke);
731 		ke->ke_runq = &runq;
732 	} else {
733 		CTR1(KTR_4BSD, "adding kse:%p to pcpu runq", ke);
734 		if (!SKE_RUNQ_PCPU(ke))
735 			ke->ke_runq = &runq_pcpu[PCPU_GET(cpuid)];
736 	}
737 #else
738 	ke->ke_runq = &runq;
739 #endif
740 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
741 		sched_tdcnt++;
742 	runq_add(ke->ke_runq, ke);
743 	maybe_resched(td);
744 }
745 
746 void
747 sched_rem(struct thread *td)
748 {
749 	struct kse *ke;
750 
751 	ke = td->td_kse;
752 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
753 	    ("sched_rem: process swapped out"));
754 	KASSERT((ke->ke_state == KES_ONRUNQ),
755 	    ("sched_rem: KSE not on run queue"));
756 	mtx_assert(&sched_lock, MA_OWNED);
757 
758 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
759 		sched_tdcnt--;
760 	runq_remove(ke->ke_sched->ske_runq, ke);
761 
762 	ke->ke_state = KES_THREAD;
763 	ke->ke_ksegrp->kg_runq_kses--;
764 }
765 
766 struct kse *
767 sched_choose(void)
768 {
769 	struct kse *ke;
770 	struct runq *rq;
771 
772 #ifdef SMP
773 	struct kse *kecpu;
774 
775 	rq = &runq;
776 	ke = runq_choose(&runq);
777 	kecpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
778 
779 	if (ke == NULL ||
780 	    (kecpu != NULL &&
781 	     kecpu->ke_thread->td_priority < ke->ke_thread->td_priority)) {
782 		CTR2(KTR_4BSD, "choosing kse %p from pcpu runq %d", kecpu,
783 		     PCPU_GET(cpuid));
784 		ke = kecpu;
785 		rq = &runq_pcpu[PCPU_GET(cpuid)];
786 	} else {
787 		CTR1(KTR_4BSD, "choosing kse %p from main runq", ke);
788 	}
789 
790 #else
791 	rq = &runq;
792 	ke = runq_choose(&runq);
793 #endif
794 
795 	if (ke != NULL) {
796 		runq_remove(rq, ke);
797 		ke->ke_state = KES_THREAD;
798 
799 		KASSERT((ke->ke_thread != NULL),
800 		    ("sched_choose: No thread on KSE"));
801 		KASSERT((ke->ke_thread->td_kse != NULL),
802 		    ("sched_choose: No KSE on thread"));
803 		KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
804 		    ("sched_choose: process swapped out"));
805 	}
806 	return (ke);
807 }
808 
809 void
810 sched_userret(struct thread *td)
811 {
812 	struct ksegrp *kg;
813 	/*
814 	 * XXX we cheat slightly on the locking here to avoid locking in
815 	 * the usual case.  Setting td_priority here is essentially an
816 	 * incomplete workaround for not setting it properly elsewhere.
817 	 * Now that some interrupt handlers are threads, not setting it
818 	 * properly elsewhere can clobber it in the window between setting
819 	 * it here and returning to user mode, so don't waste time setting
820 	 * it perfectly here.
821 	 */
822 	kg = td->td_ksegrp;
823 	if (td->td_priority != kg->kg_user_pri) {
824 		mtx_lock_spin(&sched_lock);
825 		td->td_priority = kg->kg_user_pri;
826 		mtx_unlock_spin(&sched_lock);
827 	}
828 }
829 
830 void
831 sched_bind(struct thread *td, int cpu)
832 {
833 	struct kse *ke;
834 
835 	mtx_assert(&sched_lock, MA_OWNED);
836 	KASSERT(TD_IS_RUNNING(td),
837 	    ("sched_bind: cannot bind non-running thread"));
838 
839 	ke = td->td_kse;
840 
841 	ke->ke_flags |= KEF_BOUND;
842 #ifdef SMP
843 	ke->ke_runq = &runq_pcpu[cpu];
844 	if (PCPU_GET(cpuid) == cpu)
845 		return;
846 
847 	ke->ke_state = KES_THREAD;
848 
849 	mi_switch(SW_VOL, NULL);
850 #endif
851 }
852 
853 void
854 sched_unbind(struct thread* td)
855 {
856 	mtx_assert(&sched_lock, MA_OWNED);
857 	td->td_kse->ke_flags &= ~KEF_BOUND;
858 }
859 
860 int
861 sched_load(void)
862 {
863 	return (sched_tdcnt);
864 }
865 
866 int
867 sched_sizeof_kse(void)
868 {
869 	return (sizeof(struct kse) + sizeof(struct ke_sched));
870 }
871 int
872 sched_sizeof_ksegrp(void)
873 {
874 	return (sizeof(struct ksegrp));
875 }
876 int
877 sched_sizeof_proc(void)
878 {
879 	return (sizeof(struct proc));
880 }
881 int
882 sched_sizeof_thread(void)
883 {
884 	return (sizeof(struct thread));
885 }
886 
887 fixpt_t
888 sched_pctcpu(struct thread *td)
889 {
890 	struct kse *ke;
891 
892 	ke = td->td_kse;
893 	if (ke == NULL)
894 		ke = td->td_last_kse;
895 	if (ke)
896 		return (ke->ke_pctcpu);
897 
898 	return (0);
899 }
900