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