xref: /freebsd/sys/kern/kern_cpu.c (revision 30d239bc4c510432e65a84fa1c14ed67a3ab1c92)
1 /*-
2  * Copyright (c) 2004-2007 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 #include <sys/taskqueue.h>
47 
48 #include "cpufreq_if.h"
49 
50 /*
51  * Common CPU frequency glue code.  Drivers for specific hardware can
52  * attach this interface to allow users to get/set the CPU frequency.
53  */
54 
55 /*
56  * Number of levels we can handle.  Levels are synthesized from settings
57  * so for M settings and N drivers, there may be M*N levels.
58  */
59 #define CF_MAX_LEVELS	64
60 
61 struct cf_saved_freq {
62 	struct cf_level			level;
63 	int				priority;
64 	SLIST_ENTRY(cf_saved_freq)	link;
65 };
66 
67 struct cpufreq_softc {
68 	struct sx			lock;
69 	struct cf_level			curr_level;
70 	int				curr_priority;
71 	SLIST_HEAD(, cf_saved_freq)	saved_freq;
72 	struct cf_level_lst		all_levels;
73 	int				all_count;
74 	int				max_mhz;
75 	device_t			dev;
76 	struct sysctl_ctx_list		sysctl_ctx;
77 	struct task			startup_task;
78 };
79 
80 struct cf_setting_array {
81 	struct cf_setting		sets[MAX_SETTINGS];
82 	int				count;
83 	TAILQ_ENTRY(cf_setting_array)	link;
84 };
85 
86 TAILQ_HEAD(cf_setting_lst, cf_setting_array);
87 
88 #define CF_MTX_INIT(x)		sx_init((x), "cpufreq lock")
89 #define CF_MTX_LOCK(x)		sx_xlock((x))
90 #define CF_MTX_UNLOCK(x)	sx_xunlock((x))
91 #define CF_MTX_ASSERT(x)	sx_assert((x), SX_XLOCKED)
92 
93 #define CF_DEBUG(msg...)	do {		\
94 	if (cf_verbose)				\
95 		printf("cpufreq: " msg);	\
96 	} while (0)
97 
98 static int	cpufreq_attach(device_t dev);
99 static void	cpufreq_startup_task(void *ctx, int pending);
100 static int	cpufreq_detach(device_t dev);
101 static int	cf_set_method(device_t dev, const struct cf_level *level,
102 		    int priority);
103 static int	cf_get_method(device_t dev, struct cf_level *level);
104 static int	cf_levels_method(device_t dev, struct cf_level *levels,
105 		    int *count);
106 static int	cpufreq_insert_abs(struct cpufreq_softc *sc,
107 		    struct cf_setting *sets, int count);
108 static int	cpufreq_expand_set(struct cpufreq_softc *sc,
109 		    struct cf_setting_array *set_arr);
110 static struct cf_level *cpufreq_dup_set(struct cpufreq_softc *sc,
111 		    struct cf_level *dup, struct cf_setting *set);
112 static int	cpufreq_curr_sysctl(SYSCTL_HANDLER_ARGS);
113 static int	cpufreq_levels_sysctl(SYSCTL_HANDLER_ARGS);
114 static int	cpufreq_settings_sysctl(SYSCTL_HANDLER_ARGS);
115 
116 static device_method_t cpufreq_methods[] = {
117 	DEVMETHOD(device_probe,		bus_generic_probe),
118 	DEVMETHOD(device_attach,	cpufreq_attach),
119 	DEVMETHOD(device_detach,	cpufreq_detach),
120 
121         DEVMETHOD(cpufreq_set,		cf_set_method),
122         DEVMETHOD(cpufreq_get,		cf_get_method),
123         DEVMETHOD(cpufreq_levels,	cf_levels_method),
124 	{0, 0}
125 };
126 static driver_t cpufreq_driver = {
127 	"cpufreq", cpufreq_methods, sizeof(struct cpufreq_softc)
128 };
129 static devclass_t cpufreq_dc;
130 DRIVER_MODULE(cpufreq, cpu, cpufreq_driver, cpufreq_dc, 0, 0);
131 
132 static int		cf_lowest_freq;
133 static int		cf_verbose;
134 TUNABLE_INT("debug.cpufreq.lowest", &cf_lowest_freq);
135 TUNABLE_INT("debug.cpufreq.verbose", &cf_verbose);
136 SYSCTL_NODE(_debug, OID_AUTO, cpufreq, CTLFLAG_RD, NULL, "cpufreq debugging");
137 SYSCTL_INT(_debug_cpufreq, OID_AUTO, lowest, CTLFLAG_RW, &cf_lowest_freq, 1,
138     "Don't provide levels below this frequency.");
139 SYSCTL_INT(_debug_cpufreq, OID_AUTO, verbose, CTLFLAG_RW, &cf_verbose, 1,
140     "Print verbose debugging messages");
141 
142 static int
143 cpufreq_attach(device_t dev)
144 {
145 	struct cpufreq_softc *sc;
146 	device_t parent;
147 	int numdevs;
148 
149 	CF_DEBUG("initializing %s\n", device_get_nameunit(dev));
150 	sc = device_get_softc(dev);
151 	parent = device_get_parent(dev);
152 	sc->dev = dev;
153 	sysctl_ctx_init(&sc->sysctl_ctx);
154 	TAILQ_INIT(&sc->all_levels);
155 	CF_MTX_INIT(&sc->lock);
156 	sc->curr_level.total_set.freq = CPUFREQ_VAL_UNKNOWN;
157 	SLIST_INIT(&sc->saved_freq);
158 	sc->max_mhz = CPUFREQ_VAL_UNKNOWN;
159 
160 	/*
161 	 * Only initialize one set of sysctls for all CPUs.  In the future,
162 	 * if multiple CPUs can have different settings, we can move these
163 	 * sysctls to be under every CPU instead of just the first one.
164 	 */
165 	numdevs = devclass_get_count(cpufreq_dc);
166 	if (numdevs > 1)
167 		return (0);
168 
169 	CF_DEBUG("initializing one-time data for %s\n",
170 	    device_get_nameunit(dev));
171 	SYSCTL_ADD_PROC(&sc->sysctl_ctx,
172 	    SYSCTL_CHILDREN(device_get_sysctl_tree(parent)),
173 	    OID_AUTO, "freq", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
174 	    cpufreq_curr_sysctl, "I", "Current CPU frequency");
175 	SYSCTL_ADD_PROC(&sc->sysctl_ctx,
176 	    SYSCTL_CHILDREN(device_get_sysctl_tree(parent)),
177 	    OID_AUTO, "freq_levels", CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
178 	    cpufreq_levels_sysctl, "A", "CPU frequency levels");
179 
180 	/*
181 	 * Queue a one-shot broadcast that levels have changed.
182 	 * It will run once the system has completed booting.
183 	 */
184 	TASK_INIT(&sc->startup_task, 0, cpufreq_startup_task, dev);
185 	taskqueue_enqueue(taskqueue_thread, &sc->startup_task);
186 
187 	return (0);
188 }
189 
190 /* Handle any work to be done for all drivers that attached during boot. */
191 static void
192 cpufreq_startup_task(void *ctx, int pending)
193 {
194 
195 	cpufreq_settings_changed((device_t)ctx);
196 }
197 
198 static int
199 cpufreq_detach(device_t dev)
200 {
201 	struct cpufreq_softc *sc;
202 	struct cf_saved_freq *saved_freq;
203 	int numdevs;
204 
205 	CF_DEBUG("shutdown %s\n", device_get_nameunit(dev));
206 	sc = device_get_softc(dev);
207 	sysctl_ctx_free(&sc->sysctl_ctx);
208 
209 	while ((saved_freq = SLIST_FIRST(&sc->saved_freq)) != NULL) {
210 		SLIST_REMOVE_HEAD(&sc->saved_freq, link);
211 		free(saved_freq, M_TEMP);
212 	}
213 
214 	/* Only clean up these resources when the last device is detaching. */
215 	numdevs = devclass_get_count(cpufreq_dc);
216 	if (numdevs == 1) {
217 		CF_DEBUG("final shutdown for %s\n", device_get_nameunit(dev));
218 	}
219 
220 	return (0);
221 }
222 
223 static int
224 cf_set_method(device_t dev, const struct cf_level *level, int priority)
225 {
226 	struct cpufreq_softc *sc;
227 	const struct cf_setting *set;
228 	struct cf_saved_freq *saved_freq, *curr_freq;
229 	struct pcpu *pc;
230 	int error, i;
231 
232 	sc = device_get_softc(dev);
233 	error = 0;
234 	set = NULL;
235 	saved_freq = NULL;
236 
237 	/* We are going to change levels so notify the pre-change handler. */
238 	EVENTHANDLER_INVOKE(cpufreq_pre_change, level, &error);
239 	if (error != 0) {
240 		EVENTHANDLER_INVOKE(cpufreq_post_change, level, error);
241 		return (error);
242 	}
243 
244 	CF_MTX_LOCK(&sc->lock);
245 
246 	/*
247 	 * If the requested level has a lower priority, don't allow
248 	 * the new level right now.
249 	 */
250 	if (priority < sc->curr_priority) {
251 		CF_DEBUG("ignoring, curr prio %d less than %d\n", priority,
252 		    sc->curr_priority);
253 		error = EPERM;
254 		goto out;
255 	}
256 
257 	/*
258 	 * If the caller didn't specify a level and one is saved, prepare to
259 	 * restore the saved level.  If none has been saved, return an error.
260 	 */
261 	if (level == NULL) {
262 		saved_freq = SLIST_FIRST(&sc->saved_freq);
263 		if (saved_freq == NULL) {
264 			CF_DEBUG("NULL level, no saved level\n");
265 			error = ENXIO;
266 			goto out;
267 		}
268 		level = &saved_freq->level;
269 		priority = saved_freq->priority;
270 		CF_DEBUG("restoring saved level, freq %d prio %d\n",
271 		    level->total_set.freq, priority);
272 	}
273 
274 	/* Reject levels that are below our specified threshold. */
275 	if (level->total_set.freq < cf_lowest_freq) {
276 		CF_DEBUG("rejecting freq %d, less than %d limit\n",
277 		    level->total_set.freq, cf_lowest_freq);
278 		error = EINVAL;
279 		goto out;
280 	}
281 
282 	/* If already at this level, just return. */
283 	if (CPUFREQ_CMP(sc->curr_level.total_set.freq, level->total_set.freq)) {
284 		CF_DEBUG("skipping freq %d, same as current level %d\n",
285 		    level->total_set.freq, sc->curr_level.total_set.freq);
286 		goto skip;
287 	}
288 
289 	/* First, set the absolute frequency via its driver. */
290 	set = &level->abs_set;
291 	if (set->dev) {
292 		if (!device_is_attached(set->dev)) {
293 			error = ENXIO;
294 			goto out;
295 		}
296 
297 		/* Bind to the target CPU before switching. */
298 		pc = cpu_get_pcpu(set->dev);
299 		thread_lock(curthread);
300 		sched_bind(curthread, pc->pc_cpuid);
301 		thread_unlock(curthread);
302 		CF_DEBUG("setting abs freq %d on %s (cpu %d)\n", set->freq,
303 		    device_get_nameunit(set->dev), PCPU_GET(cpuid));
304 		error = CPUFREQ_DRV_SET(set->dev, set);
305 		thread_lock(curthread);
306 		sched_unbind(curthread);
307 		thread_unlock(curthread);
308 		if (error) {
309 			goto out;
310 		}
311 	}
312 
313 	/* Next, set any/all relative frequencies via their drivers. */
314 	for (i = 0; i < level->rel_count; i++) {
315 		set = &level->rel_set[i];
316 		if (!device_is_attached(set->dev)) {
317 			error = ENXIO;
318 			goto out;
319 		}
320 
321 		/* Bind to the target CPU before switching. */
322 		pc = cpu_get_pcpu(set->dev);
323 		thread_lock(curthread);
324 		sched_bind(curthread, pc->pc_cpuid);
325 		thread_unlock(curthread);
326 		CF_DEBUG("setting rel freq %d on %s (cpu %d)\n", set->freq,
327 		    device_get_nameunit(set->dev), PCPU_GET(cpuid));
328 		error = CPUFREQ_DRV_SET(set->dev, set);
329 		thread_lock(curthread);
330 		sched_unbind(curthread);
331 		thread_unlock(curthread);
332 		if (error) {
333 			/* XXX Back out any successful setting? */
334 			goto out;
335 		}
336 	}
337 
338 skip:
339 	/*
340 	 * Before recording the current level, check if we're going to a
341 	 * higher priority.  If so, save the previous level and priority.
342 	 */
343 	if (sc->curr_level.total_set.freq != CPUFREQ_VAL_UNKNOWN &&
344 	    priority > sc->curr_priority) {
345 		CF_DEBUG("saving level, freq %d prio %d\n",
346 		    sc->curr_level.total_set.freq, sc->curr_priority);
347 		curr_freq = malloc(sizeof(*curr_freq), M_TEMP, M_NOWAIT);
348 		if (curr_freq == NULL) {
349 			error = ENOMEM;
350 			goto out;
351 		}
352 		curr_freq->level = sc->curr_level;
353 		curr_freq->priority = sc->curr_priority;
354 		SLIST_INSERT_HEAD(&sc->saved_freq, curr_freq, link);
355 	}
356 	sc->curr_level = *level;
357 	sc->curr_priority = priority;
358 
359 	/* If we were restoring a saved state, reset it to "unused". */
360 	if (saved_freq != NULL) {
361 		CF_DEBUG("resetting saved level\n");
362 		sc->curr_level.total_set.freq = CPUFREQ_VAL_UNKNOWN;
363 		SLIST_REMOVE_HEAD(&sc->saved_freq, link);
364 		free(saved_freq, M_TEMP);
365 	}
366 
367 out:
368 	CF_MTX_UNLOCK(&sc->lock);
369 
370 	/*
371 	 * We changed levels (or attempted to) so notify the post-change
372 	 * handler of new frequency or error.
373 	 */
374 	EVENTHANDLER_INVOKE(cpufreq_post_change, level, error);
375 	if (error && set)
376 		device_printf(set->dev, "set freq failed, err %d\n", error);
377 
378 	return (error);
379 }
380 
381 static int
382 cf_get_method(device_t dev, struct cf_level *level)
383 {
384 	struct cpufreq_softc *sc;
385 	struct cf_level *levels;
386 	struct cf_setting *curr_set, set;
387 	struct pcpu *pc;
388 	device_t *devs;
389 	int count, error, i, n, numdevs;
390 	uint64_t rate;
391 
392 	sc = device_get_softc(dev);
393 	error = 0;
394 	levels = NULL;
395 
396 	/* If we already know the current frequency, we're done. */
397 	CF_MTX_LOCK(&sc->lock);
398 	curr_set = &sc->curr_level.total_set;
399 	if (curr_set->freq != CPUFREQ_VAL_UNKNOWN) {
400 		CF_DEBUG("get returning known freq %d\n", curr_set->freq);
401 		goto out;
402 	}
403 	CF_MTX_UNLOCK(&sc->lock);
404 
405 	/*
406 	 * We need to figure out the current level.  Loop through every
407 	 * driver, getting the current setting.  Then, attempt to get a best
408 	 * match of settings against each level.
409 	 */
410 	count = CF_MAX_LEVELS;
411 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
412 	if (levels == NULL)
413 		return (ENOMEM);
414 	error = CPUFREQ_LEVELS(sc->dev, levels, &count);
415 	if (error) {
416 		if (error == E2BIG)
417 			printf("cpufreq: need to increase CF_MAX_LEVELS\n");
418 		free(levels, M_TEMP);
419 		return (error);
420 	}
421 	error = device_get_children(device_get_parent(dev), &devs, &numdevs);
422 	if (error) {
423 		free(levels, M_TEMP);
424 		return (error);
425 	}
426 
427 	/*
428 	 * Reacquire the lock and search for the given level.
429 	 *
430 	 * XXX Note: this is not quite right since we really need to go
431 	 * through each level and compare both absolute and relative
432 	 * settings for each driver in the system before making a match.
433 	 * The estimation code below catches this case though.
434 	 */
435 	CF_MTX_LOCK(&sc->lock);
436 	for (n = 0; n < numdevs && curr_set->freq == CPUFREQ_VAL_UNKNOWN; n++) {
437 		if (!device_is_attached(devs[n]))
438 			continue;
439 		error = CPUFREQ_DRV_GET(devs[n], &set);
440 		if (error)
441 			continue;
442 		for (i = 0; i < count; i++) {
443 			if (CPUFREQ_CMP(set.freq, levels[i].total_set.freq)) {
444 				sc->curr_level = levels[i];
445 				break;
446 			}
447 		}
448 	}
449 	free(devs, M_TEMP);
450 	if (curr_set->freq != CPUFREQ_VAL_UNKNOWN) {
451 		CF_DEBUG("get matched freq %d from drivers\n", curr_set->freq);
452 		goto out;
453 	}
454 
455 	/*
456 	 * We couldn't find an exact match, so attempt to estimate and then
457 	 * match against a level.
458 	 */
459 	pc = cpu_get_pcpu(dev);
460 	if (pc == NULL) {
461 		error = ENXIO;
462 		goto out;
463 	}
464 	cpu_est_clockrate(pc->pc_cpuid, &rate);
465 	rate /= 1000000;
466 	for (i = 0; i < count; i++) {
467 		if (CPUFREQ_CMP(rate, levels[i].total_set.freq)) {
468 			sc->curr_level = levels[i];
469 			CF_DEBUG("get estimated freq %d\n", curr_set->freq);
470 			break;
471 		}
472 	}
473 
474 out:
475 	if (error == 0)
476 		*level = sc->curr_level;
477 
478 	CF_MTX_UNLOCK(&sc->lock);
479 	if (levels)
480 		free(levels, M_TEMP);
481 	return (error);
482 }
483 
484 static int
485 cf_levels_method(device_t dev, struct cf_level *levels, int *count)
486 {
487 	struct cf_setting_array *set_arr;
488 	struct cf_setting_lst rel_sets;
489 	struct cpufreq_softc *sc;
490 	struct cf_level *lev;
491 	struct cf_setting *sets;
492 	struct pcpu *pc;
493 	device_t *devs;
494 	int error, i, numdevs, set_count, type;
495 	uint64_t rate;
496 
497 	if (levels == NULL || count == NULL)
498 		return (EINVAL);
499 
500 	TAILQ_INIT(&rel_sets);
501 	sc = device_get_softc(dev);
502 	error = device_get_children(device_get_parent(dev), &devs, &numdevs);
503 	if (error)
504 		return (error);
505 	sets = malloc(MAX_SETTINGS * sizeof(*sets), M_TEMP, M_NOWAIT);
506 	if (sets == NULL) {
507 		free(devs, M_TEMP);
508 		return (ENOMEM);
509 	}
510 
511 	/* Get settings from all cpufreq drivers. */
512 	CF_MTX_LOCK(&sc->lock);
513 	for (i = 0; i < numdevs; i++) {
514 		/* Skip devices that aren't ready. */
515 		if (!device_is_attached(devs[i]))
516 			continue;
517 
518 		/*
519 		 * Get settings, skipping drivers that offer no settings or
520 		 * provide settings for informational purposes only.
521 		 */
522 		error = CPUFREQ_DRV_TYPE(devs[i], &type);
523 		if (error || (type & CPUFREQ_FLAG_INFO_ONLY)) {
524 			if (error == 0) {
525 				CF_DEBUG("skipping info-only driver %s\n",
526 				    device_get_nameunit(devs[i]));
527 			}
528 			continue;
529 		}
530 		set_count = MAX_SETTINGS;
531 		error = CPUFREQ_DRV_SETTINGS(devs[i], sets, &set_count);
532 		if (error || set_count == 0)
533 			continue;
534 
535 		/* Add the settings to our absolute/relative lists. */
536 		switch (type & CPUFREQ_TYPE_MASK) {
537 		case CPUFREQ_TYPE_ABSOLUTE:
538 			error = cpufreq_insert_abs(sc, sets, set_count);
539 			break;
540 		case CPUFREQ_TYPE_RELATIVE:
541 			CF_DEBUG("adding %d relative settings\n", set_count);
542 			set_arr = malloc(sizeof(*set_arr), M_TEMP, M_NOWAIT);
543 			if (set_arr == NULL) {
544 				error = ENOMEM;
545 				goto out;
546 			}
547 			bcopy(sets, set_arr->sets, set_count * sizeof(*sets));
548 			set_arr->count = set_count;
549 			TAILQ_INSERT_TAIL(&rel_sets, set_arr, link);
550 			break;
551 		default:
552 			error = EINVAL;
553 		}
554 		if (error)
555 			goto out;
556 	}
557 
558 	/*
559 	 * If there are no absolute levels, create a fake one at 100%.  We
560 	 * then cache the clockrate for later use as our base frequency.
561 	 *
562 	 * XXX This assumes that the first time through, if we only have
563 	 * relative drivers, the CPU is currently running at 100%.
564 	 */
565 	if (TAILQ_EMPTY(&sc->all_levels)) {
566 		if (sc->max_mhz == CPUFREQ_VAL_UNKNOWN) {
567 			pc = cpu_get_pcpu(dev);
568 			cpu_est_clockrate(pc->pc_cpuid, &rate);
569 			sc->max_mhz = rate / 1000000;
570 		}
571 		memset(&sets[0], CPUFREQ_VAL_UNKNOWN, sizeof(*sets));
572 		sets[0].freq = sc->max_mhz;
573 		sets[0].dev = NULL;
574 		error = cpufreq_insert_abs(sc, sets, 1);
575 		if (error)
576 			goto out;
577 	}
578 
579 	/* Create a combined list of absolute + relative levels. */
580 	TAILQ_FOREACH(set_arr, &rel_sets, link)
581 		cpufreq_expand_set(sc, set_arr);
582 
583 	/* If the caller doesn't have enough space, return the actual count. */
584 	if (sc->all_count > *count) {
585 		*count = sc->all_count;
586 		error = E2BIG;
587 		goto out;
588 	}
589 
590 	/* Finally, output the list of levels. */
591 	i = 0;
592 	TAILQ_FOREACH(lev, &sc->all_levels, link) {
593 		/* Skip levels that have a frequency that is too low. */
594 		if (lev->total_set.freq < cf_lowest_freq) {
595 			sc->all_count--;
596 			continue;
597 		}
598 
599 		levels[i] = *lev;
600 		i++;
601 	}
602 	*count = sc->all_count;
603 	error = 0;
604 
605 out:
606 	/* Clear all levels since we regenerate them each time. */
607 	while ((lev = TAILQ_FIRST(&sc->all_levels)) != NULL) {
608 		TAILQ_REMOVE(&sc->all_levels, lev, link);
609 		free(lev, M_TEMP);
610 	}
611 	sc->all_count = 0;
612 
613 	CF_MTX_UNLOCK(&sc->lock);
614 	while ((set_arr = TAILQ_FIRST(&rel_sets)) != NULL) {
615 		TAILQ_REMOVE(&rel_sets, set_arr, link);
616 		free(set_arr, M_TEMP);
617 	}
618 	free(devs, M_TEMP);
619 	free(sets, M_TEMP);
620 	return (error);
621 }
622 
623 /*
624  * Create levels for an array of absolute settings and insert them in
625  * sorted order in the specified list.
626  */
627 static int
628 cpufreq_insert_abs(struct cpufreq_softc *sc, struct cf_setting *sets,
629     int count)
630 {
631 	struct cf_level_lst *list;
632 	struct cf_level *level, *search;
633 	int i;
634 
635 	CF_MTX_ASSERT(&sc->lock);
636 
637 	list = &sc->all_levels;
638 	for (i = 0; i < count; i++) {
639 		level = malloc(sizeof(*level), M_TEMP, M_NOWAIT | M_ZERO);
640 		if (level == NULL)
641 			return (ENOMEM);
642 		level->abs_set = sets[i];
643 		level->total_set = sets[i];
644 		level->total_set.dev = NULL;
645 		sc->all_count++;
646 
647 		if (TAILQ_EMPTY(list)) {
648 			CF_DEBUG("adding abs setting %d at head\n",
649 			    sets[i].freq);
650 			TAILQ_INSERT_HEAD(list, level, link);
651 			continue;
652 		}
653 
654 		TAILQ_FOREACH_REVERSE(search, list, cf_level_lst, link) {
655 			if (sets[i].freq <= search->total_set.freq) {
656 				CF_DEBUG("adding abs setting %d after %d\n",
657 				    sets[i].freq, search->total_set.freq);
658 				TAILQ_INSERT_AFTER(list, search, level, link);
659 				break;
660 			}
661 		}
662 	}
663 	return (0);
664 }
665 
666 /*
667  * Expand a group of relative settings, creating derived levels from them.
668  */
669 static int
670 cpufreq_expand_set(struct cpufreq_softc *sc, struct cf_setting_array *set_arr)
671 {
672 	struct cf_level *fill, *search;
673 	struct cf_setting *set;
674 	int i;
675 
676 	CF_MTX_ASSERT(&sc->lock);
677 
678 	/*
679 	 * Walk the set of all existing levels in reverse.  This is so we
680 	 * create derived states from the lowest absolute settings first
681 	 * and discard duplicates created from higher absolute settings.
682 	 * For instance, a level of 50 Mhz derived from 100 Mhz + 50% is
683 	 * preferable to 200 Mhz + 25% because absolute settings are more
684 	 * efficient since they often change the voltage as well.
685 	 */
686 	TAILQ_FOREACH_REVERSE(search, &sc->all_levels, cf_level_lst, link) {
687 		/* Add each setting to the level, duplicating if necessary. */
688 		for (i = 0; i < set_arr->count; i++) {
689 			set = &set_arr->sets[i];
690 
691 			/*
692 			 * If this setting is less than 100%, split the level
693 			 * into two and add this setting to the new level.
694 			 */
695 			fill = search;
696 			if (set->freq < 10000) {
697 				fill = cpufreq_dup_set(sc, search, set);
698 
699 				/*
700 				 * The new level was a duplicate of an existing
701 				 * level or its absolute setting is too high
702 				 * so we freed it.  For example, we discard a
703 				 * derived level of 1000 MHz/25% if a level
704 				 * of 500 MHz/100% already exists.
705 				 */
706 				if (fill == NULL)
707 					break;
708 			}
709 
710 			/* Add this setting to the existing or new level. */
711 			KASSERT(fill->rel_count < MAX_SETTINGS,
712 			    ("cpufreq: too many relative drivers (%d)",
713 			    MAX_SETTINGS));
714 			fill->rel_set[fill->rel_count] = *set;
715 			fill->rel_count++;
716 			CF_DEBUG(
717 			"expand set added rel setting %d%% to %d level\n",
718 			    set->freq / 100, fill->total_set.freq);
719 		}
720 	}
721 
722 	return (0);
723 }
724 
725 static struct cf_level *
726 cpufreq_dup_set(struct cpufreq_softc *sc, struct cf_level *dup,
727     struct cf_setting *set)
728 {
729 	struct cf_level_lst *list;
730 	struct cf_level *fill, *itr;
731 	struct cf_setting *fill_set, *itr_set;
732 	int i;
733 
734 	CF_MTX_ASSERT(&sc->lock);
735 
736 	/*
737 	 * Create a new level, copy it from the old one, and update the
738 	 * total frequency and power by the percentage specified in the
739 	 * relative setting.
740 	 */
741 	fill = malloc(sizeof(*fill), M_TEMP, M_NOWAIT);
742 	if (fill == NULL)
743 		return (NULL);
744 	*fill = *dup;
745 	fill_set = &fill->total_set;
746 	fill_set->freq =
747 	    ((uint64_t)fill_set->freq * set->freq) / 10000;
748 	if (fill_set->power != CPUFREQ_VAL_UNKNOWN) {
749 		fill_set->power = ((uint64_t)fill_set->power * set->freq)
750 		    / 10000;
751 	}
752 	if (set->lat != CPUFREQ_VAL_UNKNOWN) {
753 		if (fill_set->lat != CPUFREQ_VAL_UNKNOWN)
754 			fill_set->lat += set->lat;
755 		else
756 			fill_set->lat = set->lat;
757 	}
758 	CF_DEBUG("dup set considering derived setting %d\n", fill_set->freq);
759 
760 	/*
761 	 * If we copied an old level that we already modified (say, at 100%),
762 	 * we need to remove that setting before adding this one.  Since we
763 	 * process each setting array in order, we know any settings for this
764 	 * driver will be found at the end.
765 	 */
766 	for (i = fill->rel_count; i != 0; i--) {
767 		if (fill->rel_set[i - 1].dev != set->dev)
768 			break;
769 		CF_DEBUG("removed last relative driver: %s\n",
770 		    device_get_nameunit(set->dev));
771 		fill->rel_count--;
772 	}
773 
774 	/*
775 	 * Insert the new level in sorted order.  If it is a duplicate of an
776 	 * existing level (1) or has an absolute setting higher than the
777 	 * existing level (2), do not add it.  We can do this since any such
778 	 * level is guaranteed use less power.  For example (1), a level with
779 	 * one absolute setting of 800 Mhz uses less power than one composed
780 	 * of an absolute setting of 1600 Mhz and a relative setting at 50%.
781 	 * Also for example (2), a level of 800 Mhz/75% is preferable to
782 	 * 1600 Mhz/25% even though the latter has a lower total frequency.
783 	 */
784 	list = &sc->all_levels;
785 	KASSERT(!TAILQ_EMPTY(list), ("all levels list empty in dup set"));
786 	TAILQ_FOREACH_REVERSE(itr, list, cf_level_lst, link) {
787 		itr_set = &itr->total_set;
788 		if (CPUFREQ_CMP(fill_set->freq, itr_set->freq)) {
789 			CF_DEBUG("dup set rejecting %d (dupe)\n",
790 			    fill_set->freq);
791 			itr = NULL;
792 			break;
793 		} else if (fill_set->freq < itr_set->freq) {
794 			if (fill->abs_set.freq <= itr->abs_set.freq) {
795 				CF_DEBUG(
796 			"dup done, inserting new level %d after %d\n",
797 				    fill_set->freq, itr_set->freq);
798 				TAILQ_INSERT_AFTER(list, itr, fill, link);
799 				sc->all_count++;
800 			} else {
801 				CF_DEBUG("dup set rejecting %d (abs too big)\n",
802 				    fill_set->freq);
803 				itr = NULL;
804 			}
805 			break;
806 		}
807 	}
808 
809 	/* We didn't find a good place for this new level so free it. */
810 	if (itr == NULL) {
811 		CF_DEBUG("dup set freeing new level %d (not optimal)\n",
812 		    fill_set->freq);
813 		free(fill, M_TEMP);
814 		fill = NULL;
815 	}
816 
817 	return (fill);
818 }
819 
820 static int
821 cpufreq_curr_sysctl(SYSCTL_HANDLER_ARGS)
822 {
823 	struct cpufreq_softc *sc;
824 	struct cf_level *levels;
825 	int count, devcount, error, freq, i, n;
826 	device_t *devs;
827 
828 	devs = NULL;
829 	sc = oidp->oid_arg1;
830 	levels = malloc(CF_MAX_LEVELS * sizeof(*levels), M_TEMP, M_NOWAIT);
831 	if (levels == NULL)
832 		return (ENOMEM);
833 
834 	error = CPUFREQ_GET(sc->dev, &levels[0]);
835 	if (error)
836 		goto out;
837 	freq = levels[0].total_set.freq;
838 	error = sysctl_handle_int(oidp, &freq, 0, req);
839 	if (error != 0 || req->newptr == NULL)
840 		goto out;
841 
842 	/*
843 	 * While we only call cpufreq_get() on one device (assuming all
844 	 * CPUs have equal levels), we call cpufreq_set() on all CPUs.
845 	 * This is needed for some MP systems.
846 	 */
847 	error = devclass_get_devices(cpufreq_dc, &devs, &devcount);
848 	if (error)
849 		goto out;
850 	for (n = 0; n < devcount; n++) {
851 		count = CF_MAX_LEVELS;
852 		error = CPUFREQ_LEVELS(devs[n], levels, &count);
853 		if (error) {
854 			if (error == E2BIG)
855 				printf(
856 			"cpufreq: need to increase CF_MAX_LEVELS\n");
857 			break;
858 		}
859 		for (i = 0; i < count; i++) {
860 			if (CPUFREQ_CMP(levels[i].total_set.freq, freq)) {
861 				error = CPUFREQ_SET(devs[n], &levels[i],
862 				    CPUFREQ_PRIO_USER);
863 				break;
864 			}
865 		}
866 		if (i == count) {
867 			error = EINVAL;
868 			break;
869 		}
870 	}
871 
872 out:
873 	if (devs)
874 		free(devs, M_TEMP);
875 	if (levels)
876 		free(levels, M_TEMP);
877 	return (error);
878 }
879 
880 static int
881 cpufreq_levels_sysctl(SYSCTL_HANDLER_ARGS)
882 {
883 	struct cpufreq_softc *sc;
884 	struct cf_level *levels;
885 	struct cf_setting *set;
886 	struct sbuf sb;
887 	int count, error, i;
888 
889 	sc = oidp->oid_arg1;
890 	sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND);
891 
892 	/* Get settings from the device and generate the output string. */
893 	count = CF_MAX_LEVELS;
894 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
895 	if (levels == NULL)
896 		return (ENOMEM);
897 	error = CPUFREQ_LEVELS(sc->dev, levels, &count);
898 	if (error) {
899 		if (error == E2BIG)
900 			printf("cpufreq: need to increase CF_MAX_LEVELS\n");
901 		goto out;
902 	}
903 	if (count) {
904 		for (i = 0; i < count; i++) {
905 			set = &levels[i].total_set;
906 			sbuf_printf(&sb, "%d/%d ", set->freq, set->power);
907 		}
908 	} else
909 		sbuf_cpy(&sb, "0");
910 	sbuf_trim(&sb);
911 	sbuf_finish(&sb);
912 	error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
913 
914 out:
915 	free(levels, M_TEMP);
916 	sbuf_delete(&sb);
917 	return (error);
918 }
919 
920 static int
921 cpufreq_settings_sysctl(SYSCTL_HANDLER_ARGS)
922 {
923 	device_t dev;
924 	struct cf_setting *sets;
925 	struct sbuf sb;
926 	int error, i, set_count;
927 
928 	dev = oidp->oid_arg1;
929 	sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND);
930 
931 	/* Get settings from the device and generate the output string. */
932 	set_count = MAX_SETTINGS;
933 	sets = malloc(set_count * sizeof(*sets), M_TEMP, M_NOWAIT);
934 	if (sets == NULL)
935 		return (ENOMEM);
936 	error = CPUFREQ_DRV_SETTINGS(dev, sets, &set_count);
937 	if (error)
938 		goto out;
939 	if (set_count) {
940 		for (i = 0; i < set_count; i++)
941 			sbuf_printf(&sb, "%d/%d ", sets[i].freq, sets[i].power);
942 	} else
943 		sbuf_cpy(&sb, "0");
944 	sbuf_trim(&sb);
945 	sbuf_finish(&sb);
946 	error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
947 
948 out:
949 	free(sets, M_TEMP);
950 	sbuf_delete(&sb);
951 	return (error);
952 }
953 
954 int
955 cpufreq_register(device_t dev)
956 {
957 	struct cpufreq_softc *sc;
958 	device_t cf_dev, cpu_dev;
959 
960 	/* Add a sysctl to get each driver's settings separately. */
961 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
962 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
963 	    OID_AUTO, "freq_settings", CTLTYPE_STRING | CTLFLAG_RD, dev, 0,
964 	    cpufreq_settings_sysctl, "A", "CPU frequency driver settings");
965 
966 	/*
967 	 * Add only one cpufreq device to each CPU.  Currently, all CPUs
968 	 * must offer the same levels and be switched at the same time.
969 	 */
970 	cpu_dev = device_get_parent(dev);
971 	if ((cf_dev = device_find_child(cpu_dev, "cpufreq", -1))) {
972 		sc = device_get_softc(cf_dev);
973 		sc->max_mhz = CPUFREQ_VAL_UNKNOWN;
974 		return (0);
975 	}
976 
977 	/* Add the child device and possibly sysctls. */
978 	cf_dev = BUS_ADD_CHILD(cpu_dev, 0, "cpufreq", -1);
979 	if (cf_dev == NULL)
980 		return (ENOMEM);
981 	device_quiet(cf_dev);
982 
983 	return (device_probe_and_attach(cf_dev));
984 }
985 
986 int
987 cpufreq_unregister(device_t dev)
988 {
989 	device_t cf_dev, *devs;
990 	int cfcount, devcount, error, i, type;
991 
992 	/*
993 	 * If this is the last cpufreq child device, remove the control
994 	 * device as well.  We identify cpufreq children by calling a method
995 	 * they support.
996 	 */
997 	error = device_get_children(device_get_parent(dev), &devs, &devcount);
998 	if (error)
999 		return (error);
1000 	cf_dev = device_find_child(device_get_parent(dev), "cpufreq", -1);
1001 	if (cf_dev == NULL) {
1002 		device_printf(dev,
1003 	"warning: cpufreq_unregister called with no cpufreq device active\n");
1004 		return (0);
1005 	}
1006 	cfcount = 0;
1007 	for (i = 0; i < devcount; i++) {
1008 		if (!device_is_attached(devs[i]))
1009 			continue;
1010 		if (CPUFREQ_DRV_TYPE(devs[i], &type) == 0)
1011 			cfcount++;
1012 	}
1013 	if (cfcount <= 1)
1014 		device_delete_child(device_get_parent(cf_dev), cf_dev);
1015 	free(devs, M_TEMP);
1016 
1017 	return (0);
1018 }
1019 
1020 int
1021 cpufreq_settings_changed(device_t dev)
1022 {
1023 
1024 	EVENTHANDLER_INVOKE(cpufreq_levels_changed,
1025 	    device_get_unit(device_get_parent(dev)));
1026 	return (0);
1027 }
1028