xref: /freebsd/sys/kern/kern_cpu.c (revision ca9ac06c99bfd0150b85d4d83c396ce6237c0e05)
1 /*-
2  * Copyright (c) 2004-2005 Nate Lawson (SDG)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/bus.h>
32 #include <sys/cpu.h>
33 #include <sys/eventhandler.h>
34 #include <sys/kernel.h>
35 #include <sys/lock.h>
36 #include <sys/malloc.h>
37 #include <sys/module.h>
38 #include <sys/proc.h>
39 #include <sys/queue.h>
40 #include <sys/sched.h>
41 #include <sys/sysctl.h>
42 #include <sys/systm.h>
43 #include <sys/sbuf.h>
44 #include <sys/sx.h>
45 #include <sys/timetc.h>
46 
47 #include "cpufreq_if.h"
48 
49 /*
50  * Common CPU frequency glue code.  Drivers for specific hardware can
51  * attach this interface to allow users to get/set the CPU frequency.
52  */
53 
54 /*
55  * Number of levels we can handle.  Levels are synthesized from settings
56  * so for M settings and N drivers, there may be M*N levels.
57  */
58 #define CF_MAX_LEVELS	64
59 
60 struct cpufreq_softc {
61 	struct sx			lock;
62 	struct cf_level			curr_level;
63 	int				curr_priority;
64 	struct cf_level			saved_level;
65 	int				saved_priority;
66 	struct cf_level_lst		all_levels;
67 	int				all_count;
68 	int				max_mhz;
69 	device_t			dev;
70 	struct sysctl_ctx_list		sysctl_ctx;
71 };
72 
73 struct cf_setting_array {
74 	struct cf_setting		sets[MAX_SETTINGS];
75 	int				count;
76 	TAILQ_ENTRY(cf_setting_array)	link;
77 };
78 
79 TAILQ_HEAD(cf_setting_lst, cf_setting_array);
80 
81 #define CF_MTX_INIT(x)		sx_init((x), "cpufreq lock")
82 #define CF_MTX_LOCK(x)		sx_xlock((x))
83 #define CF_MTX_UNLOCK(x)	sx_xunlock((x))
84 #define CF_MTX_ASSERT(x)	sx_assert((x), SX_XLOCKED)
85 
86 static int	cpufreq_attach(device_t dev);
87 static int	cpufreq_detach(device_t dev);
88 static void	cpufreq_evaluate(void *arg);
89 static int	cf_set_method(device_t dev, const struct cf_level *level,
90 		    int priority);
91 static int	cf_get_method(device_t dev, struct cf_level *level);
92 static int	cf_levels_method(device_t dev, struct cf_level *levels,
93 		    int *count);
94 static int	cpufreq_insert_abs(struct cpufreq_softc *sc,
95 		    struct cf_setting *sets, int count);
96 static int	cpufreq_expand_set(struct cpufreq_softc *sc,
97 		    struct cf_setting_array *set_arr);
98 static struct cf_level *cpufreq_dup_set(struct cpufreq_softc *sc,
99 		    struct cf_level *dup, struct cf_setting *set);
100 static int	cpufreq_curr_sysctl(SYSCTL_HANDLER_ARGS);
101 static int	cpufreq_levels_sysctl(SYSCTL_HANDLER_ARGS);
102 static int	cpufreq_settings_sysctl(SYSCTL_HANDLER_ARGS);
103 
104 static device_method_t cpufreq_methods[] = {
105 	DEVMETHOD(device_probe,		bus_generic_probe),
106 	DEVMETHOD(device_attach,	cpufreq_attach),
107 	DEVMETHOD(device_detach,	cpufreq_detach),
108 
109         DEVMETHOD(cpufreq_set,		cf_set_method),
110         DEVMETHOD(cpufreq_get,		cf_get_method),
111         DEVMETHOD(cpufreq_levels,	cf_levels_method),
112 	{0, 0}
113 };
114 static driver_t cpufreq_driver = {
115 	"cpufreq", cpufreq_methods, sizeof(struct cpufreq_softc)
116 };
117 static devclass_t cpufreq_dc;
118 DRIVER_MODULE(cpufreq, cpu, cpufreq_driver, cpufreq_dc, 0, 0);
119 
120 static eventhandler_tag	cf_ev_tag;
121 
122 static int		cf_lowest_freq;
123 TUNABLE_INT("debug.cpufreq.lowest", &cf_lowest_freq);
124 SYSCTL_NODE(_debug, OID_AUTO, cpufreq, CTLFLAG_RD, NULL, "cpufreq debugging");
125 SYSCTL_INT(_debug_cpufreq, OID_AUTO, lowest, CTLFLAG_RW, &cf_lowest_freq, 1,
126     "Don't provide levels below this frequency.");
127 
128 static int
129 cpufreq_attach(device_t dev)
130 {
131 	struct cpufreq_softc *sc;
132 	device_t parent;
133 	int numdevs;
134 
135 	sc = device_get_softc(dev);
136 	parent = device_get_parent(dev);
137 	sc->dev = dev;
138 	sysctl_ctx_init(&sc->sysctl_ctx);
139 	TAILQ_INIT(&sc->all_levels);
140 	CF_MTX_INIT(&sc->lock);
141 	sc->curr_level.total_set.freq = CPUFREQ_VAL_UNKNOWN;
142 	sc->saved_level.total_set.freq = CPUFREQ_VAL_UNKNOWN;
143 	sc->max_mhz = CPUFREQ_VAL_UNKNOWN;
144 
145 	/*
146 	 * Only initialize one set of sysctls for all CPUs.  In the future,
147 	 * if multiple CPUs can have different settings, we can move these
148 	 * sysctls to be under every CPU instead of just the first one.
149 	 */
150 	numdevs = devclass_get_count(cpufreq_dc);
151 	if (numdevs > 1)
152 		return (0);
153 
154 	SYSCTL_ADD_PROC(&sc->sysctl_ctx,
155 	    SYSCTL_CHILDREN(device_get_sysctl_tree(parent)),
156 	    OID_AUTO, "freq", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
157 	    cpufreq_curr_sysctl, "I", "Current CPU frequency");
158 	SYSCTL_ADD_PROC(&sc->sysctl_ctx,
159 	    SYSCTL_CHILDREN(device_get_sysctl_tree(parent)),
160 	    OID_AUTO, "freq_levels", CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
161 	    cpufreq_levels_sysctl, "A", "CPU frequency levels");
162 	cf_ev_tag = EVENTHANDLER_REGISTER(cpufreq_changed, cpufreq_evaluate,
163 	    NULL, EVENTHANDLER_PRI_ANY);
164 
165 	return (0);
166 }
167 
168 static int
169 cpufreq_detach(device_t dev)
170 {
171 	struct cpufreq_softc *sc;
172 	int numdevs;
173 
174 	sc = device_get_softc(dev);
175 	sysctl_ctx_free(&sc->sysctl_ctx);
176 
177 	/* Only clean up these resources when the last device is detaching. */
178 	numdevs = devclass_get_count(cpufreq_dc);
179 	if (numdevs == 1)
180 		EVENTHANDLER_DEREGISTER(cpufreq_changed, cf_ev_tag);
181 
182 	return (0);
183 }
184 
185 static void
186 cpufreq_evaluate(void *arg)
187 {
188 	/* TODO: Re-evaluate when notified of changes to drivers. */
189 }
190 
191 static int
192 cf_set_method(device_t dev, const struct cf_level *level, int priority)
193 {
194 	struct cpufreq_softc *sc;
195 	const struct cf_setting *set;
196 	struct pcpu *pc;
197 	int cpu_id, error, i;
198 
199 	sc = device_get_softc(dev);
200 	error = 0;
201 	set = NULL;
202 
203 	/*
204 	 * Check that the TSC isn't being used as a timecounter.
205 	 * If it is, then return EBUSY and refuse to change the
206 	 * clock speed.
207 	 */
208 	if (strcmp(timecounter->tc_name, "TSC") == 0)
209 		return (EBUSY);
210 
211 	/*
212 	 * If the caller didn't specify a level and one is saved, prepare to
213 	 * restore the saved level.  If none has been saved, return an error.
214 	 * If they did specify one, but the requested level has a lower
215 	 * priority, don't allow the new level right now.
216 	 */
217 	CF_MTX_LOCK(&sc->lock);
218 	if (level == NULL) {
219 		if (sc->saved_level.total_set.freq != CPUFREQ_VAL_UNKNOWN) {
220 			level = &sc->saved_level;
221 			priority = sc->saved_priority;
222 		} else {
223 			error = ENXIO;
224 			goto out;
225 		}
226 	} else if (priority < sc->curr_priority) {
227 		error = EPERM;
228 		goto out;
229 	}
230 
231 	/* Reject levels that are below our specified threshold. */
232 	if (level->total_set.freq <= cf_lowest_freq) {
233 		error = EINVAL;
234 		goto out;
235 	}
236 
237 	/* If already at this level, just return. */
238 	if (CPUFREQ_CMP(sc->curr_level.total_set.freq, level->total_set.freq))
239 		goto out;
240 
241 	/* First, set the absolute frequency via its driver. */
242 	set = &level->abs_set;
243 	if (set->dev) {
244 		if (!device_is_attached(set->dev)) {
245 			error = ENXIO;
246 			goto out;
247 		}
248 
249 		/* Bind to the target CPU before switching, if necessary. */
250 		cpu_id = PCPU_GET(cpuid);
251 		pc = cpu_get_pcpu(set->dev);
252 		if (cpu_id != pc->pc_cpuid) {
253 			mtx_lock_spin(&sched_lock);
254 			sched_bind(curthread, pc->pc_cpuid);
255 			mtx_unlock_spin(&sched_lock);
256 		}
257 		error = CPUFREQ_DRV_SET(set->dev, set);
258 		if (cpu_id != pc->pc_cpuid) {
259 			mtx_lock_spin(&sched_lock);
260 			sched_unbind(curthread);
261 			mtx_unlock_spin(&sched_lock);
262 		}
263 		if (error) {
264 			goto out;
265 		}
266 	}
267 
268 	/* Next, set any/all relative frequencies via their drivers. */
269 	for (i = 0; i < level->rel_count; i++) {
270 		set = &level->rel_set[i];
271 		if (!device_is_attached(set->dev)) {
272 			error = ENXIO;
273 			goto out;
274 		}
275 
276 		/* Bind to the target CPU before switching, if necessary. */
277 		cpu_id = PCPU_GET(cpuid);
278 		pc = cpu_get_pcpu(set->dev);
279 		if (cpu_id != pc->pc_cpuid) {
280 			mtx_lock_spin(&sched_lock);
281 			sched_bind(curthread, pc->pc_cpuid);
282 			mtx_unlock_spin(&sched_lock);
283 		}
284 		error = CPUFREQ_DRV_SET(set->dev, set);
285 		if (cpu_id != pc->pc_cpuid) {
286 			mtx_lock_spin(&sched_lock);
287 			sched_unbind(curthread);
288 			mtx_unlock_spin(&sched_lock);
289 		}
290 		if (error) {
291 			/* XXX Back out any successful setting? */
292 			goto out;
293 		}
294 	}
295 
296 	/* If we were restoring a saved state, reset it to "unused". */
297 	if (level == &sc->saved_level) {
298 		sc->saved_level.total_set.freq = CPUFREQ_VAL_UNKNOWN;
299 		sc->saved_priority = 0;
300 	}
301 
302 	/*
303 	 * Before recording the current level, check if we're going to a
304 	 * higher priority and have not saved a level yet.  If so, save the
305 	 * previous level and priority.
306 	 */
307 	if (sc->curr_level.total_set.freq != CPUFREQ_VAL_UNKNOWN &&
308 	    sc->saved_level.total_set.freq == CPUFREQ_VAL_UNKNOWN &&
309 	    priority > sc->curr_priority) {
310 		sc->saved_level = sc->curr_level;
311 		sc->saved_priority = sc->curr_priority;
312 	}
313 	sc->curr_level = *level;
314 	sc->curr_priority = priority;
315 	error = 0;
316 
317 out:
318 	CF_MTX_UNLOCK(&sc->lock);
319 	if (error && set)
320 		device_printf(set->dev, "set freq failed, err %d\n", error);
321 	return (error);
322 }
323 
324 static int
325 cf_get_method(device_t dev, struct cf_level *level)
326 {
327 	struct cpufreq_softc *sc;
328 	struct cf_level *levels;
329 	struct cf_setting *curr_set, set;
330 	struct pcpu *pc;
331 	device_t *devs;
332 	int count, error, i, numdevs;
333 	uint64_t rate;
334 
335 	sc = device_get_softc(dev);
336 	error = 0;
337 	levels = NULL;
338 
339 	/* If we already know the current frequency, we're done. */
340 	CF_MTX_LOCK(&sc->lock);
341 	curr_set = &sc->curr_level.total_set;
342 	if (curr_set->freq != CPUFREQ_VAL_UNKNOWN)
343 		goto out;
344 	CF_MTX_UNLOCK(&sc->lock);
345 
346 	/*
347 	 * We need to figure out the current level.  Loop through every
348 	 * driver, getting the current setting.  Then, attempt to get a best
349 	 * match of settings against each level.
350 	 */
351 	count = CF_MAX_LEVELS;
352 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
353 	if (levels == NULL)
354 		return (ENOMEM);
355 	error = CPUFREQ_LEVELS(sc->dev, levels, &count);
356 	if (error) {
357 		if (error == E2BIG)
358 			printf("cpufreq: need to increase CF_MAX_LEVELS\n");
359 		free(levels, M_TEMP);
360 		return (error);
361 	}
362 	error = device_get_children(device_get_parent(dev), &devs, &numdevs);
363 	if (error) {
364 		free(levels, M_TEMP);
365 		return (error);
366 	}
367 
368 	/*
369 	 * Reacquire the lock and search for the given level.
370 	 *
371 	 * XXX Note: this is not quite right since we really need to go
372 	 * through each level and compare both absolute and relative
373 	 * settings for each driver in the system before making a match.
374 	 * The estimation code below catches this case though.
375 	 */
376 	CF_MTX_LOCK(&sc->lock);
377 	for (i = 0; i < numdevs && curr_set->freq == CPUFREQ_VAL_UNKNOWN; i++) {
378 		if (!device_is_attached(devs[i]))
379 			continue;
380 		error = CPUFREQ_DRV_GET(devs[i], &set);
381 		if (error)
382 			continue;
383 		for (i = 0; i < count; i++) {
384 			if (CPUFREQ_CMP(set.freq, levels[i].total_set.freq)) {
385 				sc->curr_level = levels[i];
386 				break;
387 			}
388 		}
389 	}
390 	free(devs, M_TEMP);
391 	if (curr_set->freq != CPUFREQ_VAL_UNKNOWN)
392 		goto out;
393 
394 	/*
395 	 * We couldn't find an exact match, so attempt to estimate and then
396 	 * match against a level.
397 	 */
398 	pc = cpu_get_pcpu(dev);
399 	if (pc == NULL) {
400 		error = ENXIO;
401 		goto out;
402 	}
403 	cpu_est_clockrate(pc->pc_cpuid, &rate);
404 	rate /= 1000000;
405 	for (i = 0; i < count; i++) {
406 		if (CPUFREQ_CMP(rate, levels[i].total_set.freq)) {
407 			sc->curr_level = levels[i];
408 			break;
409 		}
410 	}
411 
412 out:
413 	if (error == 0)
414 		*level = sc->curr_level;
415 
416 	CF_MTX_UNLOCK(&sc->lock);
417 	if (levels)
418 		free(levels, M_TEMP);
419 	return (error);
420 }
421 
422 static int
423 cf_levels_method(device_t dev, struct cf_level *levels, int *count)
424 {
425 	struct cf_setting_array *set_arr;
426 	struct cf_setting_lst rel_sets;
427 	struct cpufreq_softc *sc;
428 	struct cf_level *lev;
429 	struct cf_setting *sets;
430 	struct pcpu *pc;
431 	device_t *devs;
432 	int error, i, numdevs, set_count, type;
433 	uint64_t rate;
434 
435 	if (levels == NULL || count == NULL)
436 		return (EINVAL);
437 
438 	TAILQ_INIT(&rel_sets);
439 	sc = device_get_softc(dev);
440 	error = device_get_children(device_get_parent(dev), &devs, &numdevs);
441 	if (error)
442 		return (error);
443 	sets = malloc(MAX_SETTINGS * sizeof(*sets), M_TEMP, M_NOWAIT);
444 	if (sets == NULL) {
445 		free(devs, M_TEMP);
446 		return (ENOMEM);
447 	}
448 
449 	/* Get settings from all cpufreq drivers. */
450 	CF_MTX_LOCK(&sc->lock);
451 	for (i = 0; i < numdevs; i++) {
452 		/* Skip devices that aren't ready. */
453 		if (!device_is_attached(devs[i]))
454 			continue;
455 
456 		/*
457 		 * Get settings, skipping drivers that offer no settings or
458 		 * provide settings for informational purposes only.
459 		 */
460 		error = CPUFREQ_DRV_TYPE(devs[i], &type);
461 		if (error || (type & CPUFREQ_FLAG_INFO_ONLY))
462 			continue;
463 		set_count = MAX_SETTINGS;
464 		error = CPUFREQ_DRV_SETTINGS(devs[i], sets, &set_count);
465 		if (error || set_count == 0)
466 			continue;
467 
468 		/* Add the settings to our absolute/relative lists. */
469 		switch (type & CPUFREQ_TYPE_MASK) {
470 		case CPUFREQ_TYPE_ABSOLUTE:
471 			error = cpufreq_insert_abs(sc, sets, set_count);
472 			break;
473 		case CPUFREQ_TYPE_RELATIVE:
474 			set_arr = malloc(sizeof(*set_arr), M_TEMP, M_NOWAIT);
475 			if (set_arr == NULL) {
476 				error = ENOMEM;
477 				goto out;
478 			}
479 			bcopy(sets, set_arr->sets, set_count * sizeof(*sets));
480 			set_arr->count = set_count;
481 			TAILQ_INSERT_TAIL(&rel_sets, set_arr, link);
482 			break;
483 		default:
484 			error = EINVAL;
485 			break;
486 		}
487 		if (error)
488 			goto out;
489 	}
490 
491 	/*
492 	 * If there are no absolute levels, create a fake one at 100%.  We
493 	 * then cache the clockrate for later use as our base frequency.
494 	 *
495 	 * XXX This assumes that the first time through, if we only have
496 	 * relative drivers, the CPU is currently running at 100%.
497 	 */
498 	if (TAILQ_EMPTY(&sc->all_levels)) {
499 		if (sc->max_mhz == CPUFREQ_VAL_UNKNOWN) {
500 			pc = cpu_get_pcpu(dev);
501 			cpu_est_clockrate(pc->pc_cpuid, &rate);
502 			sc->max_mhz = rate / 1000000;
503 		}
504 		memset(&sets[0], CPUFREQ_VAL_UNKNOWN, sizeof(*sets));
505 		sets[0].freq = sc->max_mhz;
506 		sets[0].dev = NULL;
507 		error = cpufreq_insert_abs(sc, sets, 1);
508 		if (error)
509 			goto out;
510 	}
511 
512 	/* Create a combined list of absolute + relative levels. */
513 	TAILQ_FOREACH(set_arr, &rel_sets, link)
514 		cpufreq_expand_set(sc, set_arr);
515 
516 	/* If the caller doesn't have enough space, return the actual count. */
517 	if (sc->all_count > *count) {
518 		*count = sc->all_count;
519 		error = E2BIG;
520 		goto out;
521 	}
522 
523 	/* Finally, output the list of levels. */
524 	i = 0;
525 	TAILQ_FOREACH(lev, &sc->all_levels, link) {
526 		/* Skip levels that have a frequency that is too low. */
527 		if (lev->total_set.freq <= cf_lowest_freq) {
528 			sc->all_count--;
529 			continue;
530 		}
531 
532 		levels[i] = *lev;
533 		i++;
534 	}
535 	*count = sc->all_count;
536 	error = 0;
537 
538 out:
539 	/* Clear all levels since we regenerate them each time. */
540 	while ((lev = TAILQ_FIRST(&sc->all_levels)) != NULL) {
541 		TAILQ_REMOVE(&sc->all_levels, lev, link);
542 		free(lev, M_TEMP);
543 	}
544 	sc->all_count = 0;
545 
546 	CF_MTX_UNLOCK(&sc->lock);
547 	while ((set_arr = TAILQ_FIRST(&rel_sets)) != NULL) {
548 		TAILQ_REMOVE(&rel_sets, set_arr, link);
549 		free(set_arr, M_TEMP);
550 	}
551 	free(devs, M_TEMP);
552 	free(sets, M_TEMP);
553 	return (error);
554 }
555 
556 /*
557  * Create levels for an array of absolute settings and insert them in
558  * sorted order in the specified list.
559  */
560 static int
561 cpufreq_insert_abs(struct cpufreq_softc *sc, struct cf_setting *sets,
562     int count)
563 {
564 	struct cf_level_lst *list;
565 	struct cf_level *level, *search;
566 	int i;
567 
568 	CF_MTX_ASSERT(&sc->lock);
569 
570 	list = &sc->all_levels;
571 	for (i = 0; i < count; i++) {
572 		level = malloc(sizeof(*level), M_TEMP, M_NOWAIT | M_ZERO);
573 		if (level == NULL)
574 			return (ENOMEM);
575 		level->abs_set = sets[i];
576 		level->total_set = sets[i];
577 		level->total_set.dev = NULL;
578 		sc->all_count++;
579 
580 		if (TAILQ_EMPTY(list)) {
581 			TAILQ_INSERT_HEAD(list, level, link);
582 			continue;
583 		}
584 
585 		TAILQ_FOREACH_REVERSE(search, list, cf_level_lst, link) {
586 			if (sets[i].freq <= search->total_set.freq) {
587 				TAILQ_INSERT_AFTER(list, search, level, link);
588 				break;
589 			}
590 		}
591 	}
592 	return (0);
593 }
594 
595 /*
596  * Expand a group of relative settings, creating derived levels from them.
597  */
598 static int
599 cpufreq_expand_set(struct cpufreq_softc *sc, struct cf_setting_array *set_arr)
600 {
601 	struct cf_level *fill, *search;
602 	struct cf_setting *set;
603 	int i;
604 
605 	CF_MTX_ASSERT(&sc->lock);
606 
607 	TAILQ_FOREACH(search, &sc->all_levels, link) {
608 		/* Skip this level if we've already modified it. */
609 		for (i = 0; i < search->rel_count; i++) {
610 			if (search->rel_set[i].dev == set_arr->sets[0].dev)
611 				break;
612 		}
613 		if (i != search->rel_count)
614 			continue;
615 
616 		/* Add each setting to the level, duplicating if necessary. */
617 		for (i = 0; i < set_arr->count; i++) {
618 			set = &set_arr->sets[i];
619 
620 			/*
621 			 * If this setting is less than 100%, split the level
622 			 * into two and add this setting to the new level.
623 			 */
624 			fill = search;
625 			if (set->freq < 10000)
626 				fill = cpufreq_dup_set(sc, search, set);
627 
628 			/*
629 			 * The new level was a duplicate of an existing level
630 			 * so we freed it.  Go to the next setting.
631 			 */
632 			if (fill == NULL)
633 				continue;
634 
635 			/* Add this setting to the existing or new level. */
636 			KASSERT(fill->rel_count < MAX_SETTINGS,
637 			    ("cpufreq: too many relative drivers (%d)",
638 			    MAX_SETTINGS));
639 			fill->rel_set[fill->rel_count] = *set;
640 			fill->rel_count++;
641 		}
642 	}
643 
644 	return (0);
645 }
646 
647 static struct cf_level *
648 cpufreq_dup_set(struct cpufreq_softc *sc, struct cf_level *dup,
649     struct cf_setting *set)
650 {
651 	struct cf_level_lst *list;
652 	struct cf_level *fill, *itr;
653 	struct cf_setting *fill_set, *itr_set;
654 	int i;
655 
656 	CF_MTX_ASSERT(&sc->lock);
657 
658 	/*
659 	 * Create a new level, copy it from the old one, and update the
660 	 * total frequency and power by the percentage specified in the
661 	 * relative setting.
662 	 */
663 	fill = malloc(sizeof(*fill), M_TEMP, M_NOWAIT);
664 	if (fill == NULL)
665 		return (NULL);
666 	*fill = *dup;
667 	fill_set = &fill->total_set;
668 	fill_set->freq =
669 	    ((uint64_t)fill_set->freq * set->freq) / 10000;
670 	if (fill_set->power != CPUFREQ_VAL_UNKNOWN) {
671 		fill_set->power = ((uint64_t)fill_set->power * set->freq)
672 		    / 10000;
673 	}
674 	if (set->lat != CPUFREQ_VAL_UNKNOWN) {
675 		if (fill_set->lat != CPUFREQ_VAL_UNKNOWN)
676 			fill_set->lat += set->lat;
677 		else
678 			fill_set->lat = set->lat;
679 	}
680 
681 	/*
682 	 * If we copied an old level that we already modified (say, at 100%),
683 	 * we need to remove that setting before adding this one.  Since we
684 	 * process each setting array in order, we know any settings for this
685 	 * driver will be found at the end.
686 	 */
687 	for (i = fill->rel_count; i != 0; i--) {
688 		if (fill->rel_set[i - 1].dev != set->dev)
689 			break;
690 		fill->rel_count--;
691 	}
692 
693 	/*
694 	 * Insert the new level in sorted order.  If we find a duplicate,
695 	 * free the new level.  We can do this since any existing level will
696 	 * be guaranteed to have the same or less settings and thus consume
697 	 * less power.  For example, a level with one absolute setting of
698 	 * 800 Mhz uses less power than one composed of an absolute setting
699 	 * of 1600 Mhz and a relative setting at 50%.
700 	 */
701 	list = &sc->all_levels;
702 	if (TAILQ_EMPTY(list)) {
703 		TAILQ_INSERT_HEAD(list, fill, link);
704 	} else {
705 		TAILQ_FOREACH_REVERSE(itr, list, cf_level_lst, link) {
706 			itr_set = &itr->total_set;
707 			if (CPUFREQ_CMP(fill_set->freq, itr_set->freq)) {
708 				free(fill, M_TEMP);
709 				fill = NULL;
710 				break;
711 			} else if (fill_set->freq < itr_set->freq) {
712 				TAILQ_INSERT_AFTER(list, itr, fill, link);
713 				sc->all_count++;
714 				break;
715 			}
716 		}
717 	}
718 
719 	return (fill);
720 }
721 
722 static int
723 cpufreq_curr_sysctl(SYSCTL_HANDLER_ARGS)
724 {
725 	struct cpufreq_softc *sc;
726 	struct cf_level *levels;
727 	int count, devcount, error, freq, i, n;
728 	device_t *devs;
729 
730 	devs = NULL;
731 	sc = oidp->oid_arg1;
732 	levels = malloc(CF_MAX_LEVELS * sizeof(*levels), M_TEMP, M_NOWAIT);
733 	if (levels == NULL)
734 		return (ENOMEM);
735 
736 	error = CPUFREQ_GET(sc->dev, &levels[0]);
737 	if (error)
738 		goto out;
739 	freq = levels[0].total_set.freq;
740 	error = sysctl_handle_int(oidp, &freq, 0, req);
741 	if (error != 0 || req->newptr == NULL)
742 		goto out;
743 
744 	/*
745 	 * While we only call cpufreq_get() on one device (assuming all
746 	 * CPUs have equal levels), we call cpufreq_set() on all CPUs.
747 	 * This is needed for some MP systems.
748 	 */
749 	error = devclass_get_devices(cpufreq_dc, &devs, &devcount);
750 	if (error)
751 		goto out;
752 	for (n = 0; n < devcount; n++) {
753 		count = CF_MAX_LEVELS;
754 		error = CPUFREQ_LEVELS(devs[n], levels, &count);
755 		if (error) {
756 			if (error == E2BIG)
757 				printf(
758 			"cpufreq: need to increase CF_MAX_LEVELS\n");
759 			break;
760 		}
761 		for (i = 0; i < count; i++) {
762 			if (CPUFREQ_CMP(levels[i].total_set.freq, freq)) {
763 				error = CPUFREQ_SET(devs[n], &levels[i],
764 				    CPUFREQ_PRIO_USER);
765 				break;
766 			}
767 		}
768 		if (i == count) {
769 			error = EINVAL;
770 			break;
771 		}
772 	}
773 
774 out:
775 	if (devs)
776 		free(devs, M_TEMP);
777 	if (levels)
778 		free(levels, M_TEMP);
779 	return (error);
780 }
781 
782 static int
783 cpufreq_levels_sysctl(SYSCTL_HANDLER_ARGS)
784 {
785 	struct cpufreq_softc *sc;
786 	struct cf_level *levels;
787 	struct cf_setting *set;
788 	struct sbuf sb;
789 	int count, error, i;
790 
791 	sc = oidp->oid_arg1;
792 	sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND);
793 
794 	/* Get settings from the device and generate the output string. */
795 	count = CF_MAX_LEVELS;
796 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
797 	if (levels == NULL)
798 		return (ENOMEM);
799 	error = CPUFREQ_LEVELS(sc->dev, levels, &count);
800 	if (error) {
801 		if (error == E2BIG)
802 			printf("cpufreq: need to increase CF_MAX_LEVELS\n");
803 		goto out;
804 	}
805 	if (count) {
806 		for (i = 0; i < count; i++) {
807 			set = &levels[i].total_set;
808 			sbuf_printf(&sb, "%d/%d ", set->freq, set->power);
809 		}
810 	} else
811 		sbuf_cpy(&sb, "0");
812 	sbuf_trim(&sb);
813 	sbuf_finish(&sb);
814 	error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
815 
816 out:
817 	free(levels, M_TEMP);
818 	sbuf_delete(&sb);
819 	return (error);
820 }
821 
822 static int
823 cpufreq_settings_sysctl(SYSCTL_HANDLER_ARGS)
824 {
825 	device_t dev;
826 	struct cf_setting *sets;
827 	struct sbuf sb;
828 	int error, i, set_count;
829 
830 	dev = oidp->oid_arg1;
831 	sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND);
832 
833 	/* Get settings from the device and generate the output string. */
834 	set_count = MAX_SETTINGS;
835 	sets = malloc(set_count * sizeof(*sets), M_TEMP, M_NOWAIT);
836 	if (sets == NULL)
837 		return (ENOMEM);
838 	error = CPUFREQ_DRV_SETTINGS(dev, sets, &set_count);
839 	if (error)
840 		goto out;
841 	if (set_count) {
842 		for (i = 0; i < set_count; i++)
843 			sbuf_printf(&sb, "%d/%d ", sets[i].freq, sets[i].power);
844 	} else
845 		sbuf_cpy(&sb, "0");
846 	sbuf_trim(&sb);
847 	sbuf_finish(&sb);
848 	error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
849 
850 out:
851 	free(sets, M_TEMP);
852 	sbuf_delete(&sb);
853 	return (error);
854 }
855 
856 int
857 cpufreq_register(device_t dev)
858 {
859 	struct cpufreq_softc *sc;
860 	device_t cf_dev, cpu_dev;
861 
862 	/* Add a sysctl to get each driver's settings separately. */
863 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
864 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
865 	    OID_AUTO, "freq_settings", CTLTYPE_STRING | CTLFLAG_RD, dev, 0,
866 	    cpufreq_settings_sysctl, "A", "CPU frequency driver settings");
867 
868 	/*
869 	 * Add only one cpufreq device to each CPU.  Currently, all CPUs
870 	 * must offer the same levels and be switched at the same time.
871 	 */
872 	cpu_dev = device_get_parent(dev);
873 	if ((cf_dev = device_find_child(cpu_dev, "cpufreq", -1))) {
874 		sc = device_get_softc(cf_dev);
875 		sc->max_mhz = CPUFREQ_VAL_UNKNOWN;
876 		return (0);
877 	}
878 
879 	/* Add the child device and possibly sysctls. */
880 	cf_dev = BUS_ADD_CHILD(cpu_dev, 0, "cpufreq", -1);
881 	if (cf_dev == NULL)
882 		return (ENOMEM);
883 	device_quiet(cf_dev);
884 
885 	return (device_probe_and_attach(cf_dev));
886 }
887 
888 int
889 cpufreq_unregister(device_t dev)
890 {
891 	device_t cf_dev, *devs;
892 	int cfcount, devcount, error, i, type;
893 
894 	/*
895 	 * If this is the last cpufreq child device, remove the control
896 	 * device as well.  We identify cpufreq children by calling a method
897 	 * they support.
898 	 */
899 	error = device_get_children(device_get_parent(dev), &devs, &devcount);
900 	if (error)
901 		return (error);
902 	cf_dev = device_find_child(device_get_parent(dev), "cpufreq", -1);
903 	cfcount = 0;
904 	for (i = 0; i < devcount; i++) {
905 		if (!device_is_attached(devs[i]))
906 			continue;
907 		if (CPUFREQ_DRV_TYPE(devs[i], &type) == 0)
908 			cfcount++;
909 	}
910 	if (cfcount <= 1)
911 		device_delete_child(device_get_parent(cf_dev), cf_dev);
912 	free(devs, M_TEMP);
913 
914 	return (0);
915 }
916