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