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