]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/acpica/acpi_cpu.c
Merge xz 5.2.0.
[FreeBSD/FreeBSD.git] / sys / dev / acpica / acpi_cpu.c
1 /*-
2  * Copyright (c) 2003-2005 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
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include "opt_acpi.h"
32 #include <sys/param.h>
33 #include <sys/bus.h>
34 #include <sys/cpu.h>
35 #include <sys/kernel.h>
36 #include <sys/malloc.h>
37 #include <sys/module.h>
38 #include <sys/pcpu.h>
39 #include <sys/power.h>
40 #include <sys/proc.h>
41 #include <sys/sched.h>
42 #include <sys/sbuf.h>
43 #include <sys/smp.h>
44
45 #include <dev/pci/pcivar.h>
46 #include <machine/atomic.h>
47 #include <machine/bus.h>
48 #if defined(__amd64__) || defined(__i386__)
49 #include <machine/clock.h>
50 #endif
51 #include <sys/rman.h>
52
53 #include <contrib/dev/acpica/include/acpi.h>
54 #include <contrib/dev/acpica/include/accommon.h>
55
56 #include <dev/acpica/acpivar.h>
57
58 /*
59  * Support for ACPI Processor devices, including C[1-3] sleep states.
60  */
61
62 /* Hooks for the ACPI CA debugging infrastructure */
63 #define _COMPONENT      ACPI_PROCESSOR
64 ACPI_MODULE_NAME("PROCESSOR")
65
66 struct acpi_cx {
67     struct resource     *p_lvlx;        /* Register to read to enter state. */
68     uint32_t             type;          /* C1-3 (C4 and up treated as C3). */
69     uint32_t             trans_lat;     /* Transition latency (usec). */
70     uint32_t             power;         /* Power consumed (mW). */
71     int                  res_type;      /* Resource type for p_lvlx. */
72     int                  res_rid;       /* Resource ID for p_lvlx. */
73 };
74 #define MAX_CX_STATES    8
75
76 struct acpi_cpu_softc {
77     device_t             cpu_dev;
78     ACPI_HANDLE          cpu_handle;
79     struct pcpu         *cpu_pcpu;
80     uint32_t             cpu_acpi_id;   /* ACPI processor id */
81     uint32_t             cpu_p_blk;     /* ACPI P_BLK location */
82     uint32_t             cpu_p_blk_len; /* P_BLK length (must be 6). */
83     struct acpi_cx       cpu_cx_states[MAX_CX_STATES];
84     int                  cpu_cx_count;  /* Number of valid Cx states. */
85     int                  cpu_prev_sleep;/* Last idle sleep duration. */
86     int                  cpu_features;  /* Child driver supported features. */
87     /* Runtime state. */
88     int                  cpu_non_c2;    /* Index of lowest non-C2 state. */
89     int                  cpu_non_c3;    /* Index of lowest non-C3 state. */
90     u_int                cpu_cx_stats[MAX_CX_STATES];/* Cx usage history. */
91     /* Values for sysctl. */
92     struct sysctl_ctx_list cpu_sysctl_ctx;
93     struct sysctl_oid   *cpu_sysctl_tree;
94     int                  cpu_cx_lowest;
95     int                  cpu_cx_lowest_lim;
96     int                  cpu_disable_idle; /* Disable entry to idle function */
97     char                 cpu_cx_supported[64];
98 };
99
100 struct acpi_cpu_device {
101     struct resource_list        ad_rl;
102 };
103
104 #define CPU_GET_REG(reg, width)                                         \
105     (bus_space_read_ ## width(rman_get_bustag((reg)),                   \
106                       rman_get_bushandle((reg)), 0))
107 #define CPU_SET_REG(reg, width, val)                                    \
108     (bus_space_write_ ## width(rman_get_bustag((reg)),                  \
109                        rman_get_bushandle((reg)), 0, (val)))
110
111 #define PM_USEC(x)       ((x) >> 2)     /* ~4 clocks per usec (3.57955 Mhz) */
112
113 #define ACPI_NOTIFY_CX_STATES   0x81    /* _CST changed. */
114
115 #define CPU_QUIRK_NO_C3         (1<<0)  /* C3-type states are not usable. */
116 #define CPU_QUIRK_NO_BM_CTRL    (1<<2)  /* No bus mastering control. */
117
118 #define PCI_VENDOR_INTEL        0x8086
119 #define PCI_DEVICE_82371AB_3    0x7113  /* PIIX4 chipset for quirks. */
120 #define PCI_REVISION_A_STEP     0
121 #define PCI_REVISION_B_STEP     1
122 #define PCI_REVISION_4E         2
123 #define PCI_REVISION_4M         3
124 #define PIIX4_DEVACTB_REG       0x58
125 #define PIIX4_BRLD_EN_IRQ0      (1<<0)
126 #define PIIX4_BRLD_EN_IRQ       (1<<1)
127 #define PIIX4_BRLD_EN_IRQ8      (1<<5)
128 #define PIIX4_STOP_BREAK_MASK   (PIIX4_BRLD_EN_IRQ0 | PIIX4_BRLD_EN_IRQ | PIIX4_BRLD_EN_IRQ8)
129 #define PIIX4_PCNTRL_BST_EN     (1<<10)
130
131 /* Allow users to ignore processor orders in MADT. */
132 static int cpu_unordered;
133 SYSCTL_INT(_debug_acpi, OID_AUTO, cpu_unordered, CTLFLAG_RDTUN,
134     &cpu_unordered, 0,
135     "Do not use the MADT to match ACPI Processor objects to CPUs.");
136
137 /* Knob to disable acpi_cpu devices */
138 bool acpi_cpu_disabled = false;
139
140 /* Platform hardware resource information. */
141 static uint32_t          cpu_smi_cmd;   /* Value to write to SMI_CMD. */
142 static uint8_t           cpu_cst_cnt;   /* Indicate we are _CST aware. */
143 static int               cpu_quirks;    /* Indicate any hardware bugs. */
144
145 /* Values for sysctl. */
146 static struct sysctl_ctx_list cpu_sysctl_ctx;
147 static struct sysctl_oid *cpu_sysctl_tree;
148 static int               cpu_cx_generic;
149 static int               cpu_cx_lowest_lim;
150
151 static device_t         *cpu_devices;
152 static int               cpu_ndevices;
153 static struct acpi_cpu_softc **cpu_softc;
154 ACPI_SERIAL_DECL(cpu, "ACPI CPU");
155
156 static int      acpi_cpu_probe(device_t dev);
157 static int      acpi_cpu_attach(device_t dev);
158 static int      acpi_cpu_suspend(device_t dev);
159 static int      acpi_cpu_resume(device_t dev);
160 static int      acpi_pcpu_get_id(device_t dev, uint32_t *acpi_id,
161                     uint32_t *cpu_id);
162 static struct resource_list *acpi_cpu_get_rlist(device_t dev, device_t child);
163 static device_t acpi_cpu_add_child(device_t dev, u_int order, const char *name,
164                     int unit);
165 static int      acpi_cpu_read_ivar(device_t dev, device_t child, int index,
166                     uintptr_t *result);
167 static int      acpi_cpu_shutdown(device_t dev);
168 static void     acpi_cpu_cx_probe(struct acpi_cpu_softc *sc);
169 static void     acpi_cpu_generic_cx_probe(struct acpi_cpu_softc *sc);
170 static int      acpi_cpu_cx_cst(struct acpi_cpu_softc *sc);
171 static void     acpi_cpu_startup(void *arg);
172 static void     acpi_cpu_startup_cx(struct acpi_cpu_softc *sc);
173 static void     acpi_cpu_cx_list(struct acpi_cpu_softc *sc);
174 static void     acpi_cpu_idle(sbintime_t sbt);
175 static void     acpi_cpu_notify(ACPI_HANDLE h, UINT32 notify, void *context);
176 static int      acpi_cpu_quirks(void);
177 static int      acpi_cpu_usage_sysctl(SYSCTL_HANDLER_ARGS);
178 static int      acpi_cpu_usage_counters_sysctl(SYSCTL_HANDLER_ARGS);
179 static int      acpi_cpu_set_cx_lowest(struct acpi_cpu_softc *sc);
180 static int      acpi_cpu_cx_lowest_sysctl(SYSCTL_HANDLER_ARGS);
181 static int      acpi_cpu_global_cx_lowest_sysctl(SYSCTL_HANDLER_ARGS);
182
183 static device_method_t acpi_cpu_methods[] = {
184     /* Device interface */
185     DEVMETHOD(device_probe,     acpi_cpu_probe),
186     DEVMETHOD(device_attach,    acpi_cpu_attach),
187     DEVMETHOD(device_detach,    bus_generic_detach),
188     DEVMETHOD(device_shutdown,  acpi_cpu_shutdown),
189     DEVMETHOD(device_suspend,   acpi_cpu_suspend),
190     DEVMETHOD(device_resume,    acpi_cpu_resume),
191
192     /* Bus interface */
193     DEVMETHOD(bus_add_child,    acpi_cpu_add_child),
194     DEVMETHOD(bus_read_ivar,    acpi_cpu_read_ivar),
195     DEVMETHOD(bus_get_resource_list, acpi_cpu_get_rlist),
196     DEVMETHOD(bus_get_resource, bus_generic_rl_get_resource),
197     DEVMETHOD(bus_set_resource, bus_generic_rl_set_resource),
198     DEVMETHOD(bus_alloc_resource, bus_generic_rl_alloc_resource),
199     DEVMETHOD(bus_release_resource, bus_generic_rl_release_resource),
200     DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
201     DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
202     DEVMETHOD(bus_setup_intr,   bus_generic_setup_intr),
203     DEVMETHOD(bus_teardown_intr, bus_generic_teardown_intr),
204
205     DEVMETHOD_END
206 };
207
208 static driver_t acpi_cpu_driver = {
209     "cpu",
210     acpi_cpu_methods,
211     sizeof(struct acpi_cpu_softc),
212 };
213
214 static devclass_t acpi_cpu_devclass;
215 DRIVER_MODULE(cpu, acpi, acpi_cpu_driver, acpi_cpu_devclass, 0, 0);
216 MODULE_DEPEND(cpu, acpi, 1, 1, 1);
217
218 static int
219 acpi_cpu_probe(device_t dev)
220 {
221     int                    acpi_id, cpu_id;
222     ACPI_BUFFER            buf;
223     ACPI_HANDLE            handle;
224     ACPI_OBJECT            *obj;
225     ACPI_STATUS            status;
226
227     if (acpi_disabled("cpu") || acpi_get_type(dev) != ACPI_TYPE_PROCESSOR ||
228             acpi_cpu_disabled)
229         return (ENXIO);
230
231     handle = acpi_get_handle(dev);
232     if (cpu_softc == NULL)
233         cpu_softc = malloc(sizeof(struct acpi_cpu_softc *) *
234             (mp_maxid + 1), M_TEMP /* XXX */, M_WAITOK | M_ZERO);
235
236     /* Get our Processor object. */
237     buf.Pointer = NULL;
238     buf.Length = ACPI_ALLOCATE_BUFFER;
239     status = AcpiEvaluateObject(handle, NULL, NULL, &buf);
240     if (ACPI_FAILURE(status)) {
241         device_printf(dev, "probe failed to get Processor obj - %s\n",
242                       AcpiFormatException(status));
243         return (ENXIO);
244     }
245     obj = (ACPI_OBJECT *)buf.Pointer;
246     if (obj->Type != ACPI_TYPE_PROCESSOR) {
247         device_printf(dev, "Processor object has bad type %d\n", obj->Type);
248         AcpiOsFree(obj);
249         return (ENXIO);
250     }
251
252     /*
253      * Find the processor associated with our unit.  We could use the
254      * ProcId as a key, however, some boxes do not have the same values
255      * in their Processor object as the ProcId values in the MADT.
256      */
257     acpi_id = obj->Processor.ProcId;
258     AcpiOsFree(obj);
259     if (acpi_pcpu_get_id(dev, &acpi_id, &cpu_id) != 0)
260         return (ENXIO);
261
262     /*
263      * Check if we already probed this processor.  We scan the bus twice
264      * so it's possible we've already seen this one.
265      */
266     if (cpu_softc[cpu_id] != NULL)
267         return (ENXIO);
268
269     /* Mark this processor as in-use and save our derived id for attach. */
270     cpu_softc[cpu_id] = (void *)1;
271     acpi_set_private(dev, (void*)(intptr_t)cpu_id);
272     device_set_desc(dev, "ACPI CPU");
273
274     return (0);
275 }
276
277 static int
278 acpi_cpu_attach(device_t dev)
279 {
280     ACPI_BUFFER            buf;
281     ACPI_OBJECT            arg[4], *obj;
282     ACPI_OBJECT_LIST       arglist;
283     struct pcpu            *pcpu_data;
284     struct acpi_cpu_softc *sc;
285     struct acpi_softc     *acpi_sc;
286     ACPI_STATUS            status;
287     u_int                  features;
288     int                    cpu_id, drv_count, i;
289     driver_t              **drivers;
290     uint32_t               cap_set[3];
291
292     /* UUID needed by _OSC evaluation */
293     static uint8_t cpu_oscuuid[16] = { 0x16, 0xA6, 0x77, 0x40, 0x0C, 0x29,
294                                        0xBE, 0x47, 0x9E, 0xBD, 0xD8, 0x70,
295                                        0x58, 0x71, 0x39, 0x53 };
296
297     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
298
299     sc = device_get_softc(dev);
300     sc->cpu_dev = dev;
301     sc->cpu_handle = acpi_get_handle(dev);
302     cpu_id = (int)(intptr_t)acpi_get_private(dev);
303     cpu_softc[cpu_id] = sc;
304     pcpu_data = pcpu_find(cpu_id);
305     pcpu_data->pc_device = dev;
306     sc->cpu_pcpu = pcpu_data;
307     cpu_smi_cmd = AcpiGbl_FADT.SmiCommand;
308     cpu_cst_cnt = AcpiGbl_FADT.CstControl;
309
310     buf.Pointer = NULL;
311     buf.Length = ACPI_ALLOCATE_BUFFER;
312     status = AcpiEvaluateObject(sc->cpu_handle, NULL, NULL, &buf);
313     if (ACPI_FAILURE(status)) {
314         device_printf(dev, "attach failed to get Processor obj - %s\n",
315                       AcpiFormatException(status));
316         return (ENXIO);
317     }
318     obj = (ACPI_OBJECT *)buf.Pointer;
319     sc->cpu_p_blk = obj->Processor.PblkAddress;
320     sc->cpu_p_blk_len = obj->Processor.PblkLength;
321     sc->cpu_acpi_id = obj->Processor.ProcId;
322     AcpiOsFree(obj);
323     ACPI_DEBUG_PRINT((ACPI_DB_INFO, "acpi_cpu%d: P_BLK at %#x/%d\n",
324                      device_get_unit(dev), sc->cpu_p_blk, sc->cpu_p_blk_len));
325
326     /*
327      * If this is the first cpu we attach, create and initialize the generic
328      * resources that will be used by all acpi cpu devices.
329      */
330     if (device_get_unit(dev) == 0) {
331         /* Assume we won't be using generic Cx mode by default */
332         cpu_cx_generic = FALSE;
333
334         /* Install hw.acpi.cpu sysctl tree */
335         acpi_sc = acpi_device_get_parent_softc(dev);
336         sysctl_ctx_init(&cpu_sysctl_ctx);
337         cpu_sysctl_tree = SYSCTL_ADD_NODE(&cpu_sysctl_ctx,
338             SYSCTL_CHILDREN(acpi_sc->acpi_sysctl_tree), OID_AUTO, "cpu",
339             CTLFLAG_RD, 0, "node for CPU children");
340
341         /* Queue post cpu-probing task handler */
342         AcpiOsExecute(OSL_NOTIFY_HANDLER, acpi_cpu_startup, NULL);
343     }
344
345     /*
346      * Before calling any CPU methods, collect child driver feature hints
347      * and notify ACPI of them.  We support unified SMP power control
348      * so advertise this ourselves.  Note this is not the same as independent
349      * SMP control where each CPU can have different settings.
350      */
351     sc->cpu_features = ACPI_CAP_SMP_SAME | ACPI_CAP_SMP_SAME_C3;
352     if (devclass_get_drivers(acpi_cpu_devclass, &drivers, &drv_count) == 0) {
353         for (i = 0; i < drv_count; i++) {
354             if (ACPI_GET_FEATURES(drivers[i], &features) == 0)
355                 sc->cpu_features |= features;
356         }
357         free(drivers, M_TEMP);
358     }
359
360     /*
361      * CPU capabilities are specified in
362      * Intel Processor Vendor-Specific ACPI Interface Specification.
363      */
364     if (sc->cpu_features) {
365         arglist.Pointer = arg;
366         arglist.Count = 4;
367         arg[0].Type = ACPI_TYPE_BUFFER;
368         arg[0].Buffer.Length = sizeof(cpu_oscuuid);
369         arg[0].Buffer.Pointer = cpu_oscuuid;    /* UUID */
370         arg[1].Type = ACPI_TYPE_INTEGER;
371         arg[1].Integer.Value = 1;               /* revision */
372         arg[2].Type = ACPI_TYPE_INTEGER;
373         arg[2].Integer.Value = 1;               /* count */
374         arg[3].Type = ACPI_TYPE_BUFFER;
375         arg[3].Buffer.Length = sizeof(cap_set); /* Capabilities buffer */
376         arg[3].Buffer.Pointer = (uint8_t *)cap_set;
377         cap_set[0] = 0;                         /* status */
378         cap_set[1] = sc->cpu_features;
379         status = AcpiEvaluateObject(sc->cpu_handle, "_OSC", &arglist, NULL);
380         if (ACPI_SUCCESS(status)) {
381             if (cap_set[0] != 0)
382                 device_printf(dev, "_OSC returned status %#x\n", cap_set[0]);
383         }
384         else {
385             arglist.Pointer = arg;
386             arglist.Count = 1;
387             arg[0].Type = ACPI_TYPE_BUFFER;
388             arg[0].Buffer.Length = sizeof(cap_set);
389             arg[0].Buffer.Pointer = (uint8_t *)cap_set;
390             cap_set[0] = 1; /* revision */
391             cap_set[1] = 1; /* number of capabilities integers */
392             cap_set[2] = sc->cpu_features;
393             AcpiEvaluateObject(sc->cpu_handle, "_PDC", &arglist, NULL);
394         }
395     }
396
397     /* Probe for Cx state support. */
398     acpi_cpu_cx_probe(sc);
399
400     return (0);
401 }
402
403 static void
404 acpi_cpu_postattach(void *unused __unused)
405 {
406     device_t *devices;
407     int err;
408     int i, n;
409
410     err = devclass_get_devices(acpi_cpu_devclass, &devices, &n);
411     if (err != 0) {
412         printf("devclass_get_devices(acpi_cpu_devclass) failed\n");
413         return;
414     }
415     for (i = 0; i < n; i++)
416         bus_generic_probe(devices[i]);
417     for (i = 0; i < n; i++)
418         bus_generic_attach(devices[i]);
419     free(devices, M_TEMP);
420 }
421
422 SYSINIT(acpi_cpu, SI_SUB_CONFIGURE, SI_ORDER_MIDDLE,
423     acpi_cpu_postattach, NULL);
424
425 static void
426 disable_idle(struct acpi_cpu_softc *sc)
427 {
428     cpuset_t cpuset;
429
430     CPU_SETOF(sc->cpu_pcpu->pc_cpuid, &cpuset);
431     sc->cpu_disable_idle = TRUE;
432
433     /*
434      * Ensure that the CPU is not in idle state or in acpi_cpu_idle().
435      * Note that this code depends on the fact that the rendezvous IPI
436      * can not penetrate context where interrupts are disabled and acpi_cpu_idle
437      * is called and executed in such a context with interrupts being re-enabled
438      * right before return.
439      */
440     smp_rendezvous_cpus(cpuset, smp_no_rendevous_barrier, NULL,
441         smp_no_rendevous_barrier, NULL);
442 }
443
444 static void
445 enable_idle(struct acpi_cpu_softc *sc)
446 {
447
448     sc->cpu_disable_idle = FALSE;
449 }
450
451 static int
452 is_idle_disabled(struct acpi_cpu_softc *sc)
453 {
454
455     return (sc->cpu_disable_idle);
456 }
457
458 /*
459  * Disable any entry to the idle function during suspend and re-enable it
460  * during resume.
461  */
462 static int
463 acpi_cpu_suspend(device_t dev)
464 {
465     int error;
466
467     error = bus_generic_suspend(dev);
468     if (error)
469         return (error);
470     disable_idle(device_get_softc(dev));
471     return (0);
472 }
473
474 static int
475 acpi_cpu_resume(device_t dev)
476 {
477
478     enable_idle(device_get_softc(dev));
479     return (bus_generic_resume(dev));
480 }
481
482 /*
483  * Find the processor associated with a given ACPI ID.  By default,
484  * use the MADT to map ACPI IDs to APIC IDs and use that to locate a
485  * processor.  Some systems have inconsistent ASL and MADT however.
486  * For these systems the cpu_unordered tunable can be set in which
487  * case we assume that Processor objects are listed in the same order
488  * in both the MADT and ASL.
489  */
490 static int
491 acpi_pcpu_get_id(device_t dev, uint32_t *acpi_id, uint32_t *cpu_id)
492 {
493     struct pcpu *pc;
494     uint32_t     i, idx;
495
496     KASSERT(acpi_id != NULL, ("Null acpi_id"));
497     KASSERT(cpu_id != NULL, ("Null cpu_id"));
498     idx = device_get_unit(dev);
499
500     /*
501      * If pc_acpi_id for CPU 0 is not initialized (e.g. a non-APIC
502      * UP box) use the ACPI ID from the first processor we find.
503      */
504     if (idx == 0 && mp_ncpus == 1) {
505         pc = pcpu_find(0);
506         if (pc->pc_acpi_id == 0xffffffff)
507             pc->pc_acpi_id = *acpi_id;
508         *cpu_id = 0;
509         return (0);
510     }
511
512     CPU_FOREACH(i) {
513         pc = pcpu_find(i);
514         KASSERT(pc != NULL, ("no pcpu data for %d", i));
515         if (cpu_unordered) {
516             if (idx-- == 0) {
517                 /*
518                  * If pc_acpi_id doesn't match the ACPI ID from the
519                  * ASL, prefer the MADT-derived value.
520                  */
521                 if (pc->pc_acpi_id != *acpi_id)
522                     *acpi_id = pc->pc_acpi_id;
523                 *cpu_id = pc->pc_cpuid;
524                 return (0);
525             }
526         } else {
527             if (pc->pc_acpi_id == *acpi_id) {
528                 if (bootverbose)
529                     device_printf(dev,
530                         "Processor %s (ACPI ID %u) -> APIC ID %d\n",
531                         acpi_name(acpi_get_handle(dev)), *acpi_id,
532                         pc->pc_cpuid);
533                 *cpu_id = pc->pc_cpuid;
534                 return (0);
535             }
536         }
537     }
538
539     if (bootverbose)
540         printf("ACPI: Processor %s (ACPI ID %u) ignored\n",
541             acpi_name(acpi_get_handle(dev)), *acpi_id);
542
543     return (ESRCH);
544 }
545
546 static struct resource_list *
547 acpi_cpu_get_rlist(device_t dev, device_t child)
548 {
549     struct acpi_cpu_device *ad;
550
551     ad = device_get_ivars(child);
552     if (ad == NULL)
553         return (NULL);
554     return (&ad->ad_rl);
555 }
556
557 static device_t
558 acpi_cpu_add_child(device_t dev, u_int order, const char *name, int unit)
559 {
560     struct acpi_cpu_device *ad;
561     device_t child;
562
563     if ((ad = malloc(sizeof(*ad), M_TEMP, M_NOWAIT | M_ZERO)) == NULL)
564         return (NULL);
565
566     resource_list_init(&ad->ad_rl);
567     
568     child = device_add_child_ordered(dev, order, name, unit);
569     if (child != NULL)
570         device_set_ivars(child, ad);
571     else
572         free(ad, M_TEMP);
573     return (child);
574 }
575
576 static int
577 acpi_cpu_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
578 {
579     struct acpi_cpu_softc *sc;
580
581     sc = device_get_softc(dev);
582     switch (index) {
583     case ACPI_IVAR_HANDLE:
584         *result = (uintptr_t)sc->cpu_handle;
585         break;
586     case CPU_IVAR_PCPU:
587         *result = (uintptr_t)sc->cpu_pcpu;
588         break;
589 #if defined(__amd64__) || defined(__i386__)
590     case CPU_IVAR_NOMINAL_MHZ:
591         if (tsc_is_invariant) {
592             *result = (uintptr_t)(atomic_load_acq_64(&tsc_freq) / 1000000);
593             break;
594         }
595         /* FALLTHROUGH */
596 #endif
597     default:
598         return (ENOENT);
599     }
600     return (0);
601 }
602
603 static int
604 acpi_cpu_shutdown(device_t dev)
605 {
606     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
607
608     /* Allow children to shutdown first. */
609     bus_generic_shutdown(dev);
610
611     /*
612      * Disable any entry to the idle function.
613      */
614     disable_idle(device_get_softc(dev));
615
616     /*
617      * CPU devices are not truely detached and remain referenced,
618      * so their resources are not freed.
619      */
620
621     return_VALUE (0);
622 }
623
624 static void
625 acpi_cpu_cx_probe(struct acpi_cpu_softc *sc)
626 {
627     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
628
629     /* Use initial sleep value of 1 sec. to start with lowest idle state. */
630     sc->cpu_prev_sleep = 1000000;
631     sc->cpu_cx_lowest = 0;
632     sc->cpu_cx_lowest_lim = 0;
633
634     /*
635      * Check for the ACPI 2.0 _CST sleep states object. If we can't find
636      * any, we'll revert to generic FADT/P_BLK Cx control method which will
637      * be handled by acpi_cpu_startup. We need to defer to after having
638      * probed all the cpus in the system before probing for generic Cx
639      * states as we may already have found cpus with valid _CST packages
640      */
641     if (!cpu_cx_generic && acpi_cpu_cx_cst(sc) != 0) {
642         /*
643          * We were unable to find a _CST package for this cpu or there
644          * was an error parsing it. Switch back to generic mode.
645          */
646         cpu_cx_generic = TRUE;
647         if (bootverbose)
648             device_printf(sc->cpu_dev, "switching to generic Cx mode\n");
649     }
650
651     /*
652      * TODO: _CSD Package should be checked here.
653      */
654 }
655
656 static void
657 acpi_cpu_generic_cx_probe(struct acpi_cpu_softc *sc)
658 {
659     ACPI_GENERIC_ADDRESS         gas;
660     struct acpi_cx              *cx_ptr;
661
662     sc->cpu_cx_count = 0;
663     cx_ptr = sc->cpu_cx_states;
664
665     /* Use initial sleep value of 1 sec. to start with lowest idle state. */
666     sc->cpu_prev_sleep = 1000000;
667
668     /* C1 has been required since just after ACPI 1.0 */
669     cx_ptr->type = ACPI_STATE_C1;
670     cx_ptr->trans_lat = 0;
671     cx_ptr++;
672     sc->cpu_non_c2 = sc->cpu_cx_count;
673     sc->cpu_non_c3 = sc->cpu_cx_count;
674     sc->cpu_cx_count++;
675     cpu_deepest_sleep = 1;
676
677     /* 
678      * The spec says P_BLK must be 6 bytes long.  However, some systems
679      * use it to indicate a fractional set of features present so we
680      * take 5 as C2.  Some may also have a value of 7 to indicate
681      * another C3 but most use _CST for this (as required) and having
682      * "only" C1-C3 is not a hardship.
683      */
684     if (sc->cpu_p_blk_len < 5)
685         return; 
686
687     /* Validate and allocate resources for C2 (P_LVL2). */
688     gas.SpaceId = ACPI_ADR_SPACE_SYSTEM_IO;
689     gas.BitWidth = 8;
690     if (AcpiGbl_FADT.C2Latency <= 100) {
691         gas.Address = sc->cpu_p_blk + 4;
692         cx_ptr->res_rid = 0;
693         acpi_bus_alloc_gas(sc->cpu_dev, &cx_ptr->res_type, &cx_ptr->res_rid,
694             &gas, &cx_ptr->p_lvlx, RF_SHAREABLE);
695         if (cx_ptr->p_lvlx != NULL) {
696             cx_ptr->type = ACPI_STATE_C2;
697             cx_ptr->trans_lat = AcpiGbl_FADT.C2Latency;
698             cx_ptr++;
699             sc->cpu_non_c3 = sc->cpu_cx_count;
700             sc->cpu_cx_count++;
701             cpu_deepest_sleep = 2;
702         }
703     }
704     if (sc->cpu_p_blk_len < 6)
705         return;
706
707     /* Validate and allocate resources for C3 (P_LVL3). */
708     if (AcpiGbl_FADT.C3Latency <= 1000 && !(cpu_quirks & CPU_QUIRK_NO_C3)) {
709         gas.Address = sc->cpu_p_blk + 5;
710         cx_ptr->res_rid = 1;
711         acpi_bus_alloc_gas(sc->cpu_dev, &cx_ptr->res_type, &cx_ptr->res_rid,
712             &gas, &cx_ptr->p_lvlx, RF_SHAREABLE);
713         if (cx_ptr->p_lvlx != NULL) {
714             cx_ptr->type = ACPI_STATE_C3;
715             cx_ptr->trans_lat = AcpiGbl_FADT.C3Latency;
716             cx_ptr++;
717             sc->cpu_cx_count++;
718             cpu_deepest_sleep = 3;
719         }
720     }
721 }
722
723 /*
724  * Parse a _CST package and set up its Cx states.  Since the _CST object
725  * can change dynamically, our notify handler may call this function
726  * to clean up and probe the new _CST package.
727  */
728 static int
729 acpi_cpu_cx_cst(struct acpi_cpu_softc *sc)
730 {
731     struct       acpi_cx *cx_ptr;
732     ACPI_STATUS  status;
733     ACPI_BUFFER  buf;
734     ACPI_OBJECT *top;
735     ACPI_OBJECT *pkg;
736     uint32_t     count;
737     int          i;
738
739     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
740
741     buf.Pointer = NULL;
742     buf.Length = ACPI_ALLOCATE_BUFFER;
743     status = AcpiEvaluateObject(sc->cpu_handle, "_CST", NULL, &buf);
744     if (ACPI_FAILURE(status))
745         return (ENXIO);
746
747     /* _CST is a package with a count and at least one Cx package. */
748     top = (ACPI_OBJECT *)buf.Pointer;
749     if (!ACPI_PKG_VALID(top, 2) || acpi_PkgInt32(top, 0, &count) != 0) {
750         device_printf(sc->cpu_dev, "invalid _CST package\n");
751         AcpiOsFree(buf.Pointer);
752         return (ENXIO);
753     }
754     if (count != top->Package.Count - 1) {
755         device_printf(sc->cpu_dev, "invalid _CST state count (%d != %d)\n",
756                count, top->Package.Count - 1);
757         count = top->Package.Count - 1;
758     }
759     if (count > MAX_CX_STATES) {
760         device_printf(sc->cpu_dev, "_CST has too many states (%d)\n", count);
761         count = MAX_CX_STATES;
762     }
763
764     sc->cpu_non_c2 = 0;
765     sc->cpu_non_c3 = 0;
766     sc->cpu_cx_count = 0;
767     cx_ptr = sc->cpu_cx_states;
768
769     /*
770      * C1 has been required since just after ACPI 1.0.
771      * Reserve the first slot for it.
772      */
773     cx_ptr->type = ACPI_STATE_C0;
774     cx_ptr++;
775     sc->cpu_cx_count++;
776     cpu_deepest_sleep = 1;
777
778     /* Set up all valid states. */
779     for (i = 0; i < count; i++) {
780         pkg = &top->Package.Elements[i + 1];
781         if (!ACPI_PKG_VALID(pkg, 4) ||
782             acpi_PkgInt32(pkg, 1, &cx_ptr->type) != 0 ||
783             acpi_PkgInt32(pkg, 2, &cx_ptr->trans_lat) != 0 ||
784             acpi_PkgInt32(pkg, 3, &cx_ptr->power) != 0) {
785
786             device_printf(sc->cpu_dev, "skipping invalid Cx state package\n");
787             continue;
788         }
789
790         /* Validate the state to see if we should use it. */
791         switch (cx_ptr->type) {
792         case ACPI_STATE_C1:
793             if (sc->cpu_cx_states[0].type == ACPI_STATE_C0) {
794                 /* This is the first C1 state.  Use the reserved slot. */
795                 sc->cpu_cx_states[0] = *cx_ptr;
796             } else {
797                 sc->cpu_non_c2 = sc->cpu_cx_count;
798                 sc->cpu_non_c3 = sc->cpu_cx_count;
799                 cx_ptr++;
800                 sc->cpu_cx_count++;
801             }
802             continue;
803         case ACPI_STATE_C2:
804             sc->cpu_non_c3 = sc->cpu_cx_count;
805             if (cpu_deepest_sleep < 2)
806                     cpu_deepest_sleep = 2;
807             break;
808         case ACPI_STATE_C3:
809         default:
810             if ((cpu_quirks & CPU_QUIRK_NO_C3) != 0) {
811                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
812                                  "acpi_cpu%d: C3[%d] not available.\n",
813                                  device_get_unit(sc->cpu_dev), i));
814                 continue;
815             } else
816                 cpu_deepest_sleep = 3;
817             break;
818         }
819
820         /* Free up any previous register. */
821         if (cx_ptr->p_lvlx != NULL) {
822             bus_release_resource(sc->cpu_dev, cx_ptr->res_type, cx_ptr->res_rid,
823                 cx_ptr->p_lvlx);
824             cx_ptr->p_lvlx = NULL;
825         }
826
827         /* Allocate the control register for C2 or C3. */
828         cx_ptr->res_rid = sc->cpu_cx_count;
829         acpi_PkgGas(sc->cpu_dev, pkg, 0, &cx_ptr->res_type, &cx_ptr->res_rid,
830             &cx_ptr->p_lvlx, RF_SHAREABLE);
831         if (cx_ptr->p_lvlx) {
832             ACPI_DEBUG_PRINT((ACPI_DB_INFO,
833                              "acpi_cpu%d: Got C%d - %d latency\n",
834                              device_get_unit(sc->cpu_dev), cx_ptr->type,
835                              cx_ptr->trans_lat));
836             cx_ptr++;
837             sc->cpu_cx_count++;
838         }
839     }
840     AcpiOsFree(buf.Pointer);
841
842     /* If C1 state was not found, we need one now. */
843     cx_ptr = sc->cpu_cx_states;
844     if (cx_ptr->type == ACPI_STATE_C0) {
845         cx_ptr->type = ACPI_STATE_C1;
846         cx_ptr->trans_lat = 0;
847     }
848
849     return (0);
850 }
851
852 /*
853  * Call this *after* all CPUs have been attached.
854  */
855 static void
856 acpi_cpu_startup(void *arg)
857 {
858     struct acpi_cpu_softc *sc;
859     int i;
860
861     /* Get set of CPU devices */
862     devclass_get_devices(acpi_cpu_devclass, &cpu_devices, &cpu_ndevices);
863
864     /*
865      * Setup any quirks that might necessary now that we have probed
866      * all the CPUs
867      */
868     acpi_cpu_quirks();
869
870     if (cpu_cx_generic) {
871         /*
872          * We are using generic Cx mode, probe for available Cx states
873          * for all processors.
874          */
875         for (i = 0; i < cpu_ndevices; i++) {
876             sc = device_get_softc(cpu_devices[i]);
877             acpi_cpu_generic_cx_probe(sc);
878         }
879     } else {
880         /*
881          * We are using _CST mode, remove C3 state if necessary.
882          * As we now know for sure that we will be using _CST mode
883          * install our notify handler.
884          */
885         for (i = 0; i < cpu_ndevices; i++) {
886             sc = device_get_softc(cpu_devices[i]);
887             if (cpu_quirks & CPU_QUIRK_NO_C3) {
888                 sc->cpu_cx_count = min(sc->cpu_cx_count, sc->cpu_non_c3 + 1);
889             }
890             AcpiInstallNotifyHandler(sc->cpu_handle, ACPI_DEVICE_NOTIFY,
891                 acpi_cpu_notify, sc);
892         }
893     }
894
895     /* Perform Cx final initialization. */
896     for (i = 0; i < cpu_ndevices; i++) {
897         sc = device_get_softc(cpu_devices[i]);
898         acpi_cpu_startup_cx(sc);
899     }
900
901     /* Add a sysctl handler to handle global Cx lowest setting */
902     SYSCTL_ADD_PROC(&cpu_sysctl_ctx, SYSCTL_CHILDREN(cpu_sysctl_tree),
903         OID_AUTO, "cx_lowest", CTLTYPE_STRING | CTLFLAG_RW,
904         NULL, 0, acpi_cpu_global_cx_lowest_sysctl, "A",
905         "Global lowest Cx sleep state to use");
906
907     /* Take over idling from cpu_idle_default(). */
908     cpu_cx_lowest_lim = 0;
909     for (i = 0; i < cpu_ndevices; i++) {
910         sc = device_get_softc(cpu_devices[i]);
911         enable_idle(sc);
912     }
913     cpu_idle_hook = acpi_cpu_idle;
914 }
915
916 static void
917 acpi_cpu_cx_list(struct acpi_cpu_softc *sc)
918 {
919     struct sbuf sb;
920     int i;
921
922     /*
923      * Set up the list of Cx states
924      */
925     sbuf_new(&sb, sc->cpu_cx_supported, sizeof(sc->cpu_cx_supported),
926         SBUF_FIXEDLEN);
927     for (i = 0; i < sc->cpu_cx_count; i++)
928         sbuf_printf(&sb, "C%d/%d/%d ", i + 1, sc->cpu_cx_states[i].type,
929             sc->cpu_cx_states[i].trans_lat);
930     sbuf_trim(&sb);
931     sbuf_finish(&sb);
932 }       
933
934 static void
935 acpi_cpu_startup_cx(struct acpi_cpu_softc *sc)
936 {
937     acpi_cpu_cx_list(sc);
938     
939     SYSCTL_ADD_STRING(&sc->cpu_sysctl_ctx,
940                       SYSCTL_CHILDREN(device_get_sysctl_tree(sc->cpu_dev)),
941                       OID_AUTO, "cx_supported", CTLFLAG_RD,
942                       sc->cpu_cx_supported, 0,
943                       "Cx/microsecond values for supported Cx states");
944     SYSCTL_ADD_PROC(&sc->cpu_sysctl_ctx,
945                     SYSCTL_CHILDREN(device_get_sysctl_tree(sc->cpu_dev)),
946                     OID_AUTO, "cx_lowest", CTLTYPE_STRING | CTLFLAG_RW,
947                     (void *)sc, 0, acpi_cpu_cx_lowest_sysctl, "A",
948                     "lowest Cx sleep state to use");
949     SYSCTL_ADD_PROC(&sc->cpu_sysctl_ctx,
950                     SYSCTL_CHILDREN(device_get_sysctl_tree(sc->cpu_dev)),
951                     OID_AUTO, "cx_usage", CTLTYPE_STRING | CTLFLAG_RD,
952                     (void *)sc, 0, acpi_cpu_usage_sysctl, "A",
953                     "percent usage for each Cx state");
954     SYSCTL_ADD_PROC(&sc->cpu_sysctl_ctx,
955                     SYSCTL_CHILDREN(device_get_sysctl_tree(sc->cpu_dev)),
956                     OID_AUTO, "cx_usage_counters", CTLTYPE_STRING | CTLFLAG_RD,
957                     (void *)sc, 0, acpi_cpu_usage_counters_sysctl, "A",
958                     "Cx sleep state counters");
959
960     /* Signal platform that we can handle _CST notification. */
961     if (!cpu_cx_generic && cpu_cst_cnt != 0) {
962         ACPI_LOCK(acpi);
963         AcpiOsWritePort(cpu_smi_cmd, cpu_cst_cnt, 8);
964         ACPI_UNLOCK(acpi);
965     }
966 }
967
968 /*
969  * Idle the CPU in the lowest state possible.  This function is called with
970  * interrupts disabled.  Note that once it re-enables interrupts, a task
971  * switch can occur so do not access shared data (i.e. the softc) after
972  * interrupts are re-enabled.
973  */
974 static void
975 acpi_cpu_idle(sbintime_t sbt)
976 {
977     struct      acpi_cpu_softc *sc;
978     struct      acpi_cx *cx_next;
979     uint64_t    cputicks;
980     uint32_t    start_time, end_time;
981     int         bm_active, cx_next_idx, i, us;
982
983     /*
984      * Look up our CPU id to get our softc.  If it's NULL, we'll use C1
985      * since there is no ACPI processor object for this CPU.  This occurs
986      * for logical CPUs in the HTT case.
987      */
988     sc = cpu_softc[PCPU_GET(cpuid)];
989     if (sc == NULL) {
990         acpi_cpu_c1();
991         return;
992     }
993
994     /* If disabled, take the safe path. */
995     if (is_idle_disabled(sc)) {
996         acpi_cpu_c1();
997         return;
998     }
999
1000     /* Find the lowest state that has small enough latency. */
1001     us = sc->cpu_prev_sleep;
1002     if (sbt >= 0 && us > (sbt >> 12))
1003         us = (sbt >> 12);
1004     cx_next_idx = 0;
1005     if (cpu_disable_c2_sleep)
1006         i = min(sc->cpu_cx_lowest, sc->cpu_non_c2);
1007     else if (cpu_disable_c3_sleep)
1008         i = min(sc->cpu_cx_lowest, sc->cpu_non_c3);
1009     else
1010         i = sc->cpu_cx_lowest;
1011     for (; i >= 0; i--) {
1012         if (sc->cpu_cx_states[i].trans_lat * 3 <= us) {
1013             cx_next_idx = i;
1014             break;
1015         }
1016     }
1017
1018     /*
1019      * Check for bus master activity.  If there was activity, clear
1020      * the bit and use the lowest non-C3 state.  Note that the USB
1021      * driver polling for new devices keeps this bit set all the
1022      * time if USB is loaded.
1023      */
1024     if ((cpu_quirks & CPU_QUIRK_NO_BM_CTRL) == 0 &&
1025         cx_next_idx > sc->cpu_non_c3) {
1026         AcpiReadBitRegister(ACPI_BITREG_BUS_MASTER_STATUS, &bm_active);
1027         if (bm_active != 0) {
1028             AcpiWriteBitRegister(ACPI_BITREG_BUS_MASTER_STATUS, 1);
1029             cx_next_idx = sc->cpu_non_c3;
1030         }
1031     }
1032
1033     /* Select the next state and update statistics. */
1034     cx_next = &sc->cpu_cx_states[cx_next_idx];
1035     sc->cpu_cx_stats[cx_next_idx]++;
1036     KASSERT(cx_next->type != ACPI_STATE_C0, ("acpi_cpu_idle: C0 sleep"));
1037
1038     /*
1039      * Execute HLT (or equivalent) and wait for an interrupt.  We can't
1040      * precisely calculate the time spent in C1 since the place we wake up
1041      * is an ISR.  Assume we slept no more then half of quantum, unless
1042      * we are called inside critical section, delaying context switch.
1043      */
1044     if (cx_next->type == ACPI_STATE_C1) {
1045         cputicks = cpu_ticks();
1046         acpi_cpu_c1();
1047         end_time = ((cpu_ticks() - cputicks) << 20) / cpu_tickrate();
1048         if (curthread->td_critnest == 0)
1049                 end_time = min(end_time, 500000 / hz);
1050         sc->cpu_prev_sleep = (sc->cpu_prev_sleep * 3 + end_time) / 4;
1051         return;
1052     }
1053
1054     /*
1055      * For C3, disable bus master arbitration and enable bus master wake
1056      * if BM control is available, otherwise flush the CPU cache.
1057      */
1058     if (cx_next->type == ACPI_STATE_C3) {
1059         if ((cpu_quirks & CPU_QUIRK_NO_BM_CTRL) == 0) {
1060             AcpiWriteBitRegister(ACPI_BITREG_ARB_DISABLE, 1);
1061             AcpiWriteBitRegister(ACPI_BITREG_BUS_MASTER_RLD, 1);
1062         } else
1063             ACPI_FLUSH_CPU_CACHE();
1064     }
1065
1066     /*
1067      * Read from P_LVLx to enter C2(+), checking time spent asleep.
1068      * Use the ACPI timer for measuring sleep time.  Since we need to
1069      * get the time very close to the CPU start/stop clock logic, this
1070      * is the only reliable time source.
1071      */
1072     if (cx_next->type == ACPI_STATE_C3) {
1073         AcpiHwRead(&start_time, &AcpiGbl_FADT.XPmTimerBlock);
1074         cputicks = 0;
1075     } else {
1076         start_time = 0;
1077         cputicks = cpu_ticks();
1078     }
1079     CPU_GET_REG(cx_next->p_lvlx, 1);
1080
1081     /*
1082      * Read the end time twice.  Since it may take an arbitrary time
1083      * to enter the idle state, the first read may be executed before
1084      * the processor has stopped.  Doing it again provides enough
1085      * margin that we are certain to have a correct value.
1086      */
1087     AcpiHwRead(&end_time, &AcpiGbl_FADT.XPmTimerBlock);
1088     if (cx_next->type == ACPI_STATE_C3) {
1089         AcpiHwRead(&end_time, &AcpiGbl_FADT.XPmTimerBlock);
1090         end_time = acpi_TimerDelta(end_time, start_time);
1091     } else
1092         end_time = ((cpu_ticks() - cputicks) << 20) / cpu_tickrate();
1093
1094     /* Enable bus master arbitration and disable bus master wakeup. */
1095     if (cx_next->type == ACPI_STATE_C3 &&
1096         (cpu_quirks & CPU_QUIRK_NO_BM_CTRL) == 0) {
1097         AcpiWriteBitRegister(ACPI_BITREG_ARB_DISABLE, 0);
1098         AcpiWriteBitRegister(ACPI_BITREG_BUS_MASTER_RLD, 0);
1099     }
1100     ACPI_ENABLE_IRQS();
1101
1102     sc->cpu_prev_sleep = (sc->cpu_prev_sleep * 3 + PM_USEC(end_time)) / 4;
1103 }
1104
1105 /*
1106  * Re-evaluate the _CST object when we are notified that it changed.
1107  */
1108 static void
1109 acpi_cpu_notify(ACPI_HANDLE h, UINT32 notify, void *context)
1110 {
1111     struct acpi_cpu_softc *sc = (struct acpi_cpu_softc *)context;
1112
1113     if (notify != ACPI_NOTIFY_CX_STATES)
1114         return;
1115
1116     /*
1117      * C-state data for target CPU is going to be in flux while we execute
1118      * acpi_cpu_cx_cst, so disable entering acpi_cpu_idle.
1119      * Also, it may happen that multiple ACPI taskqueues may concurrently
1120      * execute notifications for the same CPU.  ACPI_SERIAL is used to
1121      * protect against that.
1122      */
1123     ACPI_SERIAL_BEGIN(cpu);
1124     disable_idle(sc);
1125
1126     /* Update the list of Cx states. */
1127     acpi_cpu_cx_cst(sc);
1128     acpi_cpu_cx_list(sc);
1129     acpi_cpu_set_cx_lowest(sc);
1130
1131     enable_idle(sc);
1132     ACPI_SERIAL_END(cpu);
1133
1134     acpi_UserNotify("PROCESSOR", sc->cpu_handle, notify);
1135 }
1136
1137 static int
1138 acpi_cpu_quirks(void)
1139 {
1140     device_t acpi_dev;
1141     uint32_t val;
1142
1143     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1144
1145     /*
1146      * Bus mastering arbitration control is needed to keep caches coherent
1147      * while sleeping in C3.  If it's not present but a working flush cache
1148      * instruction is present, flush the caches before entering C3 instead.
1149      * Otherwise, just disable C3 completely.
1150      */
1151     if (AcpiGbl_FADT.Pm2ControlBlock == 0 ||
1152         AcpiGbl_FADT.Pm2ControlLength == 0) {
1153         if ((AcpiGbl_FADT.Flags & ACPI_FADT_WBINVD) &&
1154             (AcpiGbl_FADT.Flags & ACPI_FADT_WBINVD_FLUSH) == 0) {
1155             cpu_quirks |= CPU_QUIRK_NO_BM_CTRL;
1156             ACPI_DEBUG_PRINT((ACPI_DB_INFO,
1157                 "acpi_cpu: no BM control, using flush cache method\n"));
1158         } else {
1159             cpu_quirks |= CPU_QUIRK_NO_C3;
1160             ACPI_DEBUG_PRINT((ACPI_DB_INFO,
1161                 "acpi_cpu: no BM control, C3 not available\n"));
1162         }
1163     }
1164
1165     /*
1166      * If we are using generic Cx mode, C3 on multiple CPUs requires using
1167      * the expensive flush cache instruction.
1168      */
1169     if (cpu_cx_generic && mp_ncpus > 1) {
1170         cpu_quirks |= CPU_QUIRK_NO_BM_CTRL;
1171         ACPI_DEBUG_PRINT((ACPI_DB_INFO,
1172             "acpi_cpu: SMP, using flush cache mode for C3\n"));
1173     }
1174
1175     /* Look for various quirks of the PIIX4 part. */
1176     acpi_dev = pci_find_device(PCI_VENDOR_INTEL, PCI_DEVICE_82371AB_3);
1177     if (acpi_dev != NULL) {
1178         switch (pci_get_revid(acpi_dev)) {
1179         /*
1180          * Disable C3 support for all PIIX4 chipsets.  Some of these parts
1181          * do not report the BMIDE status to the BM status register and
1182          * others have a livelock bug if Type-F DMA is enabled.  Linux
1183          * works around the BMIDE bug by reading the BM status directly
1184          * but we take the simpler approach of disabling C3 for these
1185          * parts.
1186          *
1187          * See erratum #18 ("C3 Power State/BMIDE and Type-F DMA
1188          * Livelock") from the January 2002 PIIX4 specification update.
1189          * Applies to all PIIX4 models.
1190          *
1191          * Also, make sure that all interrupts cause a "Stop Break"
1192          * event to exit from C2 state.
1193          * Also, BRLD_EN_BM (ACPI_BITREG_BUS_MASTER_RLD in ACPI-speak)
1194          * should be set to zero, otherwise it causes C2 to short-sleep.
1195          * PIIX4 doesn't properly support C3 and bus master activity
1196          * need not break out of C2.
1197          */
1198         case PCI_REVISION_A_STEP:
1199         case PCI_REVISION_B_STEP:
1200         case PCI_REVISION_4E:
1201         case PCI_REVISION_4M:
1202             cpu_quirks |= CPU_QUIRK_NO_C3;
1203             ACPI_DEBUG_PRINT((ACPI_DB_INFO,
1204                 "acpi_cpu: working around PIIX4 bug, disabling C3\n"));
1205
1206             val = pci_read_config(acpi_dev, PIIX4_DEVACTB_REG, 4);
1207             if ((val & PIIX4_STOP_BREAK_MASK) != PIIX4_STOP_BREAK_MASK) {
1208                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
1209                     "acpi_cpu: PIIX4: enabling IRQs to generate Stop Break\n"));
1210                 val |= PIIX4_STOP_BREAK_MASK;
1211                 pci_write_config(acpi_dev, PIIX4_DEVACTB_REG, val, 4);
1212             }
1213             AcpiReadBitRegister(ACPI_BITREG_BUS_MASTER_RLD, &val);
1214             if (val) {
1215                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
1216                     "acpi_cpu: PIIX4: reset BRLD_EN_BM\n"));
1217                 AcpiWriteBitRegister(ACPI_BITREG_BUS_MASTER_RLD, 0);
1218             }
1219             break;
1220         default:
1221             break;
1222         }
1223     }
1224
1225     return (0);
1226 }
1227
1228 static int
1229 acpi_cpu_usage_sysctl(SYSCTL_HANDLER_ARGS)
1230 {
1231     struct acpi_cpu_softc *sc;
1232     struct sbuf  sb;
1233     char         buf[128];
1234     int          i;
1235     uintmax_t    fract, sum, whole;
1236
1237     sc = (struct acpi_cpu_softc *) arg1;
1238     sum = 0;
1239     for (i = 0; i < sc->cpu_cx_count; i++)
1240         sum += sc->cpu_cx_stats[i];
1241     sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
1242     for (i = 0; i < sc->cpu_cx_count; i++) {
1243         if (sum > 0) {
1244             whole = (uintmax_t)sc->cpu_cx_stats[i] * 100;
1245             fract = (whole % sum) * 100;
1246             sbuf_printf(&sb, "%u.%02u%% ", (u_int)(whole / sum),
1247                 (u_int)(fract / sum));
1248         } else
1249             sbuf_printf(&sb, "0.00%% ");
1250     }
1251     sbuf_printf(&sb, "last %dus", sc->cpu_prev_sleep);
1252     sbuf_trim(&sb);
1253     sbuf_finish(&sb);
1254     sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
1255     sbuf_delete(&sb);
1256
1257     return (0);
1258 }
1259
1260 /*
1261  * XXX TODO: actually add support to count each entry/exit
1262  * from the Cx states.
1263  */
1264 static int
1265 acpi_cpu_usage_counters_sysctl(SYSCTL_HANDLER_ARGS)
1266 {
1267     struct acpi_cpu_softc *sc;
1268     struct sbuf  sb;
1269     char         buf[128];
1270     int          i;
1271
1272     sc = (struct acpi_cpu_softc *) arg1;
1273
1274     /* Print out the raw counters */
1275     sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
1276
1277     for (i = 0; i < sc->cpu_cx_count; i++) {
1278         sbuf_printf(&sb, "%u ", sc->cpu_cx_stats[i]);
1279     }
1280
1281     sbuf_trim(&sb);
1282     sbuf_finish(&sb);
1283     sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
1284     sbuf_delete(&sb);
1285
1286     return (0);
1287 }
1288
1289 static int
1290 acpi_cpu_set_cx_lowest(struct acpi_cpu_softc *sc)
1291 {
1292     int i;
1293
1294     ACPI_SERIAL_ASSERT(cpu);
1295     sc->cpu_cx_lowest = min(sc->cpu_cx_lowest_lim, sc->cpu_cx_count - 1);
1296
1297     /* If not disabling, cache the new lowest non-C3 state. */
1298     sc->cpu_non_c3 = 0;
1299     for (i = sc->cpu_cx_lowest; i >= 0; i--) {
1300         if (sc->cpu_cx_states[i].type < ACPI_STATE_C3) {
1301             sc->cpu_non_c3 = i;
1302             break;
1303         }
1304     }
1305
1306     /* Reset the statistics counters. */
1307     bzero(sc->cpu_cx_stats, sizeof(sc->cpu_cx_stats));
1308     return (0);
1309 }
1310
1311 static int
1312 acpi_cpu_cx_lowest_sysctl(SYSCTL_HANDLER_ARGS)
1313 {
1314     struct       acpi_cpu_softc *sc;
1315     char         state[8];
1316     int          val, error;
1317
1318     sc = (struct acpi_cpu_softc *) arg1;
1319     snprintf(state, sizeof(state), "C%d", sc->cpu_cx_lowest_lim + 1);
1320     error = sysctl_handle_string(oidp, state, sizeof(state), req);
1321     if (error != 0 || req->newptr == NULL)
1322         return (error);
1323     if (strlen(state) < 2 || toupper(state[0]) != 'C')
1324         return (EINVAL);
1325     if (strcasecmp(state, "Cmax") == 0)
1326         val = MAX_CX_STATES;
1327     else {
1328         val = (int) strtol(state + 1, NULL, 10);
1329         if (val < 1 || val > MAX_CX_STATES)
1330             return (EINVAL);
1331     }
1332
1333     ACPI_SERIAL_BEGIN(cpu);
1334     sc->cpu_cx_lowest_lim = val - 1;
1335     acpi_cpu_set_cx_lowest(sc);
1336     ACPI_SERIAL_END(cpu);
1337
1338     return (0);
1339 }
1340
1341 static int
1342 acpi_cpu_global_cx_lowest_sysctl(SYSCTL_HANDLER_ARGS)
1343 {
1344     struct      acpi_cpu_softc *sc;
1345     char        state[8];
1346     int         val, error, i;
1347
1348     snprintf(state, sizeof(state), "C%d", cpu_cx_lowest_lim + 1);
1349     error = sysctl_handle_string(oidp, state, sizeof(state), req);
1350     if (error != 0 || req->newptr == NULL)
1351         return (error);
1352     if (strlen(state) < 2 || toupper(state[0]) != 'C')
1353         return (EINVAL);
1354     if (strcasecmp(state, "Cmax") == 0)
1355         val = MAX_CX_STATES;
1356     else {
1357         val = (int) strtol(state + 1, NULL, 10);
1358         if (val < 1 || val > MAX_CX_STATES)
1359             return (EINVAL);
1360     }
1361
1362     /* Update the new lowest useable Cx state for all CPUs. */
1363     ACPI_SERIAL_BEGIN(cpu);
1364     cpu_cx_lowest_lim = val - 1;
1365     for (i = 0; i < cpu_ndevices; i++) {
1366         sc = device_get_softc(cpu_devices[i]);
1367         sc->cpu_cx_lowest_lim = cpu_cx_lowest_lim;
1368         acpi_cpu_set_cx_lowest(sc);
1369     }
1370     ACPI_SERIAL_END(cpu);
1371
1372     return (0);
1373 }