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