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