2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2004-2007 Nate Lawson (SDG)
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
35 #include <sys/eventhandler.h>
36 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
41 #include <sys/queue.h>
43 #include <sys/sched.h>
45 #include <sys/sysctl.h>
46 #include <sys/systm.h>
48 #include <sys/timetc.h>
49 #include <sys/taskqueue.h>
51 #include "cpufreq_if.h"
54 * Common CPU frequency glue code. Drivers for specific hardware can
55 * attach this interface to allow users to get/set the CPU frequency.
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.
62 #define CF_MAX_LEVELS 256
64 struct cf_saved_freq {
65 struct cf_level level;
67 SLIST_ENTRY(cf_saved_freq) link;
70 struct cpufreq_softc {
72 struct cf_level curr_level;
74 SLIST_HEAD(, cf_saved_freq) saved_freq;
75 struct cf_level_lst all_levels;
80 struct sysctl_ctx_list sysctl_ctx;
81 struct task startup_task;
82 struct cf_level *levels_buf;
85 struct cf_setting_array {
86 struct cf_setting sets[MAX_SETTINGS];
88 TAILQ_ENTRY(cf_setting_array) link;
91 TAILQ_HEAD(cf_setting_lst, cf_setting_array);
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)
98 #define CF_DEBUG(msg...) do { \
100 printf("cpufreq: " msg); \
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,
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,
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);
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),
126 DEVMETHOD(cpufreq_set, cf_set_method),
127 DEVMETHOD(cpufreq_get, cf_get_method),
128 DEVMETHOD(cpufreq_levels, cf_levels_method),
131 static driver_t cpufreq_driver = {
132 "cpufreq", cpufreq_methods, sizeof(struct cpufreq_softc)
134 static devclass_t cpufreq_dc;
135 DRIVER_MODULE(cpufreq, cpu, cpufreq_driver, cpufreq_dc, 0, 0);
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");
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.
152 cpufreq_attach(device_t dev)
154 struct cpufreq_softc *sc;
159 CF_DEBUG("initializing %s\n", device_get_nameunit(dev));
160 sc = device_get_softc(dev);
161 parent = device_get_parent(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;
177 sc->max_mhz = CPUFREQ_VAL_UNKNOWN;
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),
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");
195 * Queue a one-shot broadcast that levels have changed.
196 * It will run once the system has completed booting.
198 TASK_INIT(&sc->startup_task, 0, cpufreq_startup_task, dev);
199 taskqueue_enqueue(taskqueue_thread, &sc->startup_task);
204 /* Handle any work to be done for all drivers that attached during boot. */
206 cpufreq_startup_task(void *ctx, int pending)
209 cpufreq_settings_changed((device_t)ctx);
213 cpufreq_detach(device_t dev)
215 struct cpufreq_softc *sc;
216 struct cf_saved_freq *saved_freq;
218 CF_DEBUG("shutdown %s\n", device_get_nameunit(dev));
219 sc = device_get_softc(dev);
220 sysctl_ctx_free(&sc->sysctl_ctx);
222 while ((saved_freq = SLIST_FIRST(&sc->saved_freq)) != NULL) {
223 SLIST_REMOVE_HEAD(&sc->saved_freq, link);
224 free(saved_freq, M_TEMP);
227 free(sc->levels_buf, M_DEVBUF);
233 cf_set_method(device_t dev, const struct cf_level *level, int priority)
235 struct cpufreq_softc *sc;
236 const struct cf_setting *set;
237 struct cf_saved_freq *saved_freq, *curr_freq;
242 sc = device_get_softc(dev);
247 /* We are going to change levels so notify the pre-change handler. */
248 EVENTHANDLER_INVOKE(cpufreq_pre_change, level, &error);
250 EVENTHANDLER_INVOKE(cpufreq_post_change, level, error);
254 CF_MTX_LOCK(&sc->lock);
257 #ifdef EARLY_AP_STARTUP
258 MPASS(mp_ncpus == 1 || smp_started);
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.
267 if (mp_ncpus > 1 && !smp_started) {
268 device_printf(dev, "rejecting change, SMP not started yet\n");
276 * If the requested level has a lower priority, don't allow
277 * the new level right now.
279 if (priority < sc->curr_priority) {
280 CF_DEBUG("ignoring, curr prio %d less than %d\n", priority,
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.
291 saved_freq = SLIST_FIRST(&sc->saved_freq);
292 if (saved_freq == NULL) {
293 CF_DEBUG("NULL level, no saved level\n");
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);
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);
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);
318 /* First, set the absolute frequency via its driver. */
319 set = &level->abs_set;
321 if (!device_is_attached(set->dev)) {
326 /* Bind to the target CPU before switching. */
327 pc = cpu_get_pcpu(set->dev);
328 thread_lock(curthread);
329 pri = curthread->td_priority;
330 sched_prio(curthread, PRI_MIN);
331 sched_bind(curthread, pc->pc_cpuid);
332 thread_unlock(curthread);
333 CF_DEBUG("setting abs freq %d on %s (cpu %d)\n", set->freq,
334 device_get_nameunit(set->dev), PCPU_GET(cpuid));
335 error = CPUFREQ_DRV_SET(set->dev, set);
336 thread_lock(curthread);
337 sched_unbind(curthread);
338 sched_prio(curthread, pri);
339 thread_unlock(curthread);
345 /* Next, set any/all relative frequencies via their drivers. */
346 for (i = 0; i < level->rel_count; i++) {
347 set = &level->rel_set[i];
348 if (!device_is_attached(set->dev)) {
353 /* Bind to the target CPU before switching. */
354 pc = cpu_get_pcpu(set->dev);
355 thread_lock(curthread);
356 pri = curthread->td_priority;
357 sched_prio(curthread, PRI_MIN);
358 sched_bind(curthread, pc->pc_cpuid);
359 thread_unlock(curthread);
360 CF_DEBUG("setting rel freq %d on %s (cpu %d)\n", set->freq,
361 device_get_nameunit(set->dev), PCPU_GET(cpuid));
362 error = CPUFREQ_DRV_SET(set->dev, set);
363 thread_lock(curthread);
364 sched_unbind(curthread);
365 sched_prio(curthread, pri);
366 thread_unlock(curthread);
368 /* XXX Back out any successful setting? */
375 * Before recording the current level, check if we're going to a
376 * higher priority. If so, save the previous level and priority.
378 if (sc->curr_level.total_set.freq != CPUFREQ_VAL_UNKNOWN &&
379 priority > sc->curr_priority) {
380 CF_DEBUG("saving level, freq %d prio %d\n",
381 sc->curr_level.total_set.freq, sc->curr_priority);
382 curr_freq = malloc(sizeof(*curr_freq), M_TEMP, M_NOWAIT);
383 if (curr_freq == NULL) {
387 curr_freq->level = sc->curr_level;
388 curr_freq->priority = sc->curr_priority;
389 SLIST_INSERT_HEAD(&sc->saved_freq, curr_freq, link);
391 sc->curr_level = *level;
392 sc->curr_priority = priority;
394 /* If we were restoring a saved state, reset it to "unused". */
395 if (saved_freq != NULL) {
396 CF_DEBUG("resetting saved level\n");
397 sc->curr_level.total_set.freq = CPUFREQ_VAL_UNKNOWN;
398 SLIST_REMOVE_HEAD(&sc->saved_freq, link);
399 free(saved_freq, M_TEMP);
403 CF_MTX_UNLOCK(&sc->lock);
406 * We changed levels (or attempted to) so notify the post-change
407 * handler of new frequency or error.
409 EVENTHANDLER_INVOKE(cpufreq_post_change, level, error);
411 device_printf(set->dev, "set freq failed, err %d\n", error);
417 cpufreq_get_frequency(device_t dev)
419 struct cf_setting set;
421 if (CPUFREQ_DRV_GET(dev, &set) != 0)
427 /* Returns the index into *levels with the match */
429 cpufreq_get_level(device_t dev, struct cf_level *levels, int count)
433 if ((freq = cpufreq_get_frequency(dev)) < 0)
435 for (i = 0; i < count; i++)
436 if (freq == levels[i].total_set.freq)
443 * Used by the cpufreq core, this function will populate *level with the current
444 * frequency as either determined by a cached value sc->curr_level, or in the
445 * case the lower level driver has set the CPUFREQ_FLAG_UNCACHED flag, it will
446 * obtain the frequency from the driver itself.
449 cf_get_method(device_t dev, struct cf_level *level)
451 struct cpufreq_softc *sc;
452 struct cf_level *levels;
453 struct cf_setting *curr_set;
455 int bdiff, count, diff, error, i, type;
458 sc = device_get_softc(dev);
463 * If we already know the current frequency, and the driver didn't ask
464 * for uncached usage, we're done.
466 CF_MTX_LOCK(&sc->lock);
467 curr_set = &sc->curr_level.total_set;
468 error = CPUFREQ_DRV_TYPE(sc->cf_drv_dev, &type);
469 if (error == 0 && (type & CPUFREQ_FLAG_UNCACHED)) {
470 struct cf_setting set;
473 * If the driver wants to always report back the real frequency,
474 * first try the driver and if that fails, fall back to
477 if (CPUFREQ_DRV_GET(sc->cf_drv_dev, &set) == 0) {
478 sc->curr_level.total_set = set;
479 CF_DEBUG("get returning immediate freq %d\n",
483 } else if (curr_set->freq != CPUFREQ_VAL_UNKNOWN) {
484 CF_DEBUG("get returning known freq %d\n", curr_set->freq);
488 CF_MTX_UNLOCK(&sc->lock);
491 * We need to figure out the current level. Loop through every
492 * driver, getting the current setting. Then, attempt to get a best
493 * match of settings against each level.
495 count = CF_MAX_LEVELS;
496 levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
499 error = CPUFREQ_LEVELS(sc->dev, levels, &count);
502 printf("cpufreq: need to increase CF_MAX_LEVELS\n");
503 free(levels, M_TEMP);
508 * Reacquire the lock and search for the given level.
510 * XXX Note: this is not quite right since we really need to go
511 * through each level and compare both absolute and relative
512 * settings for each driver in the system before making a match.
513 * The estimation code below catches this case though.
515 CF_MTX_LOCK(&sc->lock);
516 i = cpufreq_get_level(sc->cf_drv_dev, levels, count);
518 sc->curr_level = levels[i];
520 CF_DEBUG("Couldn't find supported level for %s\n",
521 device_get_nameunit(sc->cf_drv_dev));
523 if (curr_set->freq != CPUFREQ_VAL_UNKNOWN) {
524 CF_DEBUG("get matched freq %d from drivers\n", curr_set->freq);
529 * We couldn't find an exact match, so attempt to estimate and then
530 * match against a level.
532 pc = cpu_get_pcpu(dev);
537 cpu_est_clockrate(pc->pc_cpuid, &rate);
540 for (i = 0; i < count; i++) {
541 diff = abs(levels[i].total_set.freq - rate);
544 sc->curr_level = levels[i];
547 CF_DEBUG("get estimated freq %d\n", curr_set->freq);
551 *level = sc->curr_level;
553 CF_MTX_UNLOCK(&sc->lock);
555 free(levels, M_TEMP);
560 * Either directly obtain settings from the cpufreq driver, or build a list of
561 * relative settings to be integrated later against an absolute max.
564 cpufreq_add_levels(device_t cf_dev, struct cf_setting_lst *rel_sets)
566 struct cf_setting_array *set_arr;
567 struct cf_setting *sets;
569 struct cpufreq_softc *sc;
570 int type, set_count, error;
572 sc = device_get_softc(cf_dev);
573 dev = sc->cf_drv_dev;
575 /* Skip devices that aren't ready. */
576 if (!device_is_attached(cf_dev))
580 * Get settings, skipping drivers that offer no settings or
581 * provide settings for informational purposes only.
583 error = CPUFREQ_DRV_TYPE(dev, &type);
584 if (error != 0 || (type & CPUFREQ_FLAG_INFO_ONLY)) {
586 CF_DEBUG("skipping info-only driver %s\n",
587 device_get_nameunit(cf_dev));
592 sets = malloc(MAX_SETTINGS * sizeof(*sets), M_TEMP, M_NOWAIT);
596 set_count = MAX_SETTINGS;
597 error = CPUFREQ_DRV_SETTINGS(dev, sets, &set_count);
598 if (error != 0 || set_count == 0)
601 /* Add the settings to our absolute/relative lists. */
602 switch (type & CPUFREQ_TYPE_MASK) {
603 case CPUFREQ_TYPE_ABSOLUTE:
604 error = cpufreq_insert_abs(sc, sets, set_count);
606 case CPUFREQ_TYPE_RELATIVE:
607 CF_DEBUG("adding %d relative settings\n", set_count);
608 set_arr = malloc(sizeof(*set_arr), M_TEMP, M_NOWAIT);
609 if (set_arr == NULL) {
613 bcopy(sets, set_arr->sets, set_count * sizeof(*sets));
614 set_arr->count = set_count;
615 TAILQ_INSERT_TAIL(rel_sets, set_arr, link);
627 cf_levels_method(device_t dev, struct cf_level *levels, int *count)
629 struct cf_setting_array *set_arr;
630 struct cf_setting_lst rel_sets;
631 struct cpufreq_softc *sc;
632 struct cf_level *lev;
637 if (levels == NULL || count == NULL)
640 TAILQ_INIT(&rel_sets);
641 sc = device_get_softc(dev);
643 CF_MTX_LOCK(&sc->lock);
644 error = cpufreq_add_levels(sc->dev, &rel_sets);
649 * If there are no absolute levels, create a fake one at 100%. We
650 * then cache the clockrate for later use as our base frequency.
652 if (TAILQ_EMPTY(&sc->all_levels)) {
653 struct cf_setting set;
655 CF_DEBUG("No absolute levels returned by driver\n");
657 if (sc->max_mhz == CPUFREQ_VAL_UNKNOWN) {
658 sc->max_mhz = cpu_get_nominal_mhz(dev);
660 * If the CPU can't report a rate for 100%, hope
661 * the CPU is running at its nominal rate right now,
662 * and use that instead.
664 if (sc->max_mhz <= 0) {
665 pc = cpu_get_pcpu(dev);
666 cpu_est_clockrate(pc->pc_cpuid, &rate);
667 sc->max_mhz = rate / 1000000;
670 memset(&set, CPUFREQ_VAL_UNKNOWN, sizeof(set));
671 set.freq = sc->max_mhz;
673 error = cpufreq_insert_abs(sc, &set, 1);
678 /* Create a combined list of absolute + relative levels. */
679 TAILQ_FOREACH(set_arr, &rel_sets, link)
680 cpufreq_expand_set(sc, set_arr);
682 /* If the caller doesn't have enough space, return the actual count. */
683 if (sc->all_count > *count) {
684 *count = sc->all_count;
689 /* Finally, output the list of levels. */
691 TAILQ_FOREACH(lev, &sc->all_levels, link) {
693 /* Skip levels that have a frequency that is too low. */
694 if (lev->total_set.freq < cf_lowest_freq) {
702 *count = sc->all_count;
706 /* Clear all levels since we regenerate them each time. */
707 while ((lev = TAILQ_FIRST(&sc->all_levels)) != NULL) {
708 TAILQ_REMOVE(&sc->all_levels, lev, link);
713 CF_MTX_UNLOCK(&sc->lock);
714 while ((set_arr = TAILQ_FIRST(&rel_sets)) != NULL) {
715 TAILQ_REMOVE(&rel_sets, set_arr, link);
716 free(set_arr, M_TEMP);
722 * Create levels for an array of absolute settings and insert them in
723 * sorted order in the specified list.
726 cpufreq_insert_abs(struct cpufreq_softc *sc, struct cf_setting *sets,
729 struct cf_level_lst *list;
730 struct cf_level *level, *search;
733 CF_MTX_ASSERT(&sc->lock);
735 list = &sc->all_levels;
736 for (i = 0; i < count; i++) {
737 level = malloc(sizeof(*level), M_TEMP, M_NOWAIT | M_ZERO);
740 level->abs_set = sets[i];
741 level->total_set = sets[i];
742 level->total_set.dev = NULL;
746 if (TAILQ_EMPTY(list)) {
747 CF_DEBUG("adding abs setting %d at head\n",
749 TAILQ_INSERT_HEAD(list, level, link);
753 TAILQ_FOREACH_REVERSE(search, list, cf_level_lst, link)
754 if (sets[i].freq <= search->total_set.freq) {
755 CF_DEBUG("adding abs setting %d after %d\n",
756 sets[i].freq, search->total_set.freq);
757 TAILQ_INSERT_AFTER(list, search, level, link);
763 TAILQ_FOREACH(search, list, link)
764 if (sets[i].freq >= search->total_set.freq) {
765 CF_DEBUG("adding abs setting %d before %d\n",
766 sets[i].freq, search->total_set.freq);
767 TAILQ_INSERT_BEFORE(search, level, link);
777 * Expand a group of relative settings, creating derived levels from them.
780 cpufreq_expand_set(struct cpufreq_softc *sc, struct cf_setting_array *set_arr)
782 struct cf_level *fill, *search;
783 struct cf_setting *set;
786 CF_MTX_ASSERT(&sc->lock);
789 * Walk the set of all existing levels in reverse. This is so we
790 * create derived states from the lowest absolute settings first
791 * and discard duplicates created from higher absolute settings.
792 * For instance, a level of 50 Mhz derived from 100 Mhz + 50% is
793 * preferable to 200 Mhz + 25% because absolute settings are more
794 * efficient since they often change the voltage as well.
796 TAILQ_FOREACH_REVERSE(search, &sc->all_levels, cf_level_lst, link) {
797 /* Add each setting to the level, duplicating if necessary. */
798 for (i = 0; i < set_arr->count; i++) {
799 set = &set_arr->sets[i];
802 * If this setting is less than 100%, split the level
803 * into two and add this setting to the new level.
806 if (set->freq < 10000) {
807 fill = cpufreq_dup_set(sc, search, set);
810 * The new level was a duplicate of an existing
811 * level or its absolute setting is too high
812 * so we freed it. For example, we discard a
813 * derived level of 1000 MHz/25% if a level
814 * of 500 MHz/100% already exists.
820 /* Add this setting to the existing or new level. */
821 KASSERT(fill->rel_count < MAX_SETTINGS,
822 ("cpufreq: too many relative drivers (%d)",
824 fill->rel_set[fill->rel_count] = *set;
827 "expand set added rel setting %d%% to %d level\n",
828 set->freq / 100, fill->total_set.freq);
835 static struct cf_level *
836 cpufreq_dup_set(struct cpufreq_softc *sc, struct cf_level *dup,
837 struct cf_setting *set)
839 struct cf_level_lst *list;
840 struct cf_level *fill, *itr;
841 struct cf_setting *fill_set, *itr_set;
844 CF_MTX_ASSERT(&sc->lock);
847 * Create a new level, copy it from the old one, and update the
848 * total frequency and power by the percentage specified in the
851 fill = malloc(sizeof(*fill), M_TEMP, M_NOWAIT);
855 fill_set = &fill->total_set;
857 ((uint64_t)fill_set->freq * set->freq) / 10000;
858 if (fill_set->power != CPUFREQ_VAL_UNKNOWN) {
859 fill_set->power = ((uint64_t)fill_set->power * set->freq)
862 if (set->lat != CPUFREQ_VAL_UNKNOWN) {
863 if (fill_set->lat != CPUFREQ_VAL_UNKNOWN)
864 fill_set->lat += set->lat;
866 fill_set->lat = set->lat;
868 CF_DEBUG("dup set considering derived setting %d\n", fill_set->freq);
871 * If we copied an old level that we already modified (say, at 100%),
872 * we need to remove that setting before adding this one. Since we
873 * process each setting array in order, we know any settings for this
874 * driver will be found at the end.
876 for (i = fill->rel_count; i != 0; i--) {
877 if (fill->rel_set[i - 1].dev != set->dev)
879 CF_DEBUG("removed last relative driver: %s\n",
880 device_get_nameunit(set->dev));
885 * Insert the new level in sorted order. If it is a duplicate of an
886 * existing level (1) or has an absolute setting higher than the
887 * existing level (2), do not add it. We can do this since any such
888 * level is guaranteed use less power. For example (1), a level with
889 * one absolute setting of 800 Mhz uses less power than one composed
890 * of an absolute setting of 1600 Mhz and a relative setting at 50%.
891 * Also for example (2), a level of 800 Mhz/75% is preferable to
892 * 1600 Mhz/25% even though the latter has a lower total frequency.
894 list = &sc->all_levels;
895 KASSERT(!TAILQ_EMPTY(list), ("all levels list empty in dup set"));
896 TAILQ_FOREACH_REVERSE(itr, list, cf_level_lst, link) {
897 itr_set = &itr->total_set;
898 if (CPUFREQ_CMP(fill_set->freq, itr_set->freq)) {
899 CF_DEBUG("dup set rejecting %d (dupe)\n",
903 } else if (fill_set->freq < itr_set->freq) {
904 if (fill->abs_set.freq <= itr->abs_set.freq) {
906 "dup done, inserting new level %d after %d\n",
907 fill_set->freq, itr_set->freq);
908 TAILQ_INSERT_AFTER(list, itr, fill, link);
911 CF_DEBUG("dup set rejecting %d (abs too big)\n",
919 /* We didn't find a good place for this new level so free it. */
921 CF_DEBUG("dup set freeing new level %d (not optimal)\n",
931 cpufreq_curr_sysctl(SYSCTL_HANDLER_ARGS)
933 struct cpufreq_softc *sc;
934 struct cf_level *levels;
935 int best, count, diff, bdiff, devcount, error, freq, i, n;
940 levels = sc->levels_buf;
942 error = CPUFREQ_GET(sc->dev, &levels[0]);
945 freq = levels[0].total_set.freq;
946 error = sysctl_handle_int(oidp, &freq, 0, req);
947 if (error != 0 || req->newptr == NULL)
951 * While we only call cpufreq_get() on one device (assuming all
952 * CPUs have equal levels), we call cpufreq_set() on all CPUs.
953 * This is needed for some MP systems.
955 error = devclass_get_devices(cpufreq_dc, &devs, &devcount);
958 for (n = 0; n < devcount; n++) {
959 count = CF_MAX_LEVELS;
960 error = CPUFREQ_LEVELS(devs[n], levels, &count);
964 "cpufreq: need to increase CF_MAX_LEVELS\n");
969 for (i = 0; i < count; i++) {
970 diff = abs(levels[i].total_set.freq - freq);
976 error = CPUFREQ_SET(devs[n], &levels[best], CPUFREQ_PRIO_USER);
986 cpufreq_levels_sysctl(SYSCTL_HANDLER_ARGS)
988 struct cpufreq_softc *sc;
989 struct cf_level *levels;
990 struct cf_setting *set;
995 sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND);
997 /* Get settings from the device and generate the output string. */
998 count = CF_MAX_LEVELS;
999 levels = sc->levels_buf;
1000 if (levels == NULL) {
1004 error = CPUFREQ_LEVELS(sc->dev, levels, &count);
1007 printf("cpufreq: need to increase CF_MAX_LEVELS\n");
1011 for (i = 0; i < count; i++) {
1012 set = &levels[i].total_set;
1013 sbuf_printf(&sb, "%d/%d ", set->freq, set->power);
1019 error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
1027 cpufreq_settings_sysctl(SYSCTL_HANDLER_ARGS)
1030 struct cf_setting *sets;
1032 int error, i, set_count;
1034 dev = oidp->oid_arg1;
1035 sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND);
1037 /* Get settings from the device and generate the output string. */
1038 set_count = MAX_SETTINGS;
1039 sets = malloc(set_count * sizeof(*sets), M_TEMP, M_NOWAIT);
1044 error = CPUFREQ_DRV_SETTINGS(dev, sets, &set_count);
1048 for (i = 0; i < set_count; i++)
1049 sbuf_printf(&sb, "%d/%d ", sets[i].freq, sets[i].power);
1054 error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
1063 cpufreq_add_freq_driver_sysctl(device_t cf_dev)
1065 struct cpufreq_softc *sc;
1067 sc = device_get_softc(cf_dev);
1068 SYSCTL_ADD_CONST_STRING(&sc->sysctl_ctx,
1069 SYSCTL_CHILDREN(device_get_sysctl_tree(cf_dev)), OID_AUTO,
1070 "freq_driver", CTLFLAG_RD, device_get_nameunit(sc->cf_drv_dev),
1071 "cpufreq driver used by this cpu");
1075 cpufreq_register(device_t dev)
1077 struct cpufreq_softc *sc;
1078 device_t cf_dev, cpu_dev;
1081 /* Add a sysctl to get each driver's settings separately. */
1082 SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
1083 SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
1084 OID_AUTO, "freq_settings",
1085 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, dev, 0,
1086 cpufreq_settings_sysctl, "A", "CPU frequency driver settings");
1089 * Add only one cpufreq device to each CPU. Currently, all CPUs
1090 * must offer the same levels and be switched at the same time.
1092 cpu_dev = device_get_parent(dev);
1093 if ((cf_dev = device_find_child(cpu_dev, "cpufreq", -1))) {
1094 sc = device_get_softc(cf_dev);
1095 sc->max_mhz = CPUFREQ_VAL_UNKNOWN;
1096 MPASS(sc->cf_drv_dev != NULL);
1100 /* Add the child device and possibly sysctls. */
1101 cf_dev = BUS_ADD_CHILD(cpu_dev, 0, "cpufreq", -1);
1104 device_quiet(cf_dev);
1106 error = device_probe_and_attach(cf_dev);
1110 sc = device_get_softc(cf_dev);
1111 sc->cf_drv_dev = dev;
1112 cpufreq_add_freq_driver_sysctl(cf_dev);
1117 cpufreq_unregister(device_t dev)
1120 struct cpufreq_softc *sc;
1123 * If this is the last cpufreq child device, remove the control
1124 * device as well. We identify cpufreq children by calling a method
1127 cf_dev = device_find_child(device_get_parent(dev), "cpufreq", -1);
1128 if (cf_dev == NULL) {
1130 "warning: cpufreq_unregister called with no cpufreq device active\n");
1133 sc = device_get_softc(cf_dev);
1134 MPASS(sc->cf_drv_dev == dev);
1135 device_delete_child(device_get_parent(cf_dev), cf_dev);
1141 cpufreq_settings_changed(device_t dev)
1144 EVENTHANDLER_INVOKE(cpufreq_levels_changed,
1145 device_get_unit(device_get_parent(dev)));