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