xref: /freebsd/sys/dev/acpica/acpi_cpu.c (revision 0f8f86b71f022b803e99151c19db81b280f245dc)
1 /*-
2  * Copyright (c) 2003 Nate Lawson (SDG)
3  * Copyright (c) 2001 Michael Smith
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
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/kernel.h>
35 #include <sys/malloc.h>
36 #include <sys/pcpu.h>
37 #include <sys/power.h>
38 #include <sys/proc.h>
39 #include <sys/sbuf.h>
40 #include <sys/smp.h>
41 
42 #include <dev/pci/pcivar.h>
43 #include <machine/atomic.h>
44 #include <machine/bus.h>
45 #ifdef __ia64__
46 #include <machine/pal.h>
47 #endif
48 #include <sys/rman.h>
49 
50 #include "acpi.h"
51 #include <dev/acpica/acpivar.h>
52 
53 /*
54  * Support for ACPI Processor devices, including ACPI 2.0 throttling
55  * and C[1-3] sleep states.
56  *
57  * TODO: implement scans of all CPUs to be sure all Cx states are
58  * equivalent.
59  */
60 
61 /* Hooks for the ACPI CA debugging infrastructure */
62 #define _COMPONENT	ACPI_PROCESSOR
63 ACPI_MODULE_NAME("PROCESSOR")
64 
65 struct acpi_cx {
66     struct resource	*p_lvlx;	/* Register to read to enter state. */
67     uint32_t		 type;		/* C1-3 (C4 and up treated as C3). */
68     uint32_t		 trans_lat;	/* Transition latency (usec). */
69     uint32_t		 power;		/* Power consumed (mW). */
70 };
71 #define MAX_CX_STATES	 8
72 
73 struct acpi_cx_stats {
74     int			 long_slp;	/* Count of sleeps >= trans_lat. */
75     int			 short_slp;	/* Count of sleeps < trans_lat. */
76 };
77 
78 struct acpi_cpu_softc {
79     device_t		 cpu_dev;
80     ACPI_HANDLE		 cpu_handle;
81     uint32_t		 acpi_id;	/* ACPI processor id */
82     uint32_t		 cpu_p_blk;	/* ACPI P_BLK location */
83     uint32_t		 cpu_p_blk_len;	/* P_BLK length (must be 6). */
84     struct resource	*cpu_p_cnt;	/* Throttling control register */
85     struct acpi_cx	 cpu_cx_states[MAX_CX_STATES];
86     int			 cpu_cx_count;	/* Number of valid Cx states. */
87 };
88 
89 #define CPU_GET_REG(reg, width) 					\
90     (bus_space_read_ ## width(rman_get_bustag((reg)), 			\
91 		      rman_get_bushandle((reg)), 0))
92 #define CPU_SET_REG(reg, width, val)					\
93     (bus_space_write_ ## width(rman_get_bustag((reg)), 			\
94 		       rman_get_bushandle((reg)), 0, (val)))
95 
96 /*
97  * Speeds are stored in counts, from 1 to CPU_MAX_SPEED, and
98  * reported to the user in tenths of a percent.
99  */
100 static uint32_t		 cpu_duty_offset;
101 static uint32_t		 cpu_duty_width;
102 #define CPU_MAX_SPEED		(1 << cpu_duty_width)
103 #define CPU_SPEED_PERCENT(x)	((1000 * (x)) / CPU_MAX_SPEED)
104 #define CPU_SPEED_PRINTABLE(x)	(CPU_SPEED_PERCENT(x) / 10),	\
105 				(CPU_SPEED_PERCENT(x) % 10)
106 #define CPU_P_CNT_THT_EN (1<<4)
107 #define PM_USEC(x)	 ((x) >> 2)	/* ~4 clocks per usec (3.57955 Mhz) */
108 
109 #define ACPI_CPU_NOTIFY_PERF_STATES	0x80	/* _PSS changed. */
110 #define ACPI_CPU_NOTIFY_CX_STATES	0x81	/* _CST changed. */
111 
112 #define CPU_QUIRK_NO_C3		0x0001	/* C3-type states are not usable. */
113 #define CPU_QUIRK_NO_THROTTLE	0x0002	/* Throttling is not usable. */
114 
115 #define PCI_VENDOR_INTEL	0x8086
116 #define PCI_DEVICE_82371AB_3	0x7113	/* PIIX4 chipset for quirks. */
117 #define PCI_REVISION_A_STEP	0
118 #define PCI_REVISION_B_STEP	1
119 #define PCI_REVISION_4E		2
120 #define PCI_REVISION_4M		3
121 
122 /* Platform hardware resource information. */
123 static uint32_t		 cpu_smi_cmd;	/* Value to write to SMI_CMD. */
124 static uint8_t		 cpu_pstate_cnt;/* Register to take over throttling. */
125 static uint8_t		 cpu_cst_cnt;	/* Indicate we are _CST aware. */
126 static uint32_t		 cpu_rid;	/* Driver-wide resource id. */
127 static uint32_t		 cpu_quirks;	/* Indicate any hardware bugs. */
128 
129 /* Runtime state. */
130 static int		 cpu_cx_count;	/* Number of valid states */
131 static uint32_t		 cpu_cx_next;	/* State to use for next sleep. */
132 static uint32_t		 cpu_non_c3;	/* Index of lowest non-C3 state. */
133 static struct acpi_cx_stats cpu_cx_stats[MAX_CX_STATES];
134 static int		 cpu_idle_busy;	/* Count of CPUs in acpi_cpu_idle. */
135 
136 /* Values for sysctl. */
137 static uint32_t		 cpu_throttle_state;
138 static uint32_t		 cpu_throttle_max;
139 static int		 cpu_cx_lowest;
140 static char 		 cpu_cx_supported[64];
141 
142 static device_t		*cpu_devices;
143 static int		 cpu_ndevices;
144 static struct acpi_cpu_softc **cpu_softc;
145 
146 static struct sysctl_ctx_list	acpi_cpu_sysctl_ctx;
147 static struct sysctl_oid	*acpi_cpu_sysctl_tree;
148 
149 static int	acpi_cpu_probe(device_t dev);
150 static int	acpi_cpu_attach(device_t dev);
151 static int	acpi_pcpu_get_id(uint32_t idx, uint32_t *acpi_id,
152 				 uint32_t *cpu_id);
153 static int	acpi_cpu_shutdown(device_t dev);
154 static int	acpi_cpu_throttle_probe(struct acpi_cpu_softc *sc);
155 static int	acpi_cpu_cx_probe(struct acpi_cpu_softc *sc);
156 static int	acpi_cpu_cx_cst(struct acpi_cpu_softc *sc);
157 static void	acpi_cpu_startup(void *arg);
158 static void	acpi_cpu_startup_throttling(void);
159 static void	acpi_cpu_startup_cx(void);
160 static void	acpi_cpu_throttle_set(uint32_t speed);
161 static void	acpi_cpu_idle(void);
162 static void	acpi_cpu_c1(void);
163 static void	acpi_pm_ticksub(uint32_t *end, const uint32_t *start);
164 static void	acpi_cpu_notify(ACPI_HANDLE h, UINT32 notify, void *context);
165 static int	acpi_cpu_quirks(struct acpi_cpu_softc *sc);
166 static int	acpi_cpu_throttle_sysctl(SYSCTL_HANDLER_ARGS);
167 static int	acpi_cpu_history_sysctl(SYSCTL_HANDLER_ARGS);
168 static int	acpi_cpu_cx_lowest_sysctl(SYSCTL_HANDLER_ARGS);
169 
170 static device_method_t acpi_cpu_methods[] = {
171     /* Device interface */
172     DEVMETHOD(device_probe,	acpi_cpu_probe),
173     DEVMETHOD(device_attach,	acpi_cpu_attach),
174     DEVMETHOD(device_shutdown,	acpi_cpu_shutdown),
175 
176     {0, 0}
177 };
178 
179 static driver_t acpi_cpu_driver = {
180     "acpi_cpu",
181     acpi_cpu_methods,
182     sizeof(struct acpi_cpu_softc),
183 };
184 
185 static devclass_t acpi_cpu_devclass;
186 DRIVER_MODULE(acpi_cpu, acpi, acpi_cpu_driver, acpi_cpu_devclass, 0, 0);
187 
188 static int
189 acpi_cpu_probe(device_t dev)
190 {
191     if (!acpi_disabled("cpu") && acpi_get_type(dev) == ACPI_TYPE_PROCESSOR) {
192 	device_set_desc(dev, "CPU");
193 	if (cpu_softc == NULL)
194 		cpu_softc = malloc(sizeof(struct acpi_cpu_softc *) *
195 		    (mp_maxid + 1), M_TEMP /* XXX */, M_WAITOK | M_ZERO);
196 	return (0);
197     }
198 
199     return (ENXIO);
200 }
201 
202 static int
203 acpi_cpu_attach(device_t dev)
204 {
205     struct acpi_cpu_softc *sc;
206     struct acpi_softc	  *acpi_sc;
207     ACPI_OBJECT		   pobj;
208     ACPI_BUFFER		   buf;
209     ACPI_STATUS		   status;
210     int			   thr_ret, cx_ret, cpu_id;
211 
212     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
213 
214     ACPI_ASSERTLOCK;
215 
216     sc = device_get_softc(dev);
217     sc->cpu_dev = dev;
218     sc->cpu_handle = acpi_get_handle(dev);
219 
220     /* Get our Processor object. */
221     buf.Pointer = &pobj;
222     buf.Length = sizeof(pobj);
223     status = AcpiEvaluateObject(sc->cpu_handle, NULL, NULL, &buf);
224     if (ACPI_FAILURE(status)) {
225 	device_printf(dev, "Couldn't get Processor object - %s\n",
226 		      AcpiFormatException(status));
227 	return_VALUE (ENXIO);
228     }
229     if (pobj.Type != ACPI_TYPE_PROCESSOR) {
230 	device_printf(dev, "Processor object has bad type %d\n", pobj.Type);
231 	return_VALUE (ENXIO);
232     }
233 
234     /*
235      * Find the processor associated with our unit.  We could use the
236      * ProcId as a key, however, some boxes do not have the same values
237      * in their Processor object as the ProcId values in the MADT.
238      */
239     sc->acpi_id = pobj.Processor.ProcId;
240     if (acpi_pcpu_get_id(device_get_unit(dev), &sc->acpi_id, &cpu_id) != 0)
241 	return_VALUE (ENXIO);
242 
243     /*
244      * Check if we already probed this processor.  We scan the bus twice
245      * so it's possible we've already seen this one.
246      */
247     if (cpu_softc[cpu_id] != NULL)
248 	return (ENXIO);
249     cpu_softc[cpu_id] = sc;
250 
251     /* Get various global values from the Processor object. */
252     sc->cpu_p_blk = pobj.Processor.PblkAddress;
253     sc->cpu_p_blk_len = pobj.Processor.PblkLength;
254     ACPI_DEBUG_PRINT((ACPI_DB_INFO, "acpi_cpu%d: P_BLK at %#x/%d\n",
255 		     device_get_unit(dev), sc->cpu_p_blk, sc->cpu_p_blk_len));
256 
257     acpi_sc = acpi_device_get_parent_softc(dev);
258     sysctl_ctx_init(&acpi_cpu_sysctl_ctx);
259     acpi_cpu_sysctl_tree = SYSCTL_ADD_NODE(&acpi_cpu_sysctl_ctx,
260 				SYSCTL_CHILDREN(acpi_sc->acpi_sysctl_tree),
261 				OID_AUTO, "cpu", CTLFLAG_RD, 0, "");
262 
263     /* If this is the first device probed, check for quirks. */
264     if (device_get_unit(dev) == 0)
265 	acpi_cpu_quirks(sc);
266 
267     /*
268      * Probe for throttling and Cx state support.
269      * If none of these is present, free up unused resources.
270      */
271     thr_ret = acpi_cpu_throttle_probe(sc);
272     cx_ret = acpi_cpu_cx_probe(sc);
273     if (thr_ret == 0 || cx_ret == 0) {
274 	status = AcpiInstallNotifyHandler(sc->cpu_handle, ACPI_DEVICE_NOTIFY,
275 					  acpi_cpu_notify, sc);
276 	if (device_get_unit(dev) == 0)
277 	    AcpiOsQueueForExecution(OSD_PRIORITY_LO, acpi_cpu_startup, NULL);
278     } else {
279 	sysctl_ctx_free(&acpi_cpu_sysctl_ctx);
280     }
281 
282     return_VALUE (0);
283 }
284 
285 /*
286  * Find the nth present CPU and return its pc_cpuid as well as set the
287  * pc_acpi_id from the most reliable source.
288  */
289 static int
290 acpi_pcpu_get_id(uint32_t idx, uint32_t *acpi_id, uint32_t *cpu_id)
291 {
292     struct pcpu	*pcpu_data;
293     uint32_t	 i;
294 
295     KASSERT(acpi_id != NULL, ("Null acpi_id"));
296     KASSERT(cpu_id != NULL, ("Null cpu_id"));
297     for (i = 0; i <= mp_maxid; i++) {
298 	if (CPU_ABSENT(i))
299 	    continue;
300 	pcpu_data = pcpu_find(i);
301 	KASSERT(pcpu_data != NULL, ("no pcpu data for %d", i));
302 	if (idx-- == 0) {
303 	    /*
304 	     * If pc_acpi_id was not initialized (e.g., a non-APIC UP box)
305 	     * override it with the value from the ASL.  Otherwise, if the
306 	     * two don't match, prefer the MADT-derived value.  Finally,
307 	     * return the pc_cpuid to reference this processor.
308 	     */
309 	    if (pcpu_data->pc_acpi_id == 0xffffffff)
310 		 pcpu_data->pc_acpi_id = *acpi_id;
311 	    else if (pcpu_data->pc_acpi_id != *acpi_id)
312 		*acpi_id = pcpu_data->pc_acpi_id;
313 	    *cpu_id = pcpu_data->pc_cpuid;
314 	    return (0);
315 	}
316     }
317 
318     return (ESRCH);
319 }
320 
321 static int
322 acpi_cpu_shutdown(device_t dev)
323 {
324     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
325 
326     /* Disable any entry to the idle function. */
327     cpu_cx_count = 0;
328 
329     /* Wait for all processors to exit acpi_cpu_idle(). */
330     smp_rendezvous(NULL, NULL, NULL, NULL);
331     while (cpu_idle_busy > 0)
332 	DELAY(1);
333 
334     return_VALUE (0);
335 }
336 
337 static int
338 acpi_cpu_throttle_probe(struct acpi_cpu_softc *sc)
339 {
340     uint32_t		 duty_end;
341     ACPI_BUFFER		 buf;
342     ACPI_OBJECT		 obj;
343     ACPI_GENERIC_ADDRESS gas;
344     ACPI_STATUS		 status;
345 
346     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
347 
348     ACPI_ASSERTLOCK;
349 
350     /* Get throttling parameters from the FADT.  0 means not supported. */
351     if (device_get_unit(sc->cpu_dev) == 0) {
352 	cpu_smi_cmd = AcpiGbl_FADT->SmiCmd;
353 	cpu_pstate_cnt = AcpiGbl_FADT->PstateCnt;
354 	cpu_cst_cnt = AcpiGbl_FADT->CstCnt;
355 	cpu_duty_offset = AcpiGbl_FADT->DutyOffset;
356 	cpu_duty_width = AcpiGbl_FADT->DutyWidth;
357     }
358     if (cpu_duty_width == 0 || (cpu_quirks & CPU_QUIRK_NO_THROTTLE) != 0)
359 	return (ENXIO);
360 
361     /* Validate the duty offset/width. */
362     duty_end = cpu_duty_offset + cpu_duty_width - 1;
363     if (duty_end > 31) {
364 	device_printf(sc->cpu_dev, "CLK_VAL field overflows P_CNT register\n");
365 	return (ENXIO);
366     }
367     if (cpu_duty_offset <= 4 && duty_end >= 4) {
368 	device_printf(sc->cpu_dev, "CLK_VAL field overlaps THT_EN bit\n");
369 	return (ENXIO);
370     }
371 
372     /*
373      * If not present, fall back to using the processor's P_BLK to find
374      * the P_CNT register.
375      *
376      * Note that some systems seem to duplicate the P_BLK pointer
377      * across multiple CPUs, so not getting the resource is not fatal.
378      */
379     buf.Pointer = &obj;
380     buf.Length = sizeof(obj);
381     status = AcpiEvaluateObject(sc->cpu_handle, "_PTC", NULL, &buf);
382     if (ACPI_SUCCESS(status)) {
383 	if (obj.Buffer.Length < sizeof(ACPI_GENERIC_ADDRESS) + 3) {
384 	    device_printf(sc->cpu_dev, "_PTC buffer too small\n");
385 	    return (ENXIO);
386 	}
387 	memcpy(&gas, obj.Buffer.Pointer + 3, sizeof(gas));
388 	sc->cpu_p_cnt = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
389 	if (sc->cpu_p_cnt != NULL) {
390 	    ACPI_DEBUG_PRINT((ACPI_DB_INFO, "acpi_cpu%d: P_CNT from _PTC\n",
391 			     device_get_unit(sc->cpu_dev)));
392 	}
393     }
394 
395     /* If _PTC not present or other failure, try the P_BLK. */
396     if (sc->cpu_p_cnt == NULL) {
397 	/*
398 	 * The spec says P_BLK must be 6 bytes long.  However, some
399 	 * systems use it to indicate a fractional set of features
400 	 * present so we take anything >= 4.
401 	 */
402 	if (sc->cpu_p_blk_len < 4)
403 	    return (ENXIO);
404 	gas.Address = sc->cpu_p_blk;
405 	gas.AddressSpaceId = ACPI_ADR_SPACE_SYSTEM_IO;
406 	gas.RegisterBitWidth = 32;
407 	sc->cpu_p_cnt = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
408 	if (sc->cpu_p_cnt != NULL) {
409 	    ACPI_DEBUG_PRINT((ACPI_DB_INFO, "acpi_cpu%d: P_CNT from P_BLK\n",
410 			     device_get_unit(sc->cpu_dev)));
411 	} else {
412 	    device_printf(sc->cpu_dev, "Failed to attach throttling P_CNT\n");
413 	    return (ENXIO);
414 	}
415     }
416     cpu_rid++;
417 
418     return (0);
419 }
420 
421 static int
422 acpi_cpu_cx_probe(struct acpi_cpu_softc *sc)
423 {
424     ACPI_GENERIC_ADDRESS gas;
425     struct acpi_cx	*cx_ptr;
426     int			 error;
427 
428     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
429 
430     /* Bus mastering arbitration control is needed for C3. */
431     if (AcpiGbl_FADT->V1_Pm2CntBlk == 0 || AcpiGbl_FADT->Pm2CntLen == 0) {
432 	cpu_quirks |= CPU_QUIRK_NO_C3;
433 	ACPI_DEBUG_PRINT((ACPI_DB_INFO,
434 			 "acpi_cpu%d: No BM control, C3 disabled\n",
435 			 device_get_unit(sc->cpu_dev)));
436     }
437 
438     /*
439      * First, check for the ACPI 2.0 _CST sleep states object.
440      * If not usable, fall back to the P_BLK's P_LVL2 and P_LVL3.
441      */
442     sc->cpu_cx_count = 0;
443     error = acpi_cpu_cx_cst(sc);
444     if (error != 0) {
445 	cx_ptr = sc->cpu_cx_states;
446 
447 	/* C1 has been required since just after ACPI 1.0 */
448 	cx_ptr->type = ACPI_STATE_C1;
449 	cx_ptr->trans_lat = 0;
450 	cpu_non_c3 = 0;
451 	cx_ptr++;
452 	sc->cpu_cx_count++;
453 
454 	/*
455 	 * The spec says P_BLK must be 6 bytes long.  However, some systems
456 	 * use it to indicate a fractional set of features present so we
457 	 * take 5 as C2.  Some may also have a value of 7 to indicate
458 	 * another C3 but most use _CST for this (as required) and having
459 	 * "only" C1-C3 is not a hardship.
460 	 */
461 	if (sc->cpu_p_blk_len < 5)
462 	    goto done;
463 
464 	/* Validate and allocate resources for C2 (P_LVL2). */
465 	gas.AddressSpaceId = ACPI_ADR_SPACE_SYSTEM_IO;
466 	gas.RegisterBitWidth = 8;
467 	if (AcpiGbl_FADT->Plvl2Lat <= 100) {
468 	    gas.Address = sc->cpu_p_blk + 4;
469 	    cx_ptr->p_lvlx = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
470 	    if (cx_ptr->p_lvlx != NULL) {
471 		cpu_rid++;
472 		cx_ptr->type = ACPI_STATE_C2;
473 		cx_ptr->trans_lat = AcpiGbl_FADT->Plvl2Lat;
474 		cpu_non_c3 = 1;
475 		cx_ptr++;
476 		sc->cpu_cx_count++;
477 	    }
478 	}
479 	if (sc->cpu_p_blk_len < 6)
480 	    goto done;
481 
482 	/* Validate and allocate resources for C3 (P_LVL3). */
483 	if (AcpiGbl_FADT->Plvl3Lat <= 1000 &&
484 	    (cpu_quirks & CPU_QUIRK_NO_C3) == 0) {
485 
486 	    gas.Address = sc->cpu_p_blk + 5;
487 	    cx_ptr->p_lvlx = acpi_bus_alloc_gas(sc->cpu_dev, &cpu_rid, &gas);
488 	    if (cx_ptr->p_lvlx != NULL) {
489 		cpu_rid++;
490 		cx_ptr->type = ACPI_STATE_C3;
491 		cx_ptr->trans_lat = AcpiGbl_FADT->Plvl3Lat;
492 		cx_ptr++;
493 		sc->cpu_cx_count++;
494 	    }
495 	}
496     }
497 
498 done:
499     /* If no valid registers were found, don't attach. */
500     if (sc->cpu_cx_count == 0)
501 	return (ENXIO);
502 
503     return (0);
504 }
505 
506 /*
507  * Parse a _CST package and set up its Cx states.  Since the _CST object
508  * can change dynamically, our notify handler may call this function
509  * to clean up and probe the new _CST package.
510  */
511 static int
512 acpi_cpu_cx_cst(struct acpi_cpu_softc *sc)
513 {
514     struct	 acpi_cx *cx_ptr;
515     ACPI_STATUS	 status;
516     ACPI_BUFFER	 buf;
517     ACPI_OBJECT	*top;
518     ACPI_OBJECT	*pkg;
519     uint32_t	 count;
520     int		 i;
521 
522     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
523 
524     buf.Pointer = NULL;
525     buf.Length = ACPI_ALLOCATE_BUFFER;
526     status = AcpiEvaluateObject(sc->cpu_handle, "_CST", NULL, &buf);
527     if (ACPI_FAILURE(status))
528 	return (ENXIO);
529 
530     /* _CST is a package with a count and at least one Cx package. */
531     top = (ACPI_OBJECT *)buf.Pointer;
532     if (!ACPI_PKG_VALID(top, 2) || acpi_PkgInt32(top, 0, &count) != 0) {
533 	device_printf(sc->cpu_dev, "Invalid _CST package\n");
534 	AcpiOsFree(buf.Pointer);
535 	return (ENXIO);
536     }
537     if (count != top->Package.Count - 1) {
538 	device_printf(sc->cpu_dev, "Invalid _CST state count (%d != %d)\n",
539 	       count, top->Package.Count - 1);
540 	count = top->Package.Count - 1;
541     }
542     if (count > MAX_CX_STATES) {
543 	device_printf(sc->cpu_dev, "_CST has too many states (%d)\n", count);
544 	count = MAX_CX_STATES;
545     }
546 
547     /* Set up all valid states. */
548     sc->cpu_cx_count = 0;
549     cx_ptr = sc->cpu_cx_states;
550     for (i = 0; i < count; i++) {
551 	pkg = &top->Package.Elements[i + 1];
552 	if (!ACPI_PKG_VALID(pkg, 4) ||
553 	    acpi_PkgInt32(pkg, 1, &cx_ptr->type) != 0 ||
554 	    acpi_PkgInt32(pkg, 2, &cx_ptr->trans_lat) != 0 ||
555 	    acpi_PkgInt32(pkg, 3, &cx_ptr->power) != 0) {
556 
557 	    device_printf(sc->cpu_dev, "Skipping invalid Cx state package\n");
558 	    continue;
559 	}
560 
561 	/* Validate the state to see if we should use it. */
562 	switch (cx_ptr->type) {
563 	case ACPI_STATE_C1:
564 	    cpu_non_c3 = i;
565 	    cx_ptr++;
566 	    sc->cpu_cx_count++;
567 	    continue;
568 	case ACPI_STATE_C2:
569 	    if (cx_ptr->trans_lat > 100) {
570 		ACPI_DEBUG_PRINT((ACPI_DB_INFO,
571 				 "acpi_cpu%d: C2[%d] not available.\n",
572 				 device_get_unit(sc->cpu_dev), i));
573 		continue;
574 	    }
575 	    cpu_non_c3 = i;
576 	    break;
577 	case ACPI_STATE_C3:
578 	default:
579 	    if (cx_ptr->trans_lat > 1000 ||
580 		(cpu_quirks & CPU_QUIRK_NO_C3) != 0) {
581 
582 		ACPI_DEBUG_PRINT((ACPI_DB_INFO,
583 				 "acpi_cpu%d: C3[%d] not available.\n",
584 				 device_get_unit(sc->cpu_dev), i));
585 		continue;
586 	    }
587 	    break;
588 	}
589 
590 #ifdef notyet
591 	/* Free up any previous register. */
592 	if (cx_ptr->p_lvlx != NULL) {
593 	    bus_release_resource(sc->cpu_dev, 0, 0, cx_ptr->p_lvlx);
594 	    cx_ptr->p_lvlx = NULL;
595 	}
596 #endif
597 
598 	/* Allocate the control register for C2 or C3. */
599 	acpi_PkgGas(sc->cpu_dev, pkg, 0, &cpu_rid, &cx_ptr->p_lvlx);
600 	if (cx_ptr->p_lvlx != NULL) {
601 	    cpu_rid++;
602 	    ACPI_DEBUG_PRINT((ACPI_DB_INFO,
603 			     "acpi_cpu%d: Got C%d - %d latency\n",
604 			     device_get_unit(sc->cpu_dev), cx_ptr->type,
605 			     cx_ptr->trans_lat));
606 	    cx_ptr++;
607 	    sc->cpu_cx_count++;
608 	}
609     }
610     AcpiOsFree(buf.Pointer);
611 
612     return (0);
613 }
614 
615 /*
616  * Call this *after* all CPUs have been attached.
617  */
618 static void
619 acpi_cpu_startup(void *arg)
620 {
621     struct acpi_cpu_softc *sc;
622     int count, i;
623 
624     /* Get set of CPU devices */
625     devclass_get_devices(acpi_cpu_devclass, &cpu_devices, &cpu_ndevices);
626 
627     /*
628      * Make sure all the processors' Cx counts match.  We should probably
629      * also check the contents of each.  However, no known systems have
630      * non-matching Cx counts so we'll deal with this later.
631      */
632     count = MAX_CX_STATES;
633     for (i = 0; i < cpu_ndevices; i++) {
634 	sc = device_get_softc(cpu_devices[i]);
635 	count = min(sc->cpu_cx_count, count);
636     }
637     cpu_cx_count = count;
638 
639     /* Perform throttling and Cx final initialization. */
640     sc = device_get_softc(cpu_devices[0]);
641     if (sc->cpu_p_cnt != NULL)
642 	acpi_cpu_startup_throttling();
643     if (cpu_cx_count > 0)
644 	acpi_cpu_startup_cx();
645 }
646 
647 /*
648  * Takes the ACPI lock to avoid fighting anyone over the SMI command
649  * port.
650  */
651 static void
652 acpi_cpu_startup_throttling()
653 {
654     ACPI_LOCK_DECL;
655 
656     /* Initialise throttling states */
657     cpu_throttle_max = CPU_MAX_SPEED;
658     cpu_throttle_state = CPU_MAX_SPEED;
659 
660     SYSCTL_ADD_INT(&acpi_cpu_sysctl_ctx,
661 		   SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
662 		   OID_AUTO, "throttle_max", CTLFLAG_RD,
663 		   &cpu_throttle_max, 0, "maximum CPU speed");
664     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx,
665 		    SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
666 		    OID_AUTO, "throttle_state",
667 		    CTLTYPE_INT | CTLFLAG_RW, &cpu_throttle_state,
668 		    0, acpi_cpu_throttle_sysctl, "I", "current CPU speed");
669 
670     /* If ACPI 2.0+, signal platform that we are taking over throttling. */
671     ACPI_LOCK;
672     if (cpu_pstate_cnt != 0)
673 	AcpiOsWritePort(cpu_smi_cmd, cpu_pstate_cnt, 8);
674 
675     /* Set initial speed to maximum. */
676     acpi_cpu_throttle_set(cpu_throttle_max);
677     ACPI_UNLOCK;
678 
679     printf("acpi_cpu: throttling enabled, %d steps (100%% to %d.%d%%), "
680 	   "currently %d.%d%%\n", CPU_MAX_SPEED, CPU_SPEED_PRINTABLE(1),
681 	   CPU_SPEED_PRINTABLE(cpu_throttle_state));
682 }
683 
684 static void
685 acpi_cpu_startup_cx()
686 {
687     struct acpi_cpu_softc *sc;
688     struct sbuf		 sb;
689     int i;
690     ACPI_LOCK_DECL;
691 
692     sc = device_get_softc(cpu_devices[0]);
693     sbuf_new(&sb, cpu_cx_supported, sizeof(cpu_cx_supported), SBUF_FIXEDLEN);
694     for (i = 0; i < cpu_cx_count; i++) {
695 	sbuf_printf(&sb, "C%d/%d ", sc->cpu_cx_states[i].type,
696 		    sc->cpu_cx_states[i].trans_lat);
697     }
698     sbuf_trim(&sb);
699     sbuf_finish(&sb);
700     SYSCTL_ADD_STRING(&acpi_cpu_sysctl_ctx,
701 		      SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
702 		      OID_AUTO, "cx_supported", CTLFLAG_RD, cpu_cx_supported,
703 		      0, "Cx/microsecond values for supported Cx states");
704     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx,
705 		    SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
706 		    OID_AUTO, "cx_lowest", CTLTYPE_INT | CTLFLAG_RW,
707 		    NULL, 0, acpi_cpu_cx_lowest_sysctl, "I",
708 		    "lowest Cx sleep state to use");
709     SYSCTL_ADD_PROC(&acpi_cpu_sysctl_ctx,
710 		    SYSCTL_CHILDREN(acpi_cpu_sysctl_tree),
711 		    OID_AUTO, "cx_history", CTLTYPE_STRING | CTLFLAG_RD,
712 		    NULL, 0, acpi_cpu_history_sysctl, "A",
713 		    "count of full sleeps for Cx state / short sleeps");
714 
715 #ifdef notyet
716     /* Signal platform that we can handle _CST notification. */
717     if (cpu_cst_cnt != 0) {
718 	ACPI_LOCK;
719 	AcpiOsWritePort(cpu_smi_cmd, cpu_cst_cnt, 8);
720 	ACPI_UNLOCK;
721     }
722 #endif
723 
724     /* Take over idling from cpu_idle_default(). */
725     cpu_cx_next = cpu_cx_lowest;
726     cpu_idle_hook = acpi_cpu_idle;
727 }
728 
729 /*
730  * Set CPUs to the new state.
731  *
732  * Must be called with the ACPI lock held.
733  */
734 static void
735 acpi_cpu_throttle_set(uint32_t speed)
736 {
737     struct acpi_cpu_softc	*sc;
738     int				i;
739     uint32_t			p_cnt, clk_val;
740 
741     ACPI_ASSERTLOCK;
742 
743     /* Iterate over processors */
744     for (i = 0; i < cpu_ndevices; i++) {
745 	sc = device_get_softc(cpu_devices[i]);
746 	if (sc->cpu_p_cnt == NULL)
747 	    continue;
748 
749 	/* Get the current P_CNT value and disable throttling */
750 	p_cnt = CPU_GET_REG(sc->cpu_p_cnt, 4);
751 	p_cnt &= ~CPU_P_CNT_THT_EN;
752 	CPU_SET_REG(sc->cpu_p_cnt, 4, p_cnt);
753 
754 	/* If we're at maximum speed, that's all */
755 	if (speed < CPU_MAX_SPEED) {
756 	    /* Mask the old CLK_VAL off and or-in the new value */
757 	    clk_val = (CPU_MAX_SPEED - 1) << cpu_duty_offset;
758 	    p_cnt &= ~clk_val;
759 	    p_cnt |= (speed << cpu_duty_offset);
760 
761 	    /* Write the new P_CNT value and then enable throttling */
762 	    CPU_SET_REG(sc->cpu_p_cnt, 4, p_cnt);
763 	    p_cnt |= CPU_P_CNT_THT_EN;
764 	    CPU_SET_REG(sc->cpu_p_cnt, 4, p_cnt);
765 	}
766 	ACPI_VPRINT(sc->cpu_dev, acpi_device_get_parent_softc(sc->cpu_dev),
767 		    "set speed to %d.%d%%\n", CPU_SPEED_PRINTABLE(speed));
768     }
769     cpu_throttle_state = speed;
770 }
771 
772 /*
773  * Idle the CPU in the lowest state possible.
774  * This function is called with interrupts disabled.
775  */
776 static void
777 acpi_cpu_idle()
778 {
779     struct	acpi_cpu_softc *sc;
780     struct	acpi_cx *cx_next;
781     uint32_t	start_time, end_time;
782     int		bm_active, i, asleep;
783 
784     /* If disabled, return immediately. */
785     if (cpu_cx_count == 0) {
786 	ACPI_ENABLE_IRQS();
787 	return;
788     }
789 
790     /*
791      * Look up our CPU id to get our softc.  If it's NULL, we'll use C1
792      * since there is no ACPI processor object for this CPU.  This occurs
793      * for logical CPUs in the HTT case.
794      */
795     sc = cpu_softc[PCPU_GET(cpuid)];
796     if (sc == NULL) {
797 	acpi_cpu_c1();
798 	return;
799     }
800 
801     /* Record that a CPU is in the idle function. */
802     atomic_add_int(&cpu_idle_busy, 1);
803 
804     /*
805      * Check for bus master activity.  If there was activity, clear
806      * the bit and use the lowest non-C3 state.  Note that the USB
807      * driver polling for new devices keeps this bit set all the
808      * time if USB is enabled.
809      */
810     AcpiGetRegister(ACPI_BITREG_BUS_MASTER_STATUS, &bm_active,
811 		    ACPI_MTX_DO_NOT_LOCK);
812     if (bm_active != 0) {
813 	AcpiSetRegister(ACPI_BITREG_BUS_MASTER_STATUS, 1,
814 			ACPI_MTX_DO_NOT_LOCK);
815 	cpu_cx_next = min(cpu_cx_next, cpu_non_c3);
816     }
817 
818     /* Perform the actual sleep based on the Cx-specific semantics. */
819     cx_next = &sc->cpu_cx_states[cpu_cx_next];
820     switch (cx_next->type) {
821     case ACPI_STATE_C0:
822 	panic("acpi_cpu_idle: attempting to sleep in C0");
823 	/* NOTREACHED */
824     case ACPI_STATE_C1:
825 	/* Execute HLT (or equivalent) and wait for an interrupt. */
826 	acpi_cpu_c1();
827 
828 	/*
829 	 * We can't calculate the time spent in C1 since the place we
830 	 * wake up is an ISR.  Use a constant time of 1 ms.
831 	 */
832 	start_time = 0;
833 	end_time = 1000;
834 	break;
835     case ACPI_STATE_C2:
836 	/*
837 	 * Read from P_LVLx to enter C2, checking time spent asleep.
838 	 * Use the ACPI timer for measuring sleep time.  Since we need to
839 	 * get the time very close to the CPU start/stop clock logic, this
840 	 * is the only reliable time source.
841 	 */
842 	AcpiHwLowLevelRead(32, &start_time, &AcpiGbl_FADT->XPmTmrBlk);
843 	CPU_GET_REG(cx_next->p_lvlx, 1);
844 
845 	/*
846 	 * Read the end time twice.  Since it may take an arbitrary time
847 	 * to enter the idle state, the first read may be executed before
848 	 * the processor has stopped.  Doing it again provides enough
849 	 * margin that we are certain to have a correct value.
850 	 */
851 	AcpiHwLowLevelRead(32, &end_time, &AcpiGbl_FADT->XPmTmrBlk);
852 	AcpiHwLowLevelRead(32, &end_time, &AcpiGbl_FADT->XPmTmrBlk);
853 	ACPI_ENABLE_IRQS();
854 	break;
855     case ACPI_STATE_C3:
856     default:
857 	/* Disable bus master arbitration and enable bus master wakeup. */
858 	AcpiSetRegister(ACPI_BITREG_ARB_DISABLE, 1, ACPI_MTX_DO_NOT_LOCK);
859 	AcpiSetRegister(ACPI_BITREG_BUS_MASTER_RLD, 1, ACPI_MTX_DO_NOT_LOCK);
860 
861 	/* Read from P_LVLx to enter C3, checking time spent asleep. */
862 	AcpiHwLowLevelRead(32, &start_time, &AcpiGbl_FADT->XPmTmrBlk);
863 	CPU_GET_REG(cx_next->p_lvlx, 1);
864 
865 	/* Read the end time twice.  See comment for C2 above. */
866 	AcpiHwLowLevelRead(32, &end_time, &AcpiGbl_FADT->XPmTmrBlk);
867 	AcpiHwLowLevelRead(32, &end_time, &AcpiGbl_FADT->XPmTmrBlk);
868 
869 	/* Enable bus master arbitration and disable bus master wakeup. */
870 	AcpiSetRegister(ACPI_BITREG_ARB_DISABLE, 0, ACPI_MTX_DO_NOT_LOCK);
871 	AcpiSetRegister(ACPI_BITREG_BUS_MASTER_RLD, 0, ACPI_MTX_DO_NOT_LOCK);
872 	ACPI_ENABLE_IRQS();
873 	break;
874     }
875 
876     /* Find the actual time asleep in microseconds, minus overhead. */
877     acpi_pm_ticksub(&end_time, &start_time);
878     asleep = PM_USEC(end_time) - cx_next->trans_lat;
879 
880     /* Record statistics */
881     if (asleep < cx_next->trans_lat)
882 	cpu_cx_stats[cpu_cx_next].short_slp++;
883     else
884 	cpu_cx_stats[cpu_cx_next].long_slp++;
885 
886     /*
887      * If we slept 100 us or more, use the lowest Cx state.
888      * Otherwise, find the lowest state that has a latency less than
889      * or equal to the length of our last sleep.
890      */
891     if (asleep >= 100)
892 	cpu_cx_next = cpu_cx_lowest;
893     else {
894 	for (i = cpu_cx_lowest; i >= 0; i--) {
895 	    if (sc->cpu_cx_states[i].trans_lat <= asleep) {
896 		cpu_cx_next = i;
897 		break;
898 	    }
899 	}
900     }
901 
902     /* Decrement reference count checked by acpi_cpu_shutdown(). */
903     atomic_subtract_int(&cpu_idle_busy, 1);
904 }
905 
906 /* Put the CPU in C1 in a machine-dependant way. */
907 static void
908 acpi_cpu_c1()
909 {
910 #ifdef __ia64__
911     ia64_call_pal_static(PAL_HALT_LIGHT, 0, 0, 0);
912 #else
913     __asm __volatile("sti; hlt");
914 #endif
915 }
916 
917 /* Find the difference between two PM tick counts. */
918 static void
919 acpi_pm_ticksub(uint32_t *end, const uint32_t *start)
920 {
921     if (*end >= *start)
922 	*end = *end - *start;
923     else if (AcpiGbl_FADT->TmrValExt == 0)
924 	*end = (((0x00FFFFFF - *start) + *end + 1) & 0x00FFFFFF);
925     else
926 	*end = ((0xFFFFFFFF - *start) + *end + 1);
927 }
928 
929 /*
930  * Re-evaluate the _PSS and _CST objects when we are notified that they
931  * have changed.
932  *
933  * XXX Re-evaluation disabled until locking is done.
934  */
935 static void
936 acpi_cpu_notify(ACPI_HANDLE h, UINT32 notify, void *context)
937 {
938     struct acpi_cpu_softc *sc = (struct acpi_cpu_softc *)context;
939 
940     switch (notify) {
941     case ACPI_CPU_NOTIFY_PERF_STATES:
942 	device_printf(sc->cpu_dev, "Performance states changed\n");
943 	/* acpi_cpu_px_available(sc); */
944 	break;
945     case ACPI_CPU_NOTIFY_CX_STATES:
946 	device_printf(sc->cpu_dev, "Cx states changed\n");
947 	/* acpi_cpu_cx_cst(sc); */
948 	break;
949     default:
950 	device_printf(sc->cpu_dev, "Unknown notify %#x\n", notify);
951 	break;
952     }
953 }
954 
955 static int
956 acpi_cpu_quirks(struct acpi_cpu_softc *sc)
957 {
958 
959     /*
960      * C3 is not supported on multiple CPUs since this would require
961      * flushing all caches which is currently too expensive.
962      */
963     if (mp_ncpus > 1)
964 	cpu_quirks |= CPU_QUIRK_NO_C3;
965 
966 #ifdef notyet
967     /* Look for various quirks of the PIIX4 part. */
968     acpi_dev = pci_find_device(PCI_VENDOR_INTEL, PCI_DEVICE_82371AB_3);
969     if (acpi_dev != NULL) {
970 	switch (pci_get_revid(acpi_dev)) {
971 	/*
972 	 * Disable throttling control on PIIX4 A and B-step.
973 	 * See specification changes #13 ("Manual Throttle Duty Cycle")
974 	 * and #14 ("Enabling and Disabling Manual Throttle"), plus
975 	 * erratum #5 ("STPCLK# Deassertion Time") from the January
976 	 * 2002 PIIX4 specification update.  Note that few (if any)
977 	 * mobile systems ever used this part.
978 	 */
979 	case PCI_REVISION_A_STEP:
980 	case PCI_REVISION_B_STEP:
981 	    cpu_quirks |= CPU_QUIRK_NO_THROTTLE;
982 	    /* FALLTHROUGH */
983 	/*
984 	 * Disable C3 support for all PIIX4 chipsets.  Some of these parts
985 	 * do not report the BMIDE status to the BM status register and
986 	 * others have a livelock bug if Type-F DMA is enabled.  Linux
987 	 * works around the BMIDE bug by reading the BM status directly
988 	 * but we take the simpler approach of disabling C3 for these
989 	 * parts.
990 	 *
991 	 * See erratum #18 ("C3 Power State/BMIDE and Type-F DMA
992 	 * Livelock") from the January 2002 PIIX4 specification update.
993 	 * Applies to all PIIX4 models.
994 	 */
995 	case PCI_REVISION_4E:
996 	case PCI_REVISION_4M:
997 	    cpu_quirks |= CPU_QUIRK_NO_C3;
998 	    break;
999 	default:
1000 	    break;
1001 	}
1002     }
1003 #endif
1004 
1005     return (0);
1006 }
1007 
1008 /* Handle changes in the CPU throttling setting. */
1009 static int
1010 acpi_cpu_throttle_sysctl(SYSCTL_HANDLER_ARGS)
1011 {
1012     uint32_t	*argp;
1013     uint32_t	 arg;
1014     int		 error;
1015     ACPI_LOCK_DECL;
1016 
1017     argp = (uint32_t *)oidp->oid_arg1;
1018     arg = *argp;
1019     error = sysctl_handle_int(oidp, &arg, 0, req);
1020 
1021     /* Error or no new value */
1022     if (error != 0 || req->newptr == NULL)
1023 	return (error);
1024     if (arg < 1 || arg > cpu_throttle_max)
1025 	return (EINVAL);
1026 
1027     /* If throttling changed, notify the BIOS of the new rate. */
1028     ACPI_LOCK;
1029     if (*argp != arg) {
1030 	*argp = arg;
1031 	acpi_cpu_throttle_set(arg);
1032     }
1033     ACPI_UNLOCK;
1034 
1035     return (0);
1036 }
1037 
1038 static int
1039 acpi_cpu_history_sysctl(SYSCTL_HANDLER_ARGS)
1040 {
1041     struct sbuf	 sb;
1042     char	 buf[128];
1043     int		 i;
1044 
1045     sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
1046     for (i = 0; i < cpu_cx_count; i++) {
1047 	sbuf_printf(&sb, "%u/%u ", cpu_cx_stats[i].long_slp,
1048 		    cpu_cx_stats[i].short_slp);
1049     }
1050     sbuf_trim(&sb);
1051     sbuf_finish(&sb);
1052     sysctl_handle_string(oidp, sbuf_data(&sb), 0, req);
1053 
1054     return (0);
1055 }
1056 
1057 static int
1058 acpi_cpu_cx_lowest_sysctl(SYSCTL_HANDLER_ARGS)
1059 {
1060     struct	 acpi_cpu_softc *sc;
1061     int		 val, error, i;
1062 
1063     sc = device_get_softc(cpu_devices[0]);
1064     val = cpu_cx_lowest;
1065     error = sysctl_handle_int(oidp, &val, 0, req);
1066     if (error != 0 || req->newptr == NULL)
1067 	return (error);
1068     if (val < 0 || val > cpu_cx_count - 1)
1069 	return (EINVAL);
1070 
1071     /* Use the new value for the next idle slice. */
1072     cpu_cx_lowest = val;
1073     cpu_cx_next = val;
1074 
1075     /* If not disabling, cache the new lowest non-C3 state. */
1076     cpu_non_c3 = 0;
1077     for (i = cpu_cx_lowest; i >= 0; i--) {
1078 	if (sc->cpu_cx_states[i].type < ACPI_STATE_C3) {
1079 	    cpu_non_c3 = i;
1080 	    break;
1081 	}
1082     }
1083 
1084     /* Reset the statistics counters. */
1085     memset(cpu_cx_stats, 0, sizeof(cpu_cx_stats));
1086 
1087     return (0);
1088 }
1089