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