xref: /openbsd-src/sys/kern/sched_bsd.c (revision 9f11ffb7133c203312a01e4b986886bc88c7d74b)
1 /*	$OpenBSD: sched_bsd.c,v 1.49 2019/01/28 11:48:13 mpi 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 void	 updatepri(struct proc *);
65 
66 void
67 scheduler_start(void)
68 {
69 	static struct timeout schedcpu_to;
70 
71 	/*
72 	 * We avoid polluting the global namespace by keeping the scheduler
73 	 * timeouts static in this function.
74 	 * We setup the timeout here and kick schedcpu once to make it do
75 	 * its job.
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 		 * Idle threads are never placed on the runqueue,
222 		 * therefore computing their priority is pointless.
223 		 */
224 		if (p->p_cpu != NULL &&
225 		    p->p_cpu->ci_schedstate.spc_idleproc == p)
226 			continue;
227 		/*
228 		 * Increment sleep time (if sleeping). We ignore overflow.
229 		 */
230 		if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
231 			p->p_slptime++;
232 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
233 		/*
234 		 * If the process has slept the entire second,
235 		 * stop recalculating its priority until it wakes up.
236 		 */
237 		if (p->p_slptime > 1)
238 			continue;
239 		SCHED_LOCK(s);
240 		/*
241 		 * p_pctcpu is only for diagnostic tools such as ps.
242 		 */
243 #if	(FSHIFT >= CCPU_SHIFT)
244 		p->p_pctcpu += (phz == 100)?
245 			((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
246                 	100 * (((fixpt_t) p->p_cpticks)
247 				<< (FSHIFT - CCPU_SHIFT)) / phz;
248 #else
249 		p->p_pctcpu += ((FSCALE - ccpu) *
250 			(p->p_cpticks * FSCALE / phz)) >> FSHIFT;
251 #endif
252 		p->p_cpticks = 0;
253 		newcpu = (u_int) decay_cpu(loadfac, p->p_estcpu);
254 		p->p_estcpu = newcpu;
255 		resetpriority(p);
256 		if (p->p_priority >= PUSER) {
257 			if (p->p_stat == SRUN &&
258 			    (p->p_priority / SCHED_PPQ) !=
259 			    (p->p_usrpri / SCHED_PPQ)) {
260 				remrunqueue(p);
261 				p->p_priority = p->p_usrpri;
262 				setrunqueue(p);
263 			} else
264 				p->p_priority = p->p_usrpri;
265 		}
266 		SCHED_UNLOCK(s);
267 	}
268 	uvm_meter();
269 	wakeup(&lbolt);
270 	timeout_add_sec(to, 1);
271 }
272 
273 /*
274  * Recalculate the priority of a process after it has slept for a while.
275  * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
276  * least six times the loadfactor will decay p_estcpu to zero.
277  */
278 void
279 updatepri(struct proc *p)
280 {
281 	unsigned int newcpu = p->p_estcpu;
282 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
283 
284 	SCHED_ASSERT_LOCKED();
285 
286 	if (p->p_slptime > 5 * loadfac)
287 		p->p_estcpu = 0;
288 	else {
289 		p->p_slptime--;	/* the first time was done in schedcpu */
290 		while (newcpu && --p->p_slptime)
291 			newcpu = (int) decay_cpu(loadfac, newcpu);
292 		p->p_estcpu = newcpu;
293 	}
294 	resetpriority(p);
295 }
296 
297 /*
298  * General yield call.  Puts the current process back on its run queue and
299  * performs a voluntary context switch.
300  */
301 void
302 yield(void)
303 {
304 	struct proc *p = curproc;
305 	int s;
306 
307 	NET_ASSERT_UNLOCKED();
308 
309 	SCHED_LOCK(s);
310 	p->p_priority = p->p_usrpri;
311 	p->p_stat = SRUN;
312 	setrunqueue(p);
313 	p->p_ru.ru_nvcsw++;
314 	mi_switch();
315 	SCHED_UNLOCK(s);
316 }
317 
318 /*
319  * General preemption call.  Puts the current process back on its run queue
320  * and performs an involuntary context switch.  If a process is supplied,
321  * we switch to that process.  Otherwise, we use the normal process selection
322  * criteria.
323  */
324 void
325 preempt(void)
326 {
327 	struct proc *p = curproc;
328 	int s;
329 
330 	SCHED_LOCK(s);
331 	p->p_priority = p->p_usrpri;
332 	p->p_stat = SRUN;
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 timespec ts;
347 #ifdef MULTIPROCESSOR
348 	int hold_count;
349 	int sched_count;
350 #endif
351 
352 	assertwaitok();
353 	KASSERT(p->p_stat != SONPROC);
354 
355 	SCHED_ASSERT_LOCKED();
356 
357 #ifdef MULTIPROCESSOR
358 	/*
359 	 * Release the kernel_lock, as we are about to yield the CPU.
360 	 */
361 	sched_count = __mp_release_all_but_one(&sched_lock);
362 	if (_kernel_lock_held())
363 		hold_count = __mp_release_all(&kernel_lock);
364 	else
365 		hold_count = 0;
366 #endif
367 
368 	/*
369 	 * Compute the amount of time during which the current
370 	 * process was running, and add that to its total so far.
371 	 */
372 	nanouptime(&ts);
373 	if (timespeccmp(&ts, &spc->spc_runtime, <)) {
374 #if 0
375 		printf("uptime is not monotonic! "
376 		    "ts=%lld.%09lu, runtime=%lld.%09lu\n",
377 		    (long long)tv.tv_sec, tv.tv_nsec,
378 		    (long long)spc->spc_runtime.tv_sec,
379 		    spc->spc_runtime.tv_nsec);
380 #endif
381 	} else {
382 		timespecsub(&ts, &spc->spc_runtime, &ts);
383 		timespecadd(&p->p_rtime, &ts, &p->p_rtime);
384 	}
385 
386 	/* add the time counts for this thread to the process's total */
387 	tuagg_unlocked(pr, p);
388 
389 	/*
390 	 * Process is about to yield the CPU; clear the appropriate
391 	 * scheduling flags.
392 	 */
393 	atomic_clearbits_int(&spc->spc_schedflags, SPCF_SWITCHCLEAR);
394 
395 	nextproc = sched_chooseproc();
396 
397 	if (p != nextproc) {
398 		uvmexp.swtch++;
399 		cpu_switchto(p, nextproc);
400 	} else {
401 		p->p_stat = SONPROC;
402 	}
403 
404 	clear_resched(curcpu());
405 
406 	SCHED_ASSERT_LOCKED();
407 
408 	/*
409 	 * To preserve lock ordering, we need to release the sched lock
410 	 * and grab it after we grab the big lock.
411 	 * In the future, when the sched lock isn't recursive, we'll
412 	 * just release it here.
413 	 */
414 #ifdef MULTIPROCESSOR
415 	__mp_unlock(&sched_lock);
416 #endif
417 
418 	SCHED_ASSERT_UNLOCKED();
419 
420 	/*
421 	 * We're running again; record our new start time.  We might
422 	 * be running on a new CPU now, so don't use the cache'd
423 	 * schedstate_percpu pointer.
424 	 */
425 	KASSERT(p->p_cpu == curcpu());
426 
427 	nanouptime(&p->p_cpu->ci_schedstate.spc_runtime);
428 
429 #ifdef MULTIPROCESSOR
430 	/*
431 	 * Reacquire the kernel_lock now.  We do this after we've
432 	 * released the scheduler lock to avoid deadlock, and before
433 	 * we reacquire the interlock and the scheduler lock.
434 	 */
435 	if (hold_count)
436 		__mp_acquire_count(&kernel_lock, hold_count);
437 	__mp_acquire_count(&sched_lock, sched_count + 1);
438 #endif
439 }
440 
441 static __inline void
442 resched_proc(struct proc *p, u_char pri)
443 {
444 	struct cpu_info *ci;
445 
446 	/*
447 	 * XXXSMP
448 	 * This does not handle the case where its last
449 	 * CPU is running a higher-priority process, but every
450 	 * other CPU is running a lower-priority process.  There
451 	 * are ways to handle this situation, but they're not
452 	 * currently very pretty, and we also need to weigh the
453 	 * cost of moving a process from one CPU to another.
454 	 *
455 	 * XXXSMP
456 	 * There is also the issue of locking the other CPU's
457 	 * sched state, which we currently do not do.
458 	 */
459 	ci = (p->p_cpu != NULL) ? p->p_cpu : curcpu();
460 	if (pri < ci->ci_schedstate.spc_curpriority)
461 		need_resched(ci);
462 }
463 
464 /*
465  * Change process state to be runnable,
466  * placing it on the run queue if it is in memory,
467  * and awakening the swapper if it isn't in memory.
468  */
469 void
470 setrunnable(struct proc *p)
471 {
472 	SCHED_ASSERT_LOCKED();
473 
474 	switch (p->p_stat) {
475 	case 0:
476 	case SRUN:
477 	case SONPROC:
478 	case SDEAD:
479 	case SIDL:
480 	default:
481 		panic("setrunnable");
482 	case SSTOP:
483 		/*
484 		 * If we're being traced (possibly because someone attached us
485 		 * while we were stopped), check for a signal from the debugger.
486 		 */
487 		if ((p->p_p->ps_flags & PS_TRACED) != 0 && p->p_xstat != 0)
488 			atomic_setbits_int(&p->p_siglist, sigmask(p->p_xstat));
489 	case SSLEEP:
490 		unsleep(p);		/* e.g. when sending signals */
491 		break;
492 	}
493 	p->p_stat = SRUN;
494 	p->p_cpu = sched_choosecpu(p);
495 	setrunqueue(p);
496 	if (p->p_slptime > 1)
497 		updatepri(p);
498 	p->p_slptime = 0;
499 	resched_proc(p, p->p_priority);
500 }
501 
502 /*
503  * Compute the priority of a process when running in user mode.
504  * Arrange to reschedule if the resulting priority is better
505  * than that of the current process.
506  */
507 void
508 resetpriority(struct proc *p)
509 {
510 	unsigned int newpriority;
511 
512 	SCHED_ASSERT_LOCKED();
513 
514 	newpriority = PUSER + p->p_estcpu +
515 	    NICE_WEIGHT * (p->p_p->ps_nice - NZERO);
516 	newpriority = min(newpriority, MAXPRI);
517 	p->p_usrpri = newpriority;
518 	resched_proc(p, p->p_usrpri);
519 }
520 
521 /*
522  * We adjust the priority of the current process.  The priority of a process
523  * gets worse as it accumulates CPU time.  The cpu usage estimator (p_estcpu)
524  * is increased here.  The formula for computing priorities (in kern_synch.c)
525  * will compute a different value each time p_estcpu increases. This can
526  * cause a switch, but unless the priority crosses a PPQ boundary the actual
527  * queue will not change.  The cpu usage estimator ramps up quite quickly
528  * when the process is running (linearly), and decays away exponentially, at
529  * a rate which is proportionally slower when the system is busy.  The basic
530  * principle is that the system will 90% forget that the process used a lot
531  * of CPU time in 5 * loadav seconds.  This causes the system to favor
532  * processes which haven't run much recently, and to round-robin among other
533  * processes.
534  */
535 void
536 schedclock(struct proc *p)
537 {
538 	struct cpu_info *ci = curcpu();
539 	struct schedstate_percpu *spc = &ci->ci_schedstate;
540 	int s;
541 
542 	if (p == spc->spc_idleproc)
543 		return;
544 
545 	SCHED_LOCK(s);
546 	p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
547 	resetpriority(p);
548 	if (p->p_priority >= PUSER)
549 		p->p_priority = p->p_usrpri;
550 	SCHED_UNLOCK(s);
551 }
552 
553 void (*cpu_setperf)(int);
554 
555 #define PERFPOL_MANUAL 0
556 #define PERFPOL_AUTO 1
557 #define PERFPOL_HIGH 2
558 int perflevel = 100;
559 int perfpolicy = PERFPOL_MANUAL;
560 
561 #ifndef SMALL_KERNEL
562 /*
563  * The code below handles CPU throttling.
564  */
565 #include <sys/sysctl.h>
566 
567 void setperf_auto(void *);
568 struct timeout setperf_to = TIMEOUT_INITIALIZER(setperf_auto, NULL);
569 
570 void
571 setperf_auto(void *v)
572 {
573 	static uint64_t *idleticks, *totalticks;
574 	static int downbeats;
575 
576 	int i, j;
577 	int speedup;
578 	CPU_INFO_ITERATOR cii;
579 	struct cpu_info *ci;
580 	uint64_t idle, total, allidle, alltotal;
581 
582 	if (perfpolicy != PERFPOL_AUTO)
583 		return;
584 
585 	if (!idleticks)
586 		if (!(idleticks = mallocarray(ncpusfound, sizeof(*idleticks),
587 		    M_DEVBUF, M_NOWAIT | M_ZERO)))
588 			return;
589 	if (!totalticks)
590 		if (!(totalticks = mallocarray(ncpusfound, sizeof(*totalticks),
591 		    M_DEVBUF, M_NOWAIT | M_ZERO))) {
592 			free(idleticks, M_DEVBUF,
593 			    sizeof(*idleticks) * ncpusfound);
594 			return;
595 		}
596 
597 	alltotal = allidle = 0;
598 	j = 0;
599 	speedup = 0;
600 	CPU_INFO_FOREACH(cii, ci) {
601 		total = 0;
602 		for (i = 0; i < CPUSTATES; i++) {
603 			total += ci->ci_schedstate.spc_cp_time[i];
604 		}
605 		total -= totalticks[j];
606 		idle = ci->ci_schedstate.spc_cp_time[CP_IDLE] - idleticks[j];
607 		if (idle < total / 3)
608 			speedup = 1;
609 		alltotal += total;
610 		allidle += idle;
611 		idleticks[j] += idle;
612 		totalticks[j] += total;
613 		j++;
614 	}
615 	if (allidle < alltotal / 2)
616 		speedup = 1;
617 	if (speedup)
618 		downbeats = 5;
619 
620 	if (speedup && perflevel != 100) {
621 		perflevel = 100;
622 		cpu_setperf(perflevel);
623 	} else if (!speedup && perflevel != 0 && --downbeats <= 0) {
624 		perflevel = 0;
625 		cpu_setperf(perflevel);
626 	}
627 
628 	timeout_add_msec(&setperf_to, 100);
629 }
630 
631 int
632 sysctl_hwsetperf(void *oldp, size_t *oldlenp, void *newp, size_t newlen)
633 {
634 	int err, newperf;
635 
636 	if (!cpu_setperf)
637 		return EOPNOTSUPP;
638 
639 	if (perfpolicy != PERFPOL_MANUAL)
640 		return sysctl_rdint(oldp, oldlenp, newp, perflevel);
641 
642 	newperf = perflevel;
643 	err = sysctl_int(oldp, oldlenp, newp, newlen, &newperf);
644 	if (err)
645 		return err;
646 	if (newperf > 100)
647 		newperf = 100;
648 	if (newperf < 0)
649 		newperf = 0;
650 	perflevel = newperf;
651 	cpu_setperf(perflevel);
652 
653 	return 0;
654 }
655 
656 int
657 sysctl_hwperfpolicy(void *oldp, size_t *oldlenp, void *newp, size_t newlen)
658 {
659 	char policy[32];
660 	int err;
661 
662 	if (!cpu_setperf)
663 		return EOPNOTSUPP;
664 
665 	switch (perfpolicy) {
666 	case PERFPOL_MANUAL:
667 		strlcpy(policy, "manual", sizeof(policy));
668 		break;
669 	case PERFPOL_AUTO:
670 		strlcpy(policy, "auto", sizeof(policy));
671 		break;
672 	case PERFPOL_HIGH:
673 		strlcpy(policy, "high", sizeof(policy));
674 		break;
675 	default:
676 		strlcpy(policy, "unknown", sizeof(policy));
677 		break;
678 	}
679 
680 	if (newp == NULL)
681 		return sysctl_rdstring(oldp, oldlenp, newp, policy);
682 
683 	err = sysctl_string(oldp, oldlenp, newp, newlen, policy, sizeof(policy));
684 	if (err)
685 		return err;
686 	if (strcmp(policy, "manual") == 0)
687 		perfpolicy = PERFPOL_MANUAL;
688 	else if (strcmp(policy, "auto") == 0)
689 		perfpolicy = PERFPOL_AUTO;
690 	else if (strcmp(policy, "high") == 0)
691 		perfpolicy = PERFPOL_HIGH;
692 	else
693 		return EINVAL;
694 
695 	if (perfpolicy == PERFPOL_AUTO) {
696 		timeout_add_msec(&setperf_to, 200);
697 	} else if (perfpolicy == PERFPOL_HIGH) {
698 		perflevel = 100;
699 		cpu_setperf(perflevel);
700 	}
701 	return 0;
702 }
703 #endif
704