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