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