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