xref: /openbsd-src/sys/kern/sched_bsd.c (revision cb39b41371628601fbe4c618205356d538b9d08a)
1 /*	$OpenBSD: sched_bsd.c,v 1.41 2015/03/14 03:38:50 jsg Exp $	*/
2 /*	$NetBSD: kern_synch.c,v 1.37 1996/04/22 01:38:37 christos Exp $	*/
3 
4 /*-
5  * Copyright (c) 1982, 1986, 1990, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)kern_synch.c	8.6 (Berkeley) 1/21/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/proc.h>
43 #include <sys/kernel.h>
44 #include <sys/malloc.h>
45 #include <sys/signalvar.h>
46 #include <sys/resourcevar.h>
47 #include <uvm/uvm_extern.h>
48 #include <sys/sched.h>
49 #include <sys/timeout.h>
50 
51 #ifdef KTRACE
52 #include <sys/ktrace.h>
53 #endif
54 
55 
56 int	lbolt;			/* once a second sleep address */
57 int	rrticks_init;		/* # of hardclock ticks per roundrobin() */
58 
59 #ifdef MULTIPROCESSOR
60 struct __mp_lock sched_lock;
61 #endif
62 
63 void schedcpu(void *);
64 
65 void
66 scheduler_start(void)
67 {
68 	static struct timeout schedcpu_to;
69 
70 	/*
71 	 * We avoid polluting the global namespace by keeping the scheduler
72 	 * timeouts static in this function.
73 	 * We setup the timeouts here and kick schedcpu and roundrobin once to
74 	 * make them do their job.
75 	 */
76 
77 	timeout_set(&schedcpu_to, schedcpu, &schedcpu_to);
78 
79 	rrticks_init = hz / 10;
80 	schedcpu(&schedcpu_to);
81 }
82 
83 /*
84  * Force switch among equal priority processes every 100ms.
85  */
86 void
87 roundrobin(struct cpu_info *ci)
88 {
89 	struct schedstate_percpu *spc = &ci->ci_schedstate;
90 
91 	spc->spc_rrticks = rrticks_init;
92 
93 	if (ci->ci_curproc != NULL) {
94 		if (spc->spc_schedflags & SPCF_SEENRR) {
95 			/*
96 			 * The process has already been through a roundrobin
97 			 * without switching and may be hogging the CPU.
98 			 * Indicate that the process should yield.
99 			 */
100 			atomic_setbits_int(&spc->spc_schedflags,
101 			    SPCF_SHOULDYIELD);
102 		} else {
103 			atomic_setbits_int(&spc->spc_schedflags,
104 			    SPCF_SEENRR);
105 		}
106 	}
107 
108 	if (spc->spc_nrun)
109 		need_resched(ci);
110 }
111 
112 /*
113  * Constants for digital decay and forget:
114  *	90% of (p_estcpu) usage in 5 * loadav time
115  *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
116  *          Note that, as ps(1) mentions, this can let percentages
117  *          total over 100% (I've seen 137.9% for 3 processes).
118  *
119  * Note that hardclock updates p_estcpu and p_cpticks independently.
120  *
121  * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
122  * That is, the system wants to compute a value of decay such
123  * that the following for loop:
124  * 	for (i = 0; i < (5 * loadavg); i++)
125  * 		p_estcpu *= decay;
126  * will compute
127  * 	p_estcpu *= 0.1;
128  * for all values of loadavg:
129  *
130  * Mathematically this loop can be expressed by saying:
131  * 	decay ** (5 * loadavg) ~= .1
132  *
133  * The system computes decay as:
134  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
135  *
136  * We wish to prove that the system's computation of decay
137  * will always fulfill the equation:
138  * 	decay ** (5 * loadavg) ~= .1
139  *
140  * If we compute b as:
141  * 	b = 2 * loadavg
142  * then
143  * 	decay = b / (b + 1)
144  *
145  * We now need to prove two things:
146  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
147  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
148  *
149  * Facts:
150  *         For x close to zero, exp(x) =~ 1 + x, since
151  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
152  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
153  *         For x close to zero, ln(1+x) =~ x, since
154  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
155  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
156  *         ln(.1) =~ -2.30
157  *
158  * Proof of (1):
159  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
160  *	solving for factor,
161  *      ln(factor) =~ (-2.30/5*loadav), or
162  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
163  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
164  *
165  * Proof of (2):
166  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
167  *	solving for power,
168  *      power*ln(b/(b+1)) =~ -2.30, or
169  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
170  *
171  * Actual power values for the implemented algorithm are as follows:
172  *      loadav: 1       2       3       4
173  *      power:  5.68    10.32   14.94   19.55
174  */
175 
176 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
177 #define	loadfactor(loadav)	(2 * (loadav))
178 #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
179 
180 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
181 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
182 
183 /*
184  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
185  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
186  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
187  *
188  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
189  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
190  *
191  * If you don't want to bother with the faster/more-accurate formula, you
192  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
193  * (more general) method of calculating the %age of CPU used by a process.
194  */
195 #define	CCPU_SHIFT	11
196 
197 /*
198  * Recompute process priorities, every second.
199  */
200 void
201 schedcpu(void *arg)
202 {
203 	struct timeout *to = (struct timeout *)arg;
204 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
205 	struct proc *p;
206 	int s;
207 	unsigned int newcpu;
208 	int phz;
209 
210 	/*
211 	 * If we have a statistics clock, use that to calculate CPU
212 	 * time, otherwise revert to using the profiling clock (which,
213 	 * in turn, defaults to hz if there is no separate profiling
214 	 * clock available)
215 	 */
216 	phz = stathz ? stathz : profhz;
217 	KASSERT(phz);
218 
219 	LIST_FOREACH(p, &allproc, p_list) {
220 		/*
221 		 * Increment time in/out of memory and sleep time
222 		 * (if sleeping).  We ignore overflow; with 16-bit int's
223 		 * (remember them?) overflow takes 45 days.
224 		 */
225 		if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
226 			p->p_slptime++;
227 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
228 		/*
229 		 * If the process has slept the entire second,
230 		 * stop recalculating its priority until it wakes up.
231 		 */
232 		if (p->p_slptime > 1)
233 			continue;
234 		SCHED_LOCK(s);
235 		/*
236 		 * p_pctcpu is only for ps.
237 		 */
238 #if	(FSHIFT >= CCPU_SHIFT)
239 		p->p_pctcpu += (phz == 100)?
240 			((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
241                 	100 * (((fixpt_t) p->p_cpticks)
242 				<< (FSHIFT - CCPU_SHIFT)) / phz;
243 #else
244 		p->p_pctcpu += ((FSCALE - ccpu) *
245 			(p->p_cpticks * FSCALE / phz)) >> FSHIFT;
246 #endif
247 		p->p_cpticks = 0;
248 		newcpu = (u_int) decay_cpu(loadfac, p->p_estcpu);
249 		p->p_estcpu = newcpu;
250 		resetpriority(p);
251 		if (p->p_priority >= PUSER) {
252 			if (p->p_stat == SRUN &&
253 			    (p->p_priority / SCHED_PPQ) !=
254 			    (p->p_usrpri / SCHED_PPQ)) {
255 				remrunqueue(p);
256 				p->p_priority = p->p_usrpri;
257 				setrunqueue(p);
258 			} else
259 				p->p_priority = p->p_usrpri;
260 		}
261 		SCHED_UNLOCK(s);
262 	}
263 	uvm_meter();
264 	wakeup(&lbolt);
265 	timeout_add_sec(to, 1);
266 }
267 
268 /*
269  * Recalculate the priority of a process after it has slept for a while.
270  * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
271  * least six times the loadfactor will decay p_estcpu to zero.
272  */
273 void
274 updatepri(struct proc *p)
275 {
276 	unsigned int newcpu = p->p_estcpu;
277 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
278 
279 	SCHED_ASSERT_LOCKED();
280 
281 	if (p->p_slptime > 5 * loadfac)
282 		p->p_estcpu = 0;
283 	else {
284 		p->p_slptime--;	/* the first time was done in schedcpu */
285 		while (newcpu && --p->p_slptime)
286 			newcpu = (int) decay_cpu(loadfac, newcpu);
287 		p->p_estcpu = newcpu;
288 	}
289 	resetpriority(p);
290 }
291 
292 /*
293  * General yield call.  Puts the current process back on its run queue and
294  * performs a voluntary context switch.
295  */
296 void
297 yield(void)
298 {
299 	struct proc *p = curproc;
300 	int s;
301 
302 	SCHED_LOCK(s);
303 	p->p_priority = p->p_usrpri;
304 	p->p_stat = SRUN;
305 	setrunqueue(p);
306 	p->p_ru.ru_nvcsw++;
307 	mi_switch();
308 	SCHED_UNLOCK(s);
309 }
310 
311 /*
312  * General preemption call.  Puts the current process back on its run queue
313  * and performs an involuntary context switch.  If a process is supplied,
314  * we switch to that process.  Otherwise, we use the normal process selection
315  * criteria.
316  */
317 void
318 preempt(struct proc *newp)
319 {
320 	struct proc *p = curproc;
321 	int s;
322 
323 	/*
324 	 * XXX Switching to a specific process is not supported yet.
325 	 */
326 	if (newp != NULL)
327 		panic("preempt: cpu_preempt not yet implemented");
328 
329 	SCHED_LOCK(s);
330 	p->p_priority = p->p_usrpri;
331 	p->p_stat = SRUN;
332 	p->p_cpu = sched_choosecpu(p);
333 	setrunqueue(p);
334 	p->p_ru.ru_nivcsw++;
335 	mi_switch();
336 	SCHED_UNLOCK(s);
337 }
338 
339 void
340 mi_switch(void)
341 {
342 	struct schedstate_percpu *spc = &curcpu()->ci_schedstate;
343 	struct proc *p = curproc;
344 	struct proc *nextproc;
345 	struct process *pr = p->p_p;
346 	struct rlimit *rlim;
347 	rlim_t secs;
348 	struct timespec ts;
349 #ifdef MULTIPROCESSOR
350 	int hold_count;
351 	int sched_count;
352 #endif
353 
354 	assertwaitok();
355 	KASSERT(p->p_stat != SONPROC);
356 
357 	SCHED_ASSERT_LOCKED();
358 
359 #ifdef MULTIPROCESSOR
360 	/*
361 	 * Release the kernel_lock, as we are about to yield the CPU.
362 	 */
363 	sched_count = __mp_release_all_but_one(&sched_lock);
364 	if (__mp_lock_held(&kernel_lock))
365 		hold_count = __mp_release_all(&kernel_lock);
366 	else
367 		hold_count = 0;
368 #endif
369 
370 	/*
371 	 * Compute the amount of time during which the current
372 	 * process was running, and add that to its total so far.
373 	 */
374 	nanouptime(&ts);
375 	if (timespeccmp(&ts, &spc->spc_runtime, <)) {
376 #if 0
377 		printf("uptime is not monotonic! "
378 		    "ts=%lld.%09lu, runtime=%lld.%09lu\n",
379 		    (long long)tv.tv_sec, tv.tv_nsec,
380 		    (long long)spc->spc_runtime.tv_sec,
381 		    spc->spc_runtime.tv_nsec);
382 #endif
383 	} else {
384 		timespecsub(&ts, &spc->spc_runtime, &ts);
385 		timespecadd(&p->p_rtime, &ts, &p->p_rtime);
386 	}
387 
388 	/* add the time counts for this thread to the process's total */
389 	tuagg_unlocked(pr, p);
390 
391 	/*
392 	 * Check if the process exceeds its cpu resource allocation.
393 	 * If over max, kill it.
394 	 */
395 	rlim = &pr->ps_limit->pl_rlimit[RLIMIT_CPU];
396 	secs = pr->ps_tu.tu_runtime.tv_sec;
397 	if (secs >= rlim->rlim_cur) {
398 		if (secs >= rlim->rlim_max) {
399 			psignal(p, SIGKILL);
400 		} else {
401 			psignal(p, SIGXCPU);
402 			if (rlim->rlim_cur < rlim->rlim_max)
403 				rlim->rlim_cur += 5;
404 		}
405 	}
406 
407 	/*
408 	 * Process is about to yield the CPU; clear the appropriate
409 	 * scheduling flags.
410 	 */
411 	atomic_clearbits_int(&spc->spc_schedflags, SPCF_SWITCHCLEAR);
412 
413 	nextproc = sched_chooseproc();
414 
415 	if (p != nextproc) {
416 		uvmexp.swtch++;
417 		cpu_switchto(p, nextproc);
418 	} else {
419 		p->p_stat = SONPROC;
420 	}
421 
422 	clear_resched(curcpu());
423 
424 	SCHED_ASSERT_LOCKED();
425 
426 	/*
427 	 * To preserve lock ordering, we need to release the sched lock
428 	 * and grab it after we grab the big lock.
429 	 * In the future, when the sched lock isn't recursive, we'll
430 	 * just release it here.
431 	 */
432 #ifdef MULTIPROCESSOR
433 	__mp_unlock(&sched_lock);
434 #endif
435 
436 	SCHED_ASSERT_UNLOCKED();
437 
438 	/*
439 	 * We're running again; record our new start time.  We might
440 	 * be running on a new CPU now, so don't use the cache'd
441 	 * schedstate_percpu pointer.
442 	 */
443 	KASSERT(p->p_cpu == curcpu());
444 
445 	nanouptime(&p->p_cpu->ci_schedstate.spc_runtime);
446 
447 #ifdef MULTIPROCESSOR
448 	/*
449 	 * Reacquire the kernel_lock now.  We do this after we've
450 	 * released the scheduler lock to avoid deadlock, and before
451 	 * we reacquire the interlock and the scheduler lock.
452 	 */
453 	if (hold_count)
454 		__mp_acquire_count(&kernel_lock, hold_count);
455 	__mp_acquire_count(&sched_lock, sched_count + 1);
456 #endif
457 }
458 
459 static __inline void
460 resched_proc(struct proc *p, u_char pri)
461 {
462 	struct cpu_info *ci;
463 
464 	/*
465 	 * XXXSMP
466 	 * This does not handle the case where its last
467 	 * CPU is running a higher-priority process, but every
468 	 * other CPU is running a lower-priority process.  There
469 	 * are ways to handle this situation, but they're not
470 	 * currently very pretty, and we also need to weigh the
471 	 * cost of moving a process from one CPU to another.
472 	 *
473 	 * XXXSMP
474 	 * There is also the issue of locking the other CPU's
475 	 * sched state, which we currently do not do.
476 	 */
477 	ci = (p->p_cpu != NULL) ? p->p_cpu : curcpu();
478 	if (pri < ci->ci_schedstate.spc_curpriority)
479 		need_resched(ci);
480 }
481 
482 /*
483  * Change process state to be runnable,
484  * placing it on the run queue if it is in memory,
485  * and awakening the swapper if it isn't in memory.
486  */
487 void
488 setrunnable(struct proc *p)
489 {
490 	SCHED_ASSERT_LOCKED();
491 
492 	switch (p->p_stat) {
493 	case 0:
494 	case SRUN:
495 	case SONPROC:
496 	case SDEAD:
497 	case SIDL:
498 	default:
499 		panic("setrunnable");
500 	case SSTOP:
501 		/*
502 		 * If we're being traced (possibly because someone attached us
503 		 * while we were stopped), check for a signal from the debugger.
504 		 */
505 		if ((p->p_p->ps_flags & PS_TRACED) != 0 && p->p_xstat != 0)
506 			atomic_setbits_int(&p->p_siglist, sigmask(p->p_xstat));
507 	case SSLEEP:
508 		unsleep(p);		/* e.g. when sending signals */
509 		break;
510 	}
511 	p->p_stat = SRUN;
512 	p->p_cpu = sched_choosecpu(p);
513 	setrunqueue(p);
514 	if (p->p_slptime > 1)
515 		updatepri(p);
516 	p->p_slptime = 0;
517 	resched_proc(p, p->p_priority);
518 }
519 
520 /*
521  * Compute the priority of a process when running in user mode.
522  * Arrange to reschedule if the resulting priority is better
523  * than that of the current process.
524  */
525 void
526 resetpriority(struct proc *p)
527 {
528 	unsigned int newpriority;
529 
530 	SCHED_ASSERT_LOCKED();
531 
532 	newpriority = PUSER + p->p_estcpu +
533 	    NICE_WEIGHT * (p->p_p->ps_nice - NZERO);
534 	newpriority = min(newpriority, MAXPRI);
535 	p->p_usrpri = newpriority;
536 	resched_proc(p, p->p_usrpri);
537 }
538 
539 /*
540  * We adjust the priority of the current process.  The priority of a process
541  * gets worse as it accumulates CPU time.  The cpu usage estimator (p_estcpu)
542  * is increased here.  The formula for computing priorities (in kern_synch.c)
543  * will compute a different value each time p_estcpu increases. This can
544  * cause a switch, but unless the priority crosses a PPQ boundary the actual
545  * queue will not change.  The cpu usage estimator ramps up quite quickly
546  * when the process is running (linearly), and decays away exponentially, at
547  * a rate which is proportionally slower when the system is busy.  The basic
548  * principle is that the system will 90% forget that the process used a lot
549  * of CPU time in 5 * loadav seconds.  This causes the system to favor
550  * processes which haven't run much recently, and to round-robin among other
551  * processes.
552  */
553 
554 void
555 schedclock(struct proc *p)
556 {
557 	int s;
558 
559 	SCHED_LOCK(s);
560 	p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
561 	resetpriority(p);
562 	if (p->p_priority >= PUSER)
563 		p->p_priority = p->p_usrpri;
564 	SCHED_UNLOCK(s);
565 }
566 
567 void (*cpu_setperf)(int);
568 
569 #define PERFPOL_MANUAL 0
570 #define PERFPOL_AUTO 1
571 #define PERFPOL_HIGH 2
572 int perflevel = 100;
573 int perfpolicy = PERFPOL_MANUAL;
574 
575 #ifndef SMALL_KERNEL
576 /*
577  * The code below handles CPU throttling.
578  */
579 #include <sys/sysctl.h>
580 
581 struct timeout setperf_to;
582 void setperf_auto(void *);
583 
584 void
585 setperf_auto(void *v)
586 {
587 	static uint64_t *idleticks, *totalticks;
588 	static int downbeats;
589 
590 	int i, j;
591 	int speedup;
592 	CPU_INFO_ITERATOR cii;
593 	struct cpu_info *ci;
594 	uint64_t idle, total, allidle, alltotal;
595 
596 	if (perfpolicy != PERFPOL_AUTO)
597 		return;
598 
599 	if (!idleticks)
600 		if (!(idleticks = mallocarray(ncpusfound, sizeof(*idleticks),
601 		    M_DEVBUF, M_NOWAIT | M_ZERO)))
602 			return;
603 	if (!totalticks)
604 		if (!(totalticks = mallocarray(ncpusfound, sizeof(*totalticks),
605 		    M_DEVBUF, M_NOWAIT | M_ZERO))) {
606 			free(idleticks, M_DEVBUF,
607 			    sizeof(*idleticks) * ncpusfound);
608 			return;
609 		}
610 
611 	alltotal = allidle = 0;
612 	j = 0;
613 	speedup = 0;
614 	CPU_INFO_FOREACH(cii, ci) {
615 		total = 0;
616 		for (i = 0; i < CPUSTATES; i++) {
617 			total += ci->ci_schedstate.spc_cp_time[i];
618 		}
619 		total -= totalticks[j];
620 		idle = ci->ci_schedstate.spc_cp_time[CP_IDLE] - idleticks[j];
621 		if (idle < total / 3)
622 			speedup = 1;
623 		alltotal += total;
624 		allidle += idle;
625 		idleticks[j] += idle;
626 		totalticks[j] += total;
627 		j++;
628 	}
629 	if (allidle < alltotal / 2)
630 		speedup = 1;
631 	if (speedup)
632 		downbeats = 5;
633 
634 	if (speedup && perflevel != 100) {
635 		perflevel = 100;
636 		cpu_setperf(perflevel);
637 	} else if (!speedup && perflevel != 0 && --downbeats <= 0) {
638 		perflevel = 0;
639 		cpu_setperf(perflevel);
640 	}
641 
642 	timeout_add_msec(&setperf_to, 100);
643 }
644 
645 int
646 sysctl_hwsetperf(void *oldp, size_t *oldlenp, void *newp, size_t newlen)
647 {
648 	int err, newperf;
649 
650 	if (!cpu_setperf)
651 		return EOPNOTSUPP;
652 
653 	if (perfpolicy != PERFPOL_MANUAL)
654 		return sysctl_rdint(oldp, oldlenp, newp, perflevel);
655 
656 	newperf = perflevel;
657 	err = sysctl_int(oldp, oldlenp, newp, newlen, &newperf);
658 	if (err)
659 		return err;
660 	if (newperf > 100)
661 		newperf = 100;
662 	if (newperf < 0)
663 		newperf = 0;
664 	perflevel = newperf;
665 	cpu_setperf(perflevel);
666 
667 	return 0;
668 }
669 
670 int
671 sysctl_hwperfpolicy(void *oldp, size_t *oldlenp, void *newp, size_t newlen)
672 {
673 	char policy[32];
674 	int err;
675 
676 	if (!cpu_setperf)
677 		return EOPNOTSUPP;
678 
679 	switch (perfpolicy) {
680 	case PERFPOL_MANUAL:
681 		strlcpy(policy, "manual", sizeof(policy));
682 		break;
683 	case PERFPOL_AUTO:
684 		strlcpy(policy, "auto", sizeof(policy));
685 		break;
686 	case PERFPOL_HIGH:
687 		strlcpy(policy, "high", sizeof(policy));
688 		break;
689 	default:
690 		strlcpy(policy, "unknown", sizeof(policy));
691 		break;
692 	}
693 
694 	if (newp == NULL)
695 		return sysctl_rdstring(oldp, oldlenp, newp, policy);
696 
697 	err = sysctl_string(oldp, oldlenp, newp, newlen, policy, sizeof(policy));
698 	if (err)
699 		return err;
700 	if (strcmp(policy, "manual") == 0)
701 		perfpolicy = PERFPOL_MANUAL;
702 	else if (strcmp(policy, "auto") == 0)
703 		perfpolicy = PERFPOL_AUTO;
704 	else if (strcmp(policy, "high") == 0)
705 		perfpolicy = PERFPOL_HIGH;
706 	else
707 		return EINVAL;
708 
709 	if (perfpolicy == PERFPOL_AUTO) {
710 		timeout_add_msec(&setperf_to, 200);
711 	} else if (perfpolicy == PERFPOL_HIGH) {
712 		perflevel = 100;
713 		cpu_setperf(perflevel);
714 	}
715 	return 0;
716 }
717 #endif
718 
719