Merge from vendor branch OPENSSL:
[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.6 2004/08/07 00:59:53 dillon 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
41 #include <bus/pci/pcivar.h>
42 #include <machine/atomic.h>
43 #include <machine/bus.h>
44 #include <machine/globaldata.h>
45 #include <machine/smp.h>
46 #include <sys/rman.h>
47
48 #include "acpi.h"
49 #include "acpivar.h"
50
51 /*
52  * Support for ACPI Processor devices, including ACPI 2.0 throttling
53  * and C[1-3] sleep states.
54  *
55  * TODO: implement scans of all CPUs to be sure all Cx states are
56  * equivalent.
57  */
58
59 /* Hooks for the ACPI CA debugging infrastructure */
60 #define _COMPONENT      ACPI_PROCESSOR
61 ACPI_MODULE_NAME("PROCESSOR")
62
63 struct acpi_cx {
64     struct resource     *p_lvlx;        /* Register to read to enter state. */
65     uint32_t             type;          /* C1-3 (C4 and up treated as C3). */
66     uint32_t             trans_lat;     /* Transition latency (usec). */
67     uint32_t             power;         /* Power consumed (mW). */
68 };
69 #define MAX_CX_STATES    8
70
71 struct acpi_cpu_softc {
72     device_t             cpu_dev;
73     ACPI_HANDLE          cpu_handle;
74     uint32_t             acpi_id;       /* ACPI processor id */
75     uint32_t             cpu_p_blk;     /* ACPI P_BLK location */
76     uint32_t             cpu_p_blk_len; /* P_BLK length (must be 6). */
77     struct resource     *cpu_p_cnt;     /* Throttling control register */
78     struct acpi_cx       cpu_cx_states[MAX_CX_STATES];
79     int                  cpu_cx_count;  /* Number of valid Cx states. */
80     int                  cpu_prev_sleep;/* Last idle sleep duration. */
81 };
82
83 #define CPU_GET_REG(reg, width)                                         \
84     (bus_space_read_ ## width(rman_get_bustag((reg)),                   \
85                       rman_get_bushandle((reg)), 0))
86 #define CPU_SET_REG(reg, width, val)                                    \
87     (bus_space_write_ ## width(rman_get_bustag((reg)),                  \
88                        rman_get_bushandle((reg)), 0, (val)))
89
90 /*
91  * Speeds are stored in counts, from 1 to CPU_MAX_SPEED, and
92  * reported to the user in tenths of a percent.
93  */
94 static uint32_t          cpu_duty_offset;
95 static uint32_t          cpu_duty_width;
96 #define CPU_MAX_SPEED           (1 << cpu_duty_width)
97 #define CPU_SPEED_PERCENT(x)    ((1000 * (x)) / CPU_MAX_SPEED)
98 #define CPU_SPEED_PRINTABLE(x)  (CPU_SPEED_PERCENT(x) / 10),    \
99                                 (CPU_SPEED_PERCENT(x) % 10)
100 #define CPU_P_CNT_THT_EN (1<<4)
101 #define PM_USEC(x)       ((x) >> 2)     /* ~4 clocks per usec (3.57955 Mhz) */
102
103 #define ACPI_CPU_NOTIFY_PERF_STATES     0x80    /* _PSS changed. */
104 #define ACPI_CPU_NOTIFY_CX_STATES       0x81    /* _CST changed. */
105
106 #define CPU_QUIRK_NO_C3         0x0001  /* C3-type states are not usable. */
107 #define CPU_QUIRK_NO_THROTTLE   0x0002  /* Throttling is not usable. */
108
109 #define PCI_VENDOR_INTEL        0x8086
110 #define PCI_DEVICE_82371AB_3    0x7113  /* PIIX4 chipset for quirks. */
111 #define PCI_REVISION_A_STEP     0
112 #define PCI_REVISION_B_STEP     1
113 #define PCI_REVISION_4E         2
114 #define PCI_REVISION_4M         3
115
116 /* Platform hardware resource information. */
117 static uint32_t          cpu_smi_cmd;   /* Value to write to SMI_CMD. */
118 static uint8_t           cpu_pstate_cnt;/* Register to take over throttling. */
119 static uint8_t           cpu_cst_cnt;   /* Indicate we are _CST aware. */
120 static int               cpu_rid;       /* Driver-wide resource id. */
121 static int               cpu_quirks;    /* Indicate any hardware bugs. */
122
123 /* Runtime state. */
124 static int               cpu_cx_count;  /* Number of valid states */
125 static int               cpu_non_c3;    /* Index of lowest non-C3 state. */
126 static u_int             cpu_cx_stats[MAX_CX_STATES];/* Cx usage history. */
127
128 /* Values for sysctl. */
129 static uint32_t          cpu_throttle_state;
130 static uint32_t          cpu_throttle_max;
131 static uint32_t          cpu_throttle_performance;
132 static uint32_t          cpu_throttle_economy;
133 static int               cpu_cx_lowest;
134 static char              cpu_cx_supported[64];
135
136 static device_t         *cpu_devices;
137 static int               cpu_ndevices;
138 static struct acpi_cpu_softc **cpu_softc;
139
140 static struct sysctl_ctx_list   acpi_cpu_sysctl_ctx;
141 static struct sysctl_oid        *acpi_cpu_sysctl_tree;
142
143 static int      acpi_cpu_probe(device_t dev);
144 static int      acpi_cpu_attach(device_t dev);
145 static int      acpi_pcpu_get_id(uint32_t idx, uint32_t *acpi_id,
146                                  uint32_t *cpu_id);
147 static int      acpi_cpu_shutdown(device_t dev);
148 static int      acpi_cpu_throttle_probe(struct acpi_cpu_softc *sc);
149 static void     acpi_cpu_power_profile(void *arg);
150 static int      acpi_cpu_cx_probe(struct acpi_cpu_softc *sc);
151 static int      acpi_cpu_cx_cst(struct acpi_cpu_softc *sc);
152 static void     acpi_cpu_startup(void *arg);
153 static void     acpi_cpu_startup_throttling(void);
154 static void     acpi_cpu_startup_cx(void);
155 static void     acpi_cpu_throttle_set(uint32_t speed);
156 static void     acpi_cpu_idle(void);
157 static void     acpi_cpu_c1(void);
158 static void     acpi_cpu_notify(ACPI_HANDLE h, UINT32 notify, void *context);
159 static int      acpi_cpu_quirks(struct acpi_cpu_softc *sc);
160 static int      acpi_cpu_throttle_sysctl(SYSCTL_HANDLER_ARGS);
161 static int      acpi_cpu_usage_sysctl(SYSCTL_HANDLER_ARGS);
162 static int      acpi_cpu_cx_lowest_sysctl(SYSCTL_HANDLER_ARGS);
163
164 static device_method_t acpi_cpu_methods[] = {
165     /* Device interface */
166     DEVMETHOD(device_probe,     acpi_cpu_probe),
167     DEVMETHOD(device_attach,    acpi_cpu_attach),
168     DEVMETHOD(device_shutdown,  acpi_cpu_shutdown),
169
170     {0, 0}
171 };
172
173 static driver_t acpi_cpu_driver = {
174     "cpu",
175     acpi_cpu_methods,
176     sizeof(struct acpi_cpu_softc),
177 };
178
179 static devclass_t acpi_cpu_devclass;
180 DRIVER_MODULE(cpu, acpi, acpi_cpu_driver, acpi_cpu_devclass, 0, 0);
181 MODULE_DEPEND(cpu, acpi, 1, 1, 1);
182
183 static int
184 acpi_cpu_probe(device_t dev)
185 {
186     int                    acpi_id, cpu_id, cx_count;
187     ACPI_BUFFER            buf;
188     ACPI_HANDLE            handle;
189     char                   msg[32];
190     ACPI_OBJECT            *obj;
191     ACPI_STATUS            status;
192
193     if (acpi_disabled("cpu") || acpi_get_type(dev) != ACPI_TYPE_PROCESSOR)
194         return (ENXIO);
195
196     handle = acpi_get_handle(dev);
197     if (cpu_softc == NULL)
198         cpu_softc = malloc(sizeof(struct acpi_cpu_softc *) *
199             SMP_MAXCPU, M_TEMP /* XXX */, M_INTWAIT | M_ZERO);
200
201     /* Get our Processor object. */
202     buf.Pointer = NULL;
203     buf.Length = ACPI_ALLOCATE_BUFFER;
204     status = AcpiEvaluateObject(handle, NULL, NULL, &buf);
205     if (ACPI_FAILURE(status)) {
206         device_printf(dev, "probe failed to get Processor obj - %s\n",
207                       AcpiFormatException(status));
208         return (ENXIO);
209     }
210     obj = (ACPI_OBJECT *)buf.Pointer;
211     if (obj->Type != ACPI_TYPE_PROCESSOR) {
212         device_printf(dev, "Processor object has bad type %d\n", obj->Type);
213         AcpiOsFree(obj);
214         return (ENXIO);
215     }
216
217     /*
218      * Find the processor associated with our unit.  We could use the
219      * ProcId as a key, however, some boxes do not have the same values
220      * in their Processor object as the ProcId values in the MADT.
221      */
222     acpi_id = obj->Processor.ProcId;
223     AcpiOsFree(obj);
224     if (acpi_pcpu_get_id(device_get_unit(dev), &acpi_id, &cpu_id) != 0)
225         return (ENXIO);
226
227     /*
228      * Check if we already probed this processor.  We scan the bus twice
229      * so it's possible we've already seen this one.
230      */
231     if (cpu_softc[cpu_id] != NULL)
232         return (ENXIO);
233
234     /* Get a count of Cx states for our device string. */
235     cx_count = 0;
236     buf.Pointer = NULL;
237     buf.Length = ACPI_ALLOCATE_BUFFER;
238     status = AcpiEvaluateObject(handle, "_CST", NULL, &buf);
239     if (ACPI_SUCCESS(status)) {
240         obj = (ACPI_OBJECT *)buf.Pointer;
241         if (ACPI_PKG_VALID(obj, 2))
242             acpi_PkgInt32(obj, 0, &cx_count);
243         AcpiOsFree(obj);
244     } else {
245         if (AcpiGbl_FADT->Plvl2Lat <= 100)
246             cx_count++;
247         if (AcpiGbl_FADT->Plvl3Lat <= 1000)
248             cx_count++;
249         if (cx_count > 0)
250             cx_count++;
251     }
252     if (cx_count > 0)
253         snprintf(msg, sizeof(msg), "ACPI CPU (%d Cx states)", cx_count);
254     else
255         strlcpy(msg, "ACPI CPU", sizeof(msg));
256     device_set_desc_copy(dev, msg);
257
258     /* Mark this processor as in-use and save our derived id for attach. */
259     cpu_softc[cpu_id] = (void *)1;
260     acpi_set_magic(dev, cpu_id);
261
262     return (0);
263 }
264
265 static int
266 acpi_cpu_attach(device_t dev)
267 {
268     ACPI_BUFFER            buf;
269     ACPI_OBJECT            *obj;
270     struct acpi_cpu_softc *sc;
271     struct acpi_softc     *acpi_sc;
272     ACPI_STATUS            status;
273     int                    thr_ret, cx_ret;
274
275     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
276
277     ACPI_ASSERTLOCK;
278
279     sc = device_get_softc(dev);
280     sc->cpu_dev = dev;
281     sc->cpu_handle = acpi_get_handle(dev);
282     cpu_softc[acpi_get_magic(dev)] = sc;
283
284     buf.Pointer = NULL;
285     buf.Length = ACPI_ALLOCATE_BUFFER;
286     status = AcpiEvaluateObject(sc->cpu_handle, NULL, NULL, &buf);
287     if (ACPI_FAILURE(status)) {
288         device_printf(dev, "attach failed to get Processor obj - %s\n",
289                       AcpiFormatException(status));
290         return (ENXIO);
291     }
292     obj = (ACPI_OBJECT *)buf.Pointer;
293     sc->cpu_p_blk = obj->Processor.PblkAddress;
294     sc->cpu_p_blk_len = obj->Processor.PblkLength;
295     sc->acpi_id = obj->Processor.ProcId;
296     AcpiOsFree(obj);
297     ACPI_DEBUG_PRINT((ACPI_DB_INFO, "acpi_cpu%d: P_BLK at %#x/%d\n",
298                      device_get_unit(dev), sc->cpu_p_blk, sc->cpu_p_blk_len));
299
300     acpi_sc = acpi_device_get_parent_softc(dev);
301     sysctl_ctx_init(&acpi_cpu_sysctl_ctx);
302     acpi_cpu_sysctl_tree = SYSCTL_ADD_NODE(&acpi_cpu_sysctl_ctx,
303                                 SYSCTL_CHILDREN(acpi_sc->acpi_sysctl_tree),
304                                 OID_AUTO, "cpu", CTLFLAG_RD, 0, "");
305
306     /* If this is the first device probed, check for quirks. */
307     if (device_get_unit(dev) == 0)
308         acpi_cpu_quirks(sc);
309
310     /*
311      * Probe for throttling and Cx state support.
312      * If none of these is present, free up unused resources.
313      */
314     thr_ret = acpi_cpu_throttle_probe(sc);
315     cx_ret = acpi_cpu_cx_probe(sc);
316     if (thr_ret == 0 || cx_ret == 0) {
317         status = AcpiInstallNotifyHandler(sc->cpu_handle, ACPI_DEVICE_NOTIFY,
318                                           acpi_cpu_notify, sc);
319         if (device_get_unit(dev) == 0)
320             AcpiOsQueueForExecution(OSD_PRIORITY_LO, acpi_cpu_startup, NULL);
321     } else {
322         sysctl_ctx_free(&acpi_cpu_sysctl_ctx);
323     }
324
325     return_VALUE (0);
326 }
327
328 /*
329  * Find the nth present CPU and return its pc_cpuid as well as set the
330  * pc_acpi_id from the most reliable source.
331  */
332 static int
333 acpi_pcpu_get_id(uint32_t idx, uint32_t *acpi_id, uint32_t *cpu_id)
334 {
335     struct mdglobaldata *md;
336     uint32_t     i;
337
338     KASSERT(acpi_id != NULL, ("Null acpi_id"));
339     KASSERT(cpu_id != NULL, ("Null cpu_id"));
340     for (i = 0; i <= ncpus; i++) {
341         if ((smp_active_mask & (1 << i)) == 0)
342             continue;
343         md = (struct mdglobaldata *)globaldata_find(i);
344         KASSERT(md != NULL, ("no pcpu data for %d", i));
345         if (idx-- == 0) {
346             /*
347              * If pc_acpi_id was not initialized (e.g., a non-APIC UP box)
348              * override it with the value from the ASL.  Otherwise, if the
349              * two don't match, prefer the MADT-derived value.  Finally,
350              * return the pc_cpuid to reference this processor.
351              */
352             if (md->gd_acpi_id == 0xffffffff)
353                  md->gd_acpi_id = *acpi_id;
354             else if (md->gd_acpi_id != *acpi_id)
355                 *acpi_id = md->gd_acpi_id;
356             *cpu_id = md->mi.gd_cpuid;
357             return (0);
358         }
359     }
360
361     return (ESRCH);
362 }
363
364 static int
365 acpi_cpu_shutdown(device_t dev)
366 {
367     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
368
369     /* Disable any entry to the idle function. */
370     cpu_cx_count = 0;
371
372     /* Signal and wait for all processors to exit acpi_cpu_idle(). */
373 #ifdef SMP
374     /*smp_rendezvous(NULL, NULL, NULL, NULL);*/
375     KKASSERT(0);        /* XXX use rendezvous */
376 #endif
377     DELAY(1);
378
379     return_VALUE (0);
380 }
381
382 static int
383 acpi_cpu_throttle_probe(struct acpi_cpu_softc *sc)
384 {
385     uint32_t             duty_end;
386     ACPI_BUFFER          buf;
387     ACPI_OBJECT          obj;
388     ACPI_GENERIC_ADDRESS gas;
389     ACPI_STATUS          status;
390
391     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
392
393     ACPI_ASSERTLOCK;
394
395     /* Get throttling parameters from the FADT.  0 means not supported. */
396     if (device_get_unit(sc->cpu_dev) == 0) {
397         cpu_smi_cmd = AcpiGbl_FADT->SmiCmd;
398         cpu_pstate_cnt = AcpiGbl_FADT->PstateCnt;
399         cpu_cst_cnt = AcpiGbl_FADT->CstCnt;
400         cpu_duty_offset = AcpiGbl_FADT->DutyOffset;
401         cpu_duty_width = AcpiGbl_FADT->DutyWidth;
402     }
403     if (cpu_duty_width == 0 || (cpu_quirks & CPU_QUIRK_NO_THROTTLE) != 0)
404         return (ENXIO);
405
406     /* Validate the duty offset/width. */
407     duty_end = cpu_duty_offset + cpu_duty_width - 1;
408     if (duty_end > 31) {
409         device_printf(sc->cpu_dev, "CLK_VAL field overflows P_CNT register\n");
410         return (ENXIO);
411     }
412     if (cpu_duty_offset <= 4 && duty_end >= 4) {
413         device_printf(sc->cpu_dev, "CLK_VAL field overlaps THT_EN bit\n");
414         return (ENXIO);
415     }
416
417     /*
418      * If not present, fall back to using the processor's P_BLK to find
419      * the P_CNT register.
420      *
421      * Note that some systems seem to duplicate the P_BLK pointer
422      * across multiple CPUs, so not getting the resource is not fatal.
423      */
424     buf.Pointer = &obj;
425     buf.Length = sizeof(obj);
426     status = AcpiEvaluateObject(sc->cpu_handle, "_PTC", NULL, &buf);
427     if (ACPI_SUCCESS(status)) {
428         if (obj.Buffer.Length < sizeof(ACPI_GENERIC_ADDRESS) + 3) {
429             device_printf(sc->cpu_dev, "_PTC buffer too small\n");
430             return (ENXIO);
431         }
432         memcpy(&gas, obj.Buffer.Pointer + 3, sizeof(gas));
433         sc->cpu_p_cnt = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
434         if (sc->cpu_p_cnt != NULL) {
435             ACPI_DEBUG_PRINT((ACPI_DB_INFO, "acpi_cpu%d: P_CNT from _PTC\n",
436                              device_get_unit(sc->cpu_dev)));
437         }
438     }
439
440     /* If _PTC not present or other failure, try the P_BLK. */
441     if (sc->cpu_p_cnt == NULL) {
442         /* 
443          * The spec says P_BLK must be 6 bytes long.  However, some
444          * systems use it to indicate a fractional set of features
445          * present so we take anything >= 4.
446          */
447         if (sc->cpu_p_blk_len < 4)
448             return (ENXIO);
449         gas.Address = sc->cpu_p_blk;
450         gas.AddressSpaceId = ACPI_ADR_SPACE_SYSTEM_IO;
451         gas.RegisterBitWidth = 32;
452         sc->cpu_p_cnt = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
453         if (sc->cpu_p_cnt != NULL) {
454             ACPI_DEBUG_PRINT((ACPI_DB_INFO, "acpi_cpu%d: P_CNT from P_BLK\n",
455                              device_get_unit(sc->cpu_dev)));
456         } else {
457             device_printf(sc->cpu_dev, "Failed to attach throttling P_CNT\n");
458             return (ENXIO);
459         }
460     }
461     cpu_rid++;
462
463     return (0);
464 }
465
466 static int
467 acpi_cpu_cx_probe(struct acpi_cpu_softc *sc)
468 {
469     ACPI_GENERIC_ADDRESS gas;
470     struct acpi_cx      *cx_ptr;
471     int                  error;
472
473     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
474
475     /* Bus mastering arbitration control is needed for C3. */
476     if (AcpiGbl_FADT->V1_Pm2CntBlk == 0 || AcpiGbl_FADT->Pm2CntLen == 0) {
477         cpu_quirks |= CPU_QUIRK_NO_C3;
478         ACPI_DEBUG_PRINT((ACPI_DB_INFO,
479                          "acpi_cpu%d: No BM control, C3 disabled\n",
480                          device_get_unit(sc->cpu_dev)));
481     }
482
483     /*
484      * First, check for the ACPI 2.0 _CST sleep states object.
485      * If not usable, fall back to the P_BLK's P_LVL2 and P_LVL3.
486      */
487     sc->cpu_cx_count = 0;
488     error = acpi_cpu_cx_cst(sc);
489     if (error != 0) {
490         cx_ptr = sc->cpu_cx_states;
491
492         /* C1 has been required since just after ACPI 1.0 */
493         cx_ptr->type = ACPI_STATE_C1;
494         cx_ptr->trans_lat = 0;
495         cpu_non_c3 = 0;
496         cx_ptr++;
497         sc->cpu_cx_count++;
498
499         /* 
500          * The spec says P_BLK must be 6 bytes long.  However, some systems
501          * use it to indicate a fractional set of features present so we
502          * take 5 as C2.  Some may also have a value of 7 to indicate
503          * another C3 but most use _CST for this (as required) and having
504          * "only" C1-C3 is not a hardship.
505          */
506         if (sc->cpu_p_blk_len < 5)
507             goto done;
508
509         /* Validate and allocate resources for C2 (P_LVL2). */
510         gas.AddressSpaceId = ACPI_ADR_SPACE_SYSTEM_IO;
511         gas.RegisterBitWidth = 8;
512         if (AcpiGbl_FADT->Plvl2Lat <= 100) {
513             gas.Address = sc->cpu_p_blk + 4;
514             cx_ptr->p_lvlx = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
515             if (cx_ptr->p_lvlx != NULL) {
516                 cpu_rid++;
517                 cx_ptr->type = ACPI_STATE_C2;
518                 cx_ptr->trans_lat = AcpiGbl_FADT->Plvl2Lat;
519                 cpu_non_c3 = 1;
520                 cx_ptr++;
521                 sc->cpu_cx_count++;
522             }
523         }
524         if (sc->cpu_p_blk_len < 6)
525             goto done;
526
527         /* Validate and allocate resources for C3 (P_LVL3). */
528         if (AcpiGbl_FADT->Plvl3Lat <= 1000 &&
529             (cpu_quirks & CPU_QUIRK_NO_C3) == 0) {
530
531             gas.Address = sc->cpu_p_blk + 5;
532             cx_ptr->p_lvlx = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
533             if (cx_ptr->p_lvlx != NULL) {
534                 cpu_rid++;
535                 cx_ptr->type = ACPI_STATE_C3;
536                 cx_ptr->trans_lat = AcpiGbl_FADT->Plvl3Lat;
537                 cx_ptr++;
538                 sc->cpu_cx_count++;
539             }
540         }
541     }
542
543 done:
544     /* If no valid registers were found, don't attach. */
545     if (sc->cpu_cx_count == 0)
546         return (ENXIO);
547
548     /* Use initial sleep value of 1 sec. to start with lowest idle state. */
549     sc->cpu_prev_sleep = 1000000;
550
551     return (0);
552 }
553
554 /*
555  * Parse a _CST package and set up its Cx states.  Since the _CST object
556  * can change dynamically, our notify handler may call this function
557  * to clean up and probe the new _CST package.
558  */
559 static int
560 acpi_cpu_cx_cst(struct acpi_cpu_softc *sc)
561 {
562     struct       acpi_cx *cx_ptr;
563     ACPI_STATUS  status;
564     ACPI_BUFFER  buf;
565     ACPI_OBJECT *top;
566     ACPI_OBJECT *pkg;
567     uint32_t     count;
568     int          i;
569
570     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
571
572     buf.Pointer = NULL;
573     buf.Length = ACPI_ALLOCATE_BUFFER;
574     status = AcpiEvaluateObject(sc->cpu_handle, "_CST", NULL, &buf);
575     if (ACPI_FAILURE(status))
576         return (ENXIO);
577
578     /* _CST is a package with a count and at least one Cx package. */
579     top = (ACPI_OBJECT *)buf.Pointer;
580     if (!ACPI_PKG_VALID(top, 2) || acpi_PkgInt32(top, 0, &count) != 0) {
581         device_printf(sc->cpu_dev, "Invalid _CST package\n");
582         AcpiOsFree(buf.Pointer);
583         return (ENXIO);
584     }
585     if (count != top->Package.Count - 1) {
586         device_printf(sc->cpu_dev, "Invalid _CST state count (%d != %d)\n",
587                count, top->Package.Count - 1);
588         count = top->Package.Count - 1;
589     }
590     if (count > MAX_CX_STATES) {
591         device_printf(sc->cpu_dev, "_CST has too many states (%d)\n", count);
592         count = MAX_CX_STATES;
593     }
594
595     /* Set up all valid states. */
596     sc->cpu_cx_count = 0;
597     cx_ptr = sc->cpu_cx_states;
598     for (i = 0; i < count; i++) {
599         pkg = &top->Package.Elements[i + 1];
600         if (!ACPI_PKG_VALID(pkg, 4) ||
601             acpi_PkgInt32(pkg, 1, &cx_ptr->type) != 0 ||
602             acpi_PkgInt32(pkg, 2, &cx_ptr->trans_lat) != 0 ||
603             acpi_PkgInt32(pkg, 3, &cx_ptr->power) != 0) {
604
605             device_printf(sc->cpu_dev, "Skipping invalid Cx state package\n");
606             continue;
607         }
608
609         /* Validate the state to see if we should use it. */
610         switch (cx_ptr->type) {
611         case ACPI_STATE_C1:
612             cpu_non_c3 = i;
613             cx_ptr++;
614             sc->cpu_cx_count++;
615             continue;
616         case ACPI_STATE_C2:
617             if (cx_ptr->trans_lat > 100) {
618                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
619                                  "acpi_cpu%d: C2[%d] not available.\n",
620                                  device_get_unit(sc->cpu_dev), i));
621                 continue;
622             }
623             cpu_non_c3 = i;
624             break;
625         case ACPI_STATE_C3:
626         default:
627             if (cx_ptr->trans_lat > 1000 ||
628                 (cpu_quirks & CPU_QUIRK_NO_C3) != 0) {
629
630                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
631                                  "acpi_cpu%d: C3[%d] not available.\n",
632                                  device_get_unit(sc->cpu_dev), i));
633                 continue;
634             }
635             break;
636         }
637
638 #ifdef notyet
639         /* Free up any previous register. */
640         if (cx_ptr->p_lvlx != NULL) {
641             bus_release_resource(sc->cpu_dev, 0, 0, cx_ptr->p_lvlx);
642             cx_ptr->p_lvlx = NULL;
643         }
644 #endif
645
646         /* Allocate the control register for C2 or C3. */
647         acpi_PkgGas(sc->cpu_dev, pkg, 0, &cpu_rid, &cx_ptr->p_lvlx);
648         if (cx_ptr->p_lvlx != NULL) {
649             cpu_rid++;
650             ACPI_DEBUG_PRINT((ACPI_DB_INFO,
651                              "acpi_cpu%d: Got C%d - %d latency\n",
652                              device_get_unit(sc->cpu_dev), cx_ptr->type,
653                              cx_ptr->trans_lat));
654             cx_ptr++;
655             sc->cpu_cx_count++;
656         }
657     }
658     AcpiOsFree(buf.Pointer);
659
660     return (0);
661 }
662
663 /*
664  * Call this *after* all CPUs have been attached.
665  */
666 static void
667 acpi_cpu_startup(void *arg)
668 {
669     struct acpi_cpu_softc *sc;
670     int count, i;
671
672     /* Get set of CPU devices */
673     devclass_get_devices(acpi_cpu_devclass, &cpu_devices, &cpu_ndevices);
674
675     /*
676      * Make sure all the processors' Cx counts match.  We should probably
677      * also check the contents of each.  However, no known systems have
678      * non-matching Cx counts so we'll deal with this later.
679      */
680     count = MAX_CX_STATES;
681     for (i = 0; i < cpu_ndevices; i++) {
682         sc = device_get_softc(cpu_devices[i]);
683         count = min(sc->cpu_cx_count, count);
684     }
685     cpu_cx_count = count;
686
687     /* Perform throttling and Cx final initialization. */
688     sc = device_get_softc(cpu_devices[0]);
689     if (sc->cpu_p_cnt != NULL)
690         acpi_cpu_startup_throttling();
691     if (cpu_cx_count > 0)
692         acpi_cpu_startup_cx();
693
694     /* register performance profile change handler */
695     EVENTHANDLER_REGISTER(power_profile_change, acpi_cpu_power_profile, NULL, 0);
696 }
697
698 /*
699  * Power profile change hook.
700  *
701  * Uses the ACPI lock to avoid reentrancy.
702  */
703 static void
704 acpi_cpu_power_profile(void *arg)
705 {
706     int state;
707     int speed;
708     ACPI_LOCK_DECL;
709
710     state = power_profile_get_state();
711     if (state != POWER_PROFILE_PERFORMANCE &&
712         state != POWER_PROFILE_ECONOMY) {
713         return;
714     }
715
716     ACPI_LOCK;
717     switch(state) {
718     case POWER_PROFILE_PERFORMANCE:
719         speed = cpu_throttle_performance;
720         break;
721     case POWER_PROFILE_ECONOMY:
722         speed = cpu_throttle_economy;
723         break;
724     default:
725         speed = cpu_throttle_state;
726         break;
727     }
728     if (speed != cpu_throttle_state)
729         acpi_cpu_throttle_set(speed);
730     ACPI_UNLOCK;
731 }
732
733 /*
734  * Takes the ACPI lock to avoid fighting anyone over the SMI command
735  * port.
736  */
737 static void
738 acpi_cpu_startup_throttling()
739 {
740     ACPI_LOCK_DECL;
741
742     /* Initialise throttling states */
743     cpu_throttle_max = CPU_MAX_SPEED;
744     cpu_throttle_state = CPU_MAX_SPEED;
745     cpu_throttle_performance = cpu_throttle_max;
746     cpu_throttle_economy = cpu_throttle_performance / 2;
747
748     SYSCTL_ADD_INT(&acpi_cpu_sysctl_ctx,
749                    SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
750                    OID_AUTO, "throttle_max", CTLFLAG_RD,
751                    &cpu_throttle_max, 0, "maximum CPU speed");
752     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx,
753                     SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
754                     OID_AUTO, "throttle_state",
755                     CTLTYPE_INT | CTLFLAG_RW, &cpu_throttle_state,
756                     0, acpi_cpu_throttle_sysctl, "I", "current CPU speed");
757
758     /*
759      * Performance/Economy throttle settings
760      */
761     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx, 
762                     SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
763                     OID_AUTO, "performance_speed",
764                     CTLTYPE_INT | CTLFLAG_RW, &cpu_throttle_performance,
765                     0, acpi_cpu_throttle_sysctl, "I", "performance CPU speed");
766     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx,
767                     SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
768                     OID_AUTO, "economy_speed",
769                     CTLTYPE_INT | CTLFLAG_RW, &cpu_throttle_economy,
770                     0, acpi_cpu_throttle_sysctl, "I", "economy CPU speed");
771
772     /* If ACPI 2.0+, signal platform that we are taking over throttling. */
773     ACPI_LOCK;
774     if (cpu_pstate_cnt != 0)
775         AcpiOsWritePort(cpu_smi_cmd, cpu_pstate_cnt, 8);
776
777     /* Set initial speed to maximum. */
778     acpi_cpu_throttle_set(cpu_throttle_max);
779     ACPI_UNLOCK;
780
781     printf("acpi_cpu: throttling enabled, %d steps (100%% to %d.%d%%), "
782            "currently %d.%d%%\n", CPU_MAX_SPEED, CPU_SPEED_PRINTABLE(1),
783            CPU_SPEED_PRINTABLE(cpu_throttle_state));
784 }
785
786 /* XXX: not here */
787 extern void (*cpu_idle_hook)(void);
788
789 static void
790 acpi_cpu_startup_cx()
791 {
792     struct acpi_cpu_softc *sc;
793     struct sbuf          sb;
794     int i;
795
796     sc = device_get_softc(cpu_devices[0]);
797     sbuf_new(&sb, cpu_cx_supported, sizeof(cpu_cx_supported), SBUF_FIXEDLEN);
798     for (i = 0; i < cpu_cx_count; i++)
799         sbuf_printf(&sb, "C%d/%d ", i + 1, sc->cpu_cx_states[i].trans_lat);
800     sbuf_trim(&sb);
801     sbuf_finish(&sb);
802     SYSCTL_ADD_STRING(&acpi_cpu_sysctl_ctx,
803                       SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
804                       OID_AUTO, "cx_supported", CTLFLAG_RD, cpu_cx_supported,
805                       0, "Cx/microsecond values for supported Cx states");
806     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx,
807                     SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
808                     OID_AUTO, "cx_lowest", CTLTYPE_STRING | CTLFLAG_RW,
809                     NULL, 0, acpi_cpu_cx_lowest_sysctl, "A",
810                     "lowest Cx sleep state to use");
811     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx,
812                     SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
813                     OID_AUTO, "cx_usage", CTLTYPE_STRING | CTLFLAG_RD,
814                     NULL, 0, acpi_cpu_usage_sysctl, "A",
815                     "percent usage for each Cx state");
816
817 #ifdef notyet
818     /* Signal platform that we can handle _CST notification. */
819     if (cpu_cst_cnt != 0) {
820         ACPI_LOCK;
821         AcpiOsWritePort(cpu_smi_cmd, cpu_cst_cnt, 8);
822         ACPI_UNLOCK;
823     }
824 #endif
825
826     /* Take over idling from cpu_idle_default_hook(). */
827     KKASSERT(0);
828     /* XXX only set this if ncpus == 1, for now XXX */
829     cpu_idle_hook = acpi_cpu_idle;
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()
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()
988 {
989 #ifdef __ia64__
990     ia64_call_pal_static(PAL_HALT_LIGHT, 0, 0, 0);
991 #else
992     __asm __volatile("sti; hlt");
993 #endif
994 }
995
996 /*
997  * Re-evaluate the _PSS and _CST objects when we are notified that they
998  * have changed.
999  *
1000  * XXX Re-evaluation disabled until locking is done.
1001  */
1002 static void
1003 acpi_cpu_notify(ACPI_HANDLE h, UINT32 notify, void *context)
1004 {
1005     struct acpi_cpu_softc *sc = (struct acpi_cpu_softc *)context;
1006
1007     switch (notify) {
1008     case ACPI_CPU_NOTIFY_PERF_STATES:
1009         device_printf(sc->cpu_dev, "Performance states changed\n");
1010         /* acpi_cpu_px_available(sc); */
1011         break;
1012     case ACPI_CPU_NOTIFY_CX_STATES:
1013         device_printf(sc->cpu_dev, "Cx states changed\n");
1014         /* acpi_cpu_cx_cst(sc); */
1015         break;
1016     default:
1017         device_printf(sc->cpu_dev, "Unknown notify %#x\n", notify);
1018         break;
1019     }
1020 }
1021
1022 static int
1023 acpi_cpu_quirks(struct acpi_cpu_softc *sc)
1024 {
1025
1026     /*
1027      * C3 is not supported on multiple CPUs since this would require
1028      * flushing all caches which is currently too expensive.
1029      */
1030     if (ncpus > 1)
1031         cpu_quirks |= CPU_QUIRK_NO_C3;
1032
1033 #ifdef notyet
1034     /* Look for various quirks of the PIIX4 part. */
1035     acpi_dev = pci_find_device(PCI_VENDOR_INTEL, PCI_DEVICE_82371AB_3);
1036     if (acpi_dev != NULL) {
1037         switch (pci_get_revid(acpi_dev)) {
1038         /*
1039          * Disable throttling control on PIIX4 A and B-step.
1040          * See specification changes #13 ("Manual Throttle Duty Cycle")
1041          * and #14 ("Enabling and Disabling Manual Throttle"), plus
1042          * erratum #5 ("STPCLK# Deassertion Time") from the January
1043          * 2002 PIIX4 specification update.  Note that few (if any)
1044          * mobile systems ever used this part.
1045          */
1046         case PCI_REVISION_A_STEP:
1047         case PCI_REVISION_B_STEP:
1048             cpu_quirks |= CPU_QUIRK_NO_THROTTLE;
1049             /* FALLTHROUGH */
1050         /*
1051          * Disable C3 support for all PIIX4 chipsets.  Some of these parts
1052          * do not report the BMIDE status to the BM status register and
1053          * others have a livelock bug if Type-F DMA is enabled.  Linux
1054          * works around the BMIDE bug by reading the BM status directly
1055          * but we take the simpler approach of disabling C3 for these
1056          * parts.
1057          *
1058          * See erratum #18 ("C3 Power State/BMIDE and Type-F DMA
1059          * Livelock") from the January 2002 PIIX4 specification update.
1060          * Applies to all PIIX4 models.
1061          */
1062         case PCI_REVISION_4E:
1063         case PCI_REVISION_4M:
1064             cpu_quirks |= CPU_QUIRK_NO_C3;
1065             break;
1066         default:
1067             break;
1068         }
1069     }
1070 #endif
1071
1072     return (0);
1073 }
1074
1075 /* Handle changes in the CPU throttling setting. */
1076 static int
1077 acpi_cpu_throttle_sysctl(SYSCTL_HANDLER_ARGS)
1078 {
1079     uint32_t    *argp;
1080     uint32_t     arg;
1081     int          error;
1082     ACPI_LOCK_DECL;
1083
1084     argp = (uint32_t *)oidp->oid_arg1;
1085     arg = *argp;
1086     error = sysctl_handle_int(oidp, &arg, 0, req);
1087
1088     /* Error or no new value */
1089     if (error != 0 || req->newptr == NULL)
1090         return (error);
1091     if (arg < 1 || arg > cpu_throttle_max)
1092         return (EINVAL);
1093
1094     /* If throttling changed, notify the BIOS of the new rate. */
1095     ACPI_LOCK;
1096     if (*argp != arg) {
1097         *argp = arg;
1098         acpi_cpu_throttle_set(arg);
1099     }
1100     ACPI_UNLOCK;
1101
1102     return (0);
1103 }
1104
1105 static int
1106 acpi_cpu_usage_sysctl(SYSCTL_HANDLER_ARGS)
1107 {
1108     struct sbuf  sb;
1109     char         buf[128];
1110     int          i;
1111     uintmax_t    fract, sum, whole;
1112
1113     sum = 0;
1114     for (i = 0; i < cpu_cx_count; i++)
1115         sum += cpu_cx_stats[i];
1116     sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
1117     for (i = 0; i < cpu_cx_count; i++) {
1118         if (sum > 0) {
1119             whole = (uintmax_t)cpu_cx_stats[i] * 100;
1120             fract = (whole % sum) * 100;
1121             sbuf_printf(&sb, "%u.%02u%% ", (u_int)(whole / sum),
1122                 (u_int)(fract / sum));
1123         } else
1124             sbuf_printf(&sb, "0%% ");
1125     }
1126     sbuf_trim(&sb);
1127     sbuf_finish(&sb);
1128     sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
1129     sbuf_delete(&sb);
1130
1131     return (0);
1132 }
1133
1134 static int
1135 acpi_cpu_cx_lowest_sysctl(SYSCTL_HANDLER_ARGS)
1136 {
1137     struct       acpi_cpu_softc *sc;
1138     char         state[8];
1139     int          val, error, i;
1140
1141     sc = device_get_softc(cpu_devices[0]);
1142     snprintf(state, sizeof(state), "C%d", cpu_cx_lowest + 1);
1143     error = sysctl_handle_string(oidp, state, sizeof(state), req);
1144     if (error != 0 || req->newptr == NULL)
1145         return (error);
1146     if (strlen(state) < 2 || toupper(state[0]) != 'C')
1147         return (EINVAL);
1148     val = (int) strtol(state + 1, NULL, 10) - 1;
1149     if (val < 0 || val > cpu_cx_count - 1)
1150         return (EINVAL);
1151
1152     cpu_cx_lowest = val;
1153
1154     /* If not disabling, cache the new lowest non-C3 state. */
1155     cpu_non_c3 = 0;
1156     for (i = cpu_cx_lowest; i >= 0; i--) {
1157         if (sc->cpu_cx_states[i].type < ACPI_STATE_C3) {
1158             cpu_non_c3 = i;
1159             break;
1160         }
1161     }
1162
1163     /* Reset the statistics counters. */
1164     bzero(cpu_cx_stats, sizeof(cpu_cx_stats));
1165
1166     return (0);
1167 }