acpi/cstate: If there is bus master activity pick up non-C3 is enough
[dragonfly.git] / sys / dev / acpica / acpi_cpu_cstate.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  * $FreeBSD: src/sys/dev/acpica/acpi_cpu.c,v 1.72 2008/04/12 12:06:00 rpaulo Exp $
28  */
29
30 #include "opt_acpi.h"
31 #include <sys/param.h>
32 #include <sys/bus.h>
33 #include <sys/kernel.h>
34 #include <sys/malloc.h>
35 #include <sys/globaldata.h>
36 #include <sys/power.h>
37 #include <sys/proc.h>
38 #include <sys/sbuf.h>
39 #include <sys/thread2.h>
40 #include <sys/serialize.h>
41 #include <sys/msgport2.h>
42 #include <sys/microtime_pcpu.h>
43
44 #include <bus/pci/pcivar.h>
45 #include <machine/atomic.h>
46 #include <machine/globaldata.h>
47 #include <machine/md_var.h>
48 #include <machine/smp.h>
49 #include <sys/rman.h>
50
51 #include <net/netisr2.h>
52 #include <net/netmsg2.h>
53 #include <net/if_var.h>
54
55 #include "acpi.h"
56 #include "acpivar.h"
57 #include "acpi_cpu.h"
58
59 /*
60  * Support for ACPI Processor devices, including C[1-3+] sleep states.
61  */
62
63 /* Hooks for the ACPI CA debugging infrastructure */
64 #define _COMPONENT      ACPI_PROCESSOR
65 ACPI_MODULE_NAME("PROCESSOR")
66
67 struct netmsg_acpi_cst {
68         struct netmsg_base base;
69         struct acpi_cst_softc *sc;
70         int             val;
71 };
72
73 struct acpi_cst_cx {
74     uint32_t            type;           /* C1-3+. */
75     uint32_t            trans_lat;      /* Transition latency (usec). */
76     bus_space_tag_t     btag;
77     bus_space_handle_t  bhand;
78
79     struct resource     *p_lvlx;        /* Register to read to enter state. */
80     ACPI_GENERIC_ADDRESS gas;
81     int                 rid;            /* rid of p_lvlx */
82     uint32_t            power;          /* Power consumed (mW). */
83     int                 res_type;       /* Resource type for p_lvlx. */
84 };
85 #define MAX_CX_STATES    8
86
87 struct acpi_cst_softc {
88     device_t            cst_dev;
89     struct acpi_cpux_softc *cst_parent;
90     ACPI_HANDLE         cst_handle;
91     int                 cst_cpuid;
92     uint32_t            cst_flags;      /* ACPI_CST_FLAG_ */
93     uint32_t            cst_p_blk;      /* ACPI P_BLK location */
94     uint32_t            cst_p_blk_len;  /* P_BLK length (must be 6). */
95     struct acpi_cst_cx  cst_cx_states[MAX_CX_STATES];
96     int                 cst_cx_count;   /* Number of valid Cx states. */
97     int                 cst_prev_sleep; /* Last idle sleep duration. */
98     /* Runtime state. */
99     int                 cst_non_c3;     /* Index of lowest non-C3 state. */
100     u_long              cst_cx_stats[MAX_CX_STATES];/* Cx usage history. */
101     /* Values for sysctl. */
102     int                 cst_cx_lowest;  /* Current Cx lowest */
103     int                 cst_cx_lowest_req; /* Requested Cx lowest */
104     char                cst_cx_supported[64];
105 };
106
107 #define ACPI_CST_FLAG_PROBING   0x1
108
109 #define ACPI_CST_ENTER_IO(cx)   bus_space_read_1((cx)->btag, (cx)->bhand, 0)
110
111 #define ACPI_CST_QUIRK_NO_C3    (1<<0)  /* C3-type states are not usable. */
112 #define ACPI_CST_QUIRK_NO_BM_CTRL (1<<2) /* No bus mastering control. */
113
114 #define PCI_VENDOR_INTEL        0x8086
115 #define PCI_DEVICE_82371AB_3    0x7113  /* PIIX4 chipset for quirks. */
116 #define PCI_REVISION_A_STEP     0
117 #define PCI_REVISION_B_STEP     1
118 #define PCI_REVISION_4E         2
119 #define PCI_REVISION_4M         3
120 #define PIIX4_DEVACTB_REG       0x58
121 #define PIIX4_BRLD_EN_IRQ0      (1<<0)
122 #define PIIX4_BRLD_EN_IRQ       (1<<1)
123 #define PIIX4_BRLD_EN_IRQ8      (1<<5)
124 #define PIIX4_STOP_BREAK_MASK   (PIIX4_BRLD_EN_IRQ0 | \
125                                  PIIX4_BRLD_EN_IRQ | \
126                                  PIIX4_BRLD_EN_IRQ8)
127 #define PIIX4_PCNTRL_BST_EN     (1<<10)
128
129 /* Platform hardware resource information. */
130 static uint32_t          acpi_cst_smi_cmd; /* Value to write to SMI_CMD. */
131 static uint8_t           acpi_cst_ctrl; /* Indicate we are _CST aware. */
132 static int               acpi_cst_quirks; /* Indicate any hardware bugs. */
133 static boolean_t         acpi_cst_use_fadt;
134
135 /* Runtime state. */
136 static int               acpi_cst_disable_idle;
137                                         /* Disable entry to idle function */
138 static int               acpi_cst_cx_count; /* Number of valid Cx states */
139
140 /* Values for sysctl. */
141 static int               acpi_cst_cx_lowest; /* Current Cx lowest */
142 static int               acpi_cst_cx_lowest_req; /* Requested Cx lowest */
143
144 /* Number of C3 state requesters */
145 static int               acpi_cst_c3_reqs;
146
147 static device_t         *acpi_cst_devices;
148 static int               acpi_cst_ndevices;
149 static struct acpi_cst_softc **acpi_cst_softc;
150 static struct lwkt_serialize acpi_cst_slize = LWKT_SERIALIZE_INITIALIZER;
151
152 static int      acpi_cst_probe(device_t);
153 static int      acpi_cst_attach(device_t);
154 static int      acpi_cst_suspend(device_t);
155 static int      acpi_cst_resume(device_t);
156 static int      acpi_cst_shutdown(device_t);
157
158 static void     acpi_cst_notify(device_t);
159 static void     acpi_cst_postattach(void *);
160 static void     acpi_cst_idle(void);
161
162 static void     acpi_cst_cx_probe(struct acpi_cst_softc *);
163 static void     acpi_cst_cx_probe_fadt(struct acpi_cst_softc *);
164 static int      acpi_cst_cx_probe_cst(struct acpi_cst_softc *, int);
165 static int      acpi_cst_cx_reprobe_cst(struct acpi_cst_softc *);
166
167 static void     acpi_cst_startup(struct acpi_cst_softc *);
168 static void     acpi_cst_support_list(struct acpi_cst_softc *);
169 static int      acpi_cst_set_lowest(struct acpi_cst_softc *, int);
170 static int      acpi_cst_set_lowest_oncpu(struct acpi_cst_softc *, int);
171 static void     acpi_cst_non_c3(struct acpi_cst_softc *);
172 static void     acpi_cst_global_cx_count(void);
173 static int      acpi_cst_set_quirks(void);
174 static void     acpi_cst_c3_bm_rld(struct acpi_cst_softc *);
175 static void     acpi_cst_c1_halt(void); /* XXX */
176
177 static int      acpi_cst_usage_sysctl(SYSCTL_HANDLER_ARGS);
178 static int      acpi_cst_lowest_sysctl(SYSCTL_HANDLER_ARGS);
179 static int      acpi_cst_lowest_use_sysctl(SYSCTL_HANDLER_ARGS);
180 static int      acpi_cst_global_lowest_sysctl(SYSCTL_HANDLER_ARGS);
181 static int      acpi_cst_global_lowest_use_sysctl(SYSCTL_HANDLER_ARGS);
182
183 static device_method_t acpi_cst_methods[] = {
184     /* Device interface */
185     DEVMETHOD(device_probe,     acpi_cst_probe),
186     DEVMETHOD(device_attach,    acpi_cst_attach),
187     DEVMETHOD(device_detach,    bus_generic_detach),
188     DEVMETHOD(device_shutdown,  acpi_cst_shutdown),
189     DEVMETHOD(device_suspend,   acpi_cst_suspend),
190     DEVMETHOD(device_resume,    acpi_cst_resume),
191
192     /* Bus interface */
193     DEVMETHOD(bus_add_child,    bus_generic_add_child),
194     DEVMETHOD(bus_read_ivar,    bus_generic_read_ivar),
195     DEVMETHOD(bus_get_resource_list, bus_generic_get_resource_list),
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_driver_added, bus_generic_driver_added),
201     DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
202     DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
203     DEVMETHOD(bus_setup_intr,   bus_generic_setup_intr),
204     DEVMETHOD(bus_teardown_intr, bus_generic_teardown_intr),
205     DEVMETHOD_END
206 };
207
208 static driver_t acpi_cst_driver = {
209     "cpu_cst",
210     acpi_cst_methods,
211     sizeof(struct acpi_cst_softc),
212 };
213
214 static devclass_t acpi_cst_devclass;
215 DRIVER_MODULE(cpu_cst, cpu, acpi_cst_driver, acpi_cst_devclass, NULL, NULL);
216 MODULE_DEPEND(cpu_cst, acpi, 1, 1, 1);
217
218 static int
219 acpi_cst_probe(device_t dev)
220 {
221     int cpu_id;
222
223     if (acpi_disabled("cpu_cst") || acpi_get_type(dev) != ACPI_TYPE_PROCESSOR)
224         return (ENXIO);
225
226     cpu_id = acpi_get_magic(dev);
227
228     if (acpi_cst_softc == NULL)
229         acpi_cst_softc = kmalloc(sizeof(struct acpi_cst_softc *) *
230             SMP_MAXCPU, M_TEMP /* XXX */, M_INTWAIT | M_ZERO);
231
232     /*
233      * Check if we already probed this processor.  We scan the bus twice
234      * so it's possible we've already seen this one.
235      */
236     if (acpi_cst_softc[cpu_id] != NULL) {
237         device_printf(dev, "CPU%d cstate already exist\n", cpu_id);
238         return (ENXIO);
239     }
240
241     /* Mark this processor as in-use and save our derived id for attach. */
242     acpi_cst_softc[cpu_id] = (void *)1;
243     device_set_desc(dev, "ACPI CPU C-State");
244
245     return (0);
246 }
247
248 static int
249 acpi_cst_attach(device_t dev)
250 {
251     ACPI_BUFFER            buf;
252     ACPI_OBJECT            *obj;
253     struct acpi_cst_softc *sc;
254     ACPI_STATUS            status;
255
256     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
257
258     sc = device_get_softc(dev);
259     sc->cst_dev = dev;
260     sc->cst_parent = device_get_softc(device_get_parent(dev));
261     sc->cst_handle = acpi_get_handle(dev);
262     sc->cst_cpuid = acpi_get_magic(dev);
263     acpi_cst_softc[sc->cst_cpuid] = sc;
264     acpi_cst_smi_cmd = AcpiGbl_FADT.SmiCommand;
265     acpi_cst_ctrl = AcpiGbl_FADT.CstControl;
266
267     buf.Pointer = NULL;
268     buf.Length = ACPI_ALLOCATE_BUFFER;
269     status = AcpiEvaluateObject(sc->cst_handle, NULL, NULL, &buf);
270     if (ACPI_FAILURE(status)) {
271         device_printf(dev, "attach failed to get Processor obj - %s\n",
272                       AcpiFormatException(status));
273         return (ENXIO);
274     }
275     obj = (ACPI_OBJECT *)buf.Pointer;
276     sc->cst_p_blk = obj->Processor.PblkAddress;
277     sc->cst_p_blk_len = obj->Processor.PblkLength;
278     AcpiOsFree(obj);
279     ACPI_DEBUG_PRINT((ACPI_DB_INFO, "cpu_cst%d: P_BLK at %#x/%d\n",
280                      device_get_unit(dev), sc->cst_p_blk, sc->cst_p_blk_len));
281
282     /*
283      * If this is the first cpu we attach, create and initialize the generic
284      * resources that will be used by all acpi cpu devices.
285      */
286     if (device_get_unit(dev) == 0) {
287         /* Assume we won't be using FADT for Cx states by default */
288         acpi_cst_use_fadt = FALSE;
289
290         /* Queue post cpu-probing task handler */
291         AcpiOsExecute(OSL_NOTIFY_HANDLER, acpi_cst_postattach, NULL);
292     }
293
294     /* Probe for Cx state support. */
295     acpi_cst_cx_probe(sc);
296
297     /* Finally,  call identify and probe/attach for child devices. */
298     bus_generic_probe(dev);
299     bus_generic_attach(dev);
300
301     return (0);
302 }
303
304 /*
305  * Disable any entry to the idle function during suspend and re-enable it
306  * during resume.
307  */
308 static int
309 acpi_cst_suspend(device_t dev)
310 {
311     int error;
312
313     error = bus_generic_suspend(dev);
314     if (error)
315         return (error);
316     acpi_cst_disable_idle = TRUE;
317     return (0);
318 }
319
320 static int
321 acpi_cst_resume(device_t dev)
322 {
323     acpi_cst_disable_idle = FALSE;
324     return (bus_generic_resume(dev));
325 }
326
327 static int
328 acpi_cst_shutdown(device_t dev)
329 {
330     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
331
332     /* Allow children to shutdown first. */
333     bus_generic_shutdown(dev);
334
335     /*
336      * Disable any entry to the idle function.  There is a small race where
337      * an idle thread have passed this check but not gone to sleep.  This
338      * is ok since device_shutdown() does not free the softc, otherwise
339      * we'd have to be sure all threads were evicted before returning.
340      */
341     acpi_cst_disable_idle = TRUE;
342
343     return_VALUE (0);
344 }
345
346 static void
347 acpi_cst_cx_probe(struct acpi_cst_softc *sc)
348 {
349     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
350
351     /* Use initial sleep value of 1 sec. to start with lowest idle state. */
352     sc->cst_prev_sleep = 1000000;
353     sc->cst_cx_lowest = 0;
354     sc->cst_cx_lowest_req = 0;
355
356     /*
357      * Check for the ACPI 2.0 _CST sleep states object.  If we can't find
358      * any, we'll revert to FADT/P_BLK Cx control method which will be
359      * handled by acpi_cst_postattach.  We need to defer to after having
360      * probed all the cpus in the system before probing for Cx states from
361      * FADT as we may already have found cpus with valid _CST packages.
362      */
363     if (!acpi_cst_use_fadt && acpi_cst_cx_probe_cst(sc, 0) != 0) {
364         /*
365          * We were unable to find a _CST package for this cpu or there
366          * was an error parsing it. Switch back to generic mode.
367          */
368         acpi_cst_use_fadt = TRUE;
369         if (bootverbose)
370             device_printf(sc->cst_dev, "switching to FADT Cx mode\n");
371     }
372
373     /*
374      * TODO: _CSD Package should be checked here.
375      */
376 }
377
378 static void
379 acpi_cst_cx_probe_fadt(struct acpi_cst_softc *sc)
380 {
381     struct acpi_cst_cx          *cx_ptr;
382
383     sc->cst_cx_count = 0;
384     cx_ptr = sc->cst_cx_states;
385
386     /* Use initial sleep value of 1 sec. to start with lowest idle state. */
387     sc->cst_prev_sleep = 1000000;
388
389     /* C1 has been required since just after ACPI 1.0 */
390     cx_ptr->gas.SpaceId = ACPI_ADR_SPACE_FIXED_HARDWARE;
391     cx_ptr->type = ACPI_STATE_C1;
392     cx_ptr->trans_lat = 0;
393     cx_ptr++;
394     sc->cst_cx_count++;
395
396     /* C2(+) is not supported on MP system */
397     if (ncpus > 1 && (AcpiGbl_FADT.Flags & ACPI_FADT_C2_MP_SUPPORTED) == 0)
398         return;
399
400     /*
401      * The spec says P_BLK must be 6 bytes long.  However, some systems
402      * use it to indicate a fractional set of features present so we
403      * take 5 as C2.  Some may also have a value of 7 to indicate
404      * another C3 but most use _CST for this (as required) and having
405      * "only" C1-C3 is not a hardship.
406      */
407     if (sc->cst_p_blk_len < 5)
408         return; 
409
410     /* Validate and allocate resources for C2 (P_LVL2). */
411     if (AcpiGbl_FADT.C2Latency <= 100) {
412         cx_ptr->gas.SpaceId = ACPI_ADR_SPACE_SYSTEM_IO;
413         cx_ptr->gas.BitWidth = 8;
414         cx_ptr->gas.Address = sc->cst_p_blk + 4;
415
416         cx_ptr->rid = sc->cst_parent->cpux_next_rid;
417         acpi_bus_alloc_gas(sc->cst_dev, &cx_ptr->res_type, &cx_ptr->rid,
418             &cx_ptr->gas, &cx_ptr->p_lvlx, RF_SHAREABLE);
419         if (cx_ptr->p_lvlx != NULL) {
420             sc->cst_parent->cpux_next_rid++;
421             cx_ptr->type = ACPI_STATE_C2;
422             cx_ptr->trans_lat = AcpiGbl_FADT.C2Latency;
423             cx_ptr->btag = rman_get_bustag(cx_ptr->p_lvlx);
424             cx_ptr->bhand = rman_get_bushandle(cx_ptr->p_lvlx);
425             cx_ptr++;
426             sc->cst_cx_count++;
427             sc->cst_non_c3 = 1;
428         }
429     }
430     if (sc->cst_p_blk_len < 6)
431         return;
432
433     /* Validate and allocate resources for C3 (P_LVL3). */
434     if (AcpiGbl_FADT.C3Latency <= 1000 &&
435         !(acpi_cst_quirks & ACPI_CST_QUIRK_NO_C3)) {
436         cx_ptr->gas.SpaceId = ACPI_ADR_SPACE_SYSTEM_IO;
437         cx_ptr->gas.BitWidth = 8;
438         cx_ptr->gas.Address = sc->cst_p_blk + 5;
439
440         cx_ptr->rid = sc->cst_parent->cpux_next_rid;
441         acpi_bus_alloc_gas(sc->cst_dev, &cx_ptr->res_type, &cx_ptr->rid,
442             &cx_ptr->gas, &cx_ptr->p_lvlx, RF_SHAREABLE);
443         if (cx_ptr->p_lvlx != NULL) {
444             sc->cst_parent->cpux_next_rid++;
445             cx_ptr->type = ACPI_STATE_C3;
446             cx_ptr->trans_lat = AcpiGbl_FADT.C3Latency;
447             cx_ptr->btag = rman_get_bustag(cx_ptr->p_lvlx);
448             cx_ptr->bhand = rman_get_bushandle(cx_ptr->p_lvlx);
449             cx_ptr++;
450             sc->cst_cx_count++;
451         }
452     }
453 }
454
455 /*
456  * Parse a _CST package and set up its Cx states.  Since the _CST object
457  * can change dynamically, our notify handler may call this function
458  * to clean up and probe the new _CST package.
459  */
460 static int
461 acpi_cst_cx_probe_cst(struct acpi_cst_softc *sc, int reprobe)
462 {
463     struct       acpi_cst_cx *cx_ptr;
464     ACPI_STATUS  status;
465     ACPI_BUFFER  buf;
466     ACPI_OBJECT *top;
467     ACPI_OBJECT *pkg;
468     uint32_t     count;
469     int          i;
470
471     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
472
473     if (reprobe)
474         KKASSERT(mycpuid == sc->cst_cpuid);
475
476     buf.Pointer = NULL;
477     buf.Length = ACPI_ALLOCATE_BUFFER;
478     status = AcpiEvaluateObject(sc->cst_handle, "_CST", NULL, &buf);
479     if (ACPI_FAILURE(status))
480         return (ENXIO);
481
482     /* _CST is a package with a count and at least one Cx package. */
483     top = (ACPI_OBJECT *)buf.Pointer;
484     if (!ACPI_PKG_VALID(top, 2) || acpi_PkgInt32(top, 0, &count) != 0) {
485         device_printf(sc->cst_dev, "invalid _CST package\n");
486         AcpiOsFree(buf.Pointer);
487         return (ENXIO);
488     }
489     if (count != top->Package.Count - 1) {
490         device_printf(sc->cst_dev, "invalid _CST state count (%d != %d)\n",
491                count, top->Package.Count - 1);
492         count = top->Package.Count - 1;
493     }
494     if (count > MAX_CX_STATES) {
495         device_printf(sc->cst_dev, "_CST has too many states (%d)\n", count);
496         count = MAX_CX_STATES;
497     }
498
499     sc->cst_flags |= ACPI_CST_FLAG_PROBING;
500     cpu_sfence();
501
502     for (i = 0; i < sc->cst_cx_count; ++i) {
503         cx_ptr = &sc->cst_cx_states[i];
504
505         /* Free up any previous register. */
506         if (cx_ptr->p_lvlx != NULL) {
507             bus_release_resource(sc->cst_dev, cx_ptr->res_type, cx_ptr->rid,
508                 cx_ptr->p_lvlx);
509             cx_ptr->p_lvlx = NULL;
510         }
511     }
512
513     /* Set up all valid states. */
514     sc->cst_cx_count = 0;
515     cx_ptr = sc->cst_cx_states;
516     for (i = 0; i < count; i++) {
517         pkg = &top->Package.Elements[i + 1];
518         if (!ACPI_PKG_VALID(pkg, 4) ||
519             acpi_PkgInt32(pkg, 1, &cx_ptr->type) != 0 ||
520             acpi_PkgInt32(pkg, 2, &cx_ptr->trans_lat) != 0 ||
521             acpi_PkgInt32(pkg, 3, &cx_ptr->power) != 0) {
522
523             device_printf(sc->cst_dev, "skipping invalid Cx state package\n");
524             continue;
525         }
526
527         /* Validate the state to see if we should use it. */
528         switch (cx_ptr->type) {
529         case ACPI_STATE_C1:
530             sc->cst_non_c3 = i;
531             cx_ptr++;
532             sc->cst_cx_count++;
533             continue;
534         case ACPI_STATE_C2:
535             sc->cst_non_c3 = i;
536             break;
537         case ACPI_STATE_C3:
538         default:
539             if ((acpi_cst_quirks & ACPI_CST_QUIRK_NO_C3) != 0) {
540                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
541                                  "cpu_cst%d: C3[%d] not available.\n",
542                                  device_get_unit(sc->cst_dev), i));
543                 continue;
544             }
545             break;
546         }
547
548         /*
549          * Allocate the control register for C2 or C3(+).
550          */
551         KASSERT(cx_ptr->p_lvlx == NULL, ("still has lvlx"));
552         acpi_PkgRawGas(pkg, 0, &cx_ptr->gas);
553
554         cx_ptr->rid = sc->cst_parent->cpux_next_rid;
555         acpi_bus_alloc_gas(sc->cst_dev, &cx_ptr->res_type, &cx_ptr->rid,
556             &cx_ptr->gas, &cx_ptr->p_lvlx, RF_SHAREABLE);
557         if (cx_ptr->p_lvlx != NULL) {
558             sc->cst_parent->cpux_next_rid++;
559             ACPI_DEBUG_PRINT((ACPI_DB_INFO,
560                              "cpu_cst%d: Got C%d - %d latency\n",
561                              device_get_unit(sc->cst_dev), cx_ptr->type,
562                              cx_ptr->trans_lat));
563             cx_ptr->btag = rman_get_bustag(cx_ptr->p_lvlx);
564             cx_ptr->bhand = rman_get_bushandle(cx_ptr->p_lvlx);
565             cx_ptr++;
566             sc->cst_cx_count++;
567         }
568     }
569     AcpiOsFree(buf.Pointer);
570
571     if (reprobe) {
572         /* If there are C3(+) states, always enable bus master wakeup */
573         if ((acpi_cst_quirks & ACPI_CST_QUIRK_NO_BM_CTRL) == 0) {
574             for (i = 0; i < sc->cst_cx_count; ++i) {
575                 struct acpi_cst_cx *cx = &sc->cst_cx_states[i];
576
577                 if (cx->type >= ACPI_STATE_C3) {
578                     AcpiWriteBitRegister(ACPI_BITREG_BUS_MASTER_RLD, 1);
579                     break;
580                 }
581             }
582         }
583
584         /* Fix up the lowest Cx being used */
585         acpi_cst_set_lowest_oncpu(sc, sc->cst_cx_lowest_req);
586     }
587
588     /*
589      * Cache the lowest non-C3 state.
590      * NOTE: must after cst_cx_lowest is set.
591      */
592     acpi_cst_non_c3(sc);
593
594     cpu_sfence();
595     sc->cst_flags &= ~ACPI_CST_FLAG_PROBING;
596
597     return (0);
598 }
599
600 static void
601 acpi_cst_cx_reprobe_cst_handler(netmsg_t msg)
602 {
603     struct netmsg_acpi_cst *rmsg = (struct netmsg_acpi_cst *)msg;
604     int error;
605
606     error = acpi_cst_cx_probe_cst(rmsg->sc, 1);
607     lwkt_replymsg(&rmsg->base.lmsg, error);
608 }
609
610 static int
611 acpi_cst_cx_reprobe_cst(struct acpi_cst_softc *sc)
612 {
613     struct netmsg_acpi_cst msg;
614
615     netmsg_init(&msg.base, NULL, &curthread->td_msgport, MSGF_PRIORITY,
616         acpi_cst_cx_reprobe_cst_handler);
617     msg.sc = sc;
618
619     return lwkt_domsg(netisr_cpuport(sc->cst_cpuid), &msg.base.lmsg, 0);
620 }
621
622 /*
623  * Call this *after* all CPUs Cx states have been attached.
624  */
625 static void
626 acpi_cst_postattach(void *arg)
627 {
628     struct acpi_cst_softc *sc;
629     int i;
630
631     /* Get set of Cx state devices */
632     devclass_get_devices(acpi_cst_devclass, &acpi_cst_devices,
633         &acpi_cst_ndevices);
634
635     /*
636      * Setup any quirks that might necessary now that we have probed
637      * all the CPUs' Cx states.
638      */
639     acpi_cst_set_quirks();
640
641     if (acpi_cst_use_fadt) {
642         /*
643          * We are using Cx mode from FADT, probe for available Cx states
644          * for all processors.
645          */
646         for (i = 0; i < acpi_cst_ndevices; i++) {
647             sc = device_get_softc(acpi_cst_devices[i]);
648             acpi_cst_cx_probe_fadt(sc);
649         }
650     } else {
651         /*
652          * We are using _CST mode, remove C3 state if necessary.
653          *
654          * As we now know for sure that we will be using _CST mode
655          * install our notify handler.
656          */
657         for (i = 0; i < acpi_cst_ndevices; i++) {
658             sc = device_get_softc(acpi_cst_devices[i]);
659             if (acpi_cst_quirks & ACPI_CST_QUIRK_NO_C3)
660                 sc->cst_cx_count = sc->cst_non_c3 + 1;
661             sc->cst_parent->cpux_cst_notify = acpi_cst_notify;
662         }
663     }
664     acpi_cst_global_cx_count();
665
666     /* Perform Cx final initialization. */
667     for (i = 0; i < acpi_cst_ndevices; i++) {
668         sc = device_get_softc(acpi_cst_devices[i]);
669         acpi_cst_startup(sc);
670
671         if (sc->cst_parent->glob_sysctl_tree != NULL) {
672             struct acpi_cpux_softc *cpux = sc->cst_parent;
673
674             /* Add a sysctl handler to handle global Cx lowest setting */
675             SYSCTL_ADD_PROC(&cpux->glob_sysctl_ctx,
676                             SYSCTL_CHILDREN(cpux->glob_sysctl_tree),
677                             OID_AUTO, "cx_lowest",
678                             CTLTYPE_STRING | CTLFLAG_RW, NULL, 0,
679                             acpi_cst_global_lowest_sysctl, "A",
680                             "Requested global lowest Cx sleep state");
681             SYSCTL_ADD_PROC(&cpux->glob_sysctl_ctx,
682                             SYSCTL_CHILDREN(cpux->glob_sysctl_tree),
683                             OID_AUTO, "cx_lowest_use",
684                             CTLTYPE_STRING | CTLFLAG_RD, NULL, 0,
685                             acpi_cst_global_lowest_use_sysctl, "A",
686                             "Global lowest Cx sleep state to use");
687         }
688     }
689
690     /* Take over idling from cpu_idle_default(). */
691     acpi_cst_cx_lowest = 0;
692     acpi_cst_cx_lowest_req = 0;
693     acpi_cst_disable_idle = FALSE;
694     cpu_idle_hook = acpi_cst_idle;
695 }
696
697 static void
698 acpi_cst_support_list(struct acpi_cst_softc *sc)
699 {
700     struct sbuf sb;
701     int i;
702
703     /*
704      * Set up the list of Cx states
705      */
706     sbuf_new(&sb, sc->cst_cx_supported, sizeof(sc->cst_cx_supported),
707         SBUF_FIXEDLEN);
708     for (i = 0; i < sc->cst_cx_count; i++)
709         sbuf_printf(&sb, "C%d/%d ", i + 1, sc->cst_cx_states[i].trans_lat);
710     sbuf_trim(&sb);
711     sbuf_finish(&sb);
712 }       
713
714 static void
715 acpi_cst_c3_bm_rld_handler(netmsg_t msg)
716 {
717     struct netmsg_acpi_cst *rmsg = (struct netmsg_acpi_cst *)msg;
718
719     AcpiWriteBitRegister(ACPI_BITREG_BUS_MASTER_RLD, 1);
720     lwkt_replymsg(&rmsg->base.lmsg, 0);
721 }
722
723 static void
724 acpi_cst_c3_bm_rld(struct acpi_cst_softc *sc)
725 {
726     struct netmsg_acpi_cst msg;
727
728     netmsg_init(&msg.base, NULL, &curthread->td_msgport, MSGF_PRIORITY,
729         acpi_cst_c3_bm_rld_handler);
730     msg.sc = sc;
731
732     lwkt_domsg(netisr_cpuport(sc->cst_cpuid), &msg.base.lmsg, 0);
733 }
734
735 static void
736 acpi_cst_startup(struct acpi_cst_softc *sc)
737 {
738     struct acpi_cpux_softc *cpux = sc->cst_parent;
739
740     /* If there are C3(+) states, always enable bus master wakeup */
741     if ((acpi_cst_quirks & ACPI_CST_QUIRK_NO_BM_CTRL) == 0) {
742         int i;
743
744         for (i = 0; i < sc->cst_cx_count; ++i) {
745             struct acpi_cst_cx *cx = &sc->cst_cx_states[i];
746
747             if (cx->type >= ACPI_STATE_C3) {
748                 acpi_cst_c3_bm_rld(sc);
749                 break;
750             }
751         }
752     }
753
754     acpi_cst_support_list(sc);
755     
756     SYSCTL_ADD_STRING(&cpux->pcpu_sysctl_ctx,
757                       SYSCTL_CHILDREN(cpux->pcpu_sysctl_tree),
758                       OID_AUTO, "cx_supported", CTLFLAG_RD,
759                       sc->cst_cx_supported, 0,
760                       "Cx/microsecond values for supported Cx states");
761     SYSCTL_ADD_PROC(&cpux->pcpu_sysctl_ctx,
762                     SYSCTL_CHILDREN(cpux->pcpu_sysctl_tree),
763                     OID_AUTO, "cx_lowest", CTLTYPE_STRING | CTLFLAG_RW,
764                     (void *)sc, 0, acpi_cst_lowest_sysctl, "A",
765                     "requested lowest Cx sleep state");
766     SYSCTL_ADD_PROC(&cpux->pcpu_sysctl_ctx,
767                     SYSCTL_CHILDREN(cpux->pcpu_sysctl_tree),
768                     OID_AUTO, "cx_lowest_use", CTLTYPE_STRING | CTLFLAG_RD,
769                     (void *)sc, 0, acpi_cst_lowest_use_sysctl, "A",
770                     "lowest Cx sleep state to use");
771     SYSCTL_ADD_PROC(&cpux->pcpu_sysctl_ctx,
772                     SYSCTL_CHILDREN(cpux->pcpu_sysctl_tree),
773                     OID_AUTO, "cx_usage", CTLTYPE_STRING | CTLFLAG_RD,
774                     (void *)sc, 0, acpi_cst_usage_sysctl, "A",
775                     "percent usage for each Cx state");
776
777 #ifdef notyet
778     /* Signal platform that we can handle _CST notification. */
779     if (!acpi_cst_use_fadt && acpi_cst_ctrl != 0) {
780         ACPI_LOCK(acpi);
781         AcpiOsWritePort(acpi_cst_smi_cmd, acpi_cst_ctrl, 8);
782         ACPI_UNLOCK(acpi);
783     }
784 #endif
785 }
786
787 /*
788  * Idle the CPU in the lowest state possible.  This function is called with
789  * interrupts disabled.  Note that once it re-enables interrupts, a task
790  * switch can occur so do not access shared data (i.e. the softc) after
791  * interrupts are re-enabled.
792  */
793 static void
794 acpi_cst_idle(void)
795 {
796     struct      acpi_cst_softc *sc;
797     struct      acpi_cst_cx *cx_next;
798     union microtime_pcpu start, end;
799     uint64_t    dummy;
800     int         bm_active, cx_next_idx, i, tdiff;
801
802     /* If disabled, return immediately. */
803     if (acpi_cst_disable_idle) {
804         ACPI_ENABLE_IRQS();
805         return;
806     }
807
808     /*
809      * Look up our CPU id to get our softc.  If it's NULL, we'll use C1
810      * since there is no Cx state for this processor.
811      */
812     sc = acpi_cst_softc[mdcpu->mi.gd_cpuid];
813     if (sc == NULL) {
814         acpi_cst_c1_halt();
815         return;
816     }
817
818     /* Still probing; use C1 */
819     if (sc->cst_flags & ACPI_CST_FLAG_PROBING) {
820         acpi_cst_c1_halt();
821         return;
822     }
823
824     /* Find the lowest state that has small enough latency. */
825     cx_next_idx = 0;
826     for (i = sc->cst_cx_lowest; i >= 0; i--) {
827         if (sc->cst_cx_states[i].trans_lat * 3 <= sc->cst_prev_sleep) {
828             cx_next_idx = i;
829             break;
830         }
831     }
832
833     /*
834      * If C3(+) is to be entered, check for bus master activity.
835      * If there was activity, clear the bit and use the lowest
836      * non-C3 state.
837      */
838     cx_next = &sc->cst_cx_states[cx_next_idx];
839     if (cx_next->type >= ACPI_STATE_C3 &&
840         (acpi_cst_quirks & ACPI_CST_QUIRK_NO_BM_CTRL) == 0) {
841         AcpiReadBitRegister(ACPI_BITREG_BUS_MASTER_STATUS, &bm_active);
842         if (bm_active != 0) {
843             AcpiWriteBitRegister(ACPI_BITREG_BUS_MASTER_STATUS, 1);
844             cx_next_idx = sc->cst_non_c3;
845         }
846     }
847
848     /* Select the next state and update statistics. */
849     cx_next = &sc->cst_cx_states[cx_next_idx];
850     sc->cst_cx_stats[cx_next_idx]++;
851     KASSERT(cx_next->type != ACPI_STATE_C0, ("C0 sleep"));
852
853     /*
854      * Execute HLT (or equivalent) and wait for an interrupt.  We can't
855      * calculate the time spent in C1 since the place we wake up is an
856      * ISR.  Assume we slept half of quantum and return.
857      */
858     if (cx_next->type == ACPI_STATE_C1) {
859         sc->cst_prev_sleep = (sc->cst_prev_sleep * 3 + 500000 / hz) / 4;
860         acpi_cst_c1_halt();
861         return;
862     }
863
864     /*
865      * For C3(+), disable bus master arbitration if BM control is
866      * available, otherwise flush the CPU cache.
867      */
868     if (cx_next->type >= ACPI_STATE_C3) {
869         if ((acpi_cst_quirks & ACPI_CST_QUIRK_NO_BM_CTRL) == 0)
870             AcpiWriteBitRegister(ACPI_BITREG_ARB_DISABLE, 1);
871         else
872             ACPI_FLUSH_CPU_CACHE();
873     }
874
875     /*
876      * Read from P_LVLx to enter C2(+), checking time spent asleep.
877      */
878     microtime_pcpu_get(&start);
879     cpu_mfence();
880
881     ACPI_CST_ENTER_IO(cx_next);
882     /*
883      * Perform a dummy I/O read.  Since it may take an arbitrary time
884      * to enter the idle state, this read makes sure that we are frozen.
885      */
886     AcpiRead(&dummy, &AcpiGbl_FADT.XPmTimerBlock);
887
888     cpu_mfence();
889     microtime_pcpu_get(&end);
890
891     /* Enable bus master arbitration. */
892     if (cx_next->type >= ACPI_STATE_C3) {
893         if ((acpi_cst_quirks & ACPI_CST_QUIRK_NO_BM_CTRL) == 0)
894             AcpiWriteBitRegister(ACPI_BITREG_ARB_DISABLE, 0);
895     }
896     ACPI_ENABLE_IRQS();
897
898     /* Find the actual time asleep in microseconds. */
899     tdiff = microtime_pcpu_diff(&start, &end);
900     sc->cst_prev_sleep = (sc->cst_prev_sleep * 3 + tdiff) / 4;
901 }
902
903 /*
904  * Re-evaluate the _CST object when we are notified that it changed.
905  */
906 static void
907 acpi_cst_notify(device_t dev)
908 {
909     struct acpi_cst_softc *sc = device_get_softc(dev);
910
911     KASSERT(curthread->td_type != TD_TYPE_NETISR,
912         ("notify in netisr%d", mycpuid));
913
914     lwkt_serialize_enter(&acpi_cst_slize);
915
916     /* Update the list of Cx states. */
917     acpi_cst_cx_reprobe_cst(sc);
918     acpi_cst_support_list(sc);
919
920     /* Update the new lowest useable Cx state for all CPUs. */
921     acpi_cst_global_cx_count();
922
923     /*
924      * Fix up the lowest Cx being used
925      */
926     if (acpi_cst_cx_lowest_req < acpi_cst_cx_count)
927         acpi_cst_cx_lowest = acpi_cst_cx_lowest_req;
928     if (acpi_cst_cx_lowest > acpi_cst_cx_count - 1)
929         acpi_cst_cx_lowest = acpi_cst_cx_count - 1;
930
931     lwkt_serialize_exit(&acpi_cst_slize);
932 }
933
934 static int
935 acpi_cst_set_quirks(void)
936 {
937     device_t acpi_dev;
938     uint32_t val;
939
940     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
941
942     /*
943      * Bus mastering arbitration control is needed to keep caches coherent
944      * while sleeping in C3.  If it's not present but a working flush cache
945      * instruction is present, flush the caches before entering C3 instead.
946      * Otherwise, just disable C3 completely.
947      */
948     if (AcpiGbl_FADT.Pm2ControlBlock == 0 ||
949         AcpiGbl_FADT.Pm2ControlLength == 0) {
950         if ((AcpiGbl_FADT.Flags & ACPI_FADT_WBINVD) &&
951             (AcpiGbl_FADT.Flags & ACPI_FADT_WBINVD_FLUSH) == 0) {
952             acpi_cst_quirks |= ACPI_CST_QUIRK_NO_BM_CTRL;
953             ACPI_DEBUG_PRINT((ACPI_DB_INFO,
954                 "cpu_cst: no BM control, using flush cache method\n"));
955         } else {
956             acpi_cst_quirks |= ACPI_CST_QUIRK_NO_C3;
957             ACPI_DEBUG_PRINT((ACPI_DB_INFO,
958                 "cpu_cst: no BM control, C3 not available\n"));
959         }
960     }
961
962     /*
963      * If we are using FADT Cx mode, C3 on multiple CPUs requires using
964      * the expensive flush cache instruction.
965      */
966     if (acpi_cst_use_fadt && ncpus > 1) {
967         acpi_cst_quirks |= ACPI_CST_QUIRK_NO_BM_CTRL;
968         ACPI_DEBUG_PRINT((ACPI_DB_INFO,
969             "cpu_cst: SMP, using flush cache mode for C3\n"));
970     }
971
972     /* Look for various quirks of the PIIX4 part. */
973     acpi_dev = pci_find_device(PCI_VENDOR_INTEL, PCI_DEVICE_82371AB_3);
974     if (acpi_dev != NULL) {
975         switch (pci_get_revid(acpi_dev)) {
976         /*
977          * Disable C3 support for all PIIX4 chipsets.  Some of these parts
978          * do not report the BMIDE status to the BM status register and
979          * others have a livelock bug if Type-F DMA is enabled.  Linux
980          * works around the BMIDE bug by reading the BM status directly
981          * but we take the simpler approach of disabling C3 for these
982          * parts.
983          *
984          * See erratum #18 ("C3 Power State/BMIDE and Type-F DMA
985          * Livelock") from the January 2002 PIIX4 specification update.
986          * Applies to all PIIX4 models.
987          *
988          * Also, make sure that all interrupts cause a "Stop Break"
989          * event to exit from C2 state.
990          * Also, BRLD_EN_BM (ACPI_BITREG_BUS_MASTER_RLD in ACPI-speak)
991          * should be set to zero, otherwise it causes C2 to short-sleep.
992          * PIIX4 doesn't properly support C3 and bus master activity
993          * need not break out of C2.
994          */
995         case PCI_REVISION_A_STEP:
996         case PCI_REVISION_B_STEP:
997         case PCI_REVISION_4E:
998         case PCI_REVISION_4M:
999             acpi_cst_quirks |= ACPI_CST_QUIRK_NO_C3;
1000             ACPI_DEBUG_PRINT((ACPI_DB_INFO,
1001                 "cpu_cst: working around PIIX4 bug, disabling C3\n"));
1002
1003             val = pci_read_config(acpi_dev, PIIX4_DEVACTB_REG, 4);
1004             if ((val & PIIX4_STOP_BREAK_MASK) != PIIX4_STOP_BREAK_MASK) {
1005                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
1006                     "cpu_cst: PIIX4: enabling IRQs to generate Stop Break\n"));
1007                 val |= PIIX4_STOP_BREAK_MASK;
1008                 pci_write_config(acpi_dev, PIIX4_DEVACTB_REG, val, 4);
1009             }
1010             AcpiReadBitRegister(ACPI_BITREG_BUS_MASTER_RLD, &val);
1011             if (val) {
1012                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
1013                     "cpu_cst: PIIX4: reset BRLD_EN_BM\n"));
1014                 AcpiWriteBitRegister(ACPI_BITREG_BUS_MASTER_RLD, 0);
1015             }
1016             break;
1017         default:
1018             break;
1019         }
1020     }
1021
1022     return (0);
1023 }
1024
1025 static int
1026 acpi_cst_usage_sysctl(SYSCTL_HANDLER_ARGS)
1027 {
1028     struct acpi_cst_softc *sc;
1029     struct sbuf  sb;
1030     char         buf[128];
1031     int          i;
1032     uintmax_t    fract, sum, whole;
1033
1034     sc = (struct acpi_cst_softc *) arg1;
1035     sum = 0;
1036     for (i = 0; i < sc->cst_cx_count; i++)
1037         sum += sc->cst_cx_stats[i];
1038     sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
1039     for (i = 0; i < sc->cst_cx_count; i++) {
1040         if (sum > 0) {
1041             whole = (uintmax_t)sc->cst_cx_stats[i] * 100;
1042             fract = (whole % sum) * 100;
1043             sbuf_printf(&sb, "%u.%02u%% ", (u_int)(whole / sum),
1044                 (u_int)(fract / sum));
1045         } else
1046             sbuf_printf(&sb, "0.00%% ");
1047     }
1048     sbuf_printf(&sb, "last %dus", sc->cst_prev_sleep);
1049     sbuf_trim(&sb);
1050     sbuf_finish(&sb);
1051     sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
1052     sbuf_delete(&sb);
1053
1054     return (0);
1055 }
1056
1057 static int
1058 acpi_cst_set_lowest_oncpu(struct acpi_cst_softc *sc, int val)
1059 {
1060     int old_lowest, error = 0, old_lowest_req;
1061     uint32_t old_type, type;
1062
1063     KKASSERT(mycpuid == sc->cst_cpuid);
1064
1065     old_lowest_req = sc->cst_cx_lowest_req;
1066     sc->cst_cx_lowest_req = val;
1067
1068     if (val > sc->cst_cx_count - 1)
1069         val = sc->cst_cx_count - 1;
1070     old_lowest = atomic_swap_int(&sc->cst_cx_lowest, val);
1071
1072     old_type = sc->cst_cx_states[old_lowest].type;
1073     type = sc->cst_cx_states[val].type;
1074     if (old_type >= ACPI_STATE_C3 && type < ACPI_STATE_C3) {
1075         KKASSERT(acpi_cst_c3_reqs > 0);
1076         if (atomic_fetchadd_int(&acpi_cst_c3_reqs, -1) == 1) {
1077             /*
1078              * All of the CPUs exit C3(+) state, use a better
1079              * one shot timer.
1080              */
1081             error = cputimer_intr_select_caps(CPUTIMER_INTR_CAP_NONE);
1082             KKASSERT(!error || error == ERESTART);
1083             if (error == ERESTART) {
1084                 if (bootverbose)
1085                     kprintf("disable C3(+), restart intr cputimer\n");
1086                 cputimer_intr_restart();
1087             }
1088         }
1089     } else if (type >= ACPI_STATE_C3 && old_type < ACPI_STATE_C3) {
1090         if (atomic_fetchadd_int(&acpi_cst_c3_reqs, 1) == 0) {
1091             /*
1092              * When the first CPU enters C3(+) state, switch
1093              * to an one shot timer, which could handle
1094              * C3(+) state, i.e. the timer will not hang.
1095              */
1096             error = cputimer_intr_select_caps(CPUTIMER_INTR_CAP_PS);
1097             if (error == ERESTART) {
1098                 if (bootverbose)
1099                     kprintf("enable C3(+), restart intr cputimer\n");
1100                 cputimer_intr_restart();
1101             } else if (error) {
1102                 kprintf("no suitable intr cputimer found\n");
1103
1104                 /* Restore */
1105                 sc->cst_cx_lowest_req = old_lowest_req;
1106                 sc->cst_cx_lowest = old_lowest;
1107                 atomic_fetchadd_int(&acpi_cst_c3_reqs, -1);
1108             }
1109         }
1110     }
1111
1112     if (error)
1113         return error;
1114
1115     /* Cache the new lowest non-C3 state. */
1116     acpi_cst_non_c3(sc);
1117
1118     /* Reset the statistics counters. */
1119     bzero(sc->cst_cx_stats, sizeof(sc->cst_cx_stats));
1120     return (0);
1121 }
1122
1123 static void
1124 acpi_cst_set_lowest_handler(netmsg_t msg)
1125 {
1126     struct netmsg_acpi_cst *rmsg = (struct netmsg_acpi_cst *)msg;
1127     int error;
1128
1129     error = acpi_cst_set_lowest_oncpu(rmsg->sc, rmsg->val);
1130     lwkt_replymsg(&rmsg->base.lmsg, error);
1131 }
1132
1133 static int
1134 acpi_cst_set_lowest(struct acpi_cst_softc *sc, int val)
1135 {
1136     struct netmsg_acpi_cst msg;
1137
1138     netmsg_init(&msg.base, NULL, &curthread->td_msgport, MSGF_PRIORITY,
1139         acpi_cst_set_lowest_handler);
1140     msg.sc = sc;
1141     msg.val = val;
1142
1143     return lwkt_domsg(netisr_cpuport(sc->cst_cpuid), &msg.base.lmsg, 0);
1144 }
1145
1146 static int
1147 acpi_cst_lowest_sysctl(SYSCTL_HANDLER_ARGS)
1148 {
1149     struct       acpi_cst_softc *sc;
1150     char         state[8];
1151     int          val, error;
1152
1153     sc = (struct acpi_cst_softc *)arg1;
1154     ksnprintf(state, sizeof(state), "C%d", sc->cst_cx_lowest_req + 1);
1155     error = sysctl_handle_string(oidp, state, sizeof(state), req);
1156     if (error != 0 || req->newptr == NULL)
1157         return (error);
1158     if (strlen(state) < 2 || toupper(state[0]) != 'C')
1159         return (EINVAL);
1160     val = (int) strtol(state + 1, NULL, 10) - 1;
1161     if (val < 0)
1162         return (EINVAL);
1163
1164     lwkt_serialize_enter(&acpi_cst_slize);
1165     error = acpi_cst_set_lowest(sc, val);
1166     lwkt_serialize_exit(&acpi_cst_slize);
1167
1168     return error;
1169 }
1170
1171 static int
1172 acpi_cst_lowest_use_sysctl(SYSCTL_HANDLER_ARGS)
1173 {
1174     struct       acpi_cst_softc *sc;
1175     char         state[8];
1176
1177     sc = (struct acpi_cst_softc *)arg1;
1178     ksnprintf(state, sizeof(state), "C%d", sc->cst_cx_lowest + 1);
1179     return sysctl_handle_string(oidp, state, sizeof(state), req);
1180 }
1181
1182 static int
1183 acpi_cst_global_lowest_sysctl(SYSCTL_HANDLER_ARGS)
1184 {
1185     struct      acpi_cst_softc *sc;
1186     char        state[8];
1187     int         val, error, i;
1188
1189     ksnprintf(state, sizeof(state), "C%d", acpi_cst_cx_lowest_req + 1);
1190     error = sysctl_handle_string(oidp, state, sizeof(state), req);
1191     if (error != 0 || req->newptr == NULL)
1192         return (error);
1193     if (strlen(state) < 2 || toupper(state[0]) != 'C')
1194         return (EINVAL);
1195     val = (int) strtol(state + 1, NULL, 10) - 1;
1196     if (val < 0)
1197         return (EINVAL);
1198
1199     lwkt_serialize_enter(&acpi_cst_slize);
1200
1201     acpi_cst_cx_lowest_req = val;
1202     acpi_cst_cx_lowest = val;
1203     if (acpi_cst_cx_lowest > acpi_cst_cx_count - 1)
1204         acpi_cst_cx_lowest = acpi_cst_cx_count - 1;
1205
1206     /* Update the new lowest useable Cx state for all CPUs. */
1207     for (i = 0; i < acpi_cst_ndevices; i++) {
1208         sc = device_get_softc(acpi_cst_devices[i]);
1209         error = acpi_cst_set_lowest(sc, val);
1210         if (error) {
1211             KKASSERT(i == 0);
1212             break;
1213         }
1214     }
1215
1216     lwkt_serialize_exit(&acpi_cst_slize);
1217
1218     return error;
1219 }
1220
1221 static int
1222 acpi_cst_global_lowest_use_sysctl(SYSCTL_HANDLER_ARGS)
1223 {
1224     char        state[8];
1225
1226     ksnprintf(state, sizeof(state), "C%d", acpi_cst_cx_lowest + 1);
1227     return sysctl_handle_string(oidp, state, sizeof(state), req);
1228 }
1229
1230 /*
1231  * Put the CPU in C1 in a machine-dependant way.
1232  * XXX: shouldn't be here!
1233  */
1234 static void
1235 acpi_cst_c1_halt(void)
1236 {
1237     splz();
1238     if ((mycpu->gd_reqflags & RQF_IDLECHECK_WK_MASK) == 0)
1239         __asm __volatile("sti; hlt");
1240     else
1241         __asm __volatile("sti; pause");
1242 }
1243
1244 static void
1245 acpi_cst_non_c3(struct acpi_cst_softc *sc)
1246 {
1247     int i;
1248
1249     sc->cst_non_c3 = 0;
1250     for (i = sc->cst_cx_lowest; i >= 0; i--) {
1251         if (sc->cst_cx_states[i].type < ACPI_STATE_C3) {
1252             sc->cst_non_c3 = i;
1253             break;
1254         }
1255     }
1256     if (bootverbose)
1257         device_printf(sc->cst_dev, "non-C3 %d\n", sc->cst_non_c3);
1258 }
1259
1260 /*
1261  * Update the largest Cx state supported in the global acpi_cst_cx_count.
1262  * It will be used in the global Cx sysctl handler.
1263  */
1264 static void
1265 acpi_cst_global_cx_count(void)
1266 {
1267     struct acpi_cst_softc *sc;
1268     int i;
1269
1270     if (acpi_cst_ndevices == 0) {
1271         acpi_cst_cx_count = 0;
1272         return;
1273     }
1274
1275     sc = device_get_softc(acpi_cst_devices[0]);
1276     acpi_cst_cx_count = sc->cst_cx_count;
1277
1278     for (i = 1; i < acpi_cst_ndevices; i++) {
1279         struct acpi_cst_softc *sc = device_get_softc(acpi_cst_devices[i]);
1280
1281         if (sc->cst_cx_count < acpi_cst_cx_count)
1282             acpi_cst_cx_count = sc->cst_cx_count;
1283     }
1284     if (bootverbose)
1285         kprintf("cpu_cst: global Cx count %d\n", acpi_cst_cx_count);
1286 }