MASSIVE reorganization of the device operations vector. Change cdevsw
[dragonfly.git] / sys / dev / acpica5 / acpi_cpu.c
1 /*-
2  * Copyright (c) 2003 Nate Lawson (SDG)
3  * Copyright (c) 2001 Michael Smith
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD: src/sys/dev/acpica/acpi_cpu.c,v 1.41 2004/06/24 00:38:51 njl Exp $
28  * $DragonFly: src/sys/dev/acpica5/acpi_cpu.c,v 1.12 2005/12/11 01:54:07 swildner Exp $
29  */
30
31 #include "opt_acpi.h"
32 #include <sys/param.h>
33 #include <sys/bus.h>
34 #include <sys/kernel.h>
35 #include <sys/malloc.h>
36 #include <sys/globaldata.h>
37 #include <sys/power.h>
38 #include <sys/proc.h>
39 #include <sys/sbuf.h>
40 #include <sys/thread2.h>
41
42 #include <bus/pci/pcivar.h>
43 #include <machine/atomic.h>
44 #include <machine/bus.h>
45 #include <machine/globaldata.h>
46 #include <machine/md_var.h>
47 #include <machine/smp.h>
48 #include <sys/rman.h>
49
50 #include "acpi.h"
51 #include "acpivar.h"
52
53 /*
54  * Support for ACPI Processor devices, including ACPI 2.0 throttling
55  * and C[1-3] sleep states.
56  *
57  * TODO: implement scans of all CPUs to be sure all Cx states are
58  * equivalent.
59  */
60
61 /* Hooks for the ACPI CA debugging infrastructure */
62 #define _COMPONENT      ACPI_PROCESSOR
63 ACPI_MODULE_NAME("PROCESSOR")
64
65 struct acpi_cx {
66     struct resource     *p_lvlx;        /* Register to read to enter state. */
67     uint32_t             type;          /* C1-3 (C4 and up treated as C3). */
68     uint32_t             trans_lat;     /* Transition latency (usec). */
69     uint32_t             power;         /* Power consumed (mW). */
70 };
71 #define MAX_CX_STATES    8
72
73 struct acpi_cpu_softc {
74     device_t             cpu_dev;
75     ACPI_HANDLE          cpu_handle;
76     uint32_t             acpi_id;       /* ACPI processor id */
77     uint32_t             cpu_p_blk;     /* ACPI P_BLK location */
78     uint32_t             cpu_p_blk_len; /* P_BLK length (must be 6). */
79     struct resource     *cpu_p_cnt;     /* Throttling control register */
80     struct acpi_cx       cpu_cx_states[MAX_CX_STATES];
81     int                  cpu_cx_count;  /* Number of valid Cx states. */
82     int                  cpu_prev_sleep;/* Last idle sleep duration. */
83 };
84
85 #define CPU_GET_REG(reg, width)                                         \
86     (bus_space_read_ ## width(rman_get_bustag((reg)),                   \
87                       rman_get_bushandle((reg)), 0))
88 #define CPU_SET_REG(reg, width, val)                                    \
89     (bus_space_write_ ## width(rman_get_bustag((reg)),                  \
90                        rman_get_bushandle((reg)), 0, (val)))
91
92 /*
93  * Speeds are stored in counts, from 1 to CPU_MAX_SPEED, and
94  * reported to the user in tenths of a percent.
95  */
96 static uint32_t          cpu_duty_offset;
97 static uint32_t          cpu_duty_width;
98 #define CPU_MAX_SPEED           (1 << cpu_duty_width)
99 #define CPU_SPEED_PERCENT(x)    ((1000 * (x)) / CPU_MAX_SPEED)
100 #define CPU_SPEED_PRINTABLE(x)  (CPU_SPEED_PERCENT(x) / 10),    \
101                                 (CPU_SPEED_PERCENT(x) % 10)
102 #define CPU_P_CNT_THT_EN (1<<4)
103 #define PM_USEC(x)       ((x) >> 2)     /* ~4 clocks per usec (3.57955 Mhz) */
104
105 #define ACPI_CPU_NOTIFY_PERF_STATES     0x80    /* _PSS changed. */
106 #define ACPI_CPU_NOTIFY_CX_STATES       0x81    /* _CST changed. */
107
108 #define CPU_QUIRK_NO_C3         0x0001  /* C3-type states are not usable. */
109 #define CPU_QUIRK_NO_THROTTLE   0x0002  /* Throttling is not usable. */
110
111 #define PCI_VENDOR_INTEL        0x8086
112 #define PCI_DEVICE_82371AB_3    0x7113  /* PIIX4 chipset for quirks. */
113 #define PCI_REVISION_A_STEP     0
114 #define PCI_REVISION_B_STEP     1
115 #define PCI_REVISION_4E         2
116 #define PCI_REVISION_4M         3
117
118 /* Platform hardware resource information. */
119 static uint32_t          cpu_smi_cmd;   /* Value to write to SMI_CMD. */
120 static uint8_t           cpu_pstate_cnt;/* Register to take over throttling. */
121 static uint8_t           cpu_cst_cnt;   /* Indicate we are _CST aware. */
122 static int               cpu_rid;       /* Driver-wide resource id. */
123 static int               cpu_quirks;    /* Indicate any hardware bugs. */
124
125 /* Runtime state. */
126 static int               cpu_cx_count;  /* Number of valid states */
127 static int               cpu_non_c3;    /* Index of lowest non-C3 state. */
128 static u_int             cpu_cx_stats[MAX_CX_STATES];/* Cx usage history. */
129
130 /* Values for sysctl. */
131 static uint32_t          cpu_throttle_state;
132 static uint32_t          cpu_throttle_max;
133 static uint32_t          cpu_throttle_performance;
134 static uint32_t          cpu_throttle_economy;
135 static int               cpu_cx_lowest;
136 static char              cpu_cx_supported[64];
137
138 static device_t         *cpu_devices;
139 static int               cpu_ndevices;
140 static struct acpi_cpu_softc **cpu_softc;
141
142 static struct sysctl_ctx_list   acpi_cpu_sysctl_ctx;
143 static struct sysctl_oid        *acpi_cpu_sysctl_tree;
144
145 static int      acpi_cpu_probe(device_t dev);
146 static int      acpi_cpu_attach(device_t dev);
147 static int      acpi_pcpu_get_id(uint32_t idx, uint32_t *acpi_id,
148                                  uint32_t *cpu_id);
149 static int      acpi_cpu_shutdown(device_t dev);
150 static int      acpi_cpu_throttle_probe(struct acpi_cpu_softc *sc);
151 static void     acpi_cpu_power_profile(void *arg);
152 static int      acpi_cpu_cx_probe(struct acpi_cpu_softc *sc);
153 static int      acpi_cpu_cx_cst(struct acpi_cpu_softc *sc);
154 static void     acpi_cpu_startup(void *arg);
155 static void     acpi_cpu_startup_throttling(void);
156 static void     acpi_cpu_startup_cx(void);
157 static void     acpi_cpu_throttle_set(uint32_t speed);
158 static void     acpi_cpu_idle(void);
159 static void     acpi_cpu_c1(void);
160 static void     acpi_cpu_notify(ACPI_HANDLE h, UINT32 notify, void *context);
161 static int      acpi_cpu_quirks(struct acpi_cpu_softc *sc);
162 static int      acpi_cpu_throttle_sysctl(SYSCTL_HANDLER_ARGS);
163 static int      acpi_cpu_usage_sysctl(SYSCTL_HANDLER_ARGS);
164 static int      acpi_cpu_cx_lowest_sysctl(SYSCTL_HANDLER_ARGS);
165
166 static device_method_t acpi_cpu_methods[] = {
167     /* Device interface */
168     DEVMETHOD(device_probe,     acpi_cpu_probe),
169     DEVMETHOD(device_attach,    acpi_cpu_attach),
170     DEVMETHOD(device_shutdown,  acpi_cpu_shutdown),
171
172     {0, 0}
173 };
174
175 static driver_t acpi_cpu_driver = {
176     "cpu",
177     acpi_cpu_methods,
178     sizeof(struct acpi_cpu_softc),
179 };
180
181 static devclass_t acpi_cpu_devclass;
182 DRIVER_MODULE(cpu, acpi, acpi_cpu_driver, acpi_cpu_devclass, 0, 0);
183 MODULE_DEPEND(cpu, acpi, 1, 1, 1);
184
185 static int
186 acpi_cpu_probe(device_t dev)
187 {
188     int                    acpi_id, cpu_id, cx_count;
189     ACPI_BUFFER            buf;
190     ACPI_HANDLE            handle;
191     char                   msg[32];
192     ACPI_OBJECT            *obj;
193     ACPI_STATUS            status;
194
195     if (acpi_disabled("cpu") || acpi_get_type(dev) != ACPI_TYPE_PROCESSOR)
196         return (ENXIO);
197
198     handle = acpi_get_handle(dev);
199     if (cpu_softc == NULL)
200         cpu_softc = malloc(sizeof(struct acpi_cpu_softc *) *
201             SMP_MAXCPU, M_TEMP /* XXX */, M_INTWAIT | M_ZERO);
202
203     /* Get our Processor object. */
204     buf.Pointer = NULL;
205     buf.Length = ACPI_ALLOCATE_BUFFER;
206     status = AcpiEvaluateObject(handle, NULL, NULL, &buf);
207     if (ACPI_FAILURE(status)) {
208         device_printf(dev, "probe failed to get Processor obj - %s\n",
209                       AcpiFormatException(status));
210         return (ENXIO);
211     }
212     obj = (ACPI_OBJECT *)buf.Pointer;
213     if (obj->Type != ACPI_TYPE_PROCESSOR) {
214         device_printf(dev, "Processor object has bad type %d\n", obj->Type);
215         AcpiOsFree(obj);
216         return (ENXIO);
217     }
218
219     /*
220      * Find the processor associated with our unit.  We could use the
221      * ProcId as a key, however, some boxes do not have the same values
222      * in their Processor object as the ProcId values in the MADT.
223      */
224     acpi_id = obj->Processor.ProcId;
225     AcpiOsFree(obj);
226     if (acpi_pcpu_get_id(device_get_unit(dev), &acpi_id, &cpu_id) != 0)
227         return (ENXIO);
228
229     /*
230      * Check if we already probed this processor.  We scan the bus twice
231      * so it's possible we've already seen this one.
232      */
233     if (cpu_softc[cpu_id] != NULL)
234         return (ENXIO);
235
236     /* Get a count of Cx states for our device string. */
237     cx_count = 0;
238     buf.Pointer = NULL;
239     buf.Length = ACPI_ALLOCATE_BUFFER;
240     status = AcpiEvaluateObject(handle, "_CST", NULL, &buf);
241     if (ACPI_SUCCESS(status)) {
242         obj = (ACPI_OBJECT *)buf.Pointer;
243         if (ACPI_PKG_VALID(obj, 2))
244             acpi_PkgInt32(obj, 0, &cx_count);
245         AcpiOsFree(obj);
246     } else {
247         if (AcpiGbl_FADT->Plvl2Lat <= 100)
248             cx_count++;
249         if (AcpiGbl_FADT->Plvl3Lat <= 1000)
250             cx_count++;
251         if (cx_count > 0)
252             cx_count++;
253     }
254     if (cx_count > 0)
255         snprintf(msg, sizeof(msg), "ACPI CPU (%d Cx states)", cx_count);
256     else
257         strlcpy(msg, "ACPI CPU", sizeof(msg));
258     device_set_desc_copy(dev, msg);
259
260     /* Mark this processor as in-use and save our derived id for attach. */
261     cpu_softc[cpu_id] = (void *)1;
262     acpi_set_magic(dev, cpu_id);
263
264     return (0);
265 }
266
267 static int
268 acpi_cpu_attach(device_t dev)
269 {
270     ACPI_BUFFER            buf;
271     ACPI_OBJECT            *obj;
272     struct acpi_cpu_softc *sc;
273     struct acpi_softc     *acpi_sc;
274     ACPI_STATUS            status;
275     int                    thr_ret, cx_ret;
276
277     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
278
279     ACPI_ASSERTLOCK;
280
281     sc = device_get_softc(dev);
282     sc->cpu_dev = dev;
283     sc->cpu_handle = acpi_get_handle(dev);
284     cpu_softc[acpi_get_magic(dev)] = sc;
285
286     buf.Pointer = NULL;
287     buf.Length = ACPI_ALLOCATE_BUFFER;
288     status = AcpiEvaluateObject(sc->cpu_handle, NULL, NULL, &buf);
289     if (ACPI_FAILURE(status)) {
290         device_printf(dev, "attach failed to get Processor obj - %s\n",
291                       AcpiFormatException(status));
292         return (ENXIO);
293     }
294     obj = (ACPI_OBJECT *)buf.Pointer;
295     sc->cpu_p_blk = obj->Processor.PblkAddress;
296     sc->cpu_p_blk_len = obj->Processor.PblkLength;
297     sc->acpi_id = obj->Processor.ProcId;
298     AcpiOsFree(obj);
299     ACPI_DEBUG_PRINT((ACPI_DB_INFO, "acpi_cpu%d: P_BLK at %#x/%d\n",
300                      device_get_unit(dev), sc->cpu_p_blk, sc->cpu_p_blk_len));
301
302     acpi_sc = acpi_device_get_parent_softc(dev);
303     sysctl_ctx_init(&acpi_cpu_sysctl_ctx);
304     acpi_cpu_sysctl_tree = SYSCTL_ADD_NODE(&acpi_cpu_sysctl_ctx,
305                                 SYSCTL_CHILDREN(acpi_sc->acpi_sysctl_tree),
306                                 OID_AUTO, "cpu", CTLFLAG_RD, 0, "");
307
308     /* If this is the first device probed, check for quirks. */
309     if (device_get_unit(dev) == 0)
310         acpi_cpu_quirks(sc);
311
312     /*
313      * Probe for throttling and Cx state support.
314      * If none of these is present, free up unused resources.
315      */
316     thr_ret = acpi_cpu_throttle_probe(sc);
317     cx_ret = acpi_cpu_cx_probe(sc);
318     if (thr_ret == 0 || cx_ret == 0) {
319         status = AcpiInstallNotifyHandler(sc->cpu_handle, ACPI_DEVICE_NOTIFY,
320                                           acpi_cpu_notify, sc);
321         if (device_get_unit(dev) == 0)
322             AcpiOsQueueForExecution(OSD_PRIORITY_LO, acpi_cpu_startup, NULL);
323     } else {
324         sysctl_ctx_free(&acpi_cpu_sysctl_ctx);
325     }
326
327     return_VALUE (0);
328 }
329
330 /*
331  * Find the nth present CPU and return its pc_cpuid as well as set the
332  * pc_acpi_id from the most reliable source.
333  */
334 static int
335 acpi_pcpu_get_id(uint32_t idx, uint32_t *acpi_id, uint32_t *cpu_id)
336 {
337     struct mdglobaldata *md;
338     uint32_t     i;
339
340     KASSERT(acpi_id != NULL, ("Null acpi_id"));
341     KASSERT(cpu_id != NULL, ("Null cpu_id"));
342     for (i = 0; i <= ncpus; i++) {
343         if ((smp_active_mask & (1 << i)) == 0)
344             continue;
345         md = (struct mdglobaldata *)globaldata_find(i);
346         KASSERT(md != NULL, ("no pcpu data for %d", i));
347         if (idx-- == 0) {
348             /*
349              * If pc_acpi_id was not initialized (e.g., a non-APIC UP box)
350              * override it with the value from the ASL.  Otherwise, if the
351              * two don't match, prefer the MADT-derived value.  Finally,
352              * return the pc_cpuid to reference this processor.
353              */
354             if (md->gd_acpi_id == 0xffffffff)
355                  md->gd_acpi_id = *acpi_id;
356             else if (md->gd_acpi_id != *acpi_id)
357                 *acpi_id = md->gd_acpi_id;
358             *cpu_id = md->mi.gd_cpuid;
359             return (0);
360         }
361     }
362
363     return (ESRCH);
364 }
365
366 static int
367 acpi_cpu_shutdown(device_t dev)
368 {
369     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
370
371     /* Disable any entry to the idle function. */
372     cpu_cx_count = 0;
373
374     /* Signal and wait for all processors to exit acpi_cpu_idle(). */
375 #ifdef SMP
376     if (mycpu->gd_cpuid == 0)
377         lwkt_cpusync_simple(0, NULL, NULL);
378 #endif
379     DELAY(1);
380
381     return_VALUE (0);
382 }
383
384 static int
385 acpi_cpu_throttle_probe(struct acpi_cpu_softc *sc)
386 {
387     uint32_t             duty_end;
388     ACPI_BUFFER          buf;
389     ACPI_OBJECT          obj;
390     ACPI_GENERIC_ADDRESS gas;
391     ACPI_STATUS          status;
392
393     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
394
395     ACPI_ASSERTLOCK;
396
397     /* Get throttling parameters from the FADT.  0 means not supported. */
398     if (device_get_unit(sc->cpu_dev) == 0) {
399         cpu_smi_cmd = AcpiGbl_FADT->SmiCmd;
400         cpu_pstate_cnt = AcpiGbl_FADT->PstateCnt;
401         cpu_cst_cnt = AcpiGbl_FADT->CstCnt;
402         cpu_duty_offset = AcpiGbl_FADT->DutyOffset;
403         cpu_duty_width = AcpiGbl_FADT->DutyWidth;
404     }
405     if (cpu_duty_width == 0 || (cpu_quirks & CPU_QUIRK_NO_THROTTLE) != 0)
406         return (ENXIO);
407
408     /* Validate the duty offset/width. */
409     duty_end = cpu_duty_offset + cpu_duty_width - 1;
410     if (duty_end > 31) {
411         device_printf(sc->cpu_dev, "CLK_VAL field overflows P_CNT register\n");
412         return (ENXIO);
413     }
414     if (cpu_duty_offset <= 4 && duty_end >= 4) {
415         device_printf(sc->cpu_dev, "CLK_VAL field overlaps THT_EN bit\n");
416         return (ENXIO);
417     }
418
419     /*
420      * If not present, fall back to using the processor's P_BLK to find
421      * the P_CNT register.
422      *
423      * Note that some systems seem to duplicate the P_BLK pointer
424      * across multiple CPUs, so not getting the resource is not fatal.
425      */
426     buf.Pointer = &obj;
427     buf.Length = sizeof(obj);
428     status = AcpiEvaluateObject(sc->cpu_handle, "_PTC", NULL, &buf);
429     if (ACPI_SUCCESS(status)) {
430         if (obj.Buffer.Length < sizeof(ACPI_GENERIC_ADDRESS) + 3) {
431             device_printf(sc->cpu_dev, "_PTC buffer too small\n");
432             return (ENXIO);
433         }
434         memcpy(&gas, obj.Buffer.Pointer + 3, sizeof(gas));
435         sc->cpu_p_cnt = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
436         if (sc->cpu_p_cnt != NULL) {
437             ACPI_DEBUG_PRINT((ACPI_DB_INFO, "acpi_cpu%d: P_CNT from _PTC\n",
438                              device_get_unit(sc->cpu_dev)));
439         }
440     }
441
442     /* If _PTC not present or other failure, try the P_BLK. */
443     if (sc->cpu_p_cnt == NULL) {
444         /* 
445          * The spec says P_BLK must be 6 bytes long.  However, some
446          * systems use it to indicate a fractional set of features
447          * present so we take anything >= 4.
448          */
449         if (sc->cpu_p_blk_len < 4)
450             return (ENXIO);
451         gas.Address = sc->cpu_p_blk;
452         gas.AddressSpaceId = ACPI_ADR_SPACE_SYSTEM_IO;
453         gas.RegisterBitWidth = 32;
454         sc->cpu_p_cnt = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
455         if (sc->cpu_p_cnt != NULL) {
456             ACPI_DEBUG_PRINT((ACPI_DB_INFO, "acpi_cpu%d: P_CNT from P_BLK\n",
457                              device_get_unit(sc->cpu_dev)));
458         } else {
459             device_printf(sc->cpu_dev, "Failed to attach throttling P_CNT\n");
460             return (ENXIO);
461         }
462     }
463     cpu_rid++;
464
465     return (0);
466 }
467
468 static int
469 acpi_cpu_cx_probe(struct acpi_cpu_softc *sc)
470 {
471     ACPI_GENERIC_ADDRESS gas;
472     struct acpi_cx      *cx_ptr;
473     int                  error;
474
475     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
476
477     /* Bus mastering arbitration control is needed for C3. */
478     if (AcpiGbl_FADT->V1_Pm2CntBlk == 0 || AcpiGbl_FADT->Pm2CntLen == 0) {
479         cpu_quirks |= CPU_QUIRK_NO_C3;
480         ACPI_DEBUG_PRINT((ACPI_DB_INFO,
481                          "acpi_cpu%d: No BM control, C3 disabled\n",
482                          device_get_unit(sc->cpu_dev)));
483     }
484
485     /*
486      * First, check for the ACPI 2.0 _CST sleep states object.
487      * If not usable, fall back to the P_BLK's P_LVL2 and P_LVL3.
488      */
489     sc->cpu_cx_count = 0;
490     error = acpi_cpu_cx_cst(sc);
491     if (error != 0) {
492         cx_ptr = sc->cpu_cx_states;
493
494         /* C1 has been required since just after ACPI 1.0 */
495         cx_ptr->type = ACPI_STATE_C1;
496         cx_ptr->trans_lat = 0;
497         cpu_non_c3 = 0;
498         cx_ptr++;
499         sc->cpu_cx_count++;
500
501         /* 
502          * The spec says P_BLK must be 6 bytes long.  However, some systems
503          * use it to indicate a fractional set of features present so we
504          * take 5 as C2.  Some may also have a value of 7 to indicate
505          * another C3 but most use _CST for this (as required) and having
506          * "only" C1-C3 is not a hardship.
507          */
508         if (sc->cpu_p_blk_len < 5)
509             goto done;
510
511         /* Validate and allocate resources for C2 (P_LVL2). */
512         gas.AddressSpaceId = ACPI_ADR_SPACE_SYSTEM_IO;
513         gas.RegisterBitWidth = 8;
514         if (AcpiGbl_FADT->Plvl2Lat <= 100) {
515             gas.Address = sc->cpu_p_blk + 4;
516             cx_ptr->p_lvlx = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
517             if (cx_ptr->p_lvlx != NULL) {
518                 cpu_rid++;
519                 cx_ptr->type = ACPI_STATE_C2;
520                 cx_ptr->trans_lat = AcpiGbl_FADT->Plvl2Lat;
521                 cpu_non_c3 = 1;
522                 cx_ptr++;
523                 sc->cpu_cx_count++;
524             }
525         }
526         if (sc->cpu_p_blk_len < 6)
527             goto done;
528
529         /* Validate and allocate resources for C3 (P_LVL3). */
530         if (AcpiGbl_FADT->Plvl3Lat <= 1000 &&
531             (cpu_quirks & CPU_QUIRK_NO_C3) == 0) {
532
533             gas.Address = sc->cpu_p_blk + 5;
534             cx_ptr->p_lvlx = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
535             if (cx_ptr->p_lvlx != NULL) {
536                 cpu_rid++;
537                 cx_ptr->type = ACPI_STATE_C3;
538                 cx_ptr->trans_lat = AcpiGbl_FADT->Plvl3Lat;
539                 cx_ptr++;
540                 sc->cpu_cx_count++;
541             }
542         }
543     }
544
545 done:
546     /* If no valid registers were found, don't attach. */
547     if (sc->cpu_cx_count == 0)
548         return (ENXIO);
549
550     /* Use initial sleep value of 1 sec. to start with lowest idle state. */
551     sc->cpu_prev_sleep = 1000000;
552
553     return (0);
554 }
555
556 /*
557  * Parse a _CST package and set up its Cx states.  Since the _CST object
558  * can change dynamically, our notify handler may call this function
559  * to clean up and probe the new _CST package.
560  */
561 static int
562 acpi_cpu_cx_cst(struct acpi_cpu_softc *sc)
563 {
564     struct       acpi_cx *cx_ptr;
565     ACPI_STATUS  status;
566     ACPI_BUFFER  buf;
567     ACPI_OBJECT *top;
568     ACPI_OBJECT *pkg;
569     uint32_t     count;
570     int          i;
571
572     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
573
574     buf.Pointer = NULL;
575     buf.Length = ACPI_ALLOCATE_BUFFER;
576     status = AcpiEvaluateObject(sc->cpu_handle, "_CST", NULL, &buf);
577     if (ACPI_FAILURE(status))
578         return (ENXIO);
579
580     /* _CST is a package with a count and at least one Cx package. */
581     top = (ACPI_OBJECT *)buf.Pointer;
582     if (!ACPI_PKG_VALID(top, 2) || acpi_PkgInt32(top, 0, &count) != 0) {
583         device_printf(sc->cpu_dev, "Invalid _CST package\n");
584         AcpiOsFree(buf.Pointer);
585         return (ENXIO);
586     }
587     if (count != top->Package.Count - 1) {
588         device_printf(sc->cpu_dev, "Invalid _CST state count (%d != %d)\n",
589                count, top->Package.Count - 1);
590         count = top->Package.Count - 1;
591     }
592     if (count > MAX_CX_STATES) {
593         device_printf(sc->cpu_dev, "_CST has too many states (%d)\n", count);
594         count = MAX_CX_STATES;
595     }
596
597     /* Set up all valid states. */
598     sc->cpu_cx_count = 0;
599     cx_ptr = sc->cpu_cx_states;
600     for (i = 0; i < count; i++) {
601         pkg = &top->Package.Elements[i + 1];
602         if (!ACPI_PKG_VALID(pkg, 4) ||
603             acpi_PkgInt32(pkg, 1, &cx_ptr->type) != 0 ||
604             acpi_PkgInt32(pkg, 2, &cx_ptr->trans_lat) != 0 ||
605             acpi_PkgInt32(pkg, 3, &cx_ptr->power) != 0) {
606
607             device_printf(sc->cpu_dev, "Skipping invalid Cx state package\n");
608             continue;
609         }
610
611         /* Validate the state to see if we should use it. */
612         switch (cx_ptr->type) {
613         case ACPI_STATE_C1:
614             cpu_non_c3 = i;
615             cx_ptr++;
616             sc->cpu_cx_count++;
617             continue;
618         case ACPI_STATE_C2:
619             if (cx_ptr->trans_lat > 100) {
620                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
621                                  "acpi_cpu%d: C2[%d] not available.\n",
622                                  device_get_unit(sc->cpu_dev), i));
623                 continue;
624             }
625             cpu_non_c3 = i;
626             break;
627         case ACPI_STATE_C3:
628         default:
629             if (cx_ptr->trans_lat > 1000 ||
630                 (cpu_quirks & CPU_QUIRK_NO_C3) != 0) {
631
632                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
633                                  "acpi_cpu%d: C3[%d] not available.\n",
634                                  device_get_unit(sc->cpu_dev), i));
635                 continue;
636             }
637             break;
638         }
639
640 #ifdef notyet
641         /* Free up any previous register. */
642         if (cx_ptr->p_lvlx != NULL) {
643             bus_release_resource(sc->cpu_dev, 0, 0, cx_ptr->p_lvlx);
644             cx_ptr->p_lvlx = NULL;
645         }
646 #endif
647
648         /* Allocate the control register for C2 or C3. */
649         acpi_PkgGas(sc->cpu_dev, pkg, 0, &cpu_rid, &cx_ptr->p_lvlx);
650         if (cx_ptr->p_lvlx != NULL) {
651             cpu_rid++;
652             ACPI_DEBUG_PRINT((ACPI_DB_INFO,
653                              "acpi_cpu%d: Got C%d - %d latency\n",
654                              device_get_unit(sc->cpu_dev), cx_ptr->type,
655                              cx_ptr->trans_lat));
656             cx_ptr++;
657             sc->cpu_cx_count++;
658         }
659     }
660     AcpiOsFree(buf.Pointer);
661
662     return (0);
663 }
664
665 /*
666  * Call this *after* all CPUs have been attached.
667  */
668 static void
669 acpi_cpu_startup(void *arg)
670 {
671     struct acpi_cpu_softc *sc;
672     int count, i;
673
674     /* Get set of CPU devices */
675     devclass_get_devices(acpi_cpu_devclass, &cpu_devices, &cpu_ndevices);
676
677     /*
678      * Make sure all the processors' Cx counts match.  We should probably
679      * also check the contents of each.  However, no known systems have
680      * non-matching Cx counts so we'll deal with this later.
681      */
682     count = MAX_CX_STATES;
683     for (i = 0; i < cpu_ndevices; i++) {
684         sc = device_get_softc(cpu_devices[i]);
685         count = min(sc->cpu_cx_count, count);
686     }
687     cpu_cx_count = count;
688
689     /* Perform throttling and Cx final initialization. */
690     sc = device_get_softc(cpu_devices[0]);
691     if (sc->cpu_p_cnt != NULL)
692         acpi_cpu_startup_throttling();
693     if (cpu_cx_count > 0)
694         acpi_cpu_startup_cx();
695
696     /* register performance profile change handler */
697     EVENTHANDLER_REGISTER(power_profile_change, acpi_cpu_power_profile, NULL, 0);
698 }
699
700 /*
701  * Power profile change hook.
702  *
703  * Uses the ACPI lock to avoid reentrancy.
704  */
705 static void
706 acpi_cpu_power_profile(void *arg)
707 {
708     int state;
709     int speed;
710     ACPI_LOCK_DECL;
711
712     state = power_profile_get_state();
713     if (state != POWER_PROFILE_PERFORMANCE &&
714         state != POWER_PROFILE_ECONOMY) {
715         return;
716     }
717
718     ACPI_LOCK;
719     switch(state) {
720     case POWER_PROFILE_PERFORMANCE:
721         speed = cpu_throttle_performance;
722         break;
723     case POWER_PROFILE_ECONOMY:
724         speed = cpu_throttle_economy;
725         break;
726     default:
727         speed = cpu_throttle_state;
728         break;
729     }
730     if (speed != cpu_throttle_state)
731         acpi_cpu_throttle_set(speed);
732     ACPI_UNLOCK;
733 }
734
735 /*
736  * Takes the ACPI lock to avoid fighting anyone over the SMI command
737  * port.
738  */
739 static void
740 acpi_cpu_startup_throttling(void)
741 {
742     ACPI_LOCK_DECL;
743
744     /* Initialise throttling states */
745     cpu_throttle_max = CPU_MAX_SPEED;
746     cpu_throttle_state = CPU_MAX_SPEED;
747     cpu_throttle_performance = cpu_throttle_max;
748     cpu_throttle_economy = cpu_throttle_performance / 2;
749
750     SYSCTL_ADD_INT(&acpi_cpu_sysctl_ctx,
751                    SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
752                    OID_AUTO, "throttle_max", CTLFLAG_RD,
753                    &cpu_throttle_max, 0, "maximum CPU speed");
754     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx,
755                     SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
756                     OID_AUTO, "throttle_state",
757                     CTLTYPE_INT | CTLFLAG_RW, &cpu_throttle_state,
758                     0, acpi_cpu_throttle_sysctl, "I", "current CPU speed");
759
760     /*
761      * Performance/Economy throttle settings
762      */
763     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx, 
764                     SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
765                     OID_AUTO, "performance_speed",
766                     CTLTYPE_INT | CTLFLAG_RW, &cpu_throttle_performance,
767                     0, acpi_cpu_throttle_sysctl, "I", "performance CPU speed");
768     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx,
769                     SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
770                     OID_AUTO, "economy_speed",
771                     CTLTYPE_INT | CTLFLAG_RW, &cpu_throttle_economy,
772                     0, acpi_cpu_throttle_sysctl, "I", "economy CPU speed");
773
774     /* If ACPI 2.0+, signal platform that we are taking over throttling. */
775     ACPI_LOCK;
776     if (cpu_pstate_cnt != 0)
777         AcpiOsWritePort(cpu_smi_cmd, cpu_pstate_cnt, 8);
778
779     /* Set initial speed to maximum. */
780     acpi_cpu_throttle_set(cpu_throttle_max);
781     ACPI_UNLOCK;
782
783     printf("acpi_cpu: throttling enabled, %d steps (100%% to %d.%d%%), "
784            "currently %d.%d%%\n", CPU_MAX_SPEED, CPU_SPEED_PRINTABLE(1),
785            CPU_SPEED_PRINTABLE(cpu_throttle_state));
786 }
787
788 static void
789 acpi_cpu_startup_cx(void)
790 {
791     struct acpi_cpu_softc *sc;
792     struct sbuf          sb;
793     int i;
794
795     sc = device_get_softc(cpu_devices[0]);
796     sbuf_new(&sb, cpu_cx_supported, sizeof(cpu_cx_supported), SBUF_FIXEDLEN);
797     for (i = 0; i < cpu_cx_count; i++)
798         sbuf_printf(&sb, "C%d/%d ", i + 1, sc->cpu_cx_states[i].trans_lat);
799     sbuf_trim(&sb);
800     sbuf_finish(&sb);
801     SYSCTL_ADD_STRING(&acpi_cpu_sysctl_ctx,
802                       SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
803                       OID_AUTO, "cx_supported", CTLFLAG_RD, cpu_cx_supported,
804                       0, "Cx/microsecond values for supported Cx states");
805     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx,
806                     SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
807                     OID_AUTO, "cx_lowest", CTLTYPE_STRING | CTLFLAG_RW,
808                     NULL, 0, acpi_cpu_cx_lowest_sysctl, "A",
809                     "lowest Cx sleep state to use");
810     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx,
811                     SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
812                     OID_AUTO, "cx_usage", CTLTYPE_STRING | CTLFLAG_RD,
813                     NULL, 0, acpi_cpu_usage_sysctl, "A",
814                     "percent usage for each Cx state");
815
816 #ifdef notyet
817     /* Signal platform that we can handle _CST notification. */
818     if (cpu_cst_cnt != 0) {
819         ACPI_LOCK;
820         AcpiOsWritePort(cpu_smi_cmd, cpu_cst_cnt, 8);
821         ACPI_UNLOCK;
822     }
823 #endif
824
825     /* Take over idling from cpu_idle_default_hook(). */
826     if (ncpus == 1)
827         cpu_idle_hook = acpi_cpu_idle;
828     else
829         printf("Warning: ACPI idle hook not yet supported for SMP\n");
830 }
831
832 /*
833  * Set CPUs to the new state.
834  *
835  * Must be called with the ACPI lock held.
836  */
837 static void
838 acpi_cpu_throttle_set(uint32_t speed)
839 {
840     struct acpi_cpu_softc       *sc;
841     int                         i;
842     uint32_t                    p_cnt, clk_val;
843
844     ACPI_ASSERTLOCK;
845
846     /* Iterate over processors */
847     for (i = 0; i < cpu_ndevices; i++) {
848         sc = device_get_softc(cpu_devices[i]);
849         if (sc->cpu_p_cnt == NULL)
850             continue;
851
852         /* Get the current P_CNT value and disable throttling */
853         p_cnt = CPU_GET_REG(sc->cpu_p_cnt, 4);
854         p_cnt &= ~CPU_P_CNT_THT_EN;
855         CPU_SET_REG(sc->cpu_p_cnt, 4, p_cnt);
856
857         /* If we're at maximum speed, that's all */
858         if (speed < CPU_MAX_SPEED) {
859             /* Mask the old CLK_VAL off and or-in the new value */
860             clk_val = (CPU_MAX_SPEED - 1) << cpu_duty_offset;
861             p_cnt &= ~clk_val;
862             p_cnt |= (speed << cpu_duty_offset);
863
864             /* Write the new P_CNT value and then enable throttling */
865             CPU_SET_REG(sc->cpu_p_cnt, 4, p_cnt);
866             p_cnt |= CPU_P_CNT_THT_EN;
867             CPU_SET_REG(sc->cpu_p_cnt, 4, p_cnt);
868         }
869         ACPI_VPRINT(sc->cpu_dev, acpi_device_get_parent_softc(sc->cpu_dev),
870                     "set speed to %d.%d%%\n", CPU_SPEED_PRINTABLE(speed));
871     }
872     cpu_throttle_state = speed;
873 }
874
875 /*
876  * Idle the CPU in the lowest state possible.  This function is called with
877  * interrupts disabled.  Note that once it re-enables interrupts, a task
878  * switch can occur so do not access shared data (i.e. the softc) after
879  * interrupts are re-enabled.
880  */
881 static void
882 acpi_cpu_idle(void)
883 {
884     struct      acpi_cpu_softc *sc;
885     struct      acpi_cx *cx_next;
886     uint32_t    start_time, end_time;
887     int         bm_active, cx_next_idx, i;
888
889     /* If disabled, return immediately. */
890     if (cpu_cx_count == 0) {
891         ACPI_ENABLE_IRQS();
892         return;
893     }
894
895     /*
896      * Look up our CPU id to get our softc.  If it's NULL, we'll use C1
897      * since there is no ACPI processor object for this CPU.  This occurs
898      * for logical CPUs in the HTT case.
899      */
900     sc = cpu_softc[mdcpu->mi.gd_cpuid];
901     if (sc == NULL) {
902         acpi_cpu_c1();
903         return;
904     }
905
906     /*
907      * If we slept 100 us or more, use the lowest Cx state.  Otherwise,
908      * find the lowest state that has a latency less than or equal to
909      * the length of our last sleep.
910      */
911     cx_next_idx = cpu_cx_lowest;
912     if (sc->cpu_prev_sleep < 100)
913         for (i = cpu_cx_lowest; i >= 0; i--)
914             if (sc->cpu_cx_states[i].trans_lat <= sc->cpu_prev_sleep) {
915                 cx_next_idx = i;
916                 break;
917             }
918
919     /*
920      * Check for bus master activity.  If there was activity, clear
921      * the bit and use the lowest non-C3 state.  Note that the USB
922      * driver polling for new devices keeps this bit set all the
923      * time if USB is loaded.
924      */
925     AcpiGetRegister(ACPI_BITREG_BUS_MASTER_STATUS, &bm_active,
926                     ACPI_MTX_DO_NOT_LOCK);
927     if (bm_active != 0) {
928         AcpiSetRegister(ACPI_BITREG_BUS_MASTER_STATUS, 1,
929                         ACPI_MTX_DO_NOT_LOCK);
930         cx_next_idx = min(cx_next_idx, cpu_non_c3);
931     }
932
933     /* Select the next state and update statistics. */
934     cx_next = &sc->cpu_cx_states[cx_next_idx];
935     cpu_cx_stats[cx_next_idx]++;
936     KASSERT(cx_next->type != ACPI_STATE_C0, ("acpi_cpu_idle: C0 sleep"));
937
938     /*
939      * Execute HLT (or equivalent) and wait for an interrupt.  We can't
940      * calculate the time spent in C1 since the place we wake up is an
941      * ISR.  Assume we slept one quantum and return.
942      */
943     if (cx_next->type == ACPI_STATE_C1) {
944         sc->cpu_prev_sleep = 1000000 / hz;
945         acpi_cpu_c1();
946         return;
947     }
948
949     /* For C3, disable bus master arbitration and enable bus master wake. */
950     if (cx_next->type == ACPI_STATE_C3) {
951         AcpiSetRegister(ACPI_BITREG_ARB_DISABLE, 1, ACPI_MTX_DO_NOT_LOCK);
952         AcpiSetRegister(ACPI_BITREG_BUS_MASTER_RLD, 1, ACPI_MTX_DO_NOT_LOCK);
953     }
954
955     /*
956      * Read from P_LVLx to enter C2(+), checking time spent asleep.
957      * Use the ACPI timer for measuring sleep time.  Since we need to
958      * get the time very close to the CPU start/stop clock logic, this
959      * is the only reliable time source.
960      */
961     AcpiHwLowLevelRead(32, &start_time, &AcpiGbl_FADT->XPmTmrBlk);
962     CPU_GET_REG(cx_next->p_lvlx, 1);
963
964     /*
965      * Read the end time twice.  Since it may take an arbitrary time
966      * to enter the idle state, the first read may be executed before
967      * the processor has stopped.  Doing it again provides enough
968      * margin that we are certain to have a correct value.
969      */
970     AcpiHwLowLevelRead(32, &end_time, &AcpiGbl_FADT->XPmTmrBlk);
971     AcpiHwLowLevelRead(32, &end_time, &AcpiGbl_FADT->XPmTmrBlk);
972
973     /* Enable bus master arbitration and disable bus master wakeup. */
974     if (cx_next->type == ACPI_STATE_C3) {
975         AcpiSetRegister(ACPI_BITREG_ARB_DISABLE, 0, ACPI_MTX_DO_NOT_LOCK);
976         AcpiSetRegister(ACPI_BITREG_BUS_MASTER_RLD, 0, ACPI_MTX_DO_NOT_LOCK);
977     }
978
979     /* Find the actual time asleep in microseconds, minus overhead. */
980     end_time = acpi_TimerDelta(end_time, start_time);
981     sc->cpu_prev_sleep = PM_USEC(end_time) - cx_next->trans_lat;
982     ACPI_ENABLE_IRQS();
983 }
984
985 /* Put the CPU in C1 in a machine-dependant way. */
986 static void
987 acpi_cpu_c1(void)
988 {
989 #ifdef __ia64__
990     ia64_call_pal_static(PAL_HALT_LIGHT, 0, 0, 0);
991 #else
992     splz();
993 #ifdef SMP
994     if (!lwkt_runnable())
995         __asm __volatile("sti; hlt");
996     else
997         __asm __volatile("sti; pause");
998 #else
999     if (!lwkt_runnable())
1000         __asm __volatile("sti; hlt");
1001     else
1002         __asm __volatile("sti");
1003 #endif
1004 #endif /* !__ia64__ */
1005 }
1006
1007 /*
1008  * Re-evaluate the _PSS and _CST objects when we are notified that they
1009  * have changed.
1010  *
1011  * XXX Re-evaluation disabled until locking is done.
1012  */
1013 static void
1014 acpi_cpu_notify(ACPI_HANDLE h, UINT32 notify, void *context)
1015 {
1016     struct acpi_cpu_softc *sc = (struct acpi_cpu_softc *)context;
1017
1018     switch (notify) {
1019     case ACPI_CPU_NOTIFY_PERF_STATES:
1020         device_printf(sc->cpu_dev, "Performance states changed\n");
1021         /* acpi_cpu_px_available(sc); */
1022         break;
1023     case ACPI_CPU_NOTIFY_CX_STATES:
1024         device_printf(sc->cpu_dev, "Cx states changed\n");
1025         /* acpi_cpu_cx_cst(sc); */
1026         break;
1027     default:
1028         device_printf(sc->cpu_dev, "Unknown notify %#x\n", notify);
1029         break;
1030     }
1031 }
1032
1033 static int
1034 acpi_cpu_quirks(struct acpi_cpu_softc *sc)
1035 {
1036
1037     /*
1038      * C3 is not supported on multiple CPUs since this would require
1039      * flushing all caches which is currently too expensive.
1040      */
1041     if (ncpus > 1)
1042         cpu_quirks |= CPU_QUIRK_NO_C3;
1043
1044 #ifdef notyet
1045     /* Look for various quirks of the PIIX4 part. */
1046     acpi_dev = pci_find_device(PCI_VENDOR_INTEL, PCI_DEVICE_82371AB_3);
1047     if (acpi_dev != NULL) {
1048         switch (pci_get_revid(acpi_dev)) {
1049         /*
1050          * Disable throttling control on PIIX4 A and B-step.
1051          * See specification changes #13 ("Manual Throttle Duty Cycle")
1052          * and #14 ("Enabling and Disabling Manual Throttle"), plus
1053          * erratum #5 ("STPCLK# Deassertion Time") from the January
1054          * 2002 PIIX4 specification update.  Note that few (if any)
1055          * mobile systems ever used this part.
1056          */
1057         case PCI_REVISION_A_STEP:
1058         case PCI_REVISION_B_STEP:
1059             cpu_quirks |= CPU_QUIRK_NO_THROTTLE;
1060             /* FALLTHROUGH */
1061         /*
1062          * Disable C3 support for all PIIX4 chipsets.  Some of these parts
1063          * do not report the BMIDE status to the BM status register and
1064          * others have a livelock bug if Type-F DMA is enabled.  Linux
1065          * works around the BMIDE bug by reading the BM status directly
1066          * but we take the simpler approach of disabling C3 for these
1067          * parts.
1068          *
1069          * See erratum #18 ("C3 Power State/BMIDE and Type-F DMA
1070          * Livelock") from the January 2002 PIIX4 specification update.
1071          * Applies to all PIIX4 models.
1072          */
1073         case PCI_REVISION_4E:
1074         case PCI_REVISION_4M:
1075             cpu_quirks |= CPU_QUIRK_NO_C3;
1076             break;
1077         default:
1078             break;
1079         }
1080     }
1081 #endif
1082
1083     return (0);
1084 }
1085
1086 /* Handle changes in the CPU throttling setting. */
1087 static int
1088 acpi_cpu_throttle_sysctl(SYSCTL_HANDLER_ARGS)
1089 {
1090     uint32_t    *argp;
1091     uint32_t     arg;
1092     int          error;
1093     ACPI_LOCK_DECL;
1094
1095     argp = (uint32_t *)oidp->oid_arg1;
1096     arg = *argp;
1097     error = sysctl_handle_int(oidp, &arg, 0, req);
1098
1099     /* Error or no new value */
1100     if (error != 0 || req->newptr == NULL)
1101         return (error);
1102     if (arg < 1 || arg > cpu_throttle_max)
1103         return (EINVAL);
1104
1105     /* If throttling changed, notify the BIOS of the new rate. */
1106     ACPI_LOCK;
1107     if (*argp != arg) {
1108         *argp = arg;
1109         acpi_cpu_throttle_set(arg);
1110     }
1111     ACPI_UNLOCK;
1112
1113     return (0);
1114 }
1115
1116 static int
1117 acpi_cpu_usage_sysctl(SYSCTL_HANDLER_ARGS)
1118 {
1119     struct sbuf  sb;
1120     char         buf[128];
1121     int          i;
1122     uintmax_t    fract, sum, whole;
1123
1124     sum = 0;
1125     for (i = 0; i < cpu_cx_count; i++)
1126         sum += cpu_cx_stats[i];
1127     sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
1128     for (i = 0; i < cpu_cx_count; i++) {
1129         if (sum > 0) {
1130             whole = (uintmax_t)cpu_cx_stats[i] * 100;
1131             fract = (whole % sum) * 100;
1132             sbuf_printf(&sb, "%u.%02u%% ", (u_int)(whole / sum),
1133                 (u_int)(fract / sum));
1134         } else
1135             sbuf_printf(&sb, "0%% ");
1136     }
1137     sbuf_trim(&sb);
1138     sbuf_finish(&sb);
1139     sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
1140     sbuf_delete(&sb);
1141
1142     return (0);
1143 }
1144
1145 static int
1146 acpi_cpu_cx_lowest_sysctl(SYSCTL_HANDLER_ARGS)
1147 {
1148     struct       acpi_cpu_softc *sc;
1149     char         state[8];
1150     int          val, error, i;
1151
1152     sc = device_get_softc(cpu_devices[0]);
1153     snprintf(state, sizeof(state), "C%d", cpu_cx_lowest + 1);
1154     error = sysctl_handle_string(oidp, state, sizeof(state), req);
1155     if (error != 0 || req->newptr == NULL)
1156         return (error);
1157     if (strlen(state) < 2 || toupper(state[0]) != 'C')
1158         return (EINVAL);
1159     val = (int) strtol(state + 1, NULL, 10) - 1;
1160     if (val < 0 || val > cpu_cx_count - 1)
1161         return (EINVAL);
1162
1163     cpu_cx_lowest = val;
1164
1165     /* If not disabling, cache the new lowest non-C3 state. */
1166     cpu_non_c3 = 0;
1167     for (i = cpu_cx_lowest; i >= 0; i--) {
1168         if (sc->cpu_cx_states[i].type < ACPI_STATE_C3) {
1169             cpu_non_c3 = i;
1170             break;
1171         }
1172     }
1173
1174     /* Reset the statistics counters. */
1175     bzero(cpu_cx_stats, sizeof(cpu_cx_stats));
1176
1177     return (0);
1178 }