kern_cpu.c revision 142590
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: head/sys/kern/kern_cpu.c 142590 2005-02-26 22:37:49Z njl $");
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/malloc.h>
36#include <sys/module.h>
37#include <sys/proc.h>
38#include <sys/queue.h>
39#include <sys/sched.h>
40#include <sys/sysctl.h>
41#include <sys/systm.h>
42#include <sys/sbuf.h>
43#include <sys/timetc.h>
44
45#include "cpufreq_if.h"
46
47/*
48 * Common CPU frequency glue code.  Drivers for specific hardware can
49 * attach this interface to allow users to get/set the CPU frequency.
50 */
51
52/*
53 * Number of levels we can handle.  Levels are synthesized from settings
54 * so for M settings and N drivers, there may be M*N levels.
55 */
56#define CF_MAX_LEVELS	64
57
58struct cpufreq_softc {
59	struct cf_level			curr_level;
60	int				curr_priority;
61	struct cf_level			saved_level;
62	int				saved_priority;
63	struct cf_level_lst		all_levels;
64	int				all_count;
65	int				max_mhz;
66	device_t			dev;
67	struct sysctl_ctx_list		sysctl_ctx;
68};
69
70struct cf_setting_array {
71	struct cf_setting		sets[MAX_SETTINGS];
72	int				count;
73	TAILQ_ENTRY(cf_setting_array)	link;
74};
75
76TAILQ_HEAD(cf_setting_lst, cf_setting_array);
77
78static int	cpufreq_attach(device_t dev);
79static int	cpufreq_detach(device_t dev);
80static void	cpufreq_evaluate(void *arg);
81static int	cf_set_method(device_t dev, const struct cf_level *level,
82		    int priority);
83static int	cf_get_method(device_t dev, struct cf_level *level);
84static int	cf_levels_method(device_t dev, struct cf_level *levels,
85		    int *count);
86static int	cpufreq_insert_abs(struct cpufreq_softc *sc,
87		    struct cf_setting *sets, int count);
88static int	cpufreq_expand_set(struct cpufreq_softc *sc,
89		    struct cf_setting_array *set_arr);
90static struct cf_level *cpufreq_dup_set(struct cpufreq_softc *sc,
91		    struct cf_level *dup, struct cf_setting *set);
92static int	cpufreq_curr_sysctl(SYSCTL_HANDLER_ARGS);
93static int	cpufreq_levels_sysctl(SYSCTL_HANDLER_ARGS);
94static int	cpufreq_settings_sysctl(SYSCTL_HANDLER_ARGS);
95
96static device_method_t cpufreq_methods[] = {
97	DEVMETHOD(device_probe,		bus_generic_probe),
98	DEVMETHOD(device_attach,	cpufreq_attach),
99	DEVMETHOD(device_detach,	cpufreq_detach),
100
101        DEVMETHOD(cpufreq_set,		cf_set_method),
102        DEVMETHOD(cpufreq_get,		cf_get_method),
103        DEVMETHOD(cpufreq_levels,	cf_levels_method),
104	{0, 0}
105};
106static driver_t cpufreq_driver = {
107	"cpufreq", cpufreq_methods, sizeof(struct cpufreq_softc)
108};
109static devclass_t cpufreq_dc;
110DRIVER_MODULE(cpufreq, cpu, cpufreq_driver, cpufreq_dc, 0, 0);
111
112static eventhandler_tag	cf_ev_tag;
113
114static int		cf_lowest_freq;
115TUNABLE_INT("debug.cpufreq.lowest", &cf_lowest_freq);
116SYSCTL_NODE(_debug, OID_AUTO, cpufreq, CTLFLAG_RD, NULL, "cpufreq debugging");
117SYSCTL_INT(_debug_cpufreq, OID_AUTO, lowest, CTLFLAG_RW, &cf_lowest_freq, 1,
118    "Don't provide levels below this frequency.");
119
120static int
121cpufreq_attach(device_t dev)
122{
123	struct cpufreq_softc *sc;
124	device_t parent;
125	int numdevs;
126
127	sc = device_get_softc(dev);
128	parent = device_get_parent(dev);
129	sc->dev = dev;
130	sysctl_ctx_init(&sc->sysctl_ctx);
131	TAILQ_INIT(&sc->all_levels);
132	sc->curr_level.total_set.freq = CPUFREQ_VAL_UNKNOWN;
133	sc->saved_level.total_set.freq = CPUFREQ_VAL_UNKNOWN;
134	sc->max_mhz = CPUFREQ_VAL_UNKNOWN;
135
136	/*
137	 * Only initialize one set of sysctls for all CPUs.  In the future,
138	 * if multiple CPUs can have different settings, we can move these
139	 * sysctls to be under every CPU instead of just the first one.
140	 */
141	numdevs = devclass_get_count(cpufreq_dc);
142	if (numdevs > 1)
143		return (0);
144
145	SYSCTL_ADD_PROC(&sc->sysctl_ctx,
146	    SYSCTL_CHILDREN(device_get_sysctl_tree(parent)),
147	    OID_AUTO, "freq", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
148	    cpufreq_curr_sysctl, "I", "Current CPU frequency");
149	SYSCTL_ADD_PROC(&sc->sysctl_ctx,
150	    SYSCTL_CHILDREN(device_get_sysctl_tree(parent)),
151	    OID_AUTO, "freq_levels", CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
152	    cpufreq_levels_sysctl, "A", "CPU frequency levels");
153	cf_ev_tag = EVENTHANDLER_REGISTER(cpufreq_changed, cpufreq_evaluate,
154	    NULL, EVENTHANDLER_PRI_ANY);
155
156	return (0);
157}
158
159static int
160cpufreq_detach(device_t dev)
161{
162	struct cpufreq_softc *sc;
163	int numdevs;
164
165	sc = device_get_softc(dev);
166	sysctl_ctx_free(&sc->sysctl_ctx);
167
168	/* Only clean up these resources when the last device is detaching. */
169	numdevs = devclass_get_count(cpufreq_dc);
170	if (numdevs == 1)
171		EVENTHANDLER_DEREGISTER(cpufreq_changed, cf_ev_tag);
172
173	return (0);
174}
175
176static void
177cpufreq_evaluate(void *arg)
178{
179	/* TODO: Re-evaluate when notified of changes to drivers. */
180}
181
182static int
183cf_set_method(device_t dev, const struct cf_level *level, int priority)
184{
185	struct cpufreq_softc *sc;
186	const struct cf_setting *set;
187	struct pcpu *pc;
188	int cpu_id, error, i;
189
190	sc = device_get_softc(dev);
191
192	/*
193	 * Check that the TSC isn't being used as a timecounter.
194	 * If it is, then return EBUSY and refuse to change the
195	 * clock speed.
196	 */
197	if (strcmp(timecounter->tc_name, "TSC") == 0)
198		return (EBUSY);
199
200	/*
201	 * If the caller didn't specify a level and one is saved, prepare to
202	 * restore the saved level.  If none has been saved, return an error.
203	 * If they did specify one, but the requested level has a lower
204	 * priority, don't allow the new level right now.
205	 */
206	if (level == NULL) {
207		if (sc->saved_level.total_set.freq != CPUFREQ_VAL_UNKNOWN) {
208			level = &sc->saved_level;
209			priority = sc->saved_priority;
210		} else
211			return (ENXIO);
212	} else if (priority < sc->curr_priority)
213		return (EPERM);
214
215	/* Reject levels that are below our specified threshold. */
216	if (level->total_set.freq <= cf_lowest_freq)
217		return (EINVAL);
218
219	/* If already at this level, just return. */
220	if (CPUFREQ_CMP(sc->curr_level.total_set.freq, level->total_set.freq))
221		return (0);
222
223	/* First, set the absolute frequency via its driver. */
224	set = &level->abs_set;
225	if (set->dev) {
226		if (!device_is_attached(set->dev)) {
227			error = ENXIO;
228			goto out;
229		}
230
231		/* Bind to the target CPU before switching, if necessary. */
232		cpu_id = PCPU_GET(cpuid);
233		pc = cpu_get_pcpu(set->dev);
234		if (cpu_id != pc->pc_cpuid) {
235			mtx_lock_spin(&sched_lock);
236			sched_bind(curthread, pc->pc_cpuid);
237			mtx_unlock_spin(&sched_lock);
238		}
239		error = CPUFREQ_DRV_SET(set->dev, set);
240		if (cpu_id != pc->pc_cpuid) {
241			mtx_lock_spin(&sched_lock);
242			sched_unbind(curthread);
243			mtx_unlock_spin(&sched_lock);
244		}
245		if (error) {
246			goto out;
247		}
248	}
249
250	/* Next, set any/all relative frequencies via their drivers. */
251	for (i = 0; i < level->rel_count; i++) {
252		set = &level->rel_set[i];
253		if (!device_is_attached(set->dev)) {
254			error = ENXIO;
255			goto out;
256		}
257
258		/* Bind to the target CPU before switching, if necessary. */
259		cpu_id = PCPU_GET(cpuid);
260		pc = cpu_get_pcpu(set->dev);
261		if (cpu_id != pc->pc_cpuid) {
262			mtx_lock_spin(&sched_lock);
263			sched_bind(curthread, pc->pc_cpuid);
264			mtx_unlock_spin(&sched_lock);
265		}
266		error = CPUFREQ_DRV_SET(set->dev, set);
267		if (cpu_id != pc->pc_cpuid) {
268			mtx_lock_spin(&sched_lock);
269			sched_unbind(curthread);
270			mtx_unlock_spin(&sched_lock);
271		}
272		if (error) {
273			/* XXX Back out any successful setting? */
274			goto out;
275		}
276	}
277
278	/* If we were restoring a saved state, reset it to "unused". */
279	if (level == &sc->saved_level) {
280		sc->saved_level.total_set.freq = CPUFREQ_VAL_UNKNOWN;
281		sc->saved_priority = 0;
282	}
283
284	/*
285	 * Before recording the current level, check if we're going to a
286	 * higher priority and have not saved a level yet.  If so, save the
287	 * previous level and priority.
288	 */
289	if (sc->curr_level.total_set.freq != CPUFREQ_VAL_UNKNOWN &&
290	    sc->saved_level.total_set.freq == CPUFREQ_VAL_UNKNOWN &&
291	    priority > sc->curr_priority) {
292		sc->saved_level = sc->curr_level;
293		sc->saved_priority = sc->curr_priority;
294	}
295	sc->curr_level = *level;
296	sc->curr_priority = priority;
297	error = 0;
298
299out:
300	if (error)
301		device_printf(set->dev, "set freq failed, err %d\n", error);
302	return (error);
303}
304
305static int
306cf_get_method(device_t dev, struct cf_level *level)
307{
308	struct cpufreq_softc *sc;
309	struct cf_level *levels;
310	struct cf_setting *curr_set, set;
311	struct pcpu *pc;
312	device_t *devs;
313	int count, error, i, numdevs;
314	uint64_t rate;
315
316	sc = device_get_softc(dev);
317	curr_set = &sc->curr_level.total_set;
318	levels = NULL;
319
320	/* If we already know the current frequency, we're done. */
321	if (curr_set->freq != CPUFREQ_VAL_UNKNOWN)
322		goto out;
323
324	/*
325	 * We need to figure out the current level.  Loop through every
326	 * driver, getting the current setting.  Then, attempt to get a best
327	 * match of settings against each level.
328	 */
329	count = CF_MAX_LEVELS;
330	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
331	if (levels == NULL)
332		return (ENOMEM);
333	error = CPUFREQ_LEVELS(sc->dev, levels, &count);
334	if (error) {
335		if (error == E2BIG)
336			printf("cpufreq: need to increase CF_MAX_LEVELS\n");
337		goto out;
338	}
339	error = device_get_children(device_get_parent(dev), &devs, &numdevs);
340	if (error)
341		goto out;
342	for (i = 0; i < numdevs && curr_set->freq == CPUFREQ_VAL_UNKNOWN; i++) {
343		if (!device_is_attached(devs[i]))
344			continue;
345		error = CPUFREQ_DRV_GET(devs[i], &set);
346		if (error)
347			continue;
348		for (i = 0; i < count; i++) {
349			if (CPUFREQ_CMP(set.freq, levels[i].total_set.freq)) {
350				sc->curr_level = levels[i];
351				break;
352			}
353		}
354	}
355	free(devs, M_TEMP);
356	if (curr_set->freq != CPUFREQ_VAL_UNKNOWN)
357		goto out;
358
359	/*
360	 * We couldn't find an exact match, so attempt to estimate and then
361	 * match against a level.
362	 */
363	pc = cpu_get_pcpu(dev);
364	if (pc == NULL) {
365		error = ENXIO;
366		goto out;
367	}
368	cpu_est_clockrate(pc->pc_cpuid, &rate);
369	rate /= 1000000;
370	for (i = 0; i < count; i++) {
371		if (CPUFREQ_CMP(rate, levels[i].total_set.freq)) {
372			sc->curr_level = levels[i];
373			break;
374		}
375	}
376
377out:
378	if (levels)
379		free(levels, M_TEMP);
380	*level = sc->curr_level;
381	return (0);
382}
383
384static int
385cf_levels_method(device_t dev, struct cf_level *levels, int *count)
386{
387	struct cf_setting_array *set_arr;
388	struct cf_setting_lst rel_sets;
389	struct cpufreq_softc *sc;
390	struct cf_level *lev;
391	struct cf_setting *sets;
392	struct pcpu *pc;
393	device_t *devs;
394	int error, i, numdevs, set_count, type;
395	uint64_t rate;
396
397	if (levels == NULL || count == NULL)
398		return (EINVAL);
399
400	TAILQ_INIT(&rel_sets);
401	sc = device_get_softc(dev);
402	error = device_get_children(device_get_parent(dev), &devs, &numdevs);
403	if (error)
404		return (error);
405	sets = malloc(MAX_SETTINGS * sizeof(*sets), M_TEMP, M_NOWAIT);
406	if (sets == NULL) {
407		free(devs, M_TEMP);
408		return (ENOMEM);
409	}
410
411	/* Get settings from all cpufreq drivers. */
412	for (i = 0; i < numdevs; i++) {
413		/* Skip devices that aren't ready. */
414		if (!device_is_attached(devs[i]))
415			continue;
416
417		/*
418		 * Get settings, skipping drivers that offer no settings or
419		 * provide settings for informational purposes only.
420		 */
421		error = CPUFREQ_DRV_TYPE(devs[i], &type);
422		if (error || (type & CPUFREQ_FLAG_INFO_ONLY))
423			continue;
424		set_count = MAX_SETTINGS;
425		error = CPUFREQ_DRV_SETTINGS(devs[i], sets, &set_count);
426		if (error || set_count == 0)
427			continue;
428
429		/* Add the settings to our absolute/relative lists. */
430		switch (type & CPUFREQ_TYPE_MASK) {
431		case CPUFREQ_TYPE_ABSOLUTE:
432			error = cpufreq_insert_abs(sc, sets, set_count);
433			break;
434		case CPUFREQ_TYPE_RELATIVE:
435			set_arr = malloc(sizeof(*set_arr), M_TEMP, M_NOWAIT);
436			if (set_arr == NULL) {
437				error = ENOMEM;
438				goto out;
439			}
440			bcopy(sets, set_arr->sets, set_count * sizeof(*sets));
441			set_arr->count = set_count;
442			TAILQ_INSERT_TAIL(&rel_sets, set_arr, link);
443			break;
444		default:
445			error = EINVAL;
446			break;
447		}
448		if (error)
449			goto out;
450	}
451
452	/*
453	 * If there are no absolute levels, create a fake one at 100%.  We
454	 * then cache the clockrate for later use as our base frequency.
455	 *
456	 * XXX This assumes that the first time through, if we only have
457	 * relative drivers, the CPU is currently running at 100%.
458	 */
459	if (TAILQ_EMPTY(&sc->all_levels)) {
460		if (sc->max_mhz == CPUFREQ_VAL_UNKNOWN) {
461			pc = cpu_get_pcpu(dev);
462			cpu_est_clockrate(pc->pc_cpuid, &rate);
463			sc->max_mhz = rate / 1000000;
464		}
465		memset(&sets[0], CPUFREQ_VAL_UNKNOWN, sizeof(*sets));
466		sets[0].freq = sc->max_mhz;
467		sets[0].dev = NULL;
468		error = cpufreq_insert_abs(sc, sets, 1);
469		if (error)
470			goto out;
471	}
472
473	/* Create a combined list of absolute + relative levels. */
474	TAILQ_FOREACH(set_arr, &rel_sets, link)
475		cpufreq_expand_set(sc, set_arr);
476
477	/* If the caller doesn't have enough space, return the actual count. */
478	if (sc->all_count > *count) {
479		*count = sc->all_count;
480		error = E2BIG;
481		goto out;
482	}
483
484	/* Finally, output the list of levels. */
485	i = 0;
486	TAILQ_FOREACH(lev, &sc->all_levels, link) {
487		/* Skip levels that have a frequency that is too low. */
488		if (lev->total_set.freq <= cf_lowest_freq) {
489			sc->all_count--;
490			continue;
491		}
492
493		levels[i] = *lev;
494		i++;
495	}
496	*count = sc->all_count;
497	error = 0;
498
499out:
500	/* Clear all levels since we regenerate them each time. */
501	while ((lev = TAILQ_FIRST(&sc->all_levels)) != NULL) {
502		TAILQ_REMOVE(&sc->all_levels, lev, link);
503		free(lev, M_TEMP);
504	}
505	while ((set_arr = TAILQ_FIRST(&rel_sets)) != NULL) {
506		TAILQ_REMOVE(&rel_sets, set_arr, link);
507		free(set_arr, M_TEMP);
508	}
509	sc->all_count = 0;
510	free(devs, M_TEMP);
511	free(sets, M_TEMP);
512	return (error);
513}
514
515/*
516 * Create levels for an array of absolute settings and insert them in
517 * sorted order in the specified list.
518 */
519static int
520cpufreq_insert_abs(struct cpufreq_softc *sc, struct cf_setting *sets,
521    int count)
522{
523	struct cf_level_lst *list;
524	struct cf_level *level, *search;
525	int i;
526
527	list = &sc->all_levels;
528	for (i = 0; i < count; i++) {
529		level = malloc(sizeof(*level), M_TEMP, M_NOWAIT | M_ZERO);
530		if (level == NULL)
531			return (ENOMEM);
532		level->abs_set = sets[i];
533		level->total_set = sets[i];
534		level->total_set.dev = NULL;
535		sc->all_count++;
536
537		if (TAILQ_EMPTY(list)) {
538			TAILQ_INSERT_HEAD(list, level, link);
539			continue;
540		}
541
542		TAILQ_FOREACH_REVERSE(search, list, cf_level_lst, link) {
543			if (sets[i].freq <= search->total_set.freq) {
544				TAILQ_INSERT_AFTER(list, search, level, link);
545				break;
546			}
547		}
548	}
549	return (0);
550}
551
552/*
553 * Expand a group of relative settings, creating derived levels from them.
554 */
555static int
556cpufreq_expand_set(struct cpufreq_softc *sc, struct cf_setting_array *set_arr)
557{
558	struct cf_level *fill, *search;
559	struct cf_setting *set;
560	int i;
561
562	TAILQ_FOREACH(search, &sc->all_levels, link) {
563		/* Skip this level if we've already modified it. */
564		for (i = 0; i < search->rel_count; i++) {
565			if (search->rel_set[i].dev == set_arr->sets[0].dev)
566				break;
567		}
568		if (i != search->rel_count)
569			continue;
570
571		/* Add each setting to the level, duplicating if necessary. */
572		for (i = 0; i < set_arr->count; i++) {
573			set = &set_arr->sets[i];
574
575			/*
576			 * If this setting is less than 100%, split the level
577			 * into two and add this setting to the new level.
578			 */
579			fill = search;
580			if (set->freq < 10000)
581				fill = cpufreq_dup_set(sc, search, set);
582
583			/*
584			 * The new level was a duplicate of an existing level
585			 * so we freed it.  Go to the next setting.
586			 */
587			if (fill == NULL)
588				continue;
589
590			/* Add this setting to the existing or new level. */
591			KASSERT(fill->rel_count < MAX_SETTINGS,
592			    ("cpufreq: too many relative drivers (%d)",
593			    MAX_SETTINGS));
594			fill->rel_set[fill->rel_count] = *set;
595			fill->rel_count++;
596		}
597	}
598
599	return (0);
600}
601
602static struct cf_level *
603cpufreq_dup_set(struct cpufreq_softc *sc, struct cf_level *dup,
604    struct cf_setting *set)
605{
606	struct cf_level_lst *list;
607	struct cf_level *fill, *itr;
608	struct cf_setting *fill_set, *itr_set;
609	int i;
610
611	/*
612	 * Create a new level, copy it from the old one, and update the
613	 * total frequency and power by the percentage specified in the
614	 * relative setting.
615	 */
616	fill = malloc(sizeof(*fill), M_TEMP, M_NOWAIT);
617	if (fill == NULL)
618		return (NULL);
619	*fill = *dup;
620	fill_set = &fill->total_set;
621	fill_set->freq =
622	    ((uint64_t)fill_set->freq * set->freq) / 10000;
623	if (fill_set->power != CPUFREQ_VAL_UNKNOWN) {
624		fill_set->power = ((uint64_t)fill_set->power * set->freq)
625		    / 10000;
626	}
627	if (set->lat != CPUFREQ_VAL_UNKNOWN) {
628		if (fill_set->lat != CPUFREQ_VAL_UNKNOWN)
629			fill_set->lat += set->lat;
630		else
631			fill_set->lat = set->lat;
632	}
633
634	/*
635	 * If we copied an old level that we already modified (say, at 100%),
636	 * we need to remove that setting before adding this one.  Since we
637	 * process each setting array in order, we know any settings for this
638	 * driver will be found at the end.
639	 */
640	for (i = fill->rel_count; i != 0; i--) {
641		if (fill->rel_set[i - 1].dev != set->dev)
642			break;
643		fill->rel_count--;
644	}
645
646	/*
647	 * Insert the new level in sorted order.  If we find a duplicate,
648	 * free the new level.  We can do this since any existing level will
649	 * be guaranteed to have the same or less settings and thus consume
650	 * less power.  For example, a level with one absolute setting of
651	 * 800 Mhz uses less power than one composed of an absolute setting
652	 * of 1600 Mhz and a relative setting at 50%.
653	 */
654	list = &sc->all_levels;
655	if (TAILQ_EMPTY(list)) {
656		TAILQ_INSERT_HEAD(list, fill, link);
657	} else {
658		TAILQ_FOREACH_REVERSE(itr, list, cf_level_lst, link) {
659			itr_set = &itr->total_set;
660			if (CPUFREQ_CMP(fill_set->freq, itr_set->freq)) {
661				free(fill, M_TEMP);
662				fill = NULL;
663				break;
664			} else if (fill_set->freq < itr_set->freq) {
665				TAILQ_INSERT_AFTER(list, itr, fill, link);
666				sc->all_count++;
667				break;
668			}
669		}
670	}
671
672	return (fill);
673}
674
675static int
676cpufreq_curr_sysctl(SYSCTL_HANDLER_ARGS)
677{
678	struct cpufreq_softc *sc;
679	struct cf_level *levels;
680	int count, devcount, error, freq, i, n;
681	device_t *devs;
682
683	devs = NULL;
684	sc = oidp->oid_arg1;
685	levels = malloc(CF_MAX_LEVELS * sizeof(*levels), M_TEMP, M_NOWAIT);
686	if (levels == NULL)
687		return (ENOMEM);
688
689	error = CPUFREQ_GET(sc->dev, &levels[0]);
690	if (error)
691		goto out;
692	freq = levels[0].total_set.freq;
693	error = sysctl_handle_int(oidp, &freq, 0, req);
694	if (error != 0 || req->newptr == NULL)
695		goto out;
696
697	/*
698	 * While we only call cpufreq_get() on one device (assuming all
699	 * CPUs have equal levels), we call cpufreq_set() on all CPUs.
700	 * This is needed for some MP systems.
701	 */
702	error = devclass_get_devices(cpufreq_dc, &devs, &devcount);
703	if (error)
704		goto out;
705	for (n = 0; n < devcount; n++) {
706		count = CF_MAX_LEVELS;
707		error = CPUFREQ_LEVELS(devs[n], levels, &count);
708		if (error) {
709			if (error == E2BIG)
710				printf(
711			"cpufreq: need to increase CF_MAX_LEVELS\n");
712			break;
713		}
714		for (i = 0; i < count; i++) {
715			if (CPUFREQ_CMP(levels[i].total_set.freq, freq)) {
716				error = CPUFREQ_SET(devs[n], &levels[i],
717				    CPUFREQ_PRIO_USER);
718				break;
719			}
720		}
721		if (i == count) {
722			error = EINVAL;
723			break;
724		}
725	}
726
727out:
728	if (devs)
729		free(devs, M_TEMP);
730	if (levels)
731		free(levels, M_TEMP);
732	return (error);
733}
734
735static int
736cpufreq_levels_sysctl(SYSCTL_HANDLER_ARGS)
737{
738	struct cpufreq_softc *sc;
739	struct cf_level *levels;
740	struct cf_setting *set;
741	struct sbuf sb;
742	int count, error, i;
743
744	sc = oidp->oid_arg1;
745	sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND);
746
747	/* Get settings from the device and generate the output string. */
748	count = CF_MAX_LEVELS;
749	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
750	if (levels == NULL)
751		return (ENOMEM);
752	error = CPUFREQ_LEVELS(sc->dev, levels, &count);
753	if (error) {
754		if (error == E2BIG)
755			printf("cpufreq: need to increase CF_MAX_LEVELS\n");
756		goto out;
757	}
758	if (count) {
759		for (i = 0; i < count; i++) {
760			set = &levels[i].total_set;
761			sbuf_printf(&sb, "%d/%d ", set->freq, set->power);
762		}
763	} else
764		sbuf_cpy(&sb, "0");
765	sbuf_trim(&sb);
766	sbuf_finish(&sb);
767	error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
768
769out:
770	free(levels, M_TEMP);
771	sbuf_delete(&sb);
772	return (error);
773}
774
775static int
776cpufreq_settings_sysctl(SYSCTL_HANDLER_ARGS)
777{
778	device_t dev;
779	struct cf_setting *sets;
780	struct sbuf sb;
781	int error, i, set_count;
782
783	dev = oidp->oid_arg1;
784	sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND);
785
786	/* Get settings from the device and generate the output string. */
787	set_count = MAX_SETTINGS;
788	sets = malloc(set_count * sizeof(*sets), M_TEMP, M_NOWAIT);
789	if (sets == NULL)
790		return (ENOMEM);
791	error = CPUFREQ_DRV_SETTINGS(dev, sets, &set_count);
792	if (error)
793		goto out;
794	if (set_count) {
795		for (i = 0; i < set_count; i++)
796			sbuf_printf(&sb, "%d/%d ", sets[i].freq, sets[i].power);
797	} else
798		sbuf_cpy(&sb, "0");
799	sbuf_trim(&sb);
800	sbuf_finish(&sb);
801	error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
802
803out:
804	free(sets, M_TEMP);
805	sbuf_delete(&sb);
806	return (error);
807}
808
809int
810cpufreq_register(device_t dev)
811{
812	struct cpufreq_softc *sc;
813	device_t cf_dev, cpu_dev;
814
815	/* Add a sysctl to get each driver's settings separately. */
816	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
817	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
818	    OID_AUTO, "freq_settings", CTLTYPE_STRING | CTLFLAG_RD, dev, 0,
819	    cpufreq_settings_sysctl, "A", "CPU frequency driver settings");
820
821	/*
822	 * Add only one cpufreq device to each CPU.  Currently, all CPUs
823	 * must offer the same levels and be switched at the same time.
824	 */
825	cpu_dev = device_get_parent(dev);
826	if ((cf_dev = device_find_child(cpu_dev, "cpufreq", -1))) {
827		sc = device_get_softc(cf_dev);
828		sc->max_mhz = CPUFREQ_VAL_UNKNOWN;
829		return (0);
830	}
831
832	/* Add the child device and possibly sysctls. */
833	cf_dev = BUS_ADD_CHILD(cpu_dev, 0, "cpufreq", -1);
834	if (cf_dev == NULL)
835		return (ENOMEM);
836	device_quiet(cf_dev);
837
838	return (device_probe_and_attach(cf_dev));
839}
840
841int
842cpufreq_unregister(device_t dev)
843{
844	device_t cf_dev, *devs;
845	int cfcount, devcount, error, i, type;
846
847	/*
848	 * If this is the last cpufreq child device, remove the control
849	 * device as well.  We identify cpufreq children by calling a method
850	 * they support.
851	 */
852	error = device_get_children(device_get_parent(dev), &devs, &devcount);
853	if (error)
854		return (error);
855	cf_dev = device_find_child(device_get_parent(dev), "cpufreq", -1);
856	cfcount = 0;
857	for (i = 0; i < devcount; i++) {
858		if (!device_is_attached(devs[i]))
859			continue;
860		if (CPUFREQ_DRV_TYPE(devs[i], &type) == 0)
861			cfcount++;
862	}
863	if (cfcount <= 1)
864		device_delete_child(device_get_parent(cf_dev), cf_dev);
865	free(devs, M_TEMP);
866
867	return (0);
868}
869