]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/acpica/acpi.c
MFV r358616:
[FreeBSD/FreeBSD.git] / sys / dev / acpica / acpi.c
1 /*-
2  * Copyright (c) 2000 Takanori Watanabe <takawata@jp.freebsd.org>
3  * Copyright (c) 2000 Mitsuru IWASAKI <iwasaki@jp.freebsd.org>
4  * Copyright (c) 2000, 2001 Michael Smith
5  * Copyright (c) 2000 BSDi
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include "opt_acpi.h"
34
35 #include <sys/param.h>
36 #include <sys/eventhandler.h>
37 #include <sys/kernel.h>
38 #include <sys/proc.h>
39 #include <sys/fcntl.h>
40 #include <sys/malloc.h>
41 #include <sys/module.h>
42 #include <sys/bus.h>
43 #include <sys/conf.h>
44 #include <sys/ioccom.h>
45 #include <sys/reboot.h>
46 #include <sys/sysctl.h>
47 #include <sys/ctype.h>
48 #include <sys/linker.h>
49 #include <sys/power.h>
50 #include <sys/sbuf.h>
51 #include <sys/sched.h>
52 #include <sys/smp.h>
53 #include <sys/timetc.h>
54
55 #if defined(__i386__) || defined(__amd64__)
56 #include <machine/clock.h>
57 #include <machine/pci_cfgreg.h>
58 #endif
59 #include <machine/resource.h>
60 #include <machine/bus.h>
61 #include <sys/rman.h>
62 #include <isa/isavar.h>
63 #include <isa/pnpvar.h>
64
65 #include <contrib/dev/acpica/include/acpi.h>
66 #include <contrib/dev/acpica/include/accommon.h>
67 #include <contrib/dev/acpica/include/acnamesp.h>
68
69 #include <dev/acpica/acpivar.h>
70 #include <dev/acpica/acpiio.h>
71
72 #include <dev/pci/pcivar.h>
73
74 #include <vm/vm_param.h>
75
76 static MALLOC_DEFINE(M_ACPIDEV, "acpidev", "ACPI devices");
77
78 /* Hooks for the ACPI CA debugging infrastructure */
79 #define _COMPONENT      ACPI_BUS
80 ACPI_MODULE_NAME("ACPI")
81
82 static d_open_t         acpiopen;
83 static d_close_t        acpiclose;
84 static d_ioctl_t        acpiioctl;
85
86 static struct cdevsw acpi_cdevsw = {
87         .d_version =    D_VERSION,
88         .d_open =       acpiopen,
89         .d_close =      acpiclose,
90         .d_ioctl =      acpiioctl,
91         .d_name =       "acpi",
92 };
93
94 struct acpi_interface {
95         ACPI_STRING     *data;
96         int             num;
97 };
98
99 static char *sysres_ids[] = { "PNP0C01", "PNP0C02", NULL };
100 static char *pcilink_ids[] = { "PNP0C0F", NULL };
101
102 /* Global mutex for locking access to the ACPI subsystem. */
103 struct mtx      acpi_mutex;
104 struct callout  acpi_sleep_timer;
105
106 /* Bitmap of device quirks. */
107 int             acpi_quirks;
108
109 /* Supported sleep states. */
110 static BOOLEAN  acpi_sleep_states[ACPI_S_STATE_COUNT];
111
112 static void     acpi_lookup(void *arg, const char *name, device_t *dev);
113 static int      acpi_modevent(struct module *mod, int event, void *junk);
114 static int      acpi_probe(device_t dev);
115 static int      acpi_attach(device_t dev);
116 static int      acpi_suspend(device_t dev);
117 static int      acpi_resume(device_t dev);
118 static int      acpi_shutdown(device_t dev);
119 static device_t acpi_add_child(device_t bus, u_int order, const char *name,
120                         int unit);
121 static int      acpi_print_child(device_t bus, device_t child);
122 static void     acpi_probe_nomatch(device_t bus, device_t child);
123 static void     acpi_driver_added(device_t dev, driver_t *driver);
124 static int      acpi_read_ivar(device_t dev, device_t child, int index,
125                         uintptr_t *result);
126 static int      acpi_write_ivar(device_t dev, device_t child, int index,
127                         uintptr_t value);
128 static struct resource_list *acpi_get_rlist(device_t dev, device_t child);
129 static void     acpi_reserve_resources(device_t dev);
130 static int      acpi_sysres_alloc(device_t dev);
131 static int      acpi_set_resource(device_t dev, device_t child, int type,
132                         int rid, rman_res_t start, rman_res_t count);
133 static struct resource *acpi_alloc_resource(device_t bus, device_t child,
134                         int type, int *rid, rman_res_t start, rman_res_t end,
135                         rman_res_t count, u_int flags);
136 static int      acpi_adjust_resource(device_t bus, device_t child, int type,
137                         struct resource *r, rman_res_t start, rman_res_t end);
138 static int      acpi_release_resource(device_t bus, device_t child, int type,
139                         int rid, struct resource *r);
140 static void     acpi_delete_resource(device_t bus, device_t child, int type,
141                     int rid);
142 static uint32_t acpi_isa_get_logicalid(device_t dev);
143 static int      acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count);
144 static int      acpi_device_id_probe(device_t bus, device_t dev, char **ids, char **match);
145 static ACPI_STATUS acpi_device_eval_obj(device_t bus, device_t dev,
146                     ACPI_STRING pathname, ACPI_OBJECT_LIST *parameters,
147                     ACPI_BUFFER *ret);
148 static ACPI_STATUS acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level,
149                     void *context, void **retval);
150 static ACPI_STATUS acpi_device_scan_children(device_t bus, device_t dev,
151                     int max_depth, acpi_scan_cb_t user_fn, void *arg);
152 static int      acpi_set_powerstate(device_t child, int state);
153 static int      acpi_isa_pnp_probe(device_t bus, device_t child,
154                     struct isa_pnp_id *ids);
155 static void     acpi_probe_children(device_t bus);
156 static void     acpi_probe_order(ACPI_HANDLE handle, int *order);
157 static ACPI_STATUS acpi_probe_child(ACPI_HANDLE handle, UINT32 level,
158                     void *context, void **status);
159 static void     acpi_sleep_enable(void *arg);
160 static ACPI_STATUS acpi_sleep_disable(struct acpi_softc *sc);
161 static ACPI_STATUS acpi_EnterSleepState(struct acpi_softc *sc, int state);
162 static void     acpi_shutdown_final(void *arg, int howto);
163 static void     acpi_enable_fixed_events(struct acpi_softc *sc);
164 static BOOLEAN  acpi_has_hid(ACPI_HANDLE handle);
165 static void     acpi_resync_clock(struct acpi_softc *sc);
166 static int      acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate);
167 static int      acpi_wake_run_prep(ACPI_HANDLE handle, int sstate);
168 static int      acpi_wake_prep_walk(int sstate);
169 static int      acpi_wake_sysctl_walk(device_t dev);
170 static int      acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS);
171 static void     acpi_system_eventhandler_sleep(void *arg, int state);
172 static void     acpi_system_eventhandler_wakeup(void *arg, int state);
173 static int      acpi_sname2sstate(const char *sname);
174 static const char *acpi_sstate2sname(int sstate);
175 static int      acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
176 static int      acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS);
177 static int      acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS);
178 static int      acpi_pm_func(u_long cmd, void *arg, ...);
179 static int      acpi_child_location_str_method(device_t acdev, device_t child,
180                                                char *buf, size_t buflen);
181 static int      acpi_child_pnpinfo_str_method(device_t acdev, device_t child,
182                                               char *buf, size_t buflen);
183 static void     acpi_enable_pcie(void);
184 static void     acpi_hint_device_unit(device_t acdev, device_t child,
185                     const char *name, int *unitp);
186 static void     acpi_reset_interfaces(device_t dev);
187
188 static device_method_t acpi_methods[] = {
189     /* Device interface */
190     DEVMETHOD(device_probe,             acpi_probe),
191     DEVMETHOD(device_attach,            acpi_attach),
192     DEVMETHOD(device_shutdown,          acpi_shutdown),
193     DEVMETHOD(device_detach,            bus_generic_detach),
194     DEVMETHOD(device_suspend,           acpi_suspend),
195     DEVMETHOD(device_resume,            acpi_resume),
196
197     /* Bus interface */
198     DEVMETHOD(bus_add_child,            acpi_add_child),
199     DEVMETHOD(bus_print_child,          acpi_print_child),
200     DEVMETHOD(bus_probe_nomatch,        acpi_probe_nomatch),
201     DEVMETHOD(bus_driver_added,         acpi_driver_added),
202     DEVMETHOD(bus_read_ivar,            acpi_read_ivar),
203     DEVMETHOD(bus_write_ivar,           acpi_write_ivar),
204     DEVMETHOD(bus_get_resource_list,    acpi_get_rlist),
205     DEVMETHOD(bus_set_resource,         acpi_set_resource),
206     DEVMETHOD(bus_get_resource,         bus_generic_rl_get_resource),
207     DEVMETHOD(bus_alloc_resource,       acpi_alloc_resource),
208     DEVMETHOD(bus_adjust_resource,      acpi_adjust_resource),
209     DEVMETHOD(bus_release_resource,     acpi_release_resource),
210     DEVMETHOD(bus_delete_resource,      acpi_delete_resource),
211     DEVMETHOD(bus_child_pnpinfo_str,    acpi_child_pnpinfo_str_method),
212     DEVMETHOD(bus_child_location_str,   acpi_child_location_str_method),
213     DEVMETHOD(bus_activate_resource,    bus_generic_activate_resource),
214     DEVMETHOD(bus_deactivate_resource,  bus_generic_deactivate_resource),
215     DEVMETHOD(bus_setup_intr,           bus_generic_setup_intr),
216     DEVMETHOD(bus_teardown_intr,        bus_generic_teardown_intr),
217     DEVMETHOD(bus_hint_device_unit,     acpi_hint_device_unit),
218     DEVMETHOD(bus_get_cpus,             acpi_get_cpus),
219     DEVMETHOD(bus_get_domain,           acpi_get_domain),
220
221     /* ACPI bus */
222     DEVMETHOD(acpi_id_probe,            acpi_device_id_probe),
223     DEVMETHOD(acpi_evaluate_object,     acpi_device_eval_obj),
224     DEVMETHOD(acpi_pwr_for_sleep,       acpi_device_pwr_for_sleep),
225     DEVMETHOD(acpi_scan_children,       acpi_device_scan_children),
226
227     /* ISA emulation */
228     DEVMETHOD(isa_pnp_probe,            acpi_isa_pnp_probe),
229
230     DEVMETHOD_END
231 };
232
233 static driver_t acpi_driver = {
234     "acpi",
235     acpi_methods,
236     sizeof(struct acpi_softc),
237 };
238
239 static devclass_t acpi_devclass;
240 EARLY_DRIVER_MODULE(acpi, nexus, acpi_driver, acpi_devclass, acpi_modevent, 0,
241     BUS_PASS_BUS + BUS_PASS_ORDER_MIDDLE);
242 MODULE_VERSION(acpi, 1);
243
244 ACPI_SERIAL_DECL(acpi, "ACPI root bus");
245
246 /* Local pools for managing system resources for ACPI child devices. */
247 static struct rman acpi_rman_io, acpi_rman_mem;
248
249 #define ACPI_MINIMUM_AWAKETIME  5
250
251 /* Holds the description of the acpi0 device. */
252 static char acpi_desc[ACPI_OEM_ID_SIZE + ACPI_OEM_TABLE_ID_SIZE + 2];
253
254 SYSCTL_NODE(_debug, OID_AUTO, acpi, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
255     "ACPI debugging");
256 static char acpi_ca_version[12];
257 SYSCTL_STRING(_debug_acpi, OID_AUTO, acpi_ca_version, CTLFLAG_RD,
258               acpi_ca_version, 0, "Version of Intel ACPI-CA");
259
260 /*
261  * Allow overriding _OSI methods.
262  */
263 static char acpi_install_interface[256];
264 TUNABLE_STR("hw.acpi.install_interface", acpi_install_interface,
265     sizeof(acpi_install_interface));
266 static char acpi_remove_interface[256];
267 TUNABLE_STR("hw.acpi.remove_interface", acpi_remove_interface,
268     sizeof(acpi_remove_interface));
269
270 /* Allow users to dump Debug objects without ACPI debugger. */
271 static int acpi_debug_objects;
272 TUNABLE_INT("debug.acpi.enable_debug_objects", &acpi_debug_objects);
273 SYSCTL_PROC(_debug_acpi, OID_AUTO, enable_debug_objects,
274     CTLFLAG_RW | CTLTYPE_INT | CTLFLAG_NEEDGIANT, NULL, 0,
275     acpi_debug_objects_sysctl, "I",
276     "Enable Debug objects");
277
278 /* Allow the interpreter to ignore common mistakes in BIOS. */
279 static int acpi_interpreter_slack = 1;
280 TUNABLE_INT("debug.acpi.interpreter_slack", &acpi_interpreter_slack);
281 SYSCTL_INT(_debug_acpi, OID_AUTO, interpreter_slack, CTLFLAG_RDTUN,
282     &acpi_interpreter_slack, 1, "Turn on interpreter slack mode.");
283
284 /* Ignore register widths set by FADT and use default widths instead. */
285 static int acpi_ignore_reg_width = 1;
286 TUNABLE_INT("debug.acpi.default_register_width", &acpi_ignore_reg_width);
287 SYSCTL_INT(_debug_acpi, OID_AUTO, default_register_width, CTLFLAG_RDTUN,
288     &acpi_ignore_reg_width, 1, "Ignore register widths set by FADT");
289
290 /* Allow users to override quirks. */
291 TUNABLE_INT("debug.acpi.quirks", &acpi_quirks);
292
293 int acpi_susp_bounce;
294 SYSCTL_INT(_debug_acpi, OID_AUTO, suspend_bounce, CTLFLAG_RW,
295     &acpi_susp_bounce, 0, "Don't actually suspend, just test devices.");
296
297 /*
298  * ACPI can only be loaded as a module by the loader; activating it after
299  * system bootstrap time is not useful, and can be fatal to the system.
300  * It also cannot be unloaded, since the entire system bus hierarchy hangs
301  * off it.
302  */
303 static int
304 acpi_modevent(struct module *mod, int event, void *junk)
305 {
306     switch (event) {
307     case MOD_LOAD:
308         if (!cold) {
309             printf("The ACPI driver cannot be loaded after boot.\n");
310             return (EPERM);
311         }
312         break;
313     case MOD_UNLOAD:
314         if (!cold && power_pm_get_type() == POWER_PM_TYPE_ACPI)
315             return (EBUSY);
316         break;
317     default:
318         break;
319     }
320     return (0);
321 }
322
323 /*
324  * Perform early initialization.
325  */
326 ACPI_STATUS
327 acpi_Startup(void)
328 {
329     static int started = 0;
330     ACPI_STATUS status;
331     int val;
332
333     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
334
335     /* Only run the startup code once.  The MADT driver also calls this. */
336     if (started)
337         return_VALUE (AE_OK);
338     started = 1;
339
340     /*
341      * Initialize the ACPICA subsystem.
342      */
343     if (ACPI_FAILURE(status = AcpiInitializeSubsystem())) {
344         printf("ACPI: Could not initialize Subsystem: %s\n",
345             AcpiFormatException(status));
346         return_VALUE (status);
347     }
348
349     /*
350      * Pre-allocate space for RSDT/XSDT and DSDT tables and allow resizing
351      * if more tables exist.
352      */
353     if (ACPI_FAILURE(status = AcpiInitializeTables(NULL, 2, TRUE))) {
354         printf("ACPI: Table initialisation failed: %s\n",
355             AcpiFormatException(status));
356         return_VALUE (status);
357     }
358
359     /* Set up any quirks we have for this system. */
360     if (acpi_quirks == ACPI_Q_OK)
361         acpi_table_quirks(&acpi_quirks);
362
363     /* If the user manually set the disabled hint to 0, force-enable ACPI. */
364     if (resource_int_value("acpi", 0, "disabled", &val) == 0 && val == 0)
365         acpi_quirks &= ~ACPI_Q_BROKEN;
366     if (acpi_quirks & ACPI_Q_BROKEN) {
367         printf("ACPI disabled by blacklist.  Contact your BIOS vendor.\n");
368         status = AE_SUPPORT;
369     }
370
371     return_VALUE (status);
372 }
373
374 /*
375  * Detect ACPI and perform early initialisation.
376  */
377 int
378 acpi_identify(void)
379 {
380     ACPI_TABLE_RSDP     *rsdp;
381     ACPI_TABLE_HEADER   *rsdt;
382     ACPI_PHYSICAL_ADDRESS paddr;
383     struct sbuf         sb;
384
385     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
386
387     if (!cold)
388         return (ENXIO);
389
390     /* Check that we haven't been disabled with a hint. */
391     if (resource_disabled("acpi", 0))
392         return (ENXIO);
393
394     /* Check for other PM systems. */
395     if (power_pm_get_type() != POWER_PM_TYPE_NONE &&
396         power_pm_get_type() != POWER_PM_TYPE_ACPI) {
397         printf("ACPI identify failed, other PM system enabled.\n");
398         return (ENXIO);
399     }
400
401     /* Initialize root tables. */
402     if (ACPI_FAILURE(acpi_Startup())) {
403         printf("ACPI: Try disabling either ACPI or apic support.\n");
404         return (ENXIO);
405     }
406
407     if ((paddr = AcpiOsGetRootPointer()) == 0 ||
408         (rsdp = AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_RSDP))) == NULL)
409         return (ENXIO);
410     if (rsdp->Revision > 1 && rsdp->XsdtPhysicalAddress != 0)
411         paddr = (ACPI_PHYSICAL_ADDRESS)rsdp->XsdtPhysicalAddress;
412     else
413         paddr = (ACPI_PHYSICAL_ADDRESS)rsdp->RsdtPhysicalAddress;
414     AcpiOsUnmapMemory(rsdp, sizeof(ACPI_TABLE_RSDP));
415
416     if ((rsdt = AcpiOsMapMemory(paddr, sizeof(ACPI_TABLE_HEADER))) == NULL)
417         return (ENXIO);
418     sbuf_new(&sb, acpi_desc, sizeof(acpi_desc), SBUF_FIXEDLEN);
419     sbuf_bcat(&sb, rsdt->OemId, ACPI_OEM_ID_SIZE);
420     sbuf_trim(&sb);
421     sbuf_putc(&sb, ' ');
422     sbuf_bcat(&sb, rsdt->OemTableId, ACPI_OEM_TABLE_ID_SIZE);
423     sbuf_trim(&sb);
424     sbuf_finish(&sb);
425     sbuf_delete(&sb);
426     AcpiOsUnmapMemory(rsdt, sizeof(ACPI_TABLE_HEADER));
427
428     snprintf(acpi_ca_version, sizeof(acpi_ca_version), "%x", ACPI_CA_VERSION);
429
430     return (0);
431 }
432
433 /*
434  * Fetch some descriptive data from ACPI to put in our attach message.
435  */
436 static int
437 acpi_probe(device_t dev)
438 {
439
440     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
441
442     device_set_desc(dev, acpi_desc);
443
444     return_VALUE (BUS_PROBE_NOWILDCARD);
445 }
446
447 static int
448 acpi_attach(device_t dev)
449 {
450     struct acpi_softc   *sc;
451     ACPI_STATUS         status;
452     int                 error, state;
453     UINT32              flags;
454     UINT8               TypeA, TypeB;
455     char                *env;
456
457     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
458
459     sc = device_get_softc(dev);
460     sc->acpi_dev = dev;
461     callout_init(&sc->susp_force_to, 1);
462
463     error = ENXIO;
464
465     /* Initialize resource manager. */
466     acpi_rman_io.rm_type = RMAN_ARRAY;
467     acpi_rman_io.rm_start = 0;
468     acpi_rman_io.rm_end = 0xffff;
469     acpi_rman_io.rm_descr = "ACPI I/O ports";
470     if (rman_init(&acpi_rman_io) != 0)
471         panic("acpi rman_init IO ports failed");
472     acpi_rman_mem.rm_type = RMAN_ARRAY;
473     acpi_rman_mem.rm_descr = "ACPI I/O memory addresses";
474     if (rman_init(&acpi_rman_mem) != 0)
475         panic("acpi rman_init memory failed");
476
477     /* Initialise the ACPI mutex */
478     mtx_init(&acpi_mutex, "ACPI global lock", NULL, MTX_DEF);
479
480     /*
481      * Set the globals from our tunables.  This is needed because ACPI-CA
482      * uses UINT8 for some values and we have no tunable_byte.
483      */
484     AcpiGbl_EnableInterpreterSlack = acpi_interpreter_slack ? TRUE : FALSE;
485     AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
486     AcpiGbl_UseDefaultRegisterWidths = acpi_ignore_reg_width ? TRUE : FALSE;
487
488 #ifndef ACPI_DEBUG
489     /*
490      * Disable all debugging layers and levels.
491      */
492     AcpiDbgLayer = 0;
493     AcpiDbgLevel = 0;
494 #endif
495
496     /* Override OS interfaces if the user requested. */
497     acpi_reset_interfaces(dev);
498
499     /* Load ACPI name space. */
500     status = AcpiLoadTables();
501     if (ACPI_FAILURE(status)) {
502         device_printf(dev, "Could not load Namespace: %s\n",
503                       AcpiFormatException(status));
504         goto out;
505     }
506
507     /* Handle MCFG table if present. */
508     acpi_enable_pcie();
509
510     /*
511      * Note that some systems (specifically, those with namespace evaluation
512      * issues that require the avoidance of parts of the namespace) must
513      * avoid running _INI and _STA on everything, as well as dodging the final
514      * object init pass.
515      *
516      * For these devices, we set ACPI_NO_DEVICE_INIT and ACPI_NO_OBJECT_INIT).
517      *
518      * XXX We should arrange for the object init pass after we have attached
519      *     all our child devices, but on many systems it works here.
520      */
521     flags = 0;
522     if (testenv("debug.acpi.avoid"))
523         flags = ACPI_NO_DEVICE_INIT | ACPI_NO_OBJECT_INIT;
524
525     /* Bring the hardware and basic handlers online. */
526     if (ACPI_FAILURE(status = AcpiEnableSubsystem(flags))) {
527         device_printf(dev, "Could not enable ACPI: %s\n",
528                       AcpiFormatException(status));
529         goto out;
530     }
531
532     /*
533      * Call the ECDT probe function to provide EC functionality before
534      * the namespace has been evaluated.
535      *
536      * XXX This happens before the sysresource devices have been probed and
537      * attached so its resources come from nexus0.  In practice, this isn't
538      * a problem but should be addressed eventually.
539      */
540     acpi_ec_ecdt_probe(dev);
541
542     /* Bring device objects and regions online. */
543     if (ACPI_FAILURE(status = AcpiInitializeObjects(flags))) {
544         device_printf(dev, "Could not initialize ACPI objects: %s\n",
545                       AcpiFormatException(status));
546         goto out;
547     }
548
549     /*
550      * Setup our sysctl tree.
551      *
552      * XXX: This doesn't check to make sure that none of these fail.
553      */
554     sysctl_ctx_init(&sc->acpi_sysctl_ctx);
555     sc->acpi_sysctl_tree = SYSCTL_ADD_NODE(&sc->acpi_sysctl_ctx,
556         SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO, device_get_name(dev),
557         CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
558     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
559         OID_AUTO, "supported_sleep_state",
560         CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
561         0, 0, acpi_supported_sleep_state_sysctl, "A",
562         "List supported ACPI sleep states.");
563     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
564         OID_AUTO, "power_button_state",
565         CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
566         &sc->acpi_power_button_sx, 0, acpi_sleep_state_sysctl, "A",
567         "Power button ACPI sleep state.");
568     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
569         OID_AUTO, "sleep_button_state",
570         CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
571         &sc->acpi_sleep_button_sx, 0, acpi_sleep_state_sysctl, "A",
572         "Sleep button ACPI sleep state.");
573     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
574         OID_AUTO, "lid_switch_state",
575         CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
576         &sc->acpi_lid_switch_sx, 0, acpi_sleep_state_sysctl, "A",
577         "Lid ACPI sleep state. Set to S3 if you want to suspend your laptop when close the Lid.");
578     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
579         OID_AUTO, "standby_state",
580         CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
581         &sc->acpi_standby_sx, 0, acpi_sleep_state_sysctl, "A", "");
582     SYSCTL_ADD_PROC(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
583         OID_AUTO, "suspend_state",
584         CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
585         &sc->acpi_suspend_sx, 0, acpi_sleep_state_sysctl, "A", "");
586     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
587         OID_AUTO, "sleep_delay", CTLFLAG_RW, &sc->acpi_sleep_delay, 0,
588         "sleep delay in seconds");
589     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
590         OID_AUTO, "s4bios", CTLFLAG_RW, &sc->acpi_s4bios, 0, "S4BIOS mode");
591     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
592         OID_AUTO, "verbose", CTLFLAG_RW, &sc->acpi_verbose, 0, "verbose mode");
593     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
594         OID_AUTO, "disable_on_reboot", CTLFLAG_RW,
595         &sc->acpi_do_disable, 0, "Disable ACPI when rebooting/halting system");
596     SYSCTL_ADD_INT(&sc->acpi_sysctl_ctx, SYSCTL_CHILDREN(sc->acpi_sysctl_tree),
597         OID_AUTO, "handle_reboot", CTLFLAG_RW,
598         &sc->acpi_handle_reboot, 0, "Use ACPI Reset Register to reboot");
599
600     /*
601      * Default to 1 second before sleeping to give some machines time to
602      * stabilize.
603      */
604     sc->acpi_sleep_delay = 1;
605     if (bootverbose)
606         sc->acpi_verbose = 1;
607     if ((env = kern_getenv("hw.acpi.verbose")) != NULL) {
608         if (strcmp(env, "0") != 0)
609             sc->acpi_verbose = 1;
610         freeenv(env);
611     }
612
613     /* Only enable reboot by default if the FADT says it is available. */
614     if (AcpiGbl_FADT.Flags & ACPI_FADT_RESET_REGISTER)
615         sc->acpi_handle_reboot = 1;
616
617 #if !ACPI_REDUCED_HARDWARE
618     /* Only enable S4BIOS by default if the FACS says it is available. */
619     if (AcpiGbl_FACS != NULL && AcpiGbl_FACS->Flags & ACPI_FACS_S4_BIOS_PRESENT)
620         sc->acpi_s4bios = 1;
621 #endif
622
623     /* Probe all supported sleep states. */
624     acpi_sleep_states[ACPI_STATE_S0] = TRUE;
625     for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
626         if (ACPI_SUCCESS(AcpiEvaluateObject(ACPI_ROOT_OBJECT,
627             __DECONST(char *, AcpiGbl_SleepStateNames[state]), NULL, NULL)) &&
628             ACPI_SUCCESS(AcpiGetSleepTypeData(state, &TypeA, &TypeB)))
629             acpi_sleep_states[state] = TRUE;
630
631     /*
632      * Dispatch the default sleep state to devices.  The lid switch is set
633      * to UNKNOWN by default to avoid surprising users.
634      */
635     sc->acpi_power_button_sx = acpi_sleep_states[ACPI_STATE_S5] ?
636         ACPI_STATE_S5 : ACPI_STATE_UNKNOWN;
637     sc->acpi_lid_switch_sx = ACPI_STATE_UNKNOWN;
638     sc->acpi_standby_sx = acpi_sleep_states[ACPI_STATE_S1] ?
639         ACPI_STATE_S1 : ACPI_STATE_UNKNOWN;
640     sc->acpi_suspend_sx = acpi_sleep_states[ACPI_STATE_S3] ?
641         ACPI_STATE_S3 : ACPI_STATE_UNKNOWN;
642
643     /* Pick the first valid sleep state for the sleep button default. */
644     sc->acpi_sleep_button_sx = ACPI_STATE_UNKNOWN;
645     for (state = ACPI_STATE_S1; state <= ACPI_STATE_S4; state++)
646         if (acpi_sleep_states[state]) {
647             sc->acpi_sleep_button_sx = state;
648             break;
649         }
650
651     acpi_enable_fixed_events(sc);
652
653     /*
654      * Scan the namespace and attach/initialise children.
655      */
656
657     /* Register our shutdown handler. */
658     EVENTHANDLER_REGISTER(shutdown_final, acpi_shutdown_final, sc,
659         SHUTDOWN_PRI_LAST);
660
661     /*
662      * Register our acpi event handlers.
663      * XXX should be configurable eg. via userland policy manager.
664      */
665     EVENTHANDLER_REGISTER(acpi_sleep_event, acpi_system_eventhandler_sleep,
666         sc, ACPI_EVENT_PRI_LAST);
667     EVENTHANDLER_REGISTER(acpi_wakeup_event, acpi_system_eventhandler_wakeup,
668         sc, ACPI_EVENT_PRI_LAST);
669
670     /* Flag our initial states. */
671     sc->acpi_enabled = TRUE;
672     sc->acpi_sstate = ACPI_STATE_S0;
673     sc->acpi_sleep_disabled = TRUE;
674
675     /* Create the control device */
676     sc->acpi_dev_t = make_dev(&acpi_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0664,
677                               "acpi");
678     sc->acpi_dev_t->si_drv1 = sc;
679
680     if ((error = acpi_machdep_init(dev)))
681         goto out;
682
683     /* Register ACPI again to pass the correct argument of pm_func. */
684     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, sc);
685
686     if (!acpi_disabled("bus")) {
687         EVENTHANDLER_REGISTER(dev_lookup, acpi_lookup, NULL, 1000);
688         acpi_probe_children(dev);
689     }
690
691     /* Update all GPEs and enable runtime GPEs. */
692     status = AcpiUpdateAllGpes();
693     if (ACPI_FAILURE(status))
694         device_printf(dev, "Could not update all GPEs: %s\n",
695             AcpiFormatException(status));
696
697     /* Allow sleep request after a while. */
698     callout_init_mtx(&acpi_sleep_timer, &acpi_mutex, 0);
699     callout_reset(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME,
700         acpi_sleep_enable, sc);
701
702     error = 0;
703
704  out:
705     return_VALUE (error);
706 }
707
708 static void
709 acpi_set_power_children(device_t dev, int state)
710 {
711         device_t child;
712         device_t *devlist;
713         int dstate, i, numdevs;
714
715         if (device_get_children(dev, &devlist, &numdevs) != 0)
716                 return;
717
718         /*
719          * Retrieve and set D-state for the sleep state if _SxD is present.
720          * Skip children who aren't attached since they are handled separately.
721          */
722         for (i = 0; i < numdevs; i++) {
723                 child = devlist[i];
724                 dstate = state;
725                 if (device_is_attached(child) &&
726                     acpi_device_pwr_for_sleep(dev, child, &dstate) == 0)
727                         acpi_set_powerstate(child, dstate);
728         }
729         free(devlist, M_TEMP);
730 }
731
732 static int
733 acpi_suspend(device_t dev)
734 {
735     int error;
736
737     GIANT_REQUIRED;
738
739     error = bus_generic_suspend(dev);
740     if (error == 0)
741         acpi_set_power_children(dev, ACPI_STATE_D3);
742
743     return (error);
744 }
745
746 static int
747 acpi_resume(device_t dev)
748 {
749
750     GIANT_REQUIRED;
751
752     acpi_set_power_children(dev, ACPI_STATE_D0);
753
754     return (bus_generic_resume(dev));
755 }
756
757 static int
758 acpi_shutdown(device_t dev)
759 {
760
761     GIANT_REQUIRED;
762
763     /* Allow children to shutdown first. */
764     bus_generic_shutdown(dev);
765
766     /*
767      * Enable any GPEs that are able to power-on the system (i.e., RTC).
768      * Also, disable any that are not valid for this state (most).
769      */
770     acpi_wake_prep_walk(ACPI_STATE_S5);
771
772     return (0);
773 }
774
775 /*
776  * Handle a new device being added
777  */
778 static device_t
779 acpi_add_child(device_t bus, u_int order, const char *name, int unit)
780 {
781     struct acpi_device  *ad;
782     device_t            child;
783
784     if ((ad = malloc(sizeof(*ad), M_ACPIDEV, M_NOWAIT | M_ZERO)) == NULL)
785         return (NULL);
786
787     resource_list_init(&ad->ad_rl);
788
789     child = device_add_child_ordered(bus, order, name, unit);
790     if (child != NULL)
791         device_set_ivars(child, ad);
792     else
793         free(ad, M_ACPIDEV);
794     return (child);
795 }
796
797 static int
798 acpi_print_child(device_t bus, device_t child)
799 {
800     struct acpi_device   *adev = device_get_ivars(child);
801     struct resource_list *rl = &adev->ad_rl;
802     int retval = 0;
803
804     retval += bus_print_child_header(bus, child);
805     retval += resource_list_print_type(rl, "port",  SYS_RES_IOPORT, "%#jx");
806     retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#jx");
807     retval += resource_list_print_type(rl, "irq",   SYS_RES_IRQ,    "%jd");
808     retval += resource_list_print_type(rl, "drq",   SYS_RES_DRQ,    "%jd");
809     if (device_get_flags(child))
810         retval += printf(" flags %#x", device_get_flags(child));
811     retval += bus_print_child_domain(bus, child);
812     retval += bus_print_child_footer(bus, child);
813
814     return (retval);
815 }
816
817 /*
818  * If this device is an ACPI child but no one claimed it, attempt
819  * to power it off.  We'll power it back up when a driver is added.
820  *
821  * XXX Disabled for now since many necessary devices (like fdc and
822  * ATA) don't claim the devices we created for them but still expect
823  * them to be powered up.
824  */
825 static void
826 acpi_probe_nomatch(device_t bus, device_t child)
827 {
828 #ifdef ACPI_ENABLE_POWERDOWN_NODRIVER
829     acpi_set_powerstate(child, ACPI_STATE_D3);
830 #endif
831 }
832
833 /*
834  * If a new driver has a chance to probe a child, first power it up.
835  *
836  * XXX Disabled for now (see acpi_probe_nomatch for details).
837  */
838 static void
839 acpi_driver_added(device_t dev, driver_t *driver)
840 {
841     device_t child, *devlist;
842     int i, numdevs;
843
844     DEVICE_IDENTIFY(driver, dev);
845     if (device_get_children(dev, &devlist, &numdevs))
846             return;
847     for (i = 0; i < numdevs; i++) {
848         child = devlist[i];
849         if (device_get_state(child) == DS_NOTPRESENT) {
850 #ifdef ACPI_ENABLE_POWERDOWN_NODRIVER
851             acpi_set_powerstate(child, ACPI_STATE_D0);
852             if (device_probe_and_attach(child) != 0)
853                 acpi_set_powerstate(child, ACPI_STATE_D3);
854 #else
855             device_probe_and_attach(child);
856 #endif
857         }
858     }
859     free(devlist, M_TEMP);
860 }
861
862 /* Location hint for devctl(8) */
863 static int
864 acpi_child_location_str_method(device_t cbdev, device_t child, char *buf,
865     size_t buflen)
866 {
867     struct acpi_device *dinfo = device_get_ivars(child);
868     char buf2[32];
869     int pxm;
870
871     if (dinfo->ad_handle) {
872         snprintf(buf, buflen, "handle=%s", acpi_name(dinfo->ad_handle));
873         if (ACPI_SUCCESS(acpi_GetInteger(dinfo->ad_handle, "_PXM", &pxm))) {
874                 snprintf(buf2, 32, " _PXM=%d", pxm);
875                 strlcat(buf, buf2, buflen);
876         }
877     } else {
878         snprintf(buf, buflen, "");
879     }
880     return (0);
881 }
882
883 /* PnP information for devctl(8) */
884 static int
885 acpi_child_pnpinfo_str_method(device_t cbdev, device_t child, char *buf,
886     size_t buflen)
887 {
888     struct acpi_device *dinfo = device_get_ivars(child);
889     ACPI_DEVICE_INFO *adinfo;
890
891     if (ACPI_FAILURE(AcpiGetObjectInfo(dinfo->ad_handle, &adinfo))) {
892         snprintf(buf, buflen, "unknown");
893         return (0);
894     }
895
896     snprintf(buf, buflen, "_HID=%s _UID=%lu _CID=%s",
897         (adinfo->Valid & ACPI_VALID_HID) ?
898         adinfo->HardwareId.String : "none",
899         (adinfo->Valid & ACPI_VALID_UID) ?
900         strtoul(adinfo->UniqueId.String, NULL, 10) : 0UL,
901         ((adinfo->Valid & ACPI_VALID_CID) &&
902          adinfo->CompatibleIdList.Count > 0) ?
903         adinfo->CompatibleIdList.Ids[0].String : "none");
904     AcpiOsFree(adinfo);
905
906     return (0);
907 }
908
909 /*
910  * Handle per-device ivars
911  */
912 static int
913 acpi_read_ivar(device_t dev, device_t child, int index, uintptr_t *result)
914 {
915     struct acpi_device  *ad;
916
917     if ((ad = device_get_ivars(child)) == NULL) {
918         device_printf(child, "device has no ivars\n");
919         return (ENOENT);
920     }
921
922     /* ACPI and ISA compatibility ivars */
923     switch(index) {
924     case ACPI_IVAR_HANDLE:
925         *(ACPI_HANDLE *)result = ad->ad_handle;
926         break;
927     case ACPI_IVAR_PRIVATE:
928         *(void **)result = ad->ad_private;
929         break;
930     case ACPI_IVAR_FLAGS:
931         *(int *)result = ad->ad_flags;
932         break;
933     case ISA_IVAR_VENDORID:
934     case ISA_IVAR_SERIAL:
935     case ISA_IVAR_COMPATID:
936         *(int *)result = -1;
937         break;
938     case ISA_IVAR_LOGICALID:
939         *(int *)result = acpi_isa_get_logicalid(child);
940         break;
941     case PCI_IVAR_CLASS:
942         *(uint8_t*)result = (ad->ad_cls_class >> 16) & 0xff;
943         break;
944     case PCI_IVAR_SUBCLASS:
945         *(uint8_t*)result = (ad->ad_cls_class >> 8) & 0xff;
946         break;
947     case PCI_IVAR_PROGIF:
948         *(uint8_t*)result = (ad->ad_cls_class >> 0) & 0xff;
949         break;
950     default:
951         return (ENOENT);
952     }
953
954     return (0);
955 }
956
957 static int
958 acpi_write_ivar(device_t dev, device_t child, int index, uintptr_t value)
959 {
960     struct acpi_device  *ad;
961
962     if ((ad = device_get_ivars(child)) == NULL) {
963         device_printf(child, "device has no ivars\n");
964         return (ENOENT);
965     }
966
967     switch(index) {
968     case ACPI_IVAR_HANDLE:
969         ad->ad_handle = (ACPI_HANDLE)value;
970         break;
971     case ACPI_IVAR_PRIVATE:
972         ad->ad_private = (void *)value;
973         break;
974     case ACPI_IVAR_FLAGS:
975         ad->ad_flags = (int)value;
976         break;
977     default:
978         panic("bad ivar write request (%d)", index);
979         return (ENOENT);
980     }
981
982     return (0);
983 }
984
985 /*
986  * Handle child resource allocation/removal
987  */
988 static struct resource_list *
989 acpi_get_rlist(device_t dev, device_t child)
990 {
991     struct acpi_device          *ad;
992
993     ad = device_get_ivars(child);
994     return (&ad->ad_rl);
995 }
996
997 static int
998 acpi_match_resource_hint(device_t dev, int type, long value)
999 {
1000     struct acpi_device *ad = device_get_ivars(dev);
1001     struct resource_list *rl = &ad->ad_rl;
1002     struct resource_list_entry *rle;
1003
1004     STAILQ_FOREACH(rle, rl, link) {
1005         if (rle->type != type)
1006             continue;
1007         if (rle->start <= value && rle->end >= value)
1008             return (1);
1009     }
1010     return (0);
1011 }
1012
1013 /*
1014  * Wire device unit numbers based on resource matches in hints.
1015  */
1016 static void
1017 acpi_hint_device_unit(device_t acdev, device_t child, const char *name,
1018     int *unitp)
1019 {
1020     const char *s;
1021     long value;
1022     int line, matches, unit;
1023
1024     /*
1025      * Iterate over all the hints for the devices with the specified
1026      * name to see if one's resources are a subset of this device.
1027      */
1028     line = 0;
1029     while (resource_find_dev(&line, name, &unit, "at", NULL) == 0) {
1030         /* Must have an "at" for acpi or isa. */
1031         resource_string_value(name, unit, "at", &s);
1032         if (!(strcmp(s, "acpi0") == 0 || strcmp(s, "acpi") == 0 ||
1033             strcmp(s, "isa0") == 0 || strcmp(s, "isa") == 0))
1034             continue;
1035
1036         /*
1037          * Check for matching resources.  We must have at least one match.
1038          * Since I/O and memory resources cannot be shared, if we get a
1039          * match on either of those, ignore any mismatches in IRQs or DRQs.
1040          *
1041          * XXX: We may want to revisit this to be more lenient and wire
1042          * as long as it gets one match.
1043          */
1044         matches = 0;
1045         if (resource_long_value(name, unit, "port", &value) == 0) {
1046             /*
1047              * Floppy drive controllers are notorious for having a
1048              * wide variety of resources not all of which include the
1049              * first port that is specified by the hint (typically
1050              * 0x3f0) (see the comment above fdc_isa_alloc_resources()
1051              * in fdc_isa.c).  However, they do all seem to include
1052              * port + 2 (e.g. 0x3f2) so for a floppy device, look for
1053              * 'value + 2' in the port resources instead of the hint
1054              * value.
1055              */
1056             if (strcmp(name, "fdc") == 0)
1057                 value += 2;
1058             if (acpi_match_resource_hint(child, SYS_RES_IOPORT, value))
1059                 matches++;
1060             else
1061                 continue;
1062         }
1063         if (resource_long_value(name, unit, "maddr", &value) == 0) {
1064             if (acpi_match_resource_hint(child, SYS_RES_MEMORY, value))
1065                 matches++;
1066             else
1067                 continue;
1068         }
1069         if (matches > 0)
1070             goto matched;
1071         if (resource_long_value(name, unit, "irq", &value) == 0) {
1072             if (acpi_match_resource_hint(child, SYS_RES_IRQ, value))
1073                 matches++;
1074             else
1075                 continue;
1076         }
1077         if (resource_long_value(name, unit, "drq", &value) == 0) {
1078             if (acpi_match_resource_hint(child, SYS_RES_DRQ, value))
1079                 matches++;
1080             else
1081                 continue;
1082         }
1083
1084     matched:
1085         if (matches > 0) {
1086             /* We have a winner! */
1087             *unitp = unit;
1088             break;
1089         }
1090     }
1091 }
1092
1093 /*
1094  * Fetch the NUMA domain for a device by mapping the value returned by
1095  * _PXM to a NUMA domain.  If the device does not have a _PXM method,
1096  * -2 is returned.  If any other error occurs, -1 is returned.
1097  */
1098 static int
1099 acpi_parse_pxm(device_t dev)
1100 {
1101 #ifdef NUMA
1102 #if defined(__i386__) || defined(__amd64__)
1103         ACPI_HANDLE handle;
1104         ACPI_STATUS status;
1105         int pxm;
1106
1107         handle = acpi_get_handle(dev);
1108         if (handle == NULL)
1109                 return (-2);
1110         status = acpi_GetInteger(handle, "_PXM", &pxm);
1111         if (ACPI_SUCCESS(status))
1112                 return (acpi_map_pxm_to_vm_domainid(pxm));
1113         if (status == AE_NOT_FOUND)
1114                 return (-2);
1115 #endif
1116 #endif
1117         return (-1);
1118 }
1119
1120 int
1121 acpi_get_cpus(device_t dev, device_t child, enum cpu_sets op, size_t setsize,
1122     cpuset_t *cpuset)
1123 {
1124         int d, error;
1125
1126         d = acpi_parse_pxm(child);
1127         if (d < 0)
1128                 return (bus_generic_get_cpus(dev, child, op, setsize, cpuset));
1129
1130         switch (op) {
1131         case LOCAL_CPUS:
1132                 if (setsize != sizeof(cpuset_t))
1133                         return (EINVAL);
1134                 *cpuset = cpuset_domain[d];
1135                 return (0);
1136         case INTR_CPUS:
1137                 error = bus_generic_get_cpus(dev, child, op, setsize, cpuset);
1138                 if (error != 0)
1139                         return (error);
1140                 if (setsize != sizeof(cpuset_t))
1141                         return (EINVAL);
1142                 CPU_AND(cpuset, &cpuset_domain[d]);
1143                 return (0);
1144         default:
1145                 return (bus_generic_get_cpus(dev, child, op, setsize, cpuset));
1146         }
1147 }
1148
1149 /*
1150  * Fetch the NUMA domain for the given device 'dev'.
1151  *
1152  * If a device has a _PXM method, map that to a NUMA domain.
1153  * Otherwise, pass the request up to the parent.
1154  * If there's no matching domain or the domain cannot be
1155  * determined, return ENOENT.
1156  */
1157 int
1158 acpi_get_domain(device_t dev, device_t child, int *domain)
1159 {
1160         int d;
1161
1162         d = acpi_parse_pxm(child);
1163         if (d >= 0) {
1164                 *domain = d;
1165                 return (0);
1166         }
1167         if (d == -1)
1168                 return (ENOENT);
1169
1170         /* No _PXM node; go up a level */
1171         return (bus_generic_get_domain(dev, child, domain));
1172 }
1173
1174 /*
1175  * Pre-allocate/manage all memory and IO resources.  Since rman can't handle
1176  * duplicates, we merge any in the sysresource attach routine.
1177  */
1178 static int
1179 acpi_sysres_alloc(device_t dev)
1180 {
1181     struct resource *res;
1182     struct resource_list *rl;
1183     struct resource_list_entry *rle;
1184     struct rman *rm;
1185     device_t *children;
1186     int child_count, i;
1187
1188     /*
1189      * Probe/attach any sysresource devices.  This would be unnecessary if we
1190      * had multi-pass probe/attach.
1191      */
1192     if (device_get_children(dev, &children, &child_count) != 0)
1193         return (ENXIO);
1194     for (i = 0; i < child_count; i++) {
1195         if (ACPI_ID_PROBE(dev, children[i], sysres_ids, NULL) <= 0)
1196             device_probe_and_attach(children[i]);
1197     }
1198     free(children, M_TEMP);
1199
1200     rl = BUS_GET_RESOURCE_LIST(device_get_parent(dev), dev);
1201     STAILQ_FOREACH(rle, rl, link) {
1202         if (rle->res != NULL) {
1203             device_printf(dev, "duplicate resource for %jx\n", rle->start);
1204             continue;
1205         }
1206
1207         /* Only memory and IO resources are valid here. */
1208         switch (rle->type) {
1209         case SYS_RES_IOPORT:
1210             rm = &acpi_rman_io;
1211             break;
1212         case SYS_RES_MEMORY:
1213             rm = &acpi_rman_mem;
1214             break;
1215         default:
1216             continue;
1217         }
1218
1219         /* Pre-allocate resource and add to our rman pool. */
1220         res = BUS_ALLOC_RESOURCE(device_get_parent(dev), dev, rle->type,
1221             &rle->rid, rle->start, rle->start + rle->count - 1, rle->count, 0);
1222         if (res != NULL) {
1223             rman_manage_region(rm, rman_get_start(res), rman_get_end(res));
1224             rle->res = res;
1225         } else if (bootverbose)
1226             device_printf(dev, "reservation of %jx, %jx (%d) failed\n",
1227                 rle->start, rle->count, rle->type);
1228     }
1229     return (0);
1230 }
1231
1232 /*
1233  * Reserve declared resources for devices found during attach once system
1234  * resources have been allocated.
1235  */
1236 static void
1237 acpi_reserve_resources(device_t dev)
1238 {
1239     struct resource_list_entry *rle;
1240     struct resource_list *rl;
1241     struct acpi_device *ad;
1242     struct acpi_softc *sc;
1243     device_t *children;
1244     int child_count, i;
1245
1246     sc = device_get_softc(dev);
1247     if (device_get_children(dev, &children, &child_count) != 0)
1248         return;
1249     for (i = 0; i < child_count; i++) {
1250         ad = device_get_ivars(children[i]);
1251         rl = &ad->ad_rl;
1252
1253         /* Don't reserve system resources. */
1254         if (ACPI_ID_PROBE(dev, children[i], sysres_ids, NULL) <= 0)
1255             continue;
1256
1257         STAILQ_FOREACH(rle, rl, link) {
1258             /*
1259              * Don't reserve IRQ resources.  There are many sticky things
1260              * to get right otherwise (e.g. IRQs for psm, atkbd, and HPET
1261              * when using legacy routing).
1262              */
1263             if (rle->type == SYS_RES_IRQ)
1264                 continue;
1265
1266             /*
1267              * Don't reserve the resource if it is already allocated.
1268              * The acpi_ec(4) driver can allocate its resources early
1269              * if ECDT is present.
1270              */
1271             if (rle->res != NULL)
1272                 continue;
1273
1274             /*
1275              * Try to reserve the resource from our parent.  If this
1276              * fails because the resource is a system resource, just
1277              * let it be.  The resource range is already reserved so
1278              * that other devices will not use it.  If the driver
1279              * needs to allocate the resource, then
1280              * acpi_alloc_resource() will sub-alloc from the system
1281              * resource.
1282              */
1283             resource_list_reserve(rl, dev, children[i], rle->type, &rle->rid,
1284                 rle->start, rle->end, rle->count, 0);
1285         }
1286     }
1287     free(children, M_TEMP);
1288     sc->acpi_resources_reserved = 1;
1289 }
1290
1291 static int
1292 acpi_set_resource(device_t dev, device_t child, int type, int rid,
1293     rman_res_t start, rman_res_t count)
1294 {
1295     struct acpi_softc *sc = device_get_softc(dev);
1296     struct acpi_device *ad = device_get_ivars(child);
1297     struct resource_list *rl = &ad->ad_rl;
1298     ACPI_DEVICE_INFO *devinfo;
1299     rman_res_t end;
1300     int allow;
1301
1302     /* Ignore IRQ resources for PCI link devices. */
1303     if (type == SYS_RES_IRQ &&
1304         ACPI_ID_PROBE(dev, child, pcilink_ids, NULL) <= 0)
1305         return (0);
1306
1307     /*
1308      * Ignore most resources for PCI root bridges.  Some BIOSes
1309      * incorrectly enumerate the memory ranges they decode as plain
1310      * memory resources instead of as ResourceProducer ranges.  Other
1311      * BIOSes incorrectly list system resource entries for I/O ranges
1312      * under the PCI bridge.  Do allow the one known-correct case on
1313      * x86 of a PCI bridge claiming the I/O ports used for PCI config
1314      * access.
1315      */
1316     if (type == SYS_RES_MEMORY || type == SYS_RES_IOPORT) {
1317         if (ACPI_SUCCESS(AcpiGetObjectInfo(ad->ad_handle, &devinfo))) {
1318             if ((devinfo->Flags & ACPI_PCI_ROOT_BRIDGE) != 0) {
1319 #if defined(__i386__) || defined(__amd64__)
1320                 allow = (type == SYS_RES_IOPORT && start == CONF1_ADDR_PORT);
1321 #else
1322                 allow = 0;
1323 #endif
1324                 if (!allow) {
1325                     AcpiOsFree(devinfo);
1326                     return (0);
1327                 }
1328             }
1329             AcpiOsFree(devinfo);
1330         }
1331     }
1332
1333 #ifdef INTRNG
1334     /* map with default for now */
1335     if (type == SYS_RES_IRQ)
1336         start = (rman_res_t)acpi_map_intr(child, (u_int)start,
1337                         acpi_get_handle(child));
1338 #endif
1339
1340     /* If the resource is already allocated, fail. */
1341     if (resource_list_busy(rl, type, rid))
1342         return (EBUSY);
1343
1344     /* If the resource is already reserved, release it. */
1345     if (resource_list_reserved(rl, type, rid))
1346         resource_list_unreserve(rl, dev, child, type, rid);
1347
1348     /* Add the resource. */
1349     end = (start + count - 1);
1350     resource_list_add(rl, type, rid, start, end, count);
1351
1352     /* Don't reserve resources until the system resources are allocated. */
1353     if (!sc->acpi_resources_reserved)
1354         return (0);
1355
1356     /* Don't reserve system resources. */
1357     if (ACPI_ID_PROBE(dev, child, sysres_ids, NULL) <= 0)
1358         return (0);
1359
1360     /*
1361      * Don't reserve IRQ resources.  There are many sticky things to
1362      * get right otherwise (e.g. IRQs for psm, atkbd, and HPET when
1363      * using legacy routing).
1364      */
1365     if (type == SYS_RES_IRQ)
1366         return (0);
1367
1368     /*
1369      * Don't reserve resources for CPU devices.  Some of these
1370      * resources need to be allocated as shareable, but reservations
1371      * are always non-shareable.
1372      */
1373     if (device_get_devclass(child) == devclass_find("cpu"))
1374         return (0);
1375
1376     /*
1377      * Reserve the resource.
1378      *
1379      * XXX: Ignores failure for now.  Failure here is probably a
1380      * BIOS/firmware bug?
1381      */
1382     resource_list_reserve(rl, dev, child, type, &rid, start, end, count, 0);
1383     return (0);
1384 }
1385
1386 static struct resource *
1387 acpi_alloc_resource(device_t bus, device_t child, int type, int *rid,
1388     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1389 {
1390 #ifndef INTRNG
1391     ACPI_RESOURCE ares;
1392 #endif
1393     struct acpi_device *ad;
1394     struct resource_list_entry *rle;
1395     struct resource_list *rl;
1396     struct resource *res;
1397     int isdefault = RMAN_IS_DEFAULT_RANGE(start, end);
1398
1399     /*
1400      * First attempt at allocating the resource.  For direct children,
1401      * use resource_list_alloc() to handle reserved resources.  For
1402      * other devices, pass the request up to our parent.
1403      */
1404     if (bus == device_get_parent(child)) {
1405         ad = device_get_ivars(child);
1406         rl = &ad->ad_rl;
1407
1408         /*
1409          * Simulate the behavior of the ISA bus for direct children
1410          * devices.  That is, if a non-default range is specified for
1411          * a resource that doesn't exist, use bus_set_resource() to
1412          * add the resource before allocating it.  Note that these
1413          * resources will not be reserved.
1414          */
1415         if (!isdefault && resource_list_find(rl, type, *rid) == NULL)
1416                 resource_list_add(rl, type, *rid, start, end, count);
1417         res = resource_list_alloc(rl, bus, child, type, rid, start, end, count,
1418             flags);
1419 #ifndef INTRNG
1420         if (res != NULL && type == SYS_RES_IRQ) {
1421             /*
1422              * Since bus_config_intr() takes immediate effect, we cannot
1423              * configure the interrupt associated with a device when we
1424              * parse the resources but have to defer it until a driver
1425              * actually allocates the interrupt via bus_alloc_resource().
1426              *
1427              * XXX: Should we handle the lookup failing?
1428              */
1429             if (ACPI_SUCCESS(acpi_lookup_irq_resource(child, *rid, res, &ares)))
1430                 acpi_config_intr(child, &ares);
1431         }
1432 #endif
1433
1434         /*
1435          * If this is an allocation of the "default" range for a given
1436          * RID, fetch the exact bounds for this resource from the
1437          * resource list entry to try to allocate the range from the
1438          * system resource regions.
1439          */
1440         if (res == NULL && isdefault) {
1441             rle = resource_list_find(rl, type, *rid);
1442             if (rle != NULL) {
1443                 start = rle->start;
1444                 end = rle->end;
1445                 count = rle->count;
1446             }
1447         }
1448     } else
1449         res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child, type, rid,
1450             start, end, count, flags);
1451
1452     /*
1453      * If the first attempt failed and this is an allocation of a
1454      * specific range, try to satisfy the request via a suballocation
1455      * from our system resource regions.
1456      */
1457     if (res == NULL && start + count - 1 == end)
1458         res = acpi_alloc_sysres(child, type, rid, start, end, count, flags);
1459     return (res);
1460 }
1461
1462 /*
1463  * Attempt to allocate a specific resource range from the system
1464  * resource ranges.  Note that we only handle memory and I/O port
1465  * system resources.
1466  */
1467 struct resource *
1468 acpi_alloc_sysres(device_t child, int type, int *rid, rman_res_t start,
1469     rman_res_t end, rman_res_t count, u_int flags)
1470 {
1471     struct rman *rm;
1472     struct resource *res;
1473
1474     switch (type) {
1475     case SYS_RES_IOPORT:
1476         rm = &acpi_rman_io;
1477         break;
1478     case SYS_RES_MEMORY:
1479         rm = &acpi_rman_mem;
1480         break;
1481     default:
1482         return (NULL);
1483     }
1484
1485     KASSERT(start + count - 1 == end, ("wildcard resource range"));
1486     res = rman_reserve_resource(rm, start, end, count, flags & ~RF_ACTIVE,
1487         child);
1488     if (res == NULL)
1489         return (NULL);
1490
1491     rman_set_rid(res, *rid);
1492
1493     /* If requested, activate the resource using the parent's method. */
1494     if (flags & RF_ACTIVE)
1495         if (bus_activate_resource(child, type, *rid, res) != 0) {
1496             rman_release_resource(res);
1497             return (NULL);
1498         }
1499
1500     return (res);
1501 }
1502
1503 static int
1504 acpi_is_resource_managed(int type, struct resource *r)
1505 {
1506
1507     /* We only handle memory and IO resources through rman. */
1508     switch (type) {
1509     case SYS_RES_IOPORT:
1510         return (rman_is_region_manager(r, &acpi_rman_io));
1511     case SYS_RES_MEMORY:
1512         return (rman_is_region_manager(r, &acpi_rman_mem));
1513     }
1514     return (0);
1515 }
1516
1517 static int
1518 acpi_adjust_resource(device_t bus, device_t child, int type, struct resource *r,
1519     rman_res_t start, rman_res_t end)
1520 {
1521
1522     if (acpi_is_resource_managed(type, r))
1523         return (rman_adjust_resource(r, start, end));
1524     return (bus_generic_adjust_resource(bus, child, type, r, start, end));
1525 }
1526
1527 static int
1528 acpi_release_resource(device_t bus, device_t child, int type, int rid,
1529     struct resource *r)
1530 {
1531     int ret;
1532
1533     /*
1534      * If this resource belongs to one of our internal managers,
1535      * deactivate it and release it to the local pool.
1536      */
1537     if (acpi_is_resource_managed(type, r)) {
1538         if (rman_get_flags(r) & RF_ACTIVE) {
1539             ret = bus_deactivate_resource(child, type, rid, r);
1540             if (ret != 0)
1541                 return (ret);
1542         }
1543         return (rman_release_resource(r));
1544     }
1545
1546     return (bus_generic_rl_release_resource(bus, child, type, rid, r));
1547 }
1548
1549 static void
1550 acpi_delete_resource(device_t bus, device_t child, int type, int rid)
1551 {
1552     struct resource_list *rl;
1553
1554     rl = acpi_get_rlist(bus, child);
1555     if (resource_list_busy(rl, type, rid)) {
1556         device_printf(bus, "delete_resource: Resource still owned by child"
1557             " (type=%d, rid=%d)\n", type, rid);
1558         return;
1559     }
1560     resource_list_unreserve(rl, bus, child, type, rid);
1561     resource_list_delete(rl, type, rid);
1562 }
1563
1564 /* Allocate an IO port or memory resource, given its GAS. */
1565 int
1566 acpi_bus_alloc_gas(device_t dev, int *type, int *rid, ACPI_GENERIC_ADDRESS *gas,
1567     struct resource **res, u_int flags)
1568 {
1569     int error, res_type;
1570
1571     error = ENOMEM;
1572     if (type == NULL || rid == NULL || gas == NULL || res == NULL)
1573         return (EINVAL);
1574
1575     /* We only support memory and IO spaces. */
1576     switch (gas->SpaceId) {
1577     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
1578         res_type = SYS_RES_MEMORY;
1579         break;
1580     case ACPI_ADR_SPACE_SYSTEM_IO:
1581         res_type = SYS_RES_IOPORT;
1582         break;
1583     default:
1584         return (EOPNOTSUPP);
1585     }
1586
1587     /*
1588      * If the register width is less than 8, assume the BIOS author means
1589      * it is a bit field and just allocate a byte.
1590      */
1591     if (gas->BitWidth && gas->BitWidth < 8)
1592         gas->BitWidth = 8;
1593
1594     /* Validate the address after we're sure we support the space. */
1595     if (gas->Address == 0 || gas->BitWidth == 0)
1596         return (EINVAL);
1597
1598     bus_set_resource(dev, res_type, *rid, gas->Address,
1599         gas->BitWidth / 8);
1600     *res = bus_alloc_resource_any(dev, res_type, rid, RF_ACTIVE | flags);
1601     if (*res != NULL) {
1602         *type = res_type;
1603         error = 0;
1604     } else
1605         bus_delete_resource(dev, res_type, *rid);
1606
1607     return (error);
1608 }
1609
1610 /* Probe _HID and _CID for compatible ISA PNP ids. */
1611 static uint32_t
1612 acpi_isa_get_logicalid(device_t dev)
1613 {
1614     ACPI_DEVICE_INFO    *devinfo;
1615     ACPI_HANDLE         h;
1616     uint32_t            pnpid;
1617
1618     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1619
1620     /* Fetch and validate the HID. */
1621     if ((h = acpi_get_handle(dev)) == NULL ||
1622         ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1623         return_VALUE (0);
1624
1625     pnpid = (devinfo->Valid & ACPI_VALID_HID) != 0 &&
1626         devinfo->HardwareId.Length >= ACPI_EISAID_STRING_SIZE ?
1627         PNP_EISAID(devinfo->HardwareId.String) : 0;
1628     AcpiOsFree(devinfo);
1629
1630     return_VALUE (pnpid);
1631 }
1632
1633 static int
1634 acpi_isa_get_compatid(device_t dev, uint32_t *cids, int count)
1635 {
1636     ACPI_DEVICE_INFO    *devinfo;
1637     ACPI_PNP_DEVICE_ID  *ids;
1638     ACPI_HANDLE         h;
1639     uint32_t            *pnpid;
1640     int                 i, valid;
1641
1642     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1643
1644     pnpid = cids;
1645
1646     /* Fetch and validate the CID */
1647     if ((h = acpi_get_handle(dev)) == NULL ||
1648         ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
1649         return_VALUE (0);
1650
1651     if ((devinfo->Valid & ACPI_VALID_CID) == 0) {
1652         AcpiOsFree(devinfo);
1653         return_VALUE (0);
1654     }
1655
1656     if (devinfo->CompatibleIdList.Count < count)
1657         count = devinfo->CompatibleIdList.Count;
1658     ids = devinfo->CompatibleIdList.Ids;
1659     for (i = 0, valid = 0; i < count; i++)
1660         if (ids[i].Length >= ACPI_EISAID_STRING_SIZE &&
1661             strncmp(ids[i].String, "PNP", 3) == 0) {
1662             *pnpid++ = PNP_EISAID(ids[i].String);
1663             valid++;
1664         }
1665     AcpiOsFree(devinfo);
1666
1667     return_VALUE (valid);
1668 }
1669
1670 static int
1671 acpi_device_id_probe(device_t bus, device_t dev, char **ids, char **match) 
1672 {
1673     ACPI_HANDLE h;
1674     ACPI_OBJECT_TYPE t;
1675     int rv;
1676     int i;
1677
1678     h = acpi_get_handle(dev);
1679     if (ids == NULL || h == NULL)
1680         return (ENXIO);
1681     t = acpi_get_type(dev);
1682     if (t != ACPI_TYPE_DEVICE && t != ACPI_TYPE_PROCESSOR)
1683         return (ENXIO);
1684
1685     /* Try to match one of the array of IDs with a HID or CID. */
1686     for (i = 0; ids[i] != NULL; i++) {
1687         rv = acpi_MatchHid(h, ids[i]);
1688         if (rv == ACPI_MATCHHID_NOMATCH)
1689             continue;
1690         
1691         if (match != NULL) {
1692             *match = ids[i];
1693         }
1694         return ((rv == ACPI_MATCHHID_HID)?
1695                     BUS_PROBE_DEFAULT : BUS_PROBE_LOW_PRIORITY);
1696     }
1697     return (ENXIO);
1698 }
1699
1700 static ACPI_STATUS
1701 acpi_device_eval_obj(device_t bus, device_t dev, ACPI_STRING pathname,
1702     ACPI_OBJECT_LIST *parameters, ACPI_BUFFER *ret)
1703 {
1704     ACPI_HANDLE h;
1705
1706     if (dev == NULL)
1707         h = ACPI_ROOT_OBJECT;
1708     else if ((h = acpi_get_handle(dev)) == NULL)
1709         return (AE_BAD_PARAMETER);
1710     return (AcpiEvaluateObject(h, pathname, parameters, ret));
1711 }
1712
1713 int
1714 acpi_device_pwr_for_sleep(device_t bus, device_t dev, int *dstate)
1715 {
1716     struct acpi_softc *sc;
1717     ACPI_HANDLE handle;
1718     ACPI_STATUS status;
1719     char sxd[8];
1720
1721     handle = acpi_get_handle(dev);
1722
1723     /*
1724      * XXX If we find these devices, don't try to power them down.
1725      * The serial and IRDA ports on my T23 hang the system when
1726      * set to D3 and it appears that such legacy devices may
1727      * need special handling in their drivers.
1728      */
1729     if (dstate == NULL || handle == NULL ||
1730         acpi_MatchHid(handle, "PNP0500") ||
1731         acpi_MatchHid(handle, "PNP0501") ||
1732         acpi_MatchHid(handle, "PNP0502") ||
1733         acpi_MatchHid(handle, "PNP0510") ||
1734         acpi_MatchHid(handle, "PNP0511"))
1735         return (ENXIO);
1736
1737     /*
1738      * Override next state with the value from _SxD, if present.
1739      * Note illegal _S0D is evaluated because some systems expect this.
1740      */
1741     sc = device_get_softc(bus);
1742     snprintf(sxd, sizeof(sxd), "_S%dD", sc->acpi_sstate);
1743     status = acpi_GetInteger(handle, sxd, dstate);
1744     if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
1745             device_printf(dev, "failed to get %s on %s: %s\n", sxd,
1746                 acpi_name(handle), AcpiFormatException(status));
1747             return (ENXIO);
1748     }
1749
1750     return (0);
1751 }
1752
1753 /* Callback arg for our implementation of walking the namespace. */
1754 struct acpi_device_scan_ctx {
1755     acpi_scan_cb_t      user_fn;
1756     void                *arg;
1757     ACPI_HANDLE         parent;
1758 };
1759
1760 static ACPI_STATUS
1761 acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level, void *arg, void **retval)
1762 {
1763     struct acpi_device_scan_ctx *ctx;
1764     device_t dev, old_dev;
1765     ACPI_STATUS status;
1766     ACPI_OBJECT_TYPE type;
1767
1768     /*
1769      * Skip this device if we think we'll have trouble with it or it is
1770      * the parent where the scan began.
1771      */
1772     ctx = (struct acpi_device_scan_ctx *)arg;
1773     if (acpi_avoid(h) || h == ctx->parent)
1774         return (AE_OK);
1775
1776     /* If this is not a valid device type (e.g., a method), skip it. */
1777     if (ACPI_FAILURE(AcpiGetType(h, &type)))
1778         return (AE_OK);
1779     if (type != ACPI_TYPE_DEVICE && type != ACPI_TYPE_PROCESSOR &&
1780         type != ACPI_TYPE_THERMAL && type != ACPI_TYPE_POWER)
1781         return (AE_OK);
1782
1783     /*
1784      * Call the user function with the current device.  If it is unchanged
1785      * afterwards, return.  Otherwise, we update the handle to the new dev.
1786      */
1787     old_dev = acpi_get_device(h);
1788     dev = old_dev;
1789     status = ctx->user_fn(h, &dev, level, ctx->arg);
1790     if (ACPI_FAILURE(status) || old_dev == dev)
1791         return (status);
1792
1793     /* Remove the old child and its connection to the handle. */
1794     if (old_dev != NULL) {
1795         device_delete_child(device_get_parent(old_dev), old_dev);
1796         AcpiDetachData(h, acpi_fake_objhandler);
1797     }
1798
1799     /* Recreate the handle association if the user created a device. */
1800     if (dev != NULL)
1801         AcpiAttachData(h, acpi_fake_objhandler, dev);
1802
1803     return (AE_OK);
1804 }
1805
1806 static ACPI_STATUS
1807 acpi_device_scan_children(device_t bus, device_t dev, int max_depth,
1808     acpi_scan_cb_t user_fn, void *arg)
1809 {
1810     ACPI_HANDLE h;
1811     struct acpi_device_scan_ctx ctx;
1812
1813     if (acpi_disabled("children"))
1814         return (AE_OK);
1815
1816     if (dev == NULL)
1817         h = ACPI_ROOT_OBJECT;
1818     else if ((h = acpi_get_handle(dev)) == NULL)
1819         return (AE_BAD_PARAMETER);
1820     ctx.user_fn = user_fn;
1821     ctx.arg = arg;
1822     ctx.parent = h;
1823     return (AcpiWalkNamespace(ACPI_TYPE_ANY, h, max_depth,
1824         acpi_device_scan_cb, NULL, &ctx, NULL));
1825 }
1826
1827 /*
1828  * Even though ACPI devices are not PCI, we use the PCI approach for setting
1829  * device power states since it's close enough to ACPI.
1830  */
1831 static int
1832 acpi_set_powerstate(device_t child, int state)
1833 {
1834     ACPI_HANDLE h;
1835     ACPI_STATUS status;
1836
1837     h = acpi_get_handle(child);
1838     if (state < ACPI_STATE_D0 || state > ACPI_D_STATES_MAX)
1839         return (EINVAL);
1840     if (h == NULL)
1841         return (0);
1842
1843     /* Ignore errors if the power methods aren't present. */
1844     status = acpi_pwr_switch_consumer(h, state);
1845     if (ACPI_SUCCESS(status)) {
1846         if (bootverbose)
1847             device_printf(child, "set ACPI power state D%d on %s\n",
1848                 state, acpi_name(h));
1849     } else if (status != AE_NOT_FOUND)
1850         device_printf(child,
1851             "failed to set ACPI power state D%d on %s: %s\n", state,
1852             acpi_name(h), AcpiFormatException(status));
1853
1854     return (0);
1855 }
1856
1857 static int
1858 acpi_isa_pnp_probe(device_t bus, device_t child, struct isa_pnp_id *ids)
1859 {
1860     int                 result, cid_count, i;
1861     uint32_t            lid, cids[8];
1862
1863     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1864
1865     /*
1866      * ISA-style drivers attached to ACPI may persist and
1867      * probe manually if we return ENOENT.  We never want
1868      * that to happen, so don't ever return it.
1869      */
1870     result = ENXIO;
1871
1872     /* Scan the supplied IDs for a match */
1873     lid = acpi_isa_get_logicalid(child);
1874     cid_count = acpi_isa_get_compatid(child, cids, 8);
1875     while (ids && ids->ip_id) {
1876         if (lid == ids->ip_id) {
1877             result = 0;
1878             goto out;
1879         }
1880         for (i = 0; i < cid_count; i++) {
1881             if (cids[i] == ids->ip_id) {
1882                 result = 0;
1883                 goto out;
1884             }
1885         }
1886         ids++;
1887     }
1888
1889  out:
1890     if (result == 0 && ids->ip_desc)
1891         device_set_desc(child, ids->ip_desc);
1892
1893     return_VALUE (result);
1894 }
1895
1896 /*
1897  * Look for a MCFG table.  If it is present, use the settings for
1898  * domain (segment) 0 to setup PCI config space access via the memory
1899  * map.
1900  *
1901  * On non-x86 architectures (arm64 for now), this will be done from the
1902  * PCI host bridge driver.
1903  */
1904 static void
1905 acpi_enable_pcie(void)
1906 {
1907 #if defined(__i386__) || defined(__amd64__)
1908         ACPI_TABLE_HEADER *hdr;
1909         ACPI_MCFG_ALLOCATION *alloc, *end;
1910         ACPI_STATUS status;
1911
1912         status = AcpiGetTable(ACPI_SIG_MCFG, 1, &hdr);
1913         if (ACPI_FAILURE(status))
1914                 return;
1915
1916         end = (ACPI_MCFG_ALLOCATION *)((char *)hdr + hdr->Length);
1917         alloc = (ACPI_MCFG_ALLOCATION *)((ACPI_TABLE_MCFG *)hdr + 1);
1918         while (alloc < end) {
1919                 if (alloc->PciSegment == 0) {
1920                         pcie_cfgregopen(alloc->Address, alloc->StartBusNumber,
1921                             alloc->EndBusNumber);
1922                         return;
1923                 }
1924                 alloc++;
1925         }
1926 #endif
1927 }
1928
1929 /*
1930  * Scan all of the ACPI namespace and attach child devices.
1931  *
1932  * We should only expect to find devices in the \_PR, \_TZ, \_SI, and
1933  * \_SB scopes, and \_PR and \_TZ became obsolete in the ACPI 2.0 spec.
1934  * However, in violation of the spec, some systems place their PCI link
1935  * devices in \, so we have to walk the whole namespace.  We check the
1936  * type of namespace nodes, so this should be ok.
1937  */
1938 static void
1939 acpi_probe_children(device_t bus)
1940 {
1941
1942     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
1943
1944     /*
1945      * Scan the namespace and insert placeholders for all the devices that
1946      * we find.  We also probe/attach any early devices.
1947      *
1948      * Note that we use AcpiWalkNamespace rather than AcpiGetDevices because
1949      * we want to create nodes for all devices, not just those that are
1950      * currently present. (This assumes that we don't want to create/remove
1951      * devices as they appear, which might be smarter.)
1952      */
1953     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "namespace scan\n"));
1954     AcpiWalkNamespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, 100, acpi_probe_child,
1955         NULL, bus, NULL);
1956
1957     /* Pre-allocate resources for our rman from any sysresource devices. */
1958     acpi_sysres_alloc(bus);
1959
1960     /* Reserve resources already allocated to children. */
1961     acpi_reserve_resources(bus);
1962
1963     /* Create any static children by calling device identify methods. */
1964     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "device identify routines\n"));
1965     bus_generic_probe(bus);
1966
1967     /* Probe/attach all children, created statically and from the namespace. */
1968     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "acpi bus_generic_attach\n"));
1969     bus_generic_attach(bus);
1970
1971     /* Attach wake sysctls. */
1972     acpi_wake_sysctl_walk(bus);
1973
1974     ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "done attaching children\n"));
1975     return_VOID;
1976 }
1977
1978 /*
1979  * Determine the probe order for a given device.
1980  */
1981 static void
1982 acpi_probe_order(ACPI_HANDLE handle, int *order)
1983 {
1984         ACPI_OBJECT_TYPE type;
1985
1986         /*
1987          * 0. CPUs
1988          * 1. I/O port and memory system resource holders
1989          * 2. Clocks and timers (to handle early accesses)
1990          * 3. Embedded controllers (to handle early accesses)
1991          * 4. PCI Link Devices
1992          */
1993         AcpiGetType(handle, &type);
1994         if (type == ACPI_TYPE_PROCESSOR)
1995                 *order = 0;
1996         else if (acpi_MatchHid(handle, "PNP0C01") ||
1997             acpi_MatchHid(handle, "PNP0C02"))
1998                 *order = 1;
1999         else if (acpi_MatchHid(handle, "PNP0100") ||
2000             acpi_MatchHid(handle, "PNP0103") ||
2001             acpi_MatchHid(handle, "PNP0B00"))
2002                 *order = 2;
2003         else if (acpi_MatchHid(handle, "PNP0C09"))
2004                 *order = 3;
2005         else if (acpi_MatchHid(handle, "PNP0C0F"))
2006                 *order = 4;
2007 }
2008
2009 /*
2010  * Evaluate a child device and determine whether we might attach a device to
2011  * it.
2012  */
2013 static ACPI_STATUS
2014 acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
2015 {
2016     ACPI_DEVICE_INFO *devinfo;
2017     struct acpi_device  *ad;
2018     struct acpi_prw_data prw;
2019     ACPI_OBJECT_TYPE type;
2020     ACPI_HANDLE h;
2021     device_t bus, child;
2022     char *handle_str;
2023     int order;
2024
2025     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
2026
2027     if (acpi_disabled("children"))
2028         return_ACPI_STATUS (AE_OK);
2029
2030     /* Skip this device if we think we'll have trouble with it. */
2031     if (acpi_avoid(handle))
2032         return_ACPI_STATUS (AE_OK);
2033
2034     bus = (device_t)context;
2035     if (ACPI_SUCCESS(AcpiGetType(handle, &type))) {
2036         handle_str = acpi_name(handle);
2037         switch (type) {
2038         case ACPI_TYPE_DEVICE:
2039             /*
2040              * Since we scan from \, be sure to skip system scope objects.
2041              * \_SB_ and \_TZ_ are defined in ACPICA as devices to work around
2042              * BIOS bugs.  For example, \_SB_ is to allow \_SB_._INI to be run
2043              * during the initialization and \_TZ_ is to support Notify() on it.
2044              */
2045             if (strcmp(handle_str, "\\_SB_") == 0 ||
2046                 strcmp(handle_str, "\\_TZ_") == 0)
2047                 break;
2048             if (acpi_parse_prw(handle, &prw) == 0)
2049                 AcpiSetupGpeForWake(handle, prw.gpe_handle, prw.gpe_bit);
2050
2051             /*
2052              * Ignore devices that do not have a _HID or _CID.  They should
2053              * be discovered by other buses (e.g. the PCI bus driver).
2054              */
2055             if (!acpi_has_hid(handle))
2056                 break;
2057             /* FALLTHROUGH */
2058         case ACPI_TYPE_PROCESSOR:
2059         case ACPI_TYPE_THERMAL:
2060         case ACPI_TYPE_POWER:
2061             /* 
2062              * Create a placeholder device for this node.  Sort the
2063              * placeholder so that the probe/attach passes will run
2064              * breadth-first.  Orders less than ACPI_DEV_BASE_ORDER
2065              * are reserved for special objects (i.e., system
2066              * resources).
2067              */
2068             ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
2069             order = level * 10 + ACPI_DEV_BASE_ORDER;
2070             acpi_probe_order(handle, &order);
2071             child = BUS_ADD_CHILD(bus, order, NULL, -1);
2072             if (child == NULL)
2073                 break;
2074
2075             /* Associate the handle with the device_t and vice versa. */
2076             acpi_set_handle(child, handle);
2077             AcpiAttachData(handle, acpi_fake_objhandler, child);
2078
2079             /*
2080              * Check that the device is present.  If it's not present,
2081              * leave it disabled (so that we have a device_t attached to
2082              * the handle, but we don't probe it).
2083              *
2084              * XXX PCI link devices sometimes report "present" but not
2085              * "functional" (i.e. if disabled).  Go ahead and probe them
2086              * anyway since we may enable them later.
2087              */
2088             if (type == ACPI_TYPE_DEVICE && !acpi_DeviceIsPresent(child)) {
2089                 /* Never disable PCI link devices. */
2090                 if (acpi_MatchHid(handle, "PNP0C0F"))
2091                     break;
2092                 /*
2093                  * Docking stations should remain enabled since the system
2094                  * may be undocked at boot.
2095                  */
2096                 if (ACPI_SUCCESS(AcpiGetHandle(handle, "_DCK", &h)))
2097                     break;
2098
2099                 device_disable(child);
2100                 break;
2101             }
2102
2103             /*
2104              * Get the device's resource settings and attach them.
2105              * Note that if the device has _PRS but no _CRS, we need
2106              * to decide when it's appropriate to try to configure the
2107              * device.  Ignore the return value here; it's OK for the
2108              * device not to have any resources.
2109              */
2110             acpi_parse_resources(child, handle, &acpi_res_parse_set, NULL);
2111
2112             ad = device_get_ivars(child);
2113             ad->ad_cls_class = 0xffffff;
2114             if (ACPI_SUCCESS(AcpiGetObjectInfo(handle, &devinfo))) {
2115                 if ((devinfo->Valid & ACPI_VALID_CLS) != 0 &&
2116                     devinfo->ClassCode.Length >= ACPI_PCICLS_STRING_SIZE) {
2117                     ad->ad_cls_class = strtoul(devinfo->ClassCode.String,
2118                         NULL, 16);
2119                 }
2120                 AcpiOsFree(devinfo);
2121             }
2122             break;
2123         }
2124     }
2125
2126     return_ACPI_STATUS (AE_OK);
2127 }
2128
2129 /*
2130  * AcpiAttachData() requires an object handler but never uses it.  This is a
2131  * placeholder object handler so we can store a device_t in an ACPI_HANDLE.
2132  */
2133 void
2134 acpi_fake_objhandler(ACPI_HANDLE h, void *data)
2135 {
2136 }
2137
2138 static void
2139 acpi_shutdown_final(void *arg, int howto)
2140 {
2141     struct acpi_softc *sc = (struct acpi_softc *)arg;
2142     register_t intr;
2143     ACPI_STATUS status;
2144
2145     /*
2146      * XXX Shutdown code should only run on the BSP (cpuid 0).
2147      * Some chipsets do not power off the system correctly if called from
2148      * an AP.
2149      */
2150     if ((howto & RB_POWEROFF) != 0) {
2151         status = AcpiEnterSleepStatePrep(ACPI_STATE_S5);
2152         if (ACPI_FAILURE(status)) {
2153             device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
2154                 AcpiFormatException(status));
2155             return;
2156         }
2157         device_printf(sc->acpi_dev, "Powering system off\n");
2158         intr = intr_disable();
2159         status = AcpiEnterSleepState(ACPI_STATE_S5);
2160         if (ACPI_FAILURE(status)) {
2161             intr_restore(intr);
2162             device_printf(sc->acpi_dev, "power-off failed - %s\n",
2163                 AcpiFormatException(status));
2164         } else {
2165             DELAY(1000000);
2166             intr_restore(intr);
2167             device_printf(sc->acpi_dev, "power-off failed - timeout\n");
2168         }
2169     } else if ((howto & RB_HALT) == 0 && sc->acpi_handle_reboot) {
2170         /* Reboot using the reset register. */
2171         status = AcpiReset();
2172         if (ACPI_SUCCESS(status)) {
2173             DELAY(1000000);
2174             device_printf(sc->acpi_dev, "reset failed - timeout\n");
2175         } else if (status != AE_NOT_EXIST)
2176             device_printf(sc->acpi_dev, "reset failed - %s\n",
2177                 AcpiFormatException(status));
2178     } else if (sc->acpi_do_disable && !KERNEL_PANICKED()) {
2179         /*
2180          * Only disable ACPI if the user requested.  On some systems, writing
2181          * the disable value to SMI_CMD hangs the system.
2182          */
2183         device_printf(sc->acpi_dev, "Shutting down\n");
2184         AcpiTerminate();
2185     }
2186 }
2187
2188 static void
2189 acpi_enable_fixed_events(struct acpi_softc *sc)
2190 {
2191     static int  first_time = 1;
2192
2193     /* Enable and clear fixed events and install handlers. */
2194     if ((AcpiGbl_FADT.Flags & ACPI_FADT_POWER_BUTTON) == 0) {
2195         AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
2196         AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON,
2197                                      acpi_event_power_button_sleep, sc);
2198         if (first_time)
2199             device_printf(sc->acpi_dev, "Power Button (fixed)\n");
2200     }
2201     if ((AcpiGbl_FADT.Flags & ACPI_FADT_SLEEP_BUTTON) == 0) {
2202         AcpiClearEvent(ACPI_EVENT_SLEEP_BUTTON);
2203         AcpiInstallFixedEventHandler(ACPI_EVENT_SLEEP_BUTTON,
2204                                      acpi_event_sleep_button_sleep, sc);
2205         if (first_time)
2206             device_printf(sc->acpi_dev, "Sleep Button (fixed)\n");
2207     }
2208
2209     first_time = 0;
2210 }
2211
2212 /*
2213  * Returns true if the device is actually present and should
2214  * be attached to.  This requires the present, enabled, UI-visible 
2215  * and diagnostics-passed bits to be set.
2216  */
2217 BOOLEAN
2218 acpi_DeviceIsPresent(device_t dev)
2219 {
2220         ACPI_HANDLE h;
2221         UINT32 s;
2222         ACPI_STATUS status;
2223
2224         h = acpi_get_handle(dev);
2225         if (h == NULL)
2226                 return (FALSE);
2227         /*
2228          * Certain Treadripper boards always returns 0 for FreeBSD because it
2229          * only returns non-zero for the OS string "Windows 2015". Otherwise it
2230          * will return zero. Force them to always be treated as present.
2231          * Beata versions were worse: they always returned 0.
2232          */
2233         if (acpi_MatchHid(h, "AMDI0020") || acpi_MatchHid(h, "AMDI0010"))
2234                 return (TRUE);
2235
2236         status = acpi_GetInteger(h, "_STA", &s);
2237
2238         /*
2239          * If no _STA method or if it failed, then assume that
2240          * the device is present.
2241          */
2242         if (ACPI_FAILURE(status))
2243                 return (TRUE);
2244
2245         return (ACPI_DEVICE_PRESENT(s) ? TRUE : FALSE);
2246 }
2247
2248 /*
2249  * Returns true if the battery is actually present and inserted.
2250  */
2251 BOOLEAN
2252 acpi_BatteryIsPresent(device_t dev)
2253 {
2254         ACPI_HANDLE h;
2255         UINT32 s;
2256         ACPI_STATUS status;
2257
2258         h = acpi_get_handle(dev);
2259         if (h == NULL)
2260                 return (FALSE);
2261         status = acpi_GetInteger(h, "_STA", &s);
2262
2263         /*
2264          * If no _STA method or if it failed, then assume that
2265          * the device is present.
2266          */
2267         if (ACPI_FAILURE(status))
2268                 return (TRUE);
2269
2270         return (ACPI_BATTERY_PRESENT(s) ? TRUE : FALSE);
2271 }
2272
2273 /*
2274  * Returns true if a device has at least one valid device ID.
2275  */
2276 static BOOLEAN
2277 acpi_has_hid(ACPI_HANDLE h)
2278 {
2279     ACPI_DEVICE_INFO    *devinfo;
2280     BOOLEAN             ret;
2281
2282     if (h == NULL ||
2283         ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2284         return (FALSE);
2285
2286     ret = FALSE;
2287     if ((devinfo->Valid & ACPI_VALID_HID) != 0)
2288         ret = TRUE;
2289     else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2290         if (devinfo->CompatibleIdList.Count > 0)
2291             ret = TRUE;
2292
2293     AcpiOsFree(devinfo);
2294     return (ret);
2295 }
2296
2297 /*
2298  * Match a HID string against a handle
2299  * returns ACPI_MATCHHID_HID if _HID match
2300  *         ACPI_MATCHHID_CID if _CID match and not _HID match.
2301  *         ACPI_MATCHHID_NOMATCH=0 if no match.
2302  */
2303 int
2304 acpi_MatchHid(ACPI_HANDLE h, const char *hid) 
2305 {
2306     ACPI_DEVICE_INFO    *devinfo;
2307     BOOLEAN             ret;
2308     int                 i;
2309
2310     if (hid == NULL || h == NULL ||
2311         ACPI_FAILURE(AcpiGetObjectInfo(h, &devinfo)))
2312         return (ACPI_MATCHHID_NOMATCH);
2313
2314     ret = ACPI_MATCHHID_NOMATCH;
2315     if ((devinfo->Valid & ACPI_VALID_HID) != 0 &&
2316         strcmp(hid, devinfo->HardwareId.String) == 0)
2317             ret = ACPI_MATCHHID_HID;
2318     else if ((devinfo->Valid & ACPI_VALID_CID) != 0)
2319         for (i = 0; i < devinfo->CompatibleIdList.Count; i++) {
2320             if (strcmp(hid, devinfo->CompatibleIdList.Ids[i].String) == 0) {
2321                 ret = ACPI_MATCHHID_CID;
2322                 break;
2323             }
2324         }
2325
2326     AcpiOsFree(devinfo);
2327     return (ret);
2328 }
2329
2330 /*
2331  * Return the handle of a named object within our scope, ie. that of (parent)
2332  * or one if its parents.
2333  */
2334 ACPI_STATUS
2335 acpi_GetHandleInScope(ACPI_HANDLE parent, char *path, ACPI_HANDLE *result)
2336 {
2337     ACPI_HANDLE         r;
2338     ACPI_STATUS         status;
2339
2340     /* Walk back up the tree to the root */
2341     for (;;) {
2342         status = AcpiGetHandle(parent, path, &r);
2343         if (ACPI_SUCCESS(status)) {
2344             *result = r;
2345             return (AE_OK);
2346         }
2347         /* XXX Return error here? */
2348         if (status != AE_NOT_FOUND)
2349             return (AE_OK);
2350         if (ACPI_FAILURE(AcpiGetParent(parent, &r)))
2351             return (AE_NOT_FOUND);
2352         parent = r;
2353     }
2354 }
2355
2356 /*
2357  * Allocate a buffer with a preset data size.
2358  */
2359 ACPI_BUFFER *
2360 acpi_AllocBuffer(int size)
2361 {
2362     ACPI_BUFFER *buf;
2363
2364     if ((buf = malloc(size + sizeof(*buf), M_ACPIDEV, M_NOWAIT)) == NULL)
2365         return (NULL);
2366     buf->Length = size;
2367     buf->Pointer = (void *)(buf + 1);
2368     return (buf);
2369 }
2370
2371 ACPI_STATUS
2372 acpi_SetInteger(ACPI_HANDLE handle, char *path, UINT32 number)
2373 {
2374     ACPI_OBJECT arg1;
2375     ACPI_OBJECT_LIST args;
2376
2377     arg1.Type = ACPI_TYPE_INTEGER;
2378     arg1.Integer.Value = number;
2379     args.Count = 1;
2380     args.Pointer = &arg1;
2381
2382     return (AcpiEvaluateObject(handle, path, &args, NULL));
2383 }
2384
2385 /*
2386  * Evaluate a path that should return an integer.
2387  */
2388 ACPI_STATUS
2389 acpi_GetInteger(ACPI_HANDLE handle, char *path, UINT32 *number)
2390 {
2391     ACPI_STATUS status;
2392     ACPI_BUFFER buf;
2393     ACPI_OBJECT param;
2394
2395     if (handle == NULL)
2396         handle = ACPI_ROOT_OBJECT;
2397
2398     /*
2399      * Assume that what we've been pointed at is an Integer object, or
2400      * a method that will return an Integer.
2401      */
2402     buf.Pointer = &param;
2403     buf.Length = sizeof(param);
2404     status = AcpiEvaluateObject(handle, path, NULL, &buf);
2405     if (ACPI_SUCCESS(status)) {
2406         if (param.Type == ACPI_TYPE_INTEGER)
2407             *number = param.Integer.Value;
2408         else
2409             status = AE_TYPE;
2410     }
2411
2412     /* 
2413      * In some applications, a method that's expected to return an Integer
2414      * may instead return a Buffer (probably to simplify some internal
2415      * arithmetic).  We'll try to fetch whatever it is, and if it's a Buffer,
2416      * convert it into an Integer as best we can.
2417      *
2418      * This is a hack.
2419      */
2420     if (status == AE_BUFFER_OVERFLOW) {
2421         if ((buf.Pointer = AcpiOsAllocate(buf.Length)) == NULL) {
2422             status = AE_NO_MEMORY;
2423         } else {
2424             status = AcpiEvaluateObject(handle, path, NULL, &buf);
2425             if (ACPI_SUCCESS(status))
2426                 status = acpi_ConvertBufferToInteger(&buf, number);
2427             AcpiOsFree(buf.Pointer);
2428         }
2429     }
2430     return (status);
2431 }
2432
2433 ACPI_STATUS
2434 acpi_ConvertBufferToInteger(ACPI_BUFFER *bufp, UINT32 *number)
2435 {
2436     ACPI_OBJECT *p;
2437     UINT8       *val;
2438     int         i;
2439
2440     p = (ACPI_OBJECT *)bufp->Pointer;
2441     if (p->Type == ACPI_TYPE_INTEGER) {
2442         *number = p->Integer.Value;
2443         return (AE_OK);
2444     }
2445     if (p->Type != ACPI_TYPE_BUFFER)
2446         return (AE_TYPE);
2447     if (p->Buffer.Length > sizeof(int))
2448         return (AE_BAD_DATA);
2449
2450     *number = 0;
2451     val = p->Buffer.Pointer;
2452     for (i = 0; i < p->Buffer.Length; i++)
2453         *number += val[i] << (i * 8);
2454     return (AE_OK);
2455 }
2456
2457 /*
2458  * Iterate over the elements of an a package object, calling the supplied
2459  * function for each element.
2460  *
2461  * XXX possible enhancement might be to abort traversal on error.
2462  */
2463 ACPI_STATUS
2464 acpi_ForeachPackageObject(ACPI_OBJECT *pkg,
2465         void (*func)(ACPI_OBJECT *comp, void *arg), void *arg)
2466 {
2467     ACPI_OBJECT *comp;
2468     int         i;
2469
2470     if (pkg == NULL || pkg->Type != ACPI_TYPE_PACKAGE)
2471         return (AE_BAD_PARAMETER);
2472
2473     /* Iterate over components */
2474     i = 0;
2475     comp = pkg->Package.Elements;
2476     for (; i < pkg->Package.Count; i++, comp++)
2477         func(comp, arg);
2478
2479     return (AE_OK);
2480 }
2481
2482 /*
2483  * Find the (index)th resource object in a set.
2484  */
2485 ACPI_STATUS
2486 acpi_FindIndexedResource(ACPI_BUFFER *buf, int index, ACPI_RESOURCE **resp)
2487 {
2488     ACPI_RESOURCE       *rp;
2489     int                 i;
2490
2491     rp = (ACPI_RESOURCE *)buf->Pointer;
2492     i = index;
2493     while (i-- > 0) {
2494         /* Range check */
2495         if (rp > (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2496             return (AE_BAD_PARAMETER);
2497
2498         /* Check for terminator */
2499         if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2500             return (AE_NOT_FOUND);
2501         rp = ACPI_NEXT_RESOURCE(rp);
2502     }
2503     if (resp != NULL)
2504         *resp = rp;
2505
2506     return (AE_OK);
2507 }
2508
2509 /*
2510  * Append an ACPI_RESOURCE to an ACPI_BUFFER.
2511  *
2512  * Given a pointer to an ACPI_RESOURCE structure, expand the ACPI_BUFFER
2513  * provided to contain it.  If the ACPI_BUFFER is empty, allocate a sensible
2514  * backing block.  If the ACPI_RESOURCE is NULL, return an empty set of
2515  * resources.
2516  */
2517 #define ACPI_INITIAL_RESOURCE_BUFFER_SIZE       512
2518
2519 ACPI_STATUS
2520 acpi_AppendBufferResource(ACPI_BUFFER *buf, ACPI_RESOURCE *res)
2521 {
2522     ACPI_RESOURCE       *rp;
2523     void                *newp;
2524
2525     /* Initialise the buffer if necessary. */
2526     if (buf->Pointer == NULL) {
2527         buf->Length = ACPI_INITIAL_RESOURCE_BUFFER_SIZE;
2528         if ((buf->Pointer = AcpiOsAllocate(buf->Length)) == NULL)
2529             return (AE_NO_MEMORY);
2530         rp = (ACPI_RESOURCE *)buf->Pointer;
2531         rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2532         rp->Length = ACPI_RS_SIZE_MIN;
2533     }
2534     if (res == NULL)
2535         return (AE_OK);
2536
2537     /*
2538      * Scan the current buffer looking for the terminator.
2539      * This will either find the terminator or hit the end
2540      * of the buffer and return an error.
2541      */
2542     rp = (ACPI_RESOURCE *)buf->Pointer;
2543     for (;;) {
2544         /* Range check, don't go outside the buffer */
2545         if (rp >= (ACPI_RESOURCE *)((u_int8_t *)buf->Pointer + buf->Length))
2546             return (AE_BAD_PARAMETER);
2547         if (rp->Type == ACPI_RESOURCE_TYPE_END_TAG || rp->Length == 0)
2548             break;
2549         rp = ACPI_NEXT_RESOURCE(rp);
2550     }
2551
2552     /*
2553      * Check the size of the buffer and expand if required.
2554      *
2555      * Required size is:
2556      *  size of existing resources before terminator + 
2557      *  size of new resource and header +
2558      *  size of terminator.
2559      *
2560      * Note that this loop should really only run once, unless
2561      * for some reason we are stuffing a *really* huge resource.
2562      */
2563     while ((((u_int8_t *)rp - (u_int8_t *)buf->Pointer) + 
2564             res->Length + ACPI_RS_SIZE_NO_DATA +
2565             ACPI_RS_SIZE_MIN) >= buf->Length) {
2566         if ((newp = AcpiOsAllocate(buf->Length * 2)) == NULL)
2567             return (AE_NO_MEMORY);
2568         bcopy(buf->Pointer, newp, buf->Length);
2569         rp = (ACPI_RESOURCE *)((u_int8_t *)newp +
2570                                ((u_int8_t *)rp - (u_int8_t *)buf->Pointer));
2571         AcpiOsFree(buf->Pointer);
2572         buf->Pointer = newp;
2573         buf->Length += buf->Length;
2574     }
2575
2576     /* Insert the new resource. */
2577     bcopy(res, rp, res->Length + ACPI_RS_SIZE_NO_DATA);
2578
2579     /* And add the terminator. */
2580     rp = ACPI_NEXT_RESOURCE(rp);
2581     rp->Type = ACPI_RESOURCE_TYPE_END_TAG;
2582     rp->Length = ACPI_RS_SIZE_MIN;
2583
2584     return (AE_OK);
2585 }
2586
2587 UINT8
2588 acpi_DSMQuery(ACPI_HANDLE h, uint8_t *uuid, int revision)
2589 {
2590     /*
2591      * ACPI spec 9.1.1 defines this.
2592      *
2593      * "Arg2: Function Index Represents a specific function whose meaning is
2594      * specific to the UUID and Revision ID. Function indices should start
2595      * with 1. Function number zero is a query function (see the special
2596      * return code defined below)."
2597      */
2598     ACPI_BUFFER buf;
2599     ACPI_OBJECT *obj;
2600     UINT8 ret = 0;
2601
2602     if (!ACPI_SUCCESS(acpi_EvaluateDSM(h, uuid, revision, 0, NULL, &buf))) {
2603         ACPI_INFO(("Failed to enumerate DSM functions\n"));
2604         return (0);
2605     }
2606
2607     obj = (ACPI_OBJECT *)buf.Pointer;
2608     KASSERT(obj, ("Object not allowed to be NULL\n"));
2609
2610     /*
2611      * From ACPI 6.2 spec 9.1.1:
2612      * If Function Index = 0, a Buffer containing a function index bitfield.
2613      * Otherwise, the return value and type depends on the UUID and revision
2614      * ID (see below).
2615      */
2616     switch (obj->Type) {
2617     case ACPI_TYPE_BUFFER:
2618         ret = *(uint8_t *)obj->Buffer.Pointer;
2619         break;
2620     case ACPI_TYPE_INTEGER:
2621         ACPI_BIOS_WARNING((AE_INFO,
2622             "Possibly buggy BIOS with ACPI_TYPE_INTEGER for function enumeration\n"));
2623         ret = obj->Integer.Value & 0xFF;
2624         break;
2625     default:
2626         ACPI_WARNING((AE_INFO, "Unexpected return type %u\n", obj->Type));
2627     };
2628
2629     AcpiOsFree(obj);
2630     return ret;
2631 }
2632
2633 /*
2634  * DSM may return multiple types depending on the function. It is therefore
2635  * unsafe to use the typed evaluation. It is highly recommended that the caller
2636  * check the type of the returned object.
2637  */
2638 ACPI_STATUS
2639 acpi_EvaluateDSM(ACPI_HANDLE handle, uint8_t *uuid, int revision,
2640     uint64_t function, union acpi_object *package, ACPI_BUFFER *out_buf)
2641 {
2642     ACPI_OBJECT arg[4];
2643     ACPI_OBJECT_LIST arglist;
2644     ACPI_BUFFER buf;
2645     ACPI_STATUS status;
2646
2647     if (out_buf == NULL)
2648         return (AE_NO_MEMORY);
2649
2650     arg[0].Type = ACPI_TYPE_BUFFER;
2651     arg[0].Buffer.Length = ACPI_UUID_LENGTH;
2652     arg[0].Buffer.Pointer = uuid;
2653     arg[1].Type = ACPI_TYPE_INTEGER;
2654     arg[1].Integer.Value = revision;
2655     arg[2].Type = ACPI_TYPE_INTEGER;
2656     arg[2].Integer.Value = function;
2657     if (package) {
2658         arg[3] = *package;
2659     } else {
2660         arg[3].Type = ACPI_TYPE_PACKAGE;
2661         arg[3].Package.Count = 0;
2662         arg[3].Package.Elements = NULL;
2663     }
2664
2665     arglist.Pointer = arg;
2666     arglist.Count = 4;
2667     buf.Pointer = NULL;
2668     buf.Length = ACPI_ALLOCATE_BUFFER;
2669     status = AcpiEvaluateObject(handle, "_DSM", &arglist, &buf);
2670     if (ACPI_FAILURE(status))
2671         return (status);
2672
2673     KASSERT(ACPI_SUCCESS(status), ("Unexpected status"));
2674
2675     *out_buf = buf;
2676     return (status);
2677 }
2678
2679 ACPI_STATUS
2680 acpi_EvaluateOSC(ACPI_HANDLE handle, uint8_t *uuid, int revision, int count,
2681     uint32_t *caps_in, uint32_t *caps_out, bool query)
2682 {
2683         ACPI_OBJECT arg[4], *ret;
2684         ACPI_OBJECT_LIST arglist;
2685         ACPI_BUFFER buf;
2686         ACPI_STATUS status;
2687
2688         arglist.Pointer = arg;
2689         arglist.Count = 4;
2690         arg[0].Type = ACPI_TYPE_BUFFER;
2691         arg[0].Buffer.Length = ACPI_UUID_LENGTH;
2692         arg[0].Buffer.Pointer = uuid;
2693         arg[1].Type = ACPI_TYPE_INTEGER;
2694         arg[1].Integer.Value = revision;
2695         arg[2].Type = ACPI_TYPE_INTEGER;
2696         arg[2].Integer.Value = count;
2697         arg[3].Type = ACPI_TYPE_BUFFER;
2698         arg[3].Buffer.Length = count * sizeof(*caps_in);
2699         arg[3].Buffer.Pointer = (uint8_t *)caps_in;
2700         caps_in[0] = query ? 1 : 0;
2701         buf.Pointer = NULL;
2702         buf.Length = ACPI_ALLOCATE_BUFFER;
2703         status = AcpiEvaluateObjectTyped(handle, "_OSC", &arglist, &buf,
2704             ACPI_TYPE_BUFFER);
2705         if (ACPI_FAILURE(status))
2706                 return (status);
2707         if (caps_out != NULL) {
2708                 ret = buf.Pointer;
2709                 if (ret->Buffer.Length != count * sizeof(*caps_out)) {
2710                         AcpiOsFree(buf.Pointer);
2711                         return (AE_BUFFER_OVERFLOW);
2712                 }
2713                 bcopy(ret->Buffer.Pointer, caps_out, ret->Buffer.Length);
2714         }
2715         AcpiOsFree(buf.Pointer);
2716         return (status);
2717 }
2718
2719 /*
2720  * Set interrupt model.
2721  */
2722 ACPI_STATUS
2723 acpi_SetIntrModel(int model)
2724 {
2725
2726     return (acpi_SetInteger(ACPI_ROOT_OBJECT, "_PIC", model));
2727 }
2728
2729 /*
2730  * Walk subtables of a table and call a callback routine for each
2731  * subtable.  The caller should provide the first subtable and a
2732  * pointer to the end of the table.  This can be used to walk tables
2733  * such as MADT and SRAT that use subtable entries.
2734  */
2735 void
2736 acpi_walk_subtables(void *first, void *end, acpi_subtable_handler *handler,
2737     void *arg)
2738 {
2739     ACPI_SUBTABLE_HEADER *entry;
2740
2741     for (entry = first; (void *)entry < end; ) {
2742         /* Avoid an infinite loop if we hit a bogus entry. */
2743         if (entry->Length < sizeof(ACPI_SUBTABLE_HEADER))
2744             return;
2745
2746         handler(entry, arg);
2747         entry = ACPI_ADD_PTR(ACPI_SUBTABLE_HEADER, entry, entry->Length);
2748     }
2749 }
2750
2751 /*
2752  * DEPRECATED.  This interface has serious deficiencies and will be
2753  * removed.
2754  *
2755  * Immediately enter the sleep state.  In the old model, acpiconf(8) ran
2756  * rc.suspend and rc.resume so we don't have to notify devd(8) to do this.
2757  */
2758 ACPI_STATUS
2759 acpi_SetSleepState(struct acpi_softc *sc, int state)
2760 {
2761     static int once;
2762
2763     if (!once) {
2764         device_printf(sc->acpi_dev,
2765 "warning: acpi_SetSleepState() deprecated, need to update your software\n");
2766         once = 1;
2767     }
2768     return (acpi_EnterSleepState(sc, state));
2769 }
2770
2771 #if defined(__amd64__) || defined(__i386__)
2772 static void
2773 acpi_sleep_force_task(void *context)
2774 {
2775     struct acpi_softc *sc = (struct acpi_softc *)context;
2776
2777     if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
2778         device_printf(sc->acpi_dev, "force sleep state S%d failed\n",
2779             sc->acpi_next_sstate);
2780 }
2781
2782 static void
2783 acpi_sleep_force(void *arg)
2784 {
2785     struct acpi_softc *sc = (struct acpi_softc *)arg;
2786
2787     device_printf(sc->acpi_dev,
2788         "suspend request timed out, forcing sleep now\n");
2789     /*
2790      * XXX Suspending from callout causes freezes in DEVICE_SUSPEND().
2791      * Suspend from acpi_task thread instead.
2792      */
2793     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
2794         acpi_sleep_force_task, sc)))
2795         device_printf(sc->acpi_dev, "AcpiOsExecute() for sleeping failed\n");
2796 }
2797 #endif
2798
2799 /*
2800  * Request that the system enter the given suspend state.  All /dev/apm
2801  * devices and devd(8) will be notified.  Userland then has a chance to
2802  * save state and acknowledge the request.  The system sleeps once all
2803  * acks are in.
2804  */
2805 int
2806 acpi_ReqSleepState(struct acpi_softc *sc, int state)
2807 {
2808 #if defined(__amd64__) || defined(__i386__)
2809     struct apm_clone_data *clone;
2810     ACPI_STATUS status;
2811
2812     if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
2813         return (EINVAL);
2814     if (!acpi_sleep_states[state])
2815         return (EOPNOTSUPP);
2816
2817     /*
2818      * If a reboot/shutdown/suspend request is already in progress or
2819      * suspend is blocked due to an upcoming shutdown, just return.
2820      */
2821     if (rebooting || sc->acpi_next_sstate != 0 || suspend_blocked) {
2822         return (0);
2823     }
2824
2825     /* Wait until sleep is enabled. */
2826     while (sc->acpi_sleep_disabled) {
2827         AcpiOsSleep(1000);
2828     }
2829
2830     ACPI_LOCK(acpi);
2831
2832     sc->acpi_next_sstate = state;
2833
2834     /* S5 (soft-off) should be entered directly with no waiting. */
2835     if (state == ACPI_STATE_S5) {
2836         ACPI_UNLOCK(acpi);
2837         status = acpi_EnterSleepState(sc, state);
2838         return (ACPI_SUCCESS(status) ? 0 : ENXIO);
2839     }
2840
2841     /* Record the pending state and notify all apm devices. */
2842     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
2843         clone->notify_status = APM_EV_NONE;
2844         if ((clone->flags & ACPI_EVF_DEVD) == 0) {
2845             selwakeuppri(&clone->sel_read, PZERO);
2846             KNOTE_LOCKED(&clone->sel_read.si_note, 0);
2847         }
2848     }
2849
2850     /* If devd(8) is not running, immediately enter the sleep state. */
2851     if (!devctl_process_running()) {
2852         ACPI_UNLOCK(acpi);
2853         status = acpi_EnterSleepState(sc, state);
2854         return (ACPI_SUCCESS(status) ? 0 : ENXIO);
2855     }
2856
2857     /*
2858      * Set a timeout to fire if userland doesn't ack the suspend request
2859      * in time.  This way we still eventually go to sleep if we were
2860      * overheating or running low on battery, even if userland is hung.
2861      * We cancel this timeout once all userland acks are in or the
2862      * suspend request is aborted.
2863      */
2864     callout_reset(&sc->susp_force_to, 10 * hz, acpi_sleep_force, sc);
2865     ACPI_UNLOCK(acpi);
2866
2867     /* Now notify devd(8) also. */
2868     acpi_UserNotify("Suspend", ACPI_ROOT_OBJECT, state);
2869
2870     return (0);
2871 #else
2872     /* This platform does not support acpi suspend/resume. */
2873     return (EOPNOTSUPP);
2874 #endif
2875 }
2876
2877 /*
2878  * Acknowledge (or reject) a pending sleep state.  The caller has
2879  * prepared for suspend and is now ready for it to proceed.  If the
2880  * error argument is non-zero, it indicates suspend should be cancelled
2881  * and gives an errno value describing why.  Once all votes are in,
2882  * we suspend the system.
2883  */
2884 int
2885 acpi_AckSleepState(struct apm_clone_data *clone, int error)
2886 {
2887 #if defined(__amd64__) || defined(__i386__)
2888     struct acpi_softc *sc;
2889     int ret, sleeping;
2890
2891     /* If no pending sleep state, return an error. */
2892     ACPI_LOCK(acpi);
2893     sc = clone->acpi_sc;
2894     if (sc->acpi_next_sstate == 0) {
2895         ACPI_UNLOCK(acpi);
2896         return (ENXIO);
2897     }
2898
2899     /* Caller wants to abort suspend process. */
2900     if (error) {
2901         sc->acpi_next_sstate = 0;
2902         callout_stop(&sc->susp_force_to);
2903         device_printf(sc->acpi_dev,
2904             "listener on %s cancelled the pending suspend\n",
2905             devtoname(clone->cdev));
2906         ACPI_UNLOCK(acpi);
2907         return (0);
2908     }
2909
2910     /*
2911      * Mark this device as acking the suspend request.  Then, walk through
2912      * all devices, seeing if they agree yet.  We only count devices that
2913      * are writable since read-only devices couldn't ack the request.
2914      */
2915     sleeping = TRUE;
2916     clone->notify_status = APM_EV_ACKED;
2917     STAILQ_FOREACH(clone, &sc->apm_cdevs, entries) {
2918         if ((clone->flags & ACPI_EVF_WRITE) != 0 &&
2919             clone->notify_status != APM_EV_ACKED) {
2920             sleeping = FALSE;
2921             break;
2922         }
2923     }
2924
2925     /* If all devices have voted "yes", we will suspend now. */
2926     if (sleeping)
2927         callout_stop(&sc->susp_force_to);
2928     ACPI_UNLOCK(acpi);
2929     ret = 0;
2930     if (sleeping) {
2931         if (ACPI_FAILURE(acpi_EnterSleepState(sc, sc->acpi_next_sstate)))
2932                 ret = ENODEV;
2933     }
2934     return (ret);
2935 #else
2936     /* This platform does not support acpi suspend/resume. */
2937     return (EOPNOTSUPP);
2938 #endif
2939 }
2940
2941 static void
2942 acpi_sleep_enable(void *arg)
2943 {
2944     struct acpi_softc   *sc = (struct acpi_softc *)arg;
2945
2946     ACPI_LOCK_ASSERT(acpi);
2947
2948     /* Reschedule if the system is not fully up and running. */
2949     if (!AcpiGbl_SystemAwakeAndRunning) {
2950         callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
2951         return;
2952     }
2953
2954     sc->acpi_sleep_disabled = FALSE;
2955 }
2956
2957 static ACPI_STATUS
2958 acpi_sleep_disable(struct acpi_softc *sc)
2959 {
2960     ACPI_STATUS         status;
2961
2962     /* Fail if the system is not fully up and running. */
2963     if (!AcpiGbl_SystemAwakeAndRunning)
2964         return (AE_ERROR);
2965
2966     ACPI_LOCK(acpi);
2967     status = sc->acpi_sleep_disabled ? AE_ERROR : AE_OK;
2968     sc->acpi_sleep_disabled = TRUE;
2969     ACPI_UNLOCK(acpi);
2970
2971     return (status);
2972 }
2973
2974 enum acpi_sleep_state {
2975     ACPI_SS_NONE,
2976     ACPI_SS_GPE_SET,
2977     ACPI_SS_DEV_SUSPEND,
2978     ACPI_SS_SLP_PREP,
2979     ACPI_SS_SLEPT,
2980 };
2981
2982 /*
2983  * Enter the desired system sleep state.
2984  *
2985  * Currently we support S1-S5 but S4 is only S4BIOS
2986  */
2987 static ACPI_STATUS
2988 acpi_EnterSleepState(struct acpi_softc *sc, int state)
2989 {
2990     register_t intr;
2991     ACPI_STATUS status;
2992     ACPI_EVENT_STATUS power_button_status;
2993     enum acpi_sleep_state slp_state;
2994     int sleep_result;
2995
2996     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
2997
2998     if (state < ACPI_STATE_S1 || state > ACPI_S_STATES_MAX)
2999         return_ACPI_STATUS (AE_BAD_PARAMETER);
3000     if (!acpi_sleep_states[state]) {
3001         device_printf(sc->acpi_dev, "Sleep state S%d not supported by BIOS\n",
3002             state);
3003         return (AE_SUPPORT);
3004     }
3005
3006     /* Re-entry once we're suspending is not allowed. */
3007     status = acpi_sleep_disable(sc);
3008     if (ACPI_FAILURE(status)) {
3009         device_printf(sc->acpi_dev,
3010             "suspend request ignored (not ready yet)\n");
3011         return (status);
3012     }
3013
3014     if (state == ACPI_STATE_S5) {
3015         /*
3016          * Shut down cleanly and power off.  This will call us back through the
3017          * shutdown handlers.
3018          */
3019         shutdown_nice(RB_POWEROFF);
3020         return_ACPI_STATUS (AE_OK);
3021     }
3022
3023     EVENTHANDLER_INVOKE(power_suspend_early);
3024     stop_all_proc();
3025     EVENTHANDLER_INVOKE(power_suspend);
3026
3027 #ifdef EARLY_AP_STARTUP
3028     MPASS(mp_ncpus == 1 || smp_started);
3029     thread_lock(curthread);
3030     sched_bind(curthread, 0);
3031     thread_unlock(curthread);
3032 #else
3033     if (smp_started) {
3034         thread_lock(curthread);
3035         sched_bind(curthread, 0);
3036         thread_unlock(curthread);
3037     }
3038 #endif
3039
3040     /*
3041      * Be sure to hold Giant across DEVICE_SUSPEND/RESUME since non-MPSAFE
3042      * drivers need this.
3043      */
3044     mtx_lock(&Giant);
3045
3046     slp_state = ACPI_SS_NONE;
3047
3048     sc->acpi_sstate = state;
3049
3050     /* Enable any GPEs as appropriate and requested by the user. */
3051     acpi_wake_prep_walk(state);
3052     slp_state = ACPI_SS_GPE_SET;
3053
3054     /*
3055      * Inform all devices that we are going to sleep.  If at least one
3056      * device fails, DEVICE_SUSPEND() automatically resumes the tree.
3057      *
3058      * XXX Note that a better two-pass approach with a 'veto' pass
3059      * followed by a "real thing" pass would be better, but the current
3060      * bus interface does not provide for this.
3061      */
3062     if (DEVICE_SUSPEND(root_bus) != 0) {
3063         device_printf(sc->acpi_dev, "device_suspend failed\n");
3064         goto backout;
3065     }
3066     slp_state = ACPI_SS_DEV_SUSPEND;
3067
3068     status = AcpiEnterSleepStatePrep(state);
3069     if (ACPI_FAILURE(status)) {
3070         device_printf(sc->acpi_dev, "AcpiEnterSleepStatePrep failed - %s\n",
3071                       AcpiFormatException(status));
3072         goto backout;
3073     }
3074     slp_state = ACPI_SS_SLP_PREP;
3075
3076     if (sc->acpi_sleep_delay > 0)
3077         DELAY(sc->acpi_sleep_delay * 1000000);
3078
3079     suspendclock();
3080     intr = intr_disable();
3081     if (state != ACPI_STATE_S1) {
3082         sleep_result = acpi_sleep_machdep(sc, state);
3083         acpi_wakeup_machdep(sc, state, sleep_result, 0);
3084
3085         /*
3086          * XXX According to ACPI specification SCI_EN bit should be restored
3087          * by ACPI platform (BIOS, firmware) to its pre-sleep state.
3088          * Unfortunately some BIOSes fail to do that and that leads to
3089          * unexpected and serious consequences during wake up like a system
3090          * getting stuck in SMI handlers.
3091          * This hack is picked up from Linux, which claims that it follows
3092          * Windows behavior.
3093          */
3094         if (sleep_result == 1 && state != ACPI_STATE_S4)
3095             AcpiWriteBitRegister(ACPI_BITREG_SCI_ENABLE, ACPI_ENABLE_EVENT);
3096
3097         if (sleep_result == 1 && state == ACPI_STATE_S3) {
3098             /*
3099              * Prevent mis-interpretation of the wakeup by power button
3100              * as a request for power off.
3101              * Ideally we should post an appropriate wakeup event,
3102              * perhaps using acpi_event_power_button_wake or alike.
3103              *
3104              * Clearing of power button status after wakeup is mandated
3105              * by ACPI specification in section "Fixed Power Button".
3106              *
3107              * XXX As of ACPICA 20121114 AcpiGetEventStatus provides
3108              * status as 0/1 corressponding to inactive/active despite
3109              * its type being ACPI_EVENT_STATUS.  In other words,
3110              * we should not test for ACPI_EVENT_FLAG_SET for time being.
3111              */
3112             if (ACPI_SUCCESS(AcpiGetEventStatus(ACPI_EVENT_POWER_BUTTON,
3113                 &power_button_status)) && power_button_status != 0) {
3114                 AcpiClearEvent(ACPI_EVENT_POWER_BUTTON);
3115                 device_printf(sc->acpi_dev,
3116                     "cleared fixed power button status\n");
3117             }
3118         }
3119
3120         intr_restore(intr);
3121
3122         /* call acpi_wakeup_machdep() again with interrupt enabled */
3123         acpi_wakeup_machdep(sc, state, sleep_result, 1);
3124
3125         AcpiLeaveSleepStatePrep(state);
3126
3127         if (sleep_result == -1)
3128                 goto backout;
3129
3130         /* Re-enable ACPI hardware on wakeup from sleep state 4. */
3131         if (state == ACPI_STATE_S4)
3132             AcpiEnable();
3133     } else {
3134         status = AcpiEnterSleepState(state);
3135         intr_restore(intr);
3136         AcpiLeaveSleepStatePrep(state);
3137         if (ACPI_FAILURE(status)) {
3138             device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
3139                           AcpiFormatException(status));
3140             goto backout;
3141         }
3142     }
3143     slp_state = ACPI_SS_SLEPT;
3144
3145     /*
3146      * Back out state according to how far along we got in the suspend
3147      * process.  This handles both the error and success cases.
3148      */
3149 backout:
3150     if (slp_state >= ACPI_SS_SLP_PREP)
3151         resumeclock();
3152     if (slp_state >= ACPI_SS_GPE_SET) {
3153         acpi_wake_prep_walk(state);
3154         sc->acpi_sstate = ACPI_STATE_S0;
3155     }
3156     if (slp_state >= ACPI_SS_DEV_SUSPEND)
3157         DEVICE_RESUME(root_bus);
3158     if (slp_state >= ACPI_SS_SLP_PREP)
3159         AcpiLeaveSleepState(state);
3160     if (slp_state >= ACPI_SS_SLEPT) {
3161 #if defined(__i386__) || defined(__amd64__)
3162         /* NB: we are still using ACPI timecounter at this point. */
3163         resume_TSC();
3164 #endif
3165         acpi_resync_clock(sc);
3166         acpi_enable_fixed_events(sc);
3167     }
3168     sc->acpi_next_sstate = 0;
3169
3170     mtx_unlock(&Giant);
3171
3172 #ifdef EARLY_AP_STARTUP
3173     thread_lock(curthread);
3174     sched_unbind(curthread);
3175     thread_unlock(curthread);
3176 #else
3177     if (smp_started) {
3178         thread_lock(curthread);
3179         sched_unbind(curthread);
3180         thread_unlock(curthread);
3181     }
3182 #endif
3183
3184     resume_all_proc();
3185
3186     EVENTHANDLER_INVOKE(power_resume);
3187
3188     /* Allow another sleep request after a while. */
3189     callout_schedule(&acpi_sleep_timer, hz * ACPI_MINIMUM_AWAKETIME);
3190
3191     /* Run /etc/rc.resume after we are back. */
3192     if (devctl_process_running())
3193         acpi_UserNotify("Resume", ACPI_ROOT_OBJECT, state);
3194
3195     return_ACPI_STATUS (status);
3196 }
3197
3198 static void
3199 acpi_resync_clock(struct acpi_softc *sc)
3200 {
3201
3202     /*
3203      * Warm up timecounter again and reset system clock.
3204      */
3205     (void)timecounter->tc_get_timecount(timecounter);
3206     (void)timecounter->tc_get_timecount(timecounter);
3207     inittodr(time_second + sc->acpi_sleep_delay);
3208 }
3209
3210 /* Enable or disable the device's wake GPE. */
3211 int
3212 acpi_wake_set_enable(device_t dev, int enable)
3213 {
3214     struct acpi_prw_data prw;
3215     ACPI_STATUS status;
3216     int flags;
3217
3218     /* Make sure the device supports waking the system and get the GPE. */
3219     if (acpi_parse_prw(acpi_get_handle(dev), &prw) != 0)
3220         return (ENXIO);
3221
3222     flags = acpi_get_flags(dev);
3223     if (enable) {
3224         status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3225             ACPI_GPE_ENABLE);
3226         if (ACPI_FAILURE(status)) {
3227             device_printf(dev, "enable wake failed\n");
3228             return (ENXIO);
3229         }
3230         acpi_set_flags(dev, flags | ACPI_FLAG_WAKE_ENABLED);
3231     } else {
3232         status = AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit,
3233             ACPI_GPE_DISABLE);
3234         if (ACPI_FAILURE(status)) {
3235             device_printf(dev, "disable wake failed\n");
3236             return (ENXIO);
3237         }
3238         acpi_set_flags(dev, flags & ~ACPI_FLAG_WAKE_ENABLED);
3239     }
3240
3241     return (0);
3242 }
3243
3244 static int
3245 acpi_wake_sleep_prep(ACPI_HANDLE handle, int sstate)
3246 {
3247     struct acpi_prw_data prw;
3248     device_t dev;
3249
3250     /* Check that this is a wake-capable device and get its GPE. */
3251     if (acpi_parse_prw(handle, &prw) != 0)
3252         return (ENXIO);
3253     dev = acpi_get_device(handle);
3254
3255     /*
3256      * The destination sleep state must be less than (i.e., higher power)
3257      * or equal to the value specified by _PRW.  If this GPE cannot be
3258      * enabled for the next sleep state, then disable it.  If it can and
3259      * the user requested it be enabled, turn on any required power resources
3260      * and set _PSW.
3261      */
3262     if (sstate > prw.lowest_wake) {
3263         AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_DISABLE);
3264         if (bootverbose)
3265             device_printf(dev, "wake_prep disabled wake for %s (S%d)\n",
3266                 acpi_name(handle), sstate);
3267     } else if (dev && (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) != 0) {
3268         acpi_pwr_wake_enable(handle, 1);
3269         acpi_SetInteger(handle, "_PSW", 1);
3270         if (bootverbose)
3271             device_printf(dev, "wake_prep enabled for %s (S%d)\n",
3272                 acpi_name(handle), sstate);
3273     }
3274
3275     return (0);
3276 }
3277
3278 static int
3279 acpi_wake_run_prep(ACPI_HANDLE handle, int sstate)
3280 {
3281     struct acpi_prw_data prw;
3282     device_t dev;
3283
3284     /*
3285      * Check that this is a wake-capable device and get its GPE.  Return
3286      * now if the user didn't enable this device for wake.
3287      */
3288     if (acpi_parse_prw(handle, &prw) != 0)
3289         return (ENXIO);
3290     dev = acpi_get_device(handle);
3291     if (dev == NULL || (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) == 0)
3292         return (0);
3293
3294     /*
3295      * If this GPE couldn't be enabled for the previous sleep state, it was
3296      * disabled before going to sleep so re-enable it.  If it was enabled,
3297      * clear _PSW and turn off any power resources it used.
3298      */
3299     if (sstate > prw.lowest_wake) {
3300         AcpiSetGpeWakeMask(prw.gpe_handle, prw.gpe_bit, ACPI_GPE_ENABLE);
3301         if (bootverbose)
3302             device_printf(dev, "run_prep re-enabled %s\n", acpi_name(handle));
3303     } else {
3304         acpi_SetInteger(handle, "_PSW", 0);
3305         acpi_pwr_wake_enable(handle, 0);
3306         if (bootverbose)
3307             device_printf(dev, "run_prep cleaned up for %s\n",
3308                 acpi_name(handle));
3309     }
3310
3311     return (0);
3312 }
3313
3314 static ACPI_STATUS
3315 acpi_wake_prep(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
3316 {
3317     int sstate;
3318
3319     /* If suspending, run the sleep prep function, otherwise wake. */
3320     sstate = *(int *)context;
3321     if (AcpiGbl_SystemAwakeAndRunning)
3322         acpi_wake_sleep_prep(handle, sstate);
3323     else
3324         acpi_wake_run_prep(handle, sstate);
3325     return (AE_OK);
3326 }
3327
3328 /* Walk the tree rooted at acpi0 to prep devices for suspend/resume. */
3329 static int
3330 acpi_wake_prep_walk(int sstate)
3331 {
3332     ACPI_HANDLE sb_handle;
3333
3334     if (ACPI_SUCCESS(AcpiGetHandle(ACPI_ROOT_OBJECT, "\\_SB_", &sb_handle)))
3335         AcpiWalkNamespace(ACPI_TYPE_DEVICE, sb_handle, 100,
3336             acpi_wake_prep, NULL, &sstate, NULL);
3337     return (0);
3338 }
3339
3340 /* Walk the tree rooted at acpi0 to attach per-device wake sysctls. */
3341 static int
3342 acpi_wake_sysctl_walk(device_t dev)
3343 {
3344     int error, i, numdevs;
3345     device_t *devlist;
3346     device_t child;
3347     ACPI_STATUS status;
3348
3349     error = device_get_children(dev, &devlist, &numdevs);
3350     if (error != 0 || numdevs == 0) {
3351         if (numdevs == 0)
3352             free(devlist, M_TEMP);
3353         return (error);
3354     }
3355     for (i = 0; i < numdevs; i++) {
3356         child = devlist[i];
3357         acpi_wake_sysctl_walk(child);
3358         if (!device_is_attached(child))
3359             continue;
3360         status = AcpiEvaluateObject(acpi_get_handle(child), "_PRW", NULL, NULL);
3361         if (ACPI_SUCCESS(status)) {
3362             SYSCTL_ADD_PROC(device_get_sysctl_ctx(child),
3363                 SYSCTL_CHILDREN(device_get_sysctl_tree(child)), OID_AUTO,
3364                 "wake", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, child, 0,
3365                 acpi_wake_set_sysctl, "I", "Device set to wake the system");
3366         }
3367     }
3368     free(devlist, M_TEMP);
3369
3370     return (0);
3371 }
3372
3373 /* Enable or disable wake from userland. */
3374 static int
3375 acpi_wake_set_sysctl(SYSCTL_HANDLER_ARGS)
3376 {
3377     int enable, error;
3378     device_t dev;
3379
3380     dev = (device_t)arg1;
3381     enable = (acpi_get_flags(dev) & ACPI_FLAG_WAKE_ENABLED) ? 1 : 0;
3382
3383     error = sysctl_handle_int(oidp, &enable, 0, req);
3384     if (error != 0 || req->newptr == NULL)
3385         return (error);
3386     if (enable != 0 && enable != 1)
3387         return (EINVAL);
3388
3389     return (acpi_wake_set_enable(dev, enable));
3390 }
3391
3392 /* Parse a device's _PRW into a structure. */
3393 int
3394 acpi_parse_prw(ACPI_HANDLE h, struct acpi_prw_data *prw)
3395 {
3396     ACPI_STATUS                 status;
3397     ACPI_BUFFER                 prw_buffer;
3398     ACPI_OBJECT                 *res, *res2;
3399     int                         error, i, power_count;
3400
3401     if (h == NULL || prw == NULL)
3402         return (EINVAL);
3403
3404     /*
3405      * The _PRW object (7.2.9) is only required for devices that have the
3406      * ability to wake the system from a sleeping state.
3407      */
3408     error = EINVAL;
3409     prw_buffer.Pointer = NULL;
3410     prw_buffer.Length = ACPI_ALLOCATE_BUFFER;
3411     status = AcpiEvaluateObject(h, "_PRW", NULL, &prw_buffer);
3412     if (ACPI_FAILURE(status))
3413         return (ENOENT);
3414     res = (ACPI_OBJECT *)prw_buffer.Pointer;
3415     if (res == NULL)
3416         return (ENOENT);
3417     if (!ACPI_PKG_VALID(res, 2))
3418         goto out;
3419
3420     /*
3421      * Element 1 of the _PRW object:
3422      * The lowest power system sleeping state that can be entered while still
3423      * providing wake functionality.  The sleeping state being entered must
3424      * be less than (i.e., higher power) or equal to this value.
3425      */
3426     if (acpi_PkgInt32(res, 1, &prw->lowest_wake) != 0)
3427         goto out;
3428
3429     /*
3430      * Element 0 of the _PRW object:
3431      */
3432     switch (res->Package.Elements[0].Type) {
3433     case ACPI_TYPE_INTEGER:
3434         /*
3435          * If the data type of this package element is numeric, then this
3436          * _PRW package element is the bit index in the GPEx_EN, in the
3437          * GPE blocks described in the FADT, of the enable bit that is
3438          * enabled for the wake event.
3439          */
3440         prw->gpe_handle = NULL;
3441         prw->gpe_bit = res->Package.Elements[0].Integer.Value;
3442         error = 0;
3443         break;
3444     case ACPI_TYPE_PACKAGE:
3445         /*
3446          * If the data type of this package element is a package, then this
3447          * _PRW package element is itself a package containing two
3448          * elements.  The first is an object reference to the GPE Block
3449          * device that contains the GPE that will be triggered by the wake
3450          * event.  The second element is numeric and it contains the bit
3451          * index in the GPEx_EN, in the GPE Block referenced by the
3452          * first element in the package, of the enable bit that is enabled for
3453          * the wake event.
3454          *
3455          * For example, if this field is a package then it is of the form:
3456          * Package() {\_SB.PCI0.ISA.GPE, 2}
3457          */
3458         res2 = &res->Package.Elements[0];
3459         if (!ACPI_PKG_VALID(res2, 2))
3460             goto out;
3461         prw->gpe_handle = acpi_GetReference(NULL, &res2->Package.Elements[0]);
3462         if (prw->gpe_handle == NULL)
3463             goto out;
3464         if (acpi_PkgInt32(res2, 1, &prw->gpe_bit) != 0)
3465             goto out;
3466         error = 0;
3467         break;
3468     default:
3469         goto out;
3470     }
3471
3472     /* Elements 2 to N of the _PRW object are power resources. */
3473     power_count = res->Package.Count - 2;
3474     if (power_count > ACPI_PRW_MAX_POWERRES) {
3475         printf("ACPI device %s has too many power resources\n", acpi_name(h));
3476         power_count = 0;
3477     }
3478     prw->power_res_count = power_count;
3479     for (i = 0; i < power_count; i++)
3480         prw->power_res[i] = res->Package.Elements[i];
3481
3482 out:
3483     if (prw_buffer.Pointer != NULL)
3484         AcpiOsFree(prw_buffer.Pointer);
3485     return (error);
3486 }
3487
3488 /*
3489  * ACPI Event Handlers
3490  */
3491
3492 /* System Event Handlers (registered by EVENTHANDLER_REGISTER) */
3493
3494 static void
3495 acpi_system_eventhandler_sleep(void *arg, int state)
3496 {
3497     struct acpi_softc *sc = (struct acpi_softc *)arg;
3498     int ret;
3499
3500     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3501
3502     /* Check if button action is disabled or unknown. */
3503     if (state == ACPI_STATE_UNKNOWN)
3504         return;
3505
3506     /* Request that the system prepare to enter the given suspend state. */
3507     ret = acpi_ReqSleepState(sc, state);
3508     if (ret != 0)
3509         device_printf(sc->acpi_dev,
3510             "request to enter state S%d failed (err %d)\n", state, ret);
3511
3512     return_VOID;
3513 }
3514
3515 static void
3516 acpi_system_eventhandler_wakeup(void *arg, int state)
3517 {
3518
3519     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
3520
3521     /* Currently, nothing to do for wakeup. */
3522
3523     return_VOID;
3524 }
3525
3526 /* 
3527  * ACPICA Event Handlers (FixedEvent, also called from button notify handler)
3528  */
3529 static void
3530 acpi_invoke_sleep_eventhandler(void *context)
3531 {
3532
3533     EVENTHANDLER_INVOKE(acpi_sleep_event, *(int *)context);
3534 }
3535
3536 static void
3537 acpi_invoke_wake_eventhandler(void *context)
3538 {
3539
3540     EVENTHANDLER_INVOKE(acpi_wakeup_event, *(int *)context);
3541 }
3542
3543 UINT32
3544 acpi_event_power_button_sleep(void *context)
3545 {
3546     struct acpi_softc   *sc = (struct acpi_softc *)context;
3547
3548     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3549
3550     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3551         acpi_invoke_sleep_eventhandler, &sc->acpi_power_button_sx)))
3552         return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3553     return_VALUE (ACPI_INTERRUPT_HANDLED);
3554 }
3555
3556 UINT32
3557 acpi_event_power_button_wake(void *context)
3558 {
3559     struct acpi_softc   *sc = (struct acpi_softc *)context;
3560
3561     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3562
3563     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3564         acpi_invoke_wake_eventhandler, &sc->acpi_power_button_sx)))
3565         return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3566     return_VALUE (ACPI_INTERRUPT_HANDLED);
3567 }
3568
3569 UINT32
3570 acpi_event_sleep_button_sleep(void *context)
3571 {
3572     struct acpi_softc   *sc = (struct acpi_softc *)context;
3573
3574     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3575
3576     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3577         acpi_invoke_sleep_eventhandler, &sc->acpi_sleep_button_sx)))
3578         return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3579     return_VALUE (ACPI_INTERRUPT_HANDLED);
3580 }
3581
3582 UINT32
3583 acpi_event_sleep_button_wake(void *context)
3584 {
3585     struct acpi_softc   *sc = (struct acpi_softc *)context;
3586
3587     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
3588
3589     if (ACPI_FAILURE(AcpiOsExecute(OSL_NOTIFY_HANDLER,
3590         acpi_invoke_wake_eventhandler, &sc->acpi_sleep_button_sx)))
3591         return_VALUE (ACPI_INTERRUPT_NOT_HANDLED);
3592     return_VALUE (ACPI_INTERRUPT_HANDLED);
3593 }
3594
3595 /*
3596  * XXX This static buffer is suboptimal.  There is no locking so only
3597  * use this for single-threaded callers.
3598  */
3599 char *
3600 acpi_name(ACPI_HANDLE handle)
3601 {
3602     ACPI_BUFFER buf;
3603     static char data[256];
3604
3605     buf.Length = sizeof(data);
3606     buf.Pointer = data;
3607
3608     if (handle && ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf)))
3609         return (data);
3610     return ("(unknown)");
3611 }
3612
3613 /*
3614  * Debugging/bug-avoidance.  Avoid trying to fetch info on various
3615  * parts of the namespace.
3616  */
3617 int
3618 acpi_avoid(ACPI_HANDLE handle)
3619 {
3620     char        *cp, *env, *np;
3621     int         len;
3622
3623     np = acpi_name(handle);
3624     if (*np == '\\')
3625         np++;
3626     if ((env = kern_getenv("debug.acpi.avoid")) == NULL)
3627         return (0);
3628
3629     /* Scan the avoid list checking for a match */
3630     cp = env;
3631     for (;;) {
3632         while (*cp != 0 && isspace(*cp))
3633             cp++;
3634         if (*cp == 0)
3635             break;
3636         len = 0;
3637         while (cp[len] != 0 && !isspace(cp[len]))
3638             len++;
3639         if (!strncmp(cp, np, len)) {
3640             freeenv(env);
3641             return(1);
3642         }
3643         cp += len;
3644     }
3645     freeenv(env);
3646
3647     return (0);
3648 }
3649
3650 /*
3651  * Debugging/bug-avoidance.  Disable ACPI subsystem components.
3652  */
3653 int
3654 acpi_disabled(char *subsys)
3655 {
3656     char        *cp, *env;
3657     int         len;
3658
3659     if ((env = kern_getenv("debug.acpi.disabled")) == NULL)
3660         return (0);
3661     if (strcmp(env, "all") == 0) {
3662         freeenv(env);
3663         return (1);
3664     }
3665
3666     /* Scan the disable list, checking for a match. */
3667     cp = env;
3668     for (;;) {
3669         while (*cp != '\0' && isspace(*cp))
3670             cp++;
3671         if (*cp == '\0')
3672             break;
3673         len = 0;
3674         while (cp[len] != '\0' && !isspace(cp[len]))
3675             len++;
3676         if (strncmp(cp, subsys, len) == 0) {
3677             freeenv(env);
3678             return (1);
3679         }
3680         cp += len;
3681     }
3682     freeenv(env);
3683
3684     return (0);
3685 }
3686
3687 static void
3688 acpi_lookup(void *arg, const char *name, device_t *dev)
3689 {
3690     ACPI_HANDLE handle;
3691
3692     if (*dev != NULL)
3693         return;
3694
3695     /*
3696      * Allow any handle name that is specified as an absolute path and
3697      * starts with '\'.  We could restrict this to \_SB and friends,
3698      * but see acpi_probe_children() for notes on why we scan the entire
3699      * namespace for devices.
3700      *
3701      * XXX: The pathname argument to AcpiGetHandle() should be fixed to
3702      * be const.
3703      */
3704     if (name[0] != '\\')
3705         return;
3706     if (ACPI_FAILURE(AcpiGetHandle(ACPI_ROOT_OBJECT, __DECONST(char *, name),
3707         &handle)))
3708         return;
3709     *dev = acpi_get_device(handle);
3710 }
3711
3712 /*
3713  * Control interface.
3714  *
3715  * We multiplex ioctls for all participating ACPI devices here.  Individual 
3716  * drivers wanting to be accessible via /dev/acpi should use the
3717  * register/deregister interface to make their handlers visible.
3718  */
3719 struct acpi_ioctl_hook
3720 {
3721     TAILQ_ENTRY(acpi_ioctl_hook) link;
3722     u_long                       cmd;
3723     acpi_ioctl_fn                fn;
3724     void                         *arg;
3725 };
3726
3727 static TAILQ_HEAD(,acpi_ioctl_hook)     acpi_ioctl_hooks;
3728 static int                              acpi_ioctl_hooks_initted;
3729
3730 int
3731 acpi_register_ioctl(u_long cmd, acpi_ioctl_fn fn, void *arg)
3732 {
3733     struct acpi_ioctl_hook      *hp;
3734
3735     if ((hp = malloc(sizeof(*hp), M_ACPIDEV, M_NOWAIT)) == NULL)
3736         return (ENOMEM);
3737     hp->cmd = cmd;
3738     hp->fn = fn;
3739     hp->arg = arg;
3740
3741     ACPI_LOCK(acpi);
3742     if (acpi_ioctl_hooks_initted == 0) {
3743         TAILQ_INIT(&acpi_ioctl_hooks);
3744         acpi_ioctl_hooks_initted = 1;
3745     }
3746     TAILQ_INSERT_TAIL(&acpi_ioctl_hooks, hp, link);
3747     ACPI_UNLOCK(acpi);
3748
3749     return (0);
3750 }
3751
3752 void
3753 acpi_deregister_ioctl(u_long cmd, acpi_ioctl_fn fn)
3754 {
3755     struct acpi_ioctl_hook      *hp;
3756
3757     ACPI_LOCK(acpi);
3758     TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link)
3759         if (hp->cmd == cmd && hp->fn == fn)
3760             break;
3761
3762     if (hp != NULL) {
3763         TAILQ_REMOVE(&acpi_ioctl_hooks, hp, link);
3764         free(hp, M_ACPIDEV);
3765     }
3766     ACPI_UNLOCK(acpi);
3767 }
3768
3769 static int
3770 acpiopen(struct cdev *dev, int flag, int fmt, struct thread *td)
3771 {
3772     return (0);
3773 }
3774
3775 static int
3776 acpiclose(struct cdev *dev, int flag, int fmt, struct thread *td)
3777 {
3778     return (0);
3779 }
3780
3781 static int
3782 acpiioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
3783 {
3784     struct acpi_softc           *sc;
3785     struct acpi_ioctl_hook      *hp;
3786     int                         error, state;
3787
3788     error = 0;
3789     hp = NULL;
3790     sc = dev->si_drv1;
3791
3792     /*
3793      * Scan the list of registered ioctls, looking for handlers.
3794      */
3795     ACPI_LOCK(acpi);
3796     if (acpi_ioctl_hooks_initted)
3797         TAILQ_FOREACH(hp, &acpi_ioctl_hooks, link) {
3798             if (hp->cmd == cmd)
3799                 break;
3800         }
3801     ACPI_UNLOCK(acpi);
3802     if (hp)
3803         return (hp->fn(cmd, addr, hp->arg));
3804
3805     /*
3806      * Core ioctls are not permitted for non-writable user.
3807      * Currently, other ioctls just fetch information.
3808      * Not changing system behavior.
3809      */
3810     if ((flag & FWRITE) == 0)
3811         return (EPERM);
3812
3813     /* Core system ioctls. */
3814     switch (cmd) {
3815     case ACPIIO_REQSLPSTATE:
3816         state = *(int *)addr;
3817         if (state != ACPI_STATE_S5)
3818             return (acpi_ReqSleepState(sc, state));
3819         device_printf(sc->acpi_dev, "power off via acpi ioctl not supported\n");
3820         error = EOPNOTSUPP;
3821         break;
3822     case ACPIIO_ACKSLPSTATE:
3823         error = *(int *)addr;
3824         error = acpi_AckSleepState(sc->acpi_clone, error);
3825         break;
3826     case ACPIIO_SETSLPSTATE:    /* DEPRECATED */
3827         state = *(int *)addr;
3828         if (state < ACPI_STATE_S0 || state > ACPI_S_STATES_MAX)
3829             return (EINVAL);
3830         if (!acpi_sleep_states[state])
3831             return (EOPNOTSUPP);
3832         if (ACPI_FAILURE(acpi_SetSleepState(sc, state)))
3833             error = ENXIO;
3834         break;
3835     default:
3836         error = ENXIO;
3837         break;
3838     }
3839
3840     return (error);
3841 }
3842
3843 static int
3844 acpi_sname2sstate(const char *sname)
3845 {
3846     int sstate;
3847
3848     if (toupper(sname[0]) == 'S') {
3849         sstate = sname[1] - '0';
3850         if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5 &&
3851             sname[2] == '\0')
3852             return (sstate);
3853     } else if (strcasecmp(sname, "NONE") == 0)
3854         return (ACPI_STATE_UNKNOWN);
3855     return (-1);
3856 }
3857
3858 static const char *
3859 acpi_sstate2sname(int sstate)
3860 {
3861     static const char *snames[] = { "S0", "S1", "S2", "S3", "S4", "S5" };
3862
3863     if (sstate >= ACPI_STATE_S0 && sstate <= ACPI_STATE_S5)
3864         return (snames[sstate]);
3865     else if (sstate == ACPI_STATE_UNKNOWN)
3866         return ("NONE");
3867     return (NULL);
3868 }
3869
3870 static int
3871 acpi_supported_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
3872 {
3873     int error;
3874     struct sbuf sb;
3875     UINT8 state;
3876
3877     sbuf_new(&sb, NULL, 32, SBUF_AUTOEXTEND);
3878     for (state = ACPI_STATE_S1; state < ACPI_S_STATE_COUNT; state++)
3879         if (acpi_sleep_states[state])
3880             sbuf_printf(&sb, "%s ", acpi_sstate2sname(state));
3881     sbuf_trim(&sb);
3882     sbuf_finish(&sb);
3883     error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
3884     sbuf_delete(&sb);
3885     return (error);
3886 }
3887
3888 static int
3889 acpi_sleep_state_sysctl(SYSCTL_HANDLER_ARGS)
3890 {
3891     char sleep_state[10];
3892     int error, new_state, old_state;
3893
3894     old_state = *(int *)oidp->oid_arg1;
3895     strlcpy(sleep_state, acpi_sstate2sname(old_state), sizeof(sleep_state));
3896     error = sysctl_handle_string(oidp, sleep_state, sizeof(sleep_state), req);
3897     if (error == 0 && req->newptr != NULL) {
3898         new_state = acpi_sname2sstate(sleep_state);
3899         if (new_state < ACPI_STATE_S1)
3900             return (EINVAL);
3901         if (new_state < ACPI_S_STATE_COUNT && !acpi_sleep_states[new_state])
3902             return (EOPNOTSUPP);
3903         if (new_state != old_state)
3904             *(int *)oidp->oid_arg1 = new_state;
3905     }
3906     return (error);
3907 }
3908
3909 /* Inform devctl(4) when we receive a Notify. */
3910 void
3911 acpi_UserNotify(const char *subsystem, ACPI_HANDLE h, uint8_t notify)
3912 {
3913     char                notify_buf[16];
3914     ACPI_BUFFER         handle_buf;
3915     ACPI_STATUS         status;
3916
3917     if (subsystem == NULL)
3918         return;
3919
3920     handle_buf.Pointer = NULL;
3921     handle_buf.Length = ACPI_ALLOCATE_BUFFER;
3922     status = AcpiNsHandleToPathname(h, &handle_buf, FALSE);
3923     if (ACPI_FAILURE(status))
3924         return;
3925     snprintf(notify_buf, sizeof(notify_buf), "notify=0x%02x", notify);
3926     devctl_notify("ACPI", subsystem, handle_buf.Pointer, notify_buf);
3927     AcpiOsFree(handle_buf.Pointer);
3928 }
3929
3930 #ifdef ACPI_DEBUG
3931 /*
3932  * Support for parsing debug options from the kernel environment.
3933  *
3934  * Bits may be set in the AcpiDbgLayer and AcpiDbgLevel debug registers
3935  * by specifying the names of the bits in the debug.acpi.layer and
3936  * debug.acpi.level environment variables.  Bits may be unset by 
3937  * prefixing the bit name with !.
3938  */
3939 struct debugtag
3940 {
3941     char        *name;
3942     UINT32      value;
3943 };
3944
3945 static struct debugtag  dbg_layer[] = {
3946     {"ACPI_UTILITIES",          ACPI_UTILITIES},
3947     {"ACPI_HARDWARE",           ACPI_HARDWARE},
3948     {"ACPI_EVENTS",             ACPI_EVENTS},
3949     {"ACPI_TABLES",             ACPI_TABLES},
3950     {"ACPI_NAMESPACE",          ACPI_NAMESPACE},
3951     {"ACPI_PARSER",             ACPI_PARSER},
3952     {"ACPI_DISPATCHER",         ACPI_DISPATCHER},
3953     {"ACPI_EXECUTER",           ACPI_EXECUTER},
3954     {"ACPI_RESOURCES",          ACPI_RESOURCES},
3955     {"ACPI_CA_DEBUGGER",        ACPI_CA_DEBUGGER},
3956     {"ACPI_OS_SERVICES",        ACPI_OS_SERVICES},
3957     {"ACPI_CA_DISASSEMBLER",    ACPI_CA_DISASSEMBLER},
3958     {"ACPI_ALL_COMPONENTS",     ACPI_ALL_COMPONENTS},
3959
3960     {"ACPI_AC_ADAPTER",         ACPI_AC_ADAPTER},
3961     {"ACPI_BATTERY",            ACPI_BATTERY},
3962     {"ACPI_BUS",                ACPI_BUS},
3963     {"ACPI_BUTTON",             ACPI_BUTTON},
3964     {"ACPI_EC",                 ACPI_EC},
3965     {"ACPI_FAN",                ACPI_FAN},
3966     {"ACPI_POWERRES",           ACPI_POWERRES},
3967     {"ACPI_PROCESSOR",          ACPI_PROCESSOR},
3968     {"ACPI_THERMAL",            ACPI_THERMAL},
3969     {"ACPI_TIMER",              ACPI_TIMER},
3970     {"ACPI_ALL_DRIVERS",        ACPI_ALL_DRIVERS},
3971     {NULL, 0}
3972 };
3973
3974 static struct debugtag dbg_level[] = {
3975     {"ACPI_LV_INIT",            ACPI_LV_INIT},
3976     {"ACPI_LV_DEBUG_OBJECT",    ACPI_LV_DEBUG_OBJECT},
3977     {"ACPI_LV_INFO",            ACPI_LV_INFO},
3978     {"ACPI_LV_REPAIR",          ACPI_LV_REPAIR},
3979     {"ACPI_LV_ALL_EXCEPTIONS",  ACPI_LV_ALL_EXCEPTIONS},
3980
3981     /* Trace verbosity level 1 [Standard Trace Level] */
3982     {"ACPI_LV_INIT_NAMES",      ACPI_LV_INIT_NAMES},
3983     {"ACPI_LV_PARSE",           ACPI_LV_PARSE},
3984     {"ACPI_LV_LOAD",            ACPI_LV_LOAD},
3985     {"ACPI_LV_DISPATCH",        ACPI_LV_DISPATCH},
3986     {"ACPI_LV_EXEC",            ACPI_LV_EXEC},
3987     {"ACPI_LV_NAMES",           ACPI_LV_NAMES},
3988     {"ACPI_LV_OPREGION",        ACPI_LV_OPREGION},
3989     {"ACPI_LV_BFIELD",          ACPI_LV_BFIELD},
3990     {"ACPI_LV_TABLES",          ACPI_LV_TABLES},
3991     {"ACPI_LV_VALUES",          ACPI_LV_VALUES},
3992     {"ACPI_LV_OBJECTS",         ACPI_LV_OBJECTS},
3993     {"ACPI_LV_RESOURCES",       ACPI_LV_RESOURCES},
3994     {"ACPI_LV_USER_REQUESTS",   ACPI_LV_USER_REQUESTS},
3995     {"ACPI_LV_PACKAGE",         ACPI_LV_PACKAGE},
3996     {"ACPI_LV_VERBOSITY1",      ACPI_LV_VERBOSITY1},
3997
3998     /* Trace verbosity level 2 [Function tracing and memory allocation] */
3999     {"ACPI_LV_ALLOCATIONS",     ACPI_LV_ALLOCATIONS},
4000     {"ACPI_LV_FUNCTIONS",       ACPI_LV_FUNCTIONS},
4001     {"ACPI_LV_OPTIMIZATIONS",   ACPI_LV_OPTIMIZATIONS},
4002     {"ACPI_LV_VERBOSITY2",      ACPI_LV_VERBOSITY2},
4003     {"ACPI_LV_ALL",             ACPI_LV_ALL},
4004
4005     /* Trace verbosity level 3 [Threading, I/O, and Interrupts] */
4006     {"ACPI_LV_MUTEX",           ACPI_LV_MUTEX},
4007     {"ACPI_LV_THREADS",         ACPI_LV_THREADS},
4008     {"ACPI_LV_IO",              ACPI_LV_IO},
4009     {"ACPI_LV_INTERRUPTS",      ACPI_LV_INTERRUPTS},
4010     {"ACPI_LV_VERBOSITY3",      ACPI_LV_VERBOSITY3},
4011
4012     /* Exceptionally verbose output -- also used in the global "DebugLevel"  */
4013     {"ACPI_LV_AML_DISASSEMBLE", ACPI_LV_AML_DISASSEMBLE},
4014     {"ACPI_LV_VERBOSE_INFO",    ACPI_LV_VERBOSE_INFO},
4015     {"ACPI_LV_FULL_TABLES",     ACPI_LV_FULL_TABLES},
4016     {"ACPI_LV_EVENTS",          ACPI_LV_EVENTS},
4017     {"ACPI_LV_VERBOSE",         ACPI_LV_VERBOSE},
4018     {NULL, 0}
4019 };    
4020
4021 static void
4022 acpi_parse_debug(char *cp, struct debugtag *tag, UINT32 *flag)
4023 {
4024     char        *ep;
4025     int         i, l;
4026     int         set;
4027
4028     while (*cp) {
4029         if (isspace(*cp)) {
4030             cp++;
4031             continue;
4032         }
4033         ep = cp;
4034         while (*ep && !isspace(*ep))
4035             ep++;
4036         if (*cp == '!') {
4037             set = 0;
4038             cp++;
4039             if (cp == ep)
4040                 continue;
4041         } else {
4042             set = 1;
4043         }
4044         l = ep - cp;
4045         for (i = 0; tag[i].name != NULL; i++) {
4046             if (!strncmp(cp, tag[i].name, l)) {
4047                 if (set)
4048                     *flag |= tag[i].value;
4049                 else
4050                     *flag &= ~tag[i].value;
4051             }
4052         }
4053         cp = ep;
4054     }
4055 }
4056
4057 static void
4058 acpi_set_debugging(void *junk)
4059 {
4060     char        *layer, *level;
4061
4062     if (cold) {
4063         AcpiDbgLayer = 0;
4064         AcpiDbgLevel = 0;
4065     }
4066
4067     layer = kern_getenv("debug.acpi.layer");
4068     level = kern_getenv("debug.acpi.level");
4069     if (layer == NULL && level == NULL)
4070         return;
4071
4072     printf("ACPI set debug");
4073     if (layer != NULL) {
4074         if (strcmp("NONE", layer) != 0)
4075             printf(" layer '%s'", layer);
4076         acpi_parse_debug(layer, &dbg_layer[0], &AcpiDbgLayer);
4077         freeenv(layer);
4078     }
4079     if (level != NULL) {
4080         if (strcmp("NONE", level) != 0)
4081             printf(" level '%s'", level);
4082         acpi_parse_debug(level, &dbg_level[0], &AcpiDbgLevel);
4083         freeenv(level);
4084     }
4085     printf("\n");
4086 }
4087
4088 SYSINIT(acpi_debugging, SI_SUB_TUNABLES, SI_ORDER_ANY, acpi_set_debugging,
4089         NULL);
4090
4091 static int
4092 acpi_debug_sysctl(SYSCTL_HANDLER_ARGS)
4093 {
4094     int          error, *dbg;
4095     struct       debugtag *tag;
4096     struct       sbuf sb;
4097     char         temp[128];
4098
4099     if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL)
4100         return (ENOMEM);
4101     if (strcmp(oidp->oid_arg1, "debug.acpi.layer") == 0) {
4102         tag = &dbg_layer[0];
4103         dbg = &AcpiDbgLayer;
4104     } else {
4105         tag = &dbg_level[0];
4106         dbg = &AcpiDbgLevel;
4107     }
4108
4109     /* Get old values if this is a get request. */
4110     ACPI_SERIAL_BEGIN(acpi);
4111     if (*dbg == 0) {
4112         sbuf_cpy(&sb, "NONE");
4113     } else if (req->newptr == NULL) {
4114         for (; tag->name != NULL; tag++) {
4115             if ((*dbg & tag->value) == tag->value)
4116                 sbuf_printf(&sb, "%s ", tag->name);
4117         }
4118     }
4119     sbuf_trim(&sb);
4120     sbuf_finish(&sb);
4121     strlcpy(temp, sbuf_data(&sb), sizeof(temp));
4122     sbuf_delete(&sb);
4123
4124     error = sysctl_handle_string(oidp, temp, sizeof(temp), req);
4125
4126     /* Check for error or no change */
4127     if (error == 0 && req->newptr != NULL) {
4128         *dbg = 0;
4129         kern_setenv((char *)oidp->oid_arg1, temp);
4130         acpi_set_debugging(NULL);
4131     }
4132     ACPI_SERIAL_END(acpi);
4133
4134     return (error);
4135 }
4136
4137 SYSCTL_PROC(_debug_acpi, OID_AUTO, layer,
4138     CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_NEEDGIANT, "debug.acpi.layer", 0,
4139     acpi_debug_sysctl, "A",
4140     "");
4141 SYSCTL_PROC(_debug_acpi, OID_AUTO, level,
4142     CTLFLAG_RW | CTLTYPE_STRING | CTLFLAG_NEEDGIANT, "debug.acpi.level", 0,
4143     acpi_debug_sysctl, "A",
4144     "");
4145 #endif /* ACPI_DEBUG */
4146
4147 static int
4148 acpi_debug_objects_sysctl(SYSCTL_HANDLER_ARGS)
4149 {
4150         int     error;
4151         int     old;
4152
4153         old = acpi_debug_objects;
4154         error = sysctl_handle_int(oidp, &acpi_debug_objects, 0, req);
4155         if (error != 0 || req->newptr == NULL)
4156                 return (error);
4157         if (old == acpi_debug_objects || (old && acpi_debug_objects))
4158                 return (0);
4159
4160         ACPI_SERIAL_BEGIN(acpi);
4161         AcpiGbl_EnableAmlDebugObject = acpi_debug_objects ? TRUE : FALSE;
4162         ACPI_SERIAL_END(acpi);
4163
4164         return (0);
4165 }
4166
4167 static int
4168 acpi_parse_interfaces(char *str, struct acpi_interface *iface)
4169 {
4170         char *p;
4171         size_t len;
4172         int i, j;
4173
4174         p = str;
4175         while (isspace(*p) || *p == ',')
4176                 p++;
4177         len = strlen(p);
4178         if (len == 0)
4179                 return (0);
4180         p = strdup(p, M_TEMP);
4181         for (i = 0; i < len; i++)
4182                 if (p[i] == ',')
4183                         p[i] = '\0';
4184         i = j = 0;
4185         while (i < len)
4186                 if (isspace(p[i]) || p[i] == '\0')
4187                         i++;
4188                 else {
4189                         i += strlen(p + i) + 1;
4190                         j++;
4191                 }
4192         if (j == 0) {
4193                 free(p, M_TEMP);
4194                 return (0);
4195         }
4196         iface->data = malloc(sizeof(*iface->data) * j, M_TEMP, M_WAITOK);
4197         iface->num = j;
4198         i = j = 0;
4199         while (i < len)
4200                 if (isspace(p[i]) || p[i] == '\0')
4201                         i++;
4202                 else {
4203                         iface->data[j] = p + i;
4204                         i += strlen(p + i) + 1;
4205                         j++;
4206                 }
4207
4208         return (j);
4209 }
4210
4211 static void
4212 acpi_free_interfaces(struct acpi_interface *iface)
4213 {
4214
4215         free(iface->data[0], M_TEMP);
4216         free(iface->data, M_TEMP);
4217 }
4218
4219 static void
4220 acpi_reset_interfaces(device_t dev)
4221 {
4222         struct acpi_interface list;
4223         ACPI_STATUS status;
4224         int i;
4225
4226         if (acpi_parse_interfaces(acpi_install_interface, &list) > 0) {
4227                 for (i = 0; i < list.num; i++) {
4228                         status = AcpiInstallInterface(list.data[i]);
4229                         if (ACPI_FAILURE(status))
4230                                 device_printf(dev,
4231                                     "failed to install _OSI(\"%s\"): %s\n",
4232                                     list.data[i], AcpiFormatException(status));
4233                         else if (bootverbose)
4234                                 device_printf(dev, "installed _OSI(\"%s\")\n",
4235                                     list.data[i]);
4236                 }
4237                 acpi_free_interfaces(&list);
4238         }
4239         if (acpi_parse_interfaces(acpi_remove_interface, &list) > 0) {
4240                 for (i = 0; i < list.num; i++) {
4241                         status = AcpiRemoveInterface(list.data[i]);
4242                         if (ACPI_FAILURE(status))
4243                                 device_printf(dev,
4244                                     "failed to remove _OSI(\"%s\"): %s\n",
4245                                     list.data[i], AcpiFormatException(status));
4246                         else if (bootverbose)
4247                                 device_printf(dev, "removed _OSI(\"%s\")\n",
4248                                     list.data[i]);
4249                 }
4250                 acpi_free_interfaces(&list);
4251         }
4252 }
4253
4254 static int
4255 acpi_pm_func(u_long cmd, void *arg, ...)
4256 {
4257         int     state, acpi_state;
4258         int     error;
4259         struct  acpi_softc *sc;
4260         va_list ap;
4261
4262         error = 0;
4263         switch (cmd) {
4264         case POWER_CMD_SUSPEND:
4265                 sc = (struct acpi_softc *)arg;
4266                 if (sc == NULL) {
4267                         error = EINVAL;
4268                         goto out;
4269                 }
4270
4271                 va_start(ap, arg);
4272                 state = va_arg(ap, int);
4273                 va_end(ap);
4274
4275                 switch (state) {
4276                 case POWER_SLEEP_STATE_STANDBY:
4277                         acpi_state = sc->acpi_standby_sx;
4278                         break;
4279                 case POWER_SLEEP_STATE_SUSPEND:
4280                         acpi_state = sc->acpi_suspend_sx;
4281                         break;
4282                 case POWER_SLEEP_STATE_HIBERNATE:
4283                         acpi_state = ACPI_STATE_S4;
4284                         break;
4285                 default:
4286                         error = EINVAL;
4287                         goto out;
4288                 }
4289
4290                 if (ACPI_FAILURE(acpi_EnterSleepState(sc, acpi_state)))
4291                         error = ENXIO;
4292                 break;
4293         default:
4294                 error = EINVAL;
4295                 goto out;
4296         }
4297
4298 out:
4299         return (error);
4300 }
4301
4302 static void
4303 acpi_pm_register(void *arg)
4304 {
4305     if (!cold || resource_disabled("acpi", 0))
4306         return;
4307
4308     power_pm_register(POWER_PM_TYPE_ACPI, acpi_pm_func, NULL);
4309 }
4310
4311 SYSINIT(power, SI_SUB_KLD, SI_ORDER_ANY, acpi_pm_register, NULL);