xref: /openbmc/linux/drivers/gpio/gpiolib-acpi.c (revision abb84c46)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * ACPI helpers for GPIO API
4  *
5  * Copyright (C) 2012, Intel Corporation
6  * Authors: Mathias Nyman <mathias.nyman@linux.intel.com>
7  *          Mika Westerberg <mika.westerberg@linux.intel.com>
8  */
9 
10 #include <linux/acpi.h>
11 #include <linux/dmi.h>
12 #include <linux/errno.h>
13 #include <linux/export.h>
14 #include <linux/interrupt.h>
15 #include <linux/irq.h>
16 #include <linux/mutex.h>
17 #include <linux/pinctrl/pinctrl.h>
18 
19 #include <linux/gpio/consumer.h>
20 #include <linux/gpio/driver.h>
21 #include <linux/gpio/machine.h>
22 
23 #include "gpiolib.h"
24 #include "gpiolib-acpi.h"
25 
26 static int run_edge_events_on_boot = -1;
27 module_param(run_edge_events_on_boot, int, 0444);
28 MODULE_PARM_DESC(run_edge_events_on_boot,
29 		 "Run edge _AEI event-handlers at boot: 0=no, 1=yes, -1=auto");
30 
31 static char *ignore_wake;
32 module_param(ignore_wake, charp, 0444);
33 MODULE_PARM_DESC(ignore_wake,
34 		 "controller@pin combos on which to ignore the ACPI wake flag "
35 		 "ignore_wake=controller@pin[,controller@pin[,...]]");
36 
37 static char *ignore_interrupt;
38 module_param(ignore_interrupt, charp, 0444);
39 MODULE_PARM_DESC(ignore_interrupt,
40 		 "controller@pin combos on which to ignore interrupt "
41 		 "ignore_interrupt=controller@pin[,controller@pin[,...]]");
42 
43 struct acpi_gpiolib_dmi_quirk {
44 	bool no_edge_events_on_boot;
45 	char *ignore_wake;
46 	char *ignore_interrupt;
47 };
48 
49 /**
50  * struct acpi_gpio_event - ACPI GPIO event handler data
51  *
52  * @node:	  list-entry of the events list of the struct acpi_gpio_chip
53  * @handle:	  handle of ACPI method to execute when the IRQ triggers
54  * @handler:	  handler function to pass to request_irq() when requesting the IRQ
55  * @pin:	  GPIO pin number on the struct gpio_chip
56  * @irq:	  Linux IRQ number for the event, for request_irq() / free_irq()
57  * @irqflags:	  flags to pass to request_irq() when requesting the IRQ
58  * @irq_is_wake:  If the ACPI flags indicate the IRQ is a wakeup source
59  * @irq_requested:True if request_irq() has been done
60  * @desc:	  struct gpio_desc for the GPIO pin for this event
61  */
62 struct acpi_gpio_event {
63 	struct list_head node;
64 	acpi_handle handle;
65 	irq_handler_t handler;
66 	unsigned int pin;
67 	unsigned int irq;
68 	unsigned long irqflags;
69 	bool irq_is_wake;
70 	bool irq_requested;
71 	struct gpio_desc *desc;
72 };
73 
74 struct acpi_gpio_connection {
75 	struct list_head node;
76 	unsigned int pin;
77 	struct gpio_desc *desc;
78 };
79 
80 struct acpi_gpio_chip {
81 	/*
82 	 * ACPICA requires that the first field of the context parameter
83 	 * passed to acpi_install_address_space_handler() is large enough
84 	 * to hold struct acpi_connection_info.
85 	 */
86 	struct acpi_connection_info conn_info;
87 	struct list_head conns;
88 	struct mutex conn_lock;
89 	struct gpio_chip *chip;
90 	struct list_head events;
91 	struct list_head deferred_req_irqs_list_entry;
92 };
93 
94 /**
95  * struct acpi_gpio_info - ACPI GPIO specific information
96  * @adev: reference to ACPI device which consumes GPIO resource
97  * @flags: GPIO initialization flags
98  * @gpioint: if %true this GPIO is of type GpioInt otherwise type is GpioIo
99  * @pin_config: pin bias as provided by ACPI
100  * @polarity: interrupt polarity as provided by ACPI
101  * @triggering: triggering type as provided by ACPI
102  * @wake_capable: wake capability as provided by ACPI
103  * @debounce: debounce timeout as provided by ACPI
104  * @quirks: Linux specific quirks as provided by struct acpi_gpio_mapping
105  */
106 struct acpi_gpio_info {
107 	struct acpi_device *adev;
108 	enum gpiod_flags flags;
109 	bool gpioint;
110 	int pin_config;
111 	int polarity;
112 	int triggering;
113 	bool wake_capable;
114 	unsigned int debounce;
115 	unsigned int quirks;
116 };
117 
118 /*
119  * For GPIO chips which call acpi_gpiochip_request_interrupts() before late_init
120  * (so builtin drivers) we register the ACPI GpioInt IRQ handlers from a
121  * late_initcall_sync() handler, so that other builtin drivers can register their
122  * OpRegions before the event handlers can run. This list contains GPIO chips
123  * for which the acpi_gpiochip_request_irqs() call has been deferred.
124  */
125 static DEFINE_MUTEX(acpi_gpio_deferred_req_irqs_lock);
126 static LIST_HEAD(acpi_gpio_deferred_req_irqs_list);
127 static bool acpi_gpio_deferred_req_irqs_done;
128 
129 static int acpi_gpiochip_find(struct gpio_chip *gc, void *data)
130 {
131 	/* First check the actual GPIO device */
132 	if (device_match_acpi_handle(&gc->gpiodev->dev, data))
133 		return true;
134 
135 	/*
136 	 * When the ACPI device is artificially split to the banks of GPIOs,
137 	 * where each of them is represented by a separate GPIO device,
138 	 * the firmware node of the physical device may not be shared among
139 	 * the banks as they may require different values for the same property,
140 	 * e.g., number of GPIOs in a certain bank. In such case the ACPI handle
141 	 * of a GPIO device is NULL and can not be used. Hence we have to check
142 	 * the parent device to be sure that there is no match before bailing
143 	 * out.
144 	 */
145 	if (gc->parent)
146 		return device_match_acpi_handle(gc->parent, data);
147 
148 	return false;
149 }
150 
151 /**
152  * acpi_get_gpiod() - Translate ACPI GPIO pin to GPIO descriptor usable with GPIO API
153  * @path:	ACPI GPIO controller full path name, (e.g. "\\_SB.GPO1")
154  * @pin:	ACPI GPIO pin number (0-based, controller-relative)
155  *
156  * Return: GPIO descriptor to use with Linux generic GPIO API, or ERR_PTR
157  * error value. Specifically returns %-EPROBE_DEFER if the referenced GPIO
158  * controller does not have GPIO chip registered at the moment. This is to
159  * support probe deferral.
160  */
161 static struct gpio_desc *acpi_get_gpiod(char *path, unsigned int pin)
162 {
163 	struct gpio_chip *chip;
164 	acpi_handle handle;
165 	acpi_status status;
166 
167 	status = acpi_get_handle(NULL, path, &handle);
168 	if (ACPI_FAILURE(status))
169 		return ERR_PTR(-ENODEV);
170 
171 	chip = gpiochip_find(handle, acpi_gpiochip_find);
172 	if (!chip)
173 		return ERR_PTR(-EPROBE_DEFER);
174 
175 	return gpiochip_get_desc(chip, pin);
176 }
177 
178 /**
179  * acpi_get_and_request_gpiod - Translate ACPI GPIO pin to GPIO descriptor and
180  *                              hold a refcount to the GPIO device.
181  * @path:      ACPI GPIO controller full path name, (e.g. "\\_SB.GPO1")
182  * @pin:       ACPI GPIO pin number (0-based, controller-relative)
183  * @label:     Label to pass to gpiod_request()
184  *
185  * This function is a simple pass-through to acpi_get_gpiod(), except that
186  * as it is intended for use outside of the GPIO layer (in a similar fashion to
187  * gpiod_get_index() for example) it also holds a reference to the GPIO device.
188  */
189 struct gpio_desc *acpi_get_and_request_gpiod(char *path, unsigned int pin, char *label)
190 {
191 	struct gpio_desc *gpio;
192 	int ret;
193 
194 	gpio = acpi_get_gpiod(path, pin);
195 	if (IS_ERR(gpio))
196 		return gpio;
197 
198 	ret = gpiod_request(gpio, label);
199 	if (ret)
200 		return ERR_PTR(ret);
201 
202 	return gpio;
203 }
204 EXPORT_SYMBOL_GPL(acpi_get_and_request_gpiod);
205 
206 static irqreturn_t acpi_gpio_irq_handler(int irq, void *data)
207 {
208 	struct acpi_gpio_event *event = data;
209 
210 	acpi_evaluate_object(event->handle, NULL, NULL, NULL);
211 
212 	return IRQ_HANDLED;
213 }
214 
215 static irqreturn_t acpi_gpio_irq_handler_evt(int irq, void *data)
216 {
217 	struct acpi_gpio_event *event = data;
218 
219 	acpi_execute_simple_method(event->handle, NULL, event->pin);
220 
221 	return IRQ_HANDLED;
222 }
223 
224 static void acpi_gpio_chip_dh(acpi_handle handle, void *data)
225 {
226 	/* The address of this function is used as a key. */
227 }
228 
229 bool acpi_gpio_get_irq_resource(struct acpi_resource *ares,
230 				struct acpi_resource_gpio **agpio)
231 {
232 	struct acpi_resource_gpio *gpio;
233 
234 	if (ares->type != ACPI_RESOURCE_TYPE_GPIO)
235 		return false;
236 
237 	gpio = &ares->data.gpio;
238 	if (gpio->connection_type != ACPI_RESOURCE_GPIO_TYPE_INT)
239 		return false;
240 
241 	*agpio = gpio;
242 	return true;
243 }
244 EXPORT_SYMBOL_GPL(acpi_gpio_get_irq_resource);
245 
246 /**
247  * acpi_gpio_get_io_resource - Fetch details of an ACPI resource if it is a GPIO
248  *			       I/O resource or return False if not.
249  * @ares:	Pointer to the ACPI resource to fetch
250  * @agpio:	Pointer to a &struct acpi_resource_gpio to store the output pointer
251  */
252 bool acpi_gpio_get_io_resource(struct acpi_resource *ares,
253 			       struct acpi_resource_gpio **agpio)
254 {
255 	struct acpi_resource_gpio *gpio;
256 
257 	if (ares->type != ACPI_RESOURCE_TYPE_GPIO)
258 		return false;
259 
260 	gpio = &ares->data.gpio;
261 	if (gpio->connection_type != ACPI_RESOURCE_GPIO_TYPE_IO)
262 		return false;
263 
264 	*agpio = gpio;
265 	return true;
266 }
267 EXPORT_SYMBOL_GPL(acpi_gpio_get_io_resource);
268 
269 static void acpi_gpiochip_request_irq(struct acpi_gpio_chip *acpi_gpio,
270 				      struct acpi_gpio_event *event)
271 {
272 	struct device *parent = acpi_gpio->chip->parent;
273 	int ret, value;
274 
275 	ret = request_threaded_irq(event->irq, NULL, event->handler,
276 				   event->irqflags | IRQF_ONESHOT, "ACPI:Event", event);
277 	if (ret) {
278 		dev_err(parent, "Failed to setup interrupt handler for %d\n", event->irq);
279 		return;
280 	}
281 
282 	if (event->irq_is_wake)
283 		enable_irq_wake(event->irq);
284 
285 	event->irq_requested = true;
286 
287 	/* Make sure we trigger the initial state of edge-triggered IRQs */
288 	if (run_edge_events_on_boot &&
289 	    (event->irqflags & (IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING))) {
290 		value = gpiod_get_raw_value_cansleep(event->desc);
291 		if (((event->irqflags & IRQF_TRIGGER_RISING) && value == 1) ||
292 		    ((event->irqflags & IRQF_TRIGGER_FALLING) && value == 0))
293 			event->handler(event->irq, event);
294 	}
295 }
296 
297 static void acpi_gpiochip_request_irqs(struct acpi_gpio_chip *acpi_gpio)
298 {
299 	struct acpi_gpio_event *event;
300 
301 	list_for_each_entry(event, &acpi_gpio->events, node)
302 		acpi_gpiochip_request_irq(acpi_gpio, event);
303 }
304 
305 static enum gpiod_flags
306 acpi_gpio_to_gpiod_flags(const struct acpi_resource_gpio *agpio, int polarity)
307 {
308 	/* GpioInt() implies input configuration */
309 	if (agpio->connection_type == ACPI_RESOURCE_GPIO_TYPE_INT)
310 		return GPIOD_IN;
311 
312 	switch (agpio->io_restriction) {
313 	case ACPI_IO_RESTRICT_INPUT:
314 		return GPIOD_IN;
315 	case ACPI_IO_RESTRICT_OUTPUT:
316 		/*
317 		 * ACPI GPIO resources don't contain an initial value for the
318 		 * GPIO. Therefore we deduce that value from the pull field
319 		 * and the polarity instead. If the pin is pulled up we assume
320 		 * default to be high, if it is pulled down we assume default
321 		 * to be low, otherwise we leave pin untouched. For active low
322 		 * polarity values will be switched. See also
323 		 * Documentation/firmware-guide/acpi/gpio-properties.rst.
324 		 */
325 		switch (agpio->pin_config) {
326 		case ACPI_PIN_CONFIG_PULLUP:
327 			return polarity == GPIO_ACTIVE_LOW ? GPIOD_OUT_LOW : GPIOD_OUT_HIGH;
328 		case ACPI_PIN_CONFIG_PULLDOWN:
329 			return polarity == GPIO_ACTIVE_LOW ? GPIOD_OUT_HIGH : GPIOD_OUT_LOW;
330 		default:
331 			break;
332 		}
333 		break;
334 	default:
335 		break;
336 	}
337 
338 	/*
339 	 * Assume that the BIOS has configured the direction and pull
340 	 * accordingly.
341 	 */
342 	return GPIOD_ASIS;
343 }
344 
345 static struct gpio_desc *acpi_request_own_gpiod(struct gpio_chip *chip,
346 						struct acpi_resource_gpio *agpio,
347 						unsigned int index,
348 						const char *label)
349 {
350 	int polarity = GPIO_ACTIVE_HIGH;
351 	enum gpiod_flags flags = acpi_gpio_to_gpiod_flags(agpio, polarity);
352 	unsigned int pin = agpio->pin_table[index];
353 	struct gpio_desc *desc;
354 	int ret;
355 
356 	desc = gpiochip_request_own_desc(chip, pin, label, polarity, flags);
357 	if (IS_ERR(desc))
358 		return desc;
359 
360 	/* ACPI uses hundredths of milliseconds units */
361 	ret = gpio_set_debounce_timeout(desc, agpio->debounce_timeout * 10);
362 	if (ret)
363 		dev_warn(chip->parent,
364 			 "Failed to set debounce-timeout for pin 0x%04X, err %d\n",
365 			 pin, ret);
366 
367 	return desc;
368 }
369 
370 static bool acpi_gpio_in_ignore_list(const char *ignore_list, const char *controller_in,
371 				     unsigned int pin_in)
372 {
373 	const char *controller, *pin_str;
374 	unsigned int pin;
375 	char *endp;
376 	int len;
377 
378 	controller = ignore_list;
379 	while (controller) {
380 		pin_str = strchr(controller, '@');
381 		if (!pin_str)
382 			goto err;
383 
384 		len = pin_str - controller;
385 		if (len == strlen(controller_in) &&
386 		    strncmp(controller, controller_in, len) == 0) {
387 			pin = simple_strtoul(pin_str + 1, &endp, 10);
388 			if (*endp != 0 && *endp != ',')
389 				goto err;
390 
391 			if (pin == pin_in)
392 				return true;
393 		}
394 
395 		controller = strchr(controller, ',');
396 		if (controller)
397 			controller++;
398 	}
399 
400 	return false;
401 err:
402 	pr_err_once("Error: Invalid value for gpiolib_acpi.ignore_...: %s\n", ignore_list);
403 	return false;
404 }
405 
406 static bool acpi_gpio_irq_is_wake(struct device *parent,
407 				  const struct acpi_resource_gpio *agpio)
408 {
409 	unsigned int pin = agpio->pin_table[0];
410 
411 	if (agpio->wake_capable != ACPI_WAKE_CAPABLE)
412 		return false;
413 
414 	if (acpi_gpio_in_ignore_list(ignore_wake, dev_name(parent), pin)) {
415 		dev_info(parent, "Ignoring wakeup on pin %u\n", pin);
416 		return false;
417 	}
418 
419 	return true;
420 }
421 
422 /* Always returns AE_OK so that we keep looping over the resources */
423 static acpi_status acpi_gpiochip_alloc_event(struct acpi_resource *ares,
424 					     void *context)
425 {
426 	struct acpi_gpio_chip *acpi_gpio = context;
427 	struct gpio_chip *chip = acpi_gpio->chip;
428 	struct acpi_resource_gpio *agpio;
429 	acpi_handle handle, evt_handle;
430 	struct acpi_gpio_event *event;
431 	irq_handler_t handler = NULL;
432 	struct gpio_desc *desc;
433 	unsigned int pin;
434 	int ret, irq;
435 
436 	if (!acpi_gpio_get_irq_resource(ares, &agpio))
437 		return AE_OK;
438 
439 	handle = ACPI_HANDLE(chip->parent);
440 	pin = agpio->pin_table[0];
441 
442 	if (pin <= 255) {
443 		char ev_name[8];
444 		sprintf(ev_name, "_%c%02X",
445 			agpio->triggering == ACPI_EDGE_SENSITIVE ? 'E' : 'L',
446 			pin);
447 		if (ACPI_SUCCESS(acpi_get_handle(handle, ev_name, &evt_handle)))
448 			handler = acpi_gpio_irq_handler;
449 	}
450 	if (!handler) {
451 		if (ACPI_SUCCESS(acpi_get_handle(handle, "_EVT", &evt_handle)))
452 			handler = acpi_gpio_irq_handler_evt;
453 	}
454 	if (!handler)
455 		return AE_OK;
456 
457 	desc = acpi_request_own_gpiod(chip, agpio, 0, "ACPI:Event");
458 	if (IS_ERR(desc)) {
459 		dev_err(chip->parent,
460 			"Failed to request GPIO for pin 0x%04X, err %ld\n",
461 			pin, PTR_ERR(desc));
462 		return AE_OK;
463 	}
464 
465 	ret = gpiochip_lock_as_irq(chip, pin);
466 	if (ret) {
467 		dev_err(chip->parent,
468 			"Failed to lock GPIO pin 0x%04X as interrupt, err %d\n",
469 			pin, ret);
470 		goto fail_free_desc;
471 	}
472 
473 	irq = gpiod_to_irq(desc);
474 	if (irq < 0) {
475 		dev_err(chip->parent,
476 			"Failed to translate GPIO pin 0x%04X to IRQ, err %d\n",
477 			pin, irq);
478 		goto fail_unlock_irq;
479 	}
480 
481 	if (acpi_gpio_in_ignore_list(ignore_interrupt, dev_name(chip->parent), pin)) {
482 		dev_info(chip->parent, "Ignoring interrupt on pin %u\n", pin);
483 		return AE_OK;
484 	}
485 
486 	event = kzalloc(sizeof(*event), GFP_KERNEL);
487 	if (!event)
488 		goto fail_unlock_irq;
489 
490 	event->irqflags = IRQF_ONESHOT;
491 	if (agpio->triggering == ACPI_LEVEL_SENSITIVE) {
492 		if (agpio->polarity == ACPI_ACTIVE_HIGH)
493 			event->irqflags |= IRQF_TRIGGER_HIGH;
494 		else
495 			event->irqflags |= IRQF_TRIGGER_LOW;
496 	} else {
497 		switch (agpio->polarity) {
498 		case ACPI_ACTIVE_HIGH:
499 			event->irqflags |= IRQF_TRIGGER_RISING;
500 			break;
501 		case ACPI_ACTIVE_LOW:
502 			event->irqflags |= IRQF_TRIGGER_FALLING;
503 			break;
504 		default:
505 			event->irqflags |= IRQF_TRIGGER_RISING |
506 					   IRQF_TRIGGER_FALLING;
507 			break;
508 		}
509 	}
510 
511 	event->handle = evt_handle;
512 	event->handler = handler;
513 	event->irq = irq;
514 	event->irq_is_wake = acpi_gpio_irq_is_wake(chip->parent, agpio);
515 	event->pin = pin;
516 	event->desc = desc;
517 
518 	list_add_tail(&event->node, &acpi_gpio->events);
519 
520 	return AE_OK;
521 
522 fail_unlock_irq:
523 	gpiochip_unlock_as_irq(chip, pin);
524 fail_free_desc:
525 	gpiochip_free_own_desc(desc);
526 
527 	return AE_OK;
528 }
529 
530 /**
531  * acpi_gpiochip_request_interrupts() - Register isr for gpio chip ACPI events
532  * @chip:      GPIO chip
533  *
534  * ACPI5 platforms can use GPIO signaled ACPI events. These GPIO interrupts are
535  * handled by ACPI event methods which need to be called from the GPIO
536  * chip's interrupt handler. acpi_gpiochip_request_interrupts() finds out which
537  * GPIO pins have ACPI event methods and assigns interrupt handlers that calls
538  * the ACPI event methods for those pins.
539  */
540 void acpi_gpiochip_request_interrupts(struct gpio_chip *chip)
541 {
542 	struct acpi_gpio_chip *acpi_gpio;
543 	acpi_handle handle;
544 	acpi_status status;
545 	bool defer;
546 
547 	if (!chip->parent || !chip->to_irq)
548 		return;
549 
550 	handle = ACPI_HANDLE(chip->parent);
551 	if (!handle)
552 		return;
553 
554 	status = acpi_get_data(handle, acpi_gpio_chip_dh, (void **)&acpi_gpio);
555 	if (ACPI_FAILURE(status))
556 		return;
557 
558 	if (acpi_quirk_skip_gpio_event_handlers())
559 		return;
560 
561 	acpi_walk_resources(handle, METHOD_NAME__AEI,
562 			    acpi_gpiochip_alloc_event, acpi_gpio);
563 
564 	mutex_lock(&acpi_gpio_deferred_req_irqs_lock);
565 	defer = !acpi_gpio_deferred_req_irqs_done;
566 	if (defer)
567 		list_add(&acpi_gpio->deferred_req_irqs_list_entry,
568 			 &acpi_gpio_deferred_req_irqs_list);
569 	mutex_unlock(&acpi_gpio_deferred_req_irqs_lock);
570 
571 	if (defer)
572 		return;
573 
574 	acpi_gpiochip_request_irqs(acpi_gpio);
575 }
576 EXPORT_SYMBOL_GPL(acpi_gpiochip_request_interrupts);
577 
578 /**
579  * acpi_gpiochip_free_interrupts() - Free GPIO ACPI event interrupts.
580  * @chip:      GPIO chip
581  *
582  * Free interrupts associated with GPIO ACPI event method for the given
583  * GPIO chip.
584  */
585 void acpi_gpiochip_free_interrupts(struct gpio_chip *chip)
586 {
587 	struct acpi_gpio_chip *acpi_gpio;
588 	struct acpi_gpio_event *event, *ep;
589 	acpi_handle handle;
590 	acpi_status status;
591 
592 	if (!chip->parent || !chip->to_irq)
593 		return;
594 
595 	handle = ACPI_HANDLE(chip->parent);
596 	if (!handle)
597 		return;
598 
599 	status = acpi_get_data(handle, acpi_gpio_chip_dh, (void **)&acpi_gpio);
600 	if (ACPI_FAILURE(status))
601 		return;
602 
603 	mutex_lock(&acpi_gpio_deferred_req_irqs_lock);
604 	if (!list_empty(&acpi_gpio->deferred_req_irqs_list_entry))
605 		list_del_init(&acpi_gpio->deferred_req_irqs_list_entry);
606 	mutex_unlock(&acpi_gpio_deferred_req_irqs_lock);
607 
608 	list_for_each_entry_safe_reverse(event, ep, &acpi_gpio->events, node) {
609 		if (event->irq_requested) {
610 			if (event->irq_is_wake)
611 				disable_irq_wake(event->irq);
612 
613 			free_irq(event->irq, event);
614 		}
615 
616 		gpiochip_unlock_as_irq(chip, event->pin);
617 		gpiochip_free_own_desc(event->desc);
618 		list_del(&event->node);
619 		kfree(event);
620 	}
621 }
622 EXPORT_SYMBOL_GPL(acpi_gpiochip_free_interrupts);
623 
624 int acpi_dev_add_driver_gpios(struct acpi_device *adev,
625 			      const struct acpi_gpio_mapping *gpios)
626 {
627 	if (adev && gpios) {
628 		adev->driver_gpios = gpios;
629 		return 0;
630 	}
631 	return -EINVAL;
632 }
633 EXPORT_SYMBOL_GPL(acpi_dev_add_driver_gpios);
634 
635 void acpi_dev_remove_driver_gpios(struct acpi_device *adev)
636 {
637 	if (adev)
638 		adev->driver_gpios = NULL;
639 }
640 EXPORT_SYMBOL_GPL(acpi_dev_remove_driver_gpios);
641 
642 static void acpi_dev_release_driver_gpios(void *adev)
643 {
644 	acpi_dev_remove_driver_gpios(adev);
645 }
646 
647 int devm_acpi_dev_add_driver_gpios(struct device *dev,
648 				   const struct acpi_gpio_mapping *gpios)
649 {
650 	struct acpi_device *adev = ACPI_COMPANION(dev);
651 	int ret;
652 
653 	ret = acpi_dev_add_driver_gpios(adev, gpios);
654 	if (ret)
655 		return ret;
656 
657 	return devm_add_action_or_reset(dev, acpi_dev_release_driver_gpios, adev);
658 }
659 EXPORT_SYMBOL_GPL(devm_acpi_dev_add_driver_gpios);
660 
661 static bool acpi_get_driver_gpio_data(struct acpi_device *adev,
662 				      const char *name, int index,
663 				      struct fwnode_reference_args *args,
664 				      unsigned int *quirks)
665 {
666 	const struct acpi_gpio_mapping *gm;
667 
668 	if (!adev || !adev->driver_gpios)
669 		return false;
670 
671 	for (gm = adev->driver_gpios; gm->name; gm++)
672 		if (!strcmp(name, gm->name) && gm->data && index < gm->size) {
673 			const struct acpi_gpio_params *par = gm->data + index;
674 
675 			args->fwnode = acpi_fwnode_handle(adev);
676 			args->args[0] = par->crs_entry_index;
677 			args->args[1] = par->line_index;
678 			args->args[2] = par->active_low;
679 			args->nargs = 3;
680 
681 			*quirks = gm->quirks;
682 			return true;
683 		}
684 
685 	return false;
686 }
687 
688 static int
689 __acpi_gpio_update_gpiod_flags(enum gpiod_flags *flags, enum gpiod_flags update)
690 {
691 	const enum gpiod_flags mask =
692 		GPIOD_FLAGS_BIT_DIR_SET | GPIOD_FLAGS_BIT_DIR_OUT |
693 		GPIOD_FLAGS_BIT_DIR_VAL;
694 	int ret = 0;
695 
696 	/*
697 	 * Check if the BIOS has IoRestriction with explicitly set direction
698 	 * and update @flags accordingly. Otherwise use whatever caller asked
699 	 * for.
700 	 */
701 	if (update & GPIOD_FLAGS_BIT_DIR_SET) {
702 		enum gpiod_flags diff = *flags ^ update;
703 
704 		/*
705 		 * Check if caller supplied incompatible GPIO initialization
706 		 * flags.
707 		 *
708 		 * Return %-EINVAL to notify that firmware has different
709 		 * settings and we are going to use them.
710 		 */
711 		if (((*flags & GPIOD_FLAGS_BIT_DIR_SET) && (diff & GPIOD_FLAGS_BIT_DIR_OUT)) ||
712 		    ((*flags & GPIOD_FLAGS_BIT_DIR_OUT) && (diff & GPIOD_FLAGS_BIT_DIR_VAL)))
713 			ret = -EINVAL;
714 		*flags = (*flags & ~mask) | (update & mask);
715 	}
716 	return ret;
717 }
718 
719 static int acpi_gpio_update_gpiod_flags(enum gpiod_flags *flags,
720 				        struct acpi_gpio_info *info)
721 {
722 	struct device *dev = &info->adev->dev;
723 	enum gpiod_flags old = *flags;
724 	int ret;
725 
726 	ret = __acpi_gpio_update_gpiod_flags(&old, info->flags);
727 	if (info->quirks & ACPI_GPIO_QUIRK_NO_IO_RESTRICTION) {
728 		if (ret)
729 			dev_warn(dev, FW_BUG "GPIO not in correct mode, fixing\n");
730 	} else {
731 		if (ret)
732 			dev_dbg(dev, "Override GPIO initialization flags\n");
733 		*flags = old;
734 	}
735 
736 	return ret;
737 }
738 
739 static int acpi_gpio_update_gpiod_lookup_flags(unsigned long *lookupflags,
740 					       struct acpi_gpio_info *info)
741 {
742 	switch (info->pin_config) {
743 	case ACPI_PIN_CONFIG_PULLUP:
744 		*lookupflags |= GPIO_PULL_UP;
745 		break;
746 	case ACPI_PIN_CONFIG_PULLDOWN:
747 		*lookupflags |= GPIO_PULL_DOWN;
748 		break;
749 	case ACPI_PIN_CONFIG_NOPULL:
750 		*lookupflags |= GPIO_PULL_DISABLE;
751 		break;
752 	default:
753 		break;
754 	}
755 
756 	if (info->polarity == GPIO_ACTIVE_LOW)
757 		*lookupflags |= GPIO_ACTIVE_LOW;
758 
759 	return 0;
760 }
761 
762 struct acpi_gpio_lookup {
763 	struct acpi_gpio_info info;
764 	int index;
765 	u16 pin_index;
766 	bool active_low;
767 	struct gpio_desc *desc;
768 	int n;
769 };
770 
771 static int acpi_populate_gpio_lookup(struct acpi_resource *ares, void *data)
772 {
773 	struct acpi_gpio_lookup *lookup = data;
774 
775 	if (ares->type != ACPI_RESOURCE_TYPE_GPIO)
776 		return 1;
777 
778 	if (!lookup->desc) {
779 		const struct acpi_resource_gpio *agpio = &ares->data.gpio;
780 		bool gpioint = agpio->connection_type == ACPI_RESOURCE_GPIO_TYPE_INT;
781 		struct gpio_desc *desc;
782 		u16 pin_index;
783 
784 		if (lookup->info.quirks & ACPI_GPIO_QUIRK_ONLY_GPIOIO && gpioint)
785 			lookup->index++;
786 
787 		if (lookup->n++ != lookup->index)
788 			return 1;
789 
790 		pin_index = lookup->pin_index;
791 		if (pin_index >= agpio->pin_table_length)
792 			return 1;
793 
794 		if (lookup->info.quirks & ACPI_GPIO_QUIRK_ABSOLUTE_NUMBER)
795 			desc = gpio_to_desc(agpio->pin_table[pin_index]);
796 		else
797 			desc = acpi_get_gpiod(agpio->resource_source.string_ptr,
798 					      agpio->pin_table[pin_index]);
799 		lookup->desc = desc;
800 		lookup->info.pin_config = agpio->pin_config;
801 		lookup->info.debounce = agpio->debounce_timeout;
802 		lookup->info.gpioint = gpioint;
803 		lookup->info.wake_capable = acpi_gpio_irq_is_wake(&lookup->info.adev->dev, agpio);
804 
805 		/*
806 		 * Polarity and triggering are only specified for GpioInt
807 		 * resource.
808 		 * Note: we expect here:
809 		 * - ACPI_ACTIVE_LOW == GPIO_ACTIVE_LOW
810 		 * - ACPI_ACTIVE_HIGH == GPIO_ACTIVE_HIGH
811 		 */
812 		if (lookup->info.gpioint) {
813 			lookup->info.polarity = agpio->polarity;
814 			lookup->info.triggering = agpio->triggering;
815 		} else {
816 			lookup->info.polarity = lookup->active_low;
817 		}
818 
819 		lookup->info.flags = acpi_gpio_to_gpiod_flags(agpio, lookup->info.polarity);
820 	}
821 
822 	return 1;
823 }
824 
825 static int acpi_gpio_resource_lookup(struct acpi_gpio_lookup *lookup,
826 				     struct acpi_gpio_info *info)
827 {
828 	struct acpi_device *adev = lookup->info.adev;
829 	struct list_head res_list;
830 	int ret;
831 
832 	INIT_LIST_HEAD(&res_list);
833 
834 	ret = acpi_dev_get_resources(adev, &res_list,
835 				     acpi_populate_gpio_lookup,
836 				     lookup);
837 	if (ret < 0)
838 		return ret;
839 
840 	acpi_dev_free_resource_list(&res_list);
841 
842 	if (!lookup->desc)
843 		return -ENOENT;
844 
845 	if (info)
846 		*info = lookup->info;
847 	return 0;
848 }
849 
850 static int acpi_gpio_property_lookup(struct fwnode_handle *fwnode,
851 				     const char *propname, int index,
852 				     struct acpi_gpio_lookup *lookup)
853 {
854 	struct fwnode_reference_args args;
855 	unsigned int quirks = 0;
856 	int ret;
857 
858 	memset(&args, 0, sizeof(args));
859 	ret = __acpi_node_get_property_reference(fwnode, propname, index, 3,
860 						 &args);
861 	if (ret) {
862 		struct acpi_device *adev;
863 
864 		adev = to_acpi_device_node(fwnode);
865 		if (!acpi_get_driver_gpio_data(adev, propname, index, &args, &quirks))
866 			return ret;
867 	}
868 	/*
869 	 * The property was found and resolved, so need to lookup the GPIO based
870 	 * on returned args.
871 	 */
872 	if (!to_acpi_device_node(args.fwnode))
873 		return -EINVAL;
874 	if (args.nargs != 3)
875 		return -EPROTO;
876 
877 	lookup->index = args.args[0];
878 	lookup->pin_index = args.args[1];
879 	lookup->active_low = !!args.args[2];
880 
881 	lookup->info.adev = to_acpi_device_node(args.fwnode);
882 	lookup->info.quirks = quirks;
883 
884 	return 0;
885 }
886 
887 /**
888  * acpi_get_gpiod_by_index() - get a GPIO descriptor from device resources
889  * @adev: pointer to a ACPI device to get GPIO from
890  * @propname: Property name of the GPIO (optional)
891  * @index: index of GpioIo/GpioInt resource (starting from %0)
892  * @info: info pointer to fill in (optional)
893  *
894  * Function goes through ACPI resources for @adev and based on @index looks
895  * up a GpioIo/GpioInt resource, translates it to the Linux GPIO descriptor,
896  * and returns it. @index matches GpioIo/GpioInt resources only so if there
897  * are total %3 GPIO resources, the index goes from %0 to %2.
898  *
899  * If @propname is specified the GPIO is looked using device property. In
900  * that case @index is used to select the GPIO entry in the property value
901  * (in case of multiple).
902  *
903  * If the GPIO cannot be translated or there is an error, an ERR_PTR is
904  * returned.
905  *
906  * Note: if the GPIO resource has multiple entries in the pin list, this
907  * function only returns the first.
908  */
909 static struct gpio_desc *acpi_get_gpiod_by_index(struct acpi_device *adev,
910 						 const char *propname,
911 						 int index,
912 						 struct acpi_gpio_info *info)
913 {
914 	struct acpi_gpio_lookup lookup;
915 	int ret;
916 
917 	if (!adev)
918 		return ERR_PTR(-ENODEV);
919 
920 	memset(&lookup, 0, sizeof(lookup));
921 	lookup.index = index;
922 
923 	if (propname) {
924 		dev_dbg(&adev->dev, "GPIO: looking up %s\n", propname);
925 
926 		ret = acpi_gpio_property_lookup(acpi_fwnode_handle(adev),
927 						propname, index, &lookup);
928 		if (ret)
929 			return ERR_PTR(ret);
930 
931 		dev_dbg(&adev->dev, "GPIO: _DSD returned %s %d %u %u\n",
932 			dev_name(&lookup.info.adev->dev), lookup.index,
933 			lookup.pin_index, lookup.active_low);
934 	} else {
935 		dev_dbg(&adev->dev, "GPIO: looking up %d in _CRS\n", index);
936 		lookup.info.adev = adev;
937 	}
938 
939 	ret = acpi_gpio_resource_lookup(&lookup, info);
940 	return ret ? ERR_PTR(ret) : lookup.desc;
941 }
942 
943 /**
944  * acpi_get_gpiod_from_data() - get a GPIO descriptor from ACPI data node
945  * @fwnode: pointer to an ACPI firmware node to get the GPIO information from
946  * @propname: Property name of the GPIO
947  * @index: index of GpioIo/GpioInt resource (starting from %0)
948  * @info: info pointer to fill in (optional)
949  *
950  * This function uses the property-based GPIO lookup to get to the GPIO
951  * resource with the relevant information from a data-only ACPI firmware node
952  * and uses that to obtain the GPIO descriptor to return.
953  *
954  * If the GPIO cannot be translated or there is an error an ERR_PTR is
955  * returned.
956  */
957 static struct gpio_desc *acpi_get_gpiod_from_data(struct fwnode_handle *fwnode,
958 						  const char *propname,
959 						  int index,
960 						  struct acpi_gpio_info *info)
961 {
962 	struct acpi_gpio_lookup lookup;
963 	int ret;
964 
965 	if (!is_acpi_data_node(fwnode))
966 		return ERR_PTR(-ENODEV);
967 
968 	if (!propname)
969 		return ERR_PTR(-EINVAL);
970 
971 	memset(&lookup, 0, sizeof(lookup));
972 	lookup.index = index;
973 
974 	ret = acpi_gpio_property_lookup(fwnode, propname, index, &lookup);
975 	if (ret)
976 		return ERR_PTR(ret);
977 
978 	ret = acpi_gpio_resource_lookup(&lookup, info);
979 	return ret ? ERR_PTR(ret) : lookup.desc;
980 }
981 
982 static bool acpi_can_fallback_to_crs(struct acpi_device *adev,
983 				     const char *con_id)
984 {
985 	/* Never allow fallback if the device has properties */
986 	if (acpi_dev_has_props(adev) || adev->driver_gpios)
987 		return false;
988 
989 	return con_id == NULL;
990 }
991 
992 struct gpio_desc *acpi_find_gpio(struct fwnode_handle *fwnode,
993 				 const char *con_id,
994 				 unsigned int idx,
995 				 enum gpiod_flags *dflags,
996 				 unsigned long *lookupflags)
997 {
998 	struct acpi_device *adev = to_acpi_device_node(fwnode);
999 	struct acpi_gpio_info info;
1000 	struct gpio_desc *desc;
1001 	char propname[32];
1002 	int i;
1003 
1004 	/* Try first from _DSD */
1005 	for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
1006 		if (con_id) {
1007 			snprintf(propname, sizeof(propname), "%s-%s",
1008 				 con_id, gpio_suffixes[i]);
1009 		} else {
1010 			snprintf(propname, sizeof(propname), "%s",
1011 				 gpio_suffixes[i]);
1012 		}
1013 
1014 		if (adev)
1015 			desc = acpi_get_gpiod_by_index(adev,
1016 						       propname, idx, &info);
1017 		else
1018 			desc = acpi_get_gpiod_from_data(fwnode,
1019 						        propname, idx, &info);
1020 		if (!IS_ERR(desc))
1021 			break;
1022 		if (PTR_ERR(desc) == -EPROBE_DEFER)
1023 			return ERR_CAST(desc);
1024 	}
1025 
1026 	/* Then from plain _CRS GPIOs */
1027 	if (IS_ERR(desc)) {
1028 		if (!adev || !acpi_can_fallback_to_crs(adev, con_id))
1029 			return ERR_PTR(-ENOENT);
1030 
1031 		desc = acpi_get_gpiod_by_index(adev, NULL, idx, &info);
1032 		if (IS_ERR(desc))
1033 			return desc;
1034 	}
1035 
1036 	if (info.gpioint &&
1037 	    (*dflags == GPIOD_OUT_LOW || *dflags == GPIOD_OUT_HIGH)) {
1038 		dev_dbg(&adev->dev, "refusing GpioInt() entry when doing GPIOD_OUT_* lookup\n");
1039 		return ERR_PTR(-ENOENT);
1040 	}
1041 
1042 	acpi_gpio_update_gpiod_flags(dflags, &info);
1043 	acpi_gpio_update_gpiod_lookup_flags(lookupflags, &info);
1044 	return desc;
1045 }
1046 
1047 /**
1048  * acpi_dev_gpio_irq_wake_get_by() - Find GpioInt and translate it to Linux IRQ number
1049  * @adev: pointer to a ACPI device to get IRQ from
1050  * @name: optional name of GpioInt resource
1051  * @index: index of GpioInt resource (starting from %0)
1052  * @wake_capable: Set to true if the IRQ is wake capable
1053  *
1054  * If the device has one or more GpioInt resources, this function can be
1055  * used to translate from the GPIO offset in the resource to the Linux IRQ
1056  * number.
1057  *
1058  * The function is idempotent, though each time it runs it will configure GPIO
1059  * pin direction according to the flags in GpioInt resource.
1060  *
1061  * The function takes optional @name parameter. If the resource has a property
1062  * name, then only those will be taken into account.
1063  *
1064  * The GPIO is considered wake capable if the GpioInt resource specifies
1065  * SharedAndWake or ExclusiveAndWake.
1066  *
1067  * Return: Linux IRQ number (> %0) on success, negative errno on failure.
1068  */
1069 int acpi_dev_gpio_irq_wake_get_by(struct acpi_device *adev, const char *name, int index,
1070 				  bool *wake_capable)
1071 {
1072 	int idx, i;
1073 	unsigned int irq_flags;
1074 	int ret;
1075 
1076 	for (i = 0, idx = 0; idx <= index; i++) {
1077 		struct acpi_gpio_info info;
1078 		struct gpio_desc *desc;
1079 
1080 		desc = acpi_get_gpiod_by_index(adev, name, i, &info);
1081 
1082 		/* Ignore -EPROBE_DEFER, it only matters if idx matches */
1083 		if (IS_ERR(desc) && PTR_ERR(desc) != -EPROBE_DEFER)
1084 			return PTR_ERR(desc);
1085 
1086 		if (info.gpioint && idx++ == index) {
1087 			unsigned long lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
1088 			enum gpiod_flags dflags = GPIOD_ASIS;
1089 			char label[32];
1090 			int irq;
1091 
1092 			if (IS_ERR(desc))
1093 				return PTR_ERR(desc);
1094 
1095 			irq = gpiod_to_irq(desc);
1096 			if (irq < 0)
1097 				return irq;
1098 
1099 			acpi_gpio_update_gpiod_flags(&dflags, &info);
1100 			acpi_gpio_update_gpiod_lookup_flags(&lflags, &info);
1101 
1102 			snprintf(label, sizeof(label), "GpioInt() %d", index);
1103 			ret = gpiod_configure_flags(desc, label, lflags, dflags);
1104 			if (ret < 0)
1105 				return ret;
1106 
1107 			/* ACPI uses hundredths of milliseconds units */
1108 			ret = gpio_set_debounce_timeout(desc, info.debounce * 10);
1109 			if (ret)
1110 				return ret;
1111 
1112 			irq_flags = acpi_dev_get_irq_type(info.triggering,
1113 							  info.polarity);
1114 
1115 			/*
1116 			 * If the IRQ is not already in use then set type
1117 			 * if specified and different than the current one.
1118 			 */
1119 			if (can_request_irq(irq, irq_flags)) {
1120 				if (irq_flags != IRQ_TYPE_NONE &&
1121 				    irq_flags != irq_get_trigger_type(irq))
1122 					irq_set_irq_type(irq, irq_flags);
1123 			} else {
1124 				dev_dbg(&adev->dev, "IRQ %d already in use\n", irq);
1125 			}
1126 
1127 			/* avoid suspend issues with GPIOs when systems are using S3 */
1128 			if (wake_capable && acpi_gbl_FADT.flags & ACPI_FADT_LOW_POWER_S0)
1129 				*wake_capable = info.wake_capable;
1130 
1131 			return irq;
1132 		}
1133 
1134 	}
1135 	return -ENOENT;
1136 }
1137 EXPORT_SYMBOL_GPL(acpi_dev_gpio_irq_wake_get_by);
1138 
1139 static acpi_status
1140 acpi_gpio_adr_space_handler(u32 function, acpi_physical_address address,
1141 			    u32 bits, u64 *value, void *handler_context,
1142 			    void *region_context)
1143 {
1144 	struct acpi_gpio_chip *achip = region_context;
1145 	struct gpio_chip *chip = achip->chip;
1146 	struct acpi_resource_gpio *agpio;
1147 	struct acpi_resource *ares;
1148 	u16 pin_index = address;
1149 	acpi_status status;
1150 	int length;
1151 	int i;
1152 
1153 	status = acpi_buffer_to_resource(achip->conn_info.connection,
1154 					 achip->conn_info.length, &ares);
1155 	if (ACPI_FAILURE(status))
1156 		return status;
1157 
1158 	if (WARN_ON(ares->type != ACPI_RESOURCE_TYPE_GPIO)) {
1159 		ACPI_FREE(ares);
1160 		return AE_BAD_PARAMETER;
1161 	}
1162 
1163 	agpio = &ares->data.gpio;
1164 
1165 	if (WARN_ON(agpio->io_restriction == ACPI_IO_RESTRICT_INPUT &&
1166 	    function == ACPI_WRITE)) {
1167 		ACPI_FREE(ares);
1168 		return AE_BAD_PARAMETER;
1169 	}
1170 
1171 	length = min_t(u16, agpio->pin_table_length, pin_index + bits);
1172 	for (i = pin_index; i < length; ++i) {
1173 		unsigned int pin = agpio->pin_table[i];
1174 		struct acpi_gpio_connection *conn;
1175 		struct gpio_desc *desc;
1176 		bool found;
1177 
1178 		mutex_lock(&achip->conn_lock);
1179 
1180 		found = false;
1181 		list_for_each_entry(conn, &achip->conns, node) {
1182 			if (conn->pin == pin) {
1183 				found = true;
1184 				desc = conn->desc;
1185 				break;
1186 			}
1187 		}
1188 
1189 		/*
1190 		 * The same GPIO can be shared between operation region and
1191 		 * event but only if the access here is ACPI_READ. In that
1192 		 * case we "borrow" the event GPIO instead.
1193 		 */
1194 		if (!found && agpio->shareable == ACPI_SHARED &&
1195 		     function == ACPI_READ) {
1196 			struct acpi_gpio_event *event;
1197 
1198 			list_for_each_entry(event, &achip->events, node) {
1199 				if (event->pin == pin) {
1200 					desc = event->desc;
1201 					found = true;
1202 					break;
1203 				}
1204 			}
1205 		}
1206 
1207 		if (!found) {
1208 			desc = acpi_request_own_gpiod(chip, agpio, i, "ACPI:OpRegion");
1209 			if (IS_ERR(desc)) {
1210 				mutex_unlock(&achip->conn_lock);
1211 				status = AE_ERROR;
1212 				goto out;
1213 			}
1214 
1215 			conn = kzalloc(sizeof(*conn), GFP_KERNEL);
1216 			if (!conn) {
1217 				gpiochip_free_own_desc(desc);
1218 				mutex_unlock(&achip->conn_lock);
1219 				status = AE_NO_MEMORY;
1220 				goto out;
1221 			}
1222 
1223 			conn->pin = pin;
1224 			conn->desc = desc;
1225 			list_add_tail(&conn->node, &achip->conns);
1226 		}
1227 
1228 		mutex_unlock(&achip->conn_lock);
1229 
1230 		if (function == ACPI_WRITE)
1231 			gpiod_set_raw_value_cansleep(desc, !!(*value & BIT(i)));
1232 		else
1233 			*value |= (u64)gpiod_get_raw_value_cansleep(desc) << i;
1234 	}
1235 
1236 out:
1237 	ACPI_FREE(ares);
1238 	return status;
1239 }
1240 
1241 static void acpi_gpiochip_request_regions(struct acpi_gpio_chip *achip)
1242 {
1243 	struct gpio_chip *chip = achip->chip;
1244 	acpi_handle handle = ACPI_HANDLE(chip->parent);
1245 	acpi_status status;
1246 
1247 	INIT_LIST_HEAD(&achip->conns);
1248 	mutex_init(&achip->conn_lock);
1249 	status = acpi_install_address_space_handler(handle, ACPI_ADR_SPACE_GPIO,
1250 						    acpi_gpio_adr_space_handler,
1251 						    NULL, achip);
1252 	if (ACPI_FAILURE(status))
1253 		dev_err(chip->parent,
1254 		        "Failed to install GPIO OpRegion handler\n");
1255 }
1256 
1257 static void acpi_gpiochip_free_regions(struct acpi_gpio_chip *achip)
1258 {
1259 	struct gpio_chip *chip = achip->chip;
1260 	acpi_handle handle = ACPI_HANDLE(chip->parent);
1261 	struct acpi_gpio_connection *conn, *tmp;
1262 	acpi_status status;
1263 
1264 	status = acpi_remove_address_space_handler(handle, ACPI_ADR_SPACE_GPIO,
1265 						   acpi_gpio_adr_space_handler);
1266 	if (ACPI_FAILURE(status)) {
1267 		dev_err(chip->parent,
1268 			"Failed to remove GPIO OpRegion handler\n");
1269 		return;
1270 	}
1271 
1272 	list_for_each_entry_safe_reverse(conn, tmp, &achip->conns, node) {
1273 		gpiochip_free_own_desc(conn->desc);
1274 		list_del(&conn->node);
1275 		kfree(conn);
1276 	}
1277 }
1278 
1279 static struct gpio_desc *
1280 acpi_gpiochip_parse_own_gpio(struct acpi_gpio_chip *achip,
1281 			     struct fwnode_handle *fwnode,
1282 			     const char **name,
1283 			     unsigned long *lflags,
1284 			     enum gpiod_flags *dflags)
1285 {
1286 	struct gpio_chip *chip = achip->chip;
1287 	struct gpio_desc *desc;
1288 	u32 gpios[2];
1289 	int ret;
1290 
1291 	*lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
1292 	*dflags = GPIOD_ASIS;
1293 	*name = NULL;
1294 
1295 	ret = fwnode_property_read_u32_array(fwnode, "gpios", gpios,
1296 					     ARRAY_SIZE(gpios));
1297 	if (ret < 0)
1298 		return ERR_PTR(ret);
1299 
1300 	desc = gpiochip_get_desc(chip, gpios[0]);
1301 	if (IS_ERR(desc))
1302 		return desc;
1303 
1304 	if (gpios[1])
1305 		*lflags |= GPIO_ACTIVE_LOW;
1306 
1307 	if (fwnode_property_present(fwnode, "input"))
1308 		*dflags |= GPIOD_IN;
1309 	else if (fwnode_property_present(fwnode, "output-low"))
1310 		*dflags |= GPIOD_OUT_LOW;
1311 	else if (fwnode_property_present(fwnode, "output-high"))
1312 		*dflags |= GPIOD_OUT_HIGH;
1313 	else
1314 		return ERR_PTR(-EINVAL);
1315 
1316 	fwnode_property_read_string(fwnode, "line-name", name);
1317 
1318 	return desc;
1319 }
1320 
1321 static void acpi_gpiochip_scan_gpios(struct acpi_gpio_chip *achip)
1322 {
1323 	struct gpio_chip *chip = achip->chip;
1324 	struct fwnode_handle *fwnode;
1325 
1326 	device_for_each_child_node(chip->parent, fwnode) {
1327 		unsigned long lflags;
1328 		enum gpiod_flags dflags;
1329 		struct gpio_desc *desc;
1330 		const char *name;
1331 		int ret;
1332 
1333 		if (!fwnode_property_present(fwnode, "gpio-hog"))
1334 			continue;
1335 
1336 		desc = acpi_gpiochip_parse_own_gpio(achip, fwnode, &name,
1337 						    &lflags, &dflags);
1338 		if (IS_ERR(desc))
1339 			continue;
1340 
1341 		ret = gpiod_hog(desc, name, lflags, dflags);
1342 		if (ret) {
1343 			dev_err(chip->parent, "Failed to hog GPIO\n");
1344 			fwnode_handle_put(fwnode);
1345 			return;
1346 		}
1347 	}
1348 }
1349 
1350 void acpi_gpiochip_add(struct gpio_chip *chip)
1351 {
1352 	struct acpi_gpio_chip *acpi_gpio;
1353 	struct acpi_device *adev;
1354 	acpi_status status;
1355 
1356 	if (!chip || !chip->parent)
1357 		return;
1358 
1359 	adev = ACPI_COMPANION(chip->parent);
1360 	if (!adev)
1361 		return;
1362 
1363 	acpi_gpio = kzalloc(sizeof(*acpi_gpio), GFP_KERNEL);
1364 	if (!acpi_gpio) {
1365 		dev_err(chip->parent,
1366 			"Failed to allocate memory for ACPI GPIO chip\n");
1367 		return;
1368 	}
1369 
1370 	acpi_gpio->chip = chip;
1371 	INIT_LIST_HEAD(&acpi_gpio->events);
1372 	INIT_LIST_HEAD(&acpi_gpio->deferred_req_irqs_list_entry);
1373 
1374 	status = acpi_attach_data(adev->handle, acpi_gpio_chip_dh, acpi_gpio);
1375 	if (ACPI_FAILURE(status)) {
1376 		dev_err(chip->parent, "Failed to attach ACPI GPIO chip\n");
1377 		kfree(acpi_gpio);
1378 		return;
1379 	}
1380 
1381 	acpi_gpiochip_request_regions(acpi_gpio);
1382 	acpi_gpiochip_scan_gpios(acpi_gpio);
1383 	acpi_dev_clear_dependencies(adev);
1384 }
1385 
1386 void acpi_gpiochip_remove(struct gpio_chip *chip)
1387 {
1388 	struct acpi_gpio_chip *acpi_gpio;
1389 	acpi_handle handle;
1390 	acpi_status status;
1391 
1392 	if (!chip || !chip->parent)
1393 		return;
1394 
1395 	handle = ACPI_HANDLE(chip->parent);
1396 	if (!handle)
1397 		return;
1398 
1399 	status = acpi_get_data(handle, acpi_gpio_chip_dh, (void **)&acpi_gpio);
1400 	if (ACPI_FAILURE(status)) {
1401 		dev_warn(chip->parent, "Failed to retrieve ACPI GPIO chip\n");
1402 		return;
1403 	}
1404 
1405 	acpi_gpiochip_free_regions(acpi_gpio);
1406 
1407 	acpi_detach_data(handle, acpi_gpio_chip_dh);
1408 	kfree(acpi_gpio);
1409 }
1410 
1411 static int acpi_gpio_package_count(const union acpi_object *obj)
1412 {
1413 	const union acpi_object *element = obj->package.elements;
1414 	const union acpi_object *end = element + obj->package.count;
1415 	unsigned int count = 0;
1416 
1417 	while (element < end) {
1418 		switch (element->type) {
1419 		case ACPI_TYPE_LOCAL_REFERENCE:
1420 			element += 3;
1421 			fallthrough;
1422 		case ACPI_TYPE_INTEGER:
1423 			element++;
1424 			count++;
1425 			break;
1426 
1427 		default:
1428 			return -EPROTO;
1429 		}
1430 	}
1431 
1432 	return count;
1433 }
1434 
1435 static int acpi_find_gpio_count(struct acpi_resource *ares, void *data)
1436 {
1437 	unsigned int *count = data;
1438 
1439 	if (ares->type == ACPI_RESOURCE_TYPE_GPIO)
1440 		*count += ares->data.gpio.pin_table_length;
1441 
1442 	return 1;
1443 }
1444 
1445 /**
1446  * acpi_gpio_count - count the GPIOs associated with a device / function
1447  * @dev:	GPIO consumer, can be %NULL for system-global GPIOs
1448  * @con_id:	function within the GPIO consumer
1449  *
1450  * Return:
1451  * The number of GPIOs associated with a device / function or %-ENOENT,
1452  * if no GPIO has been assigned to the requested function.
1453  */
1454 int acpi_gpio_count(struct device *dev, const char *con_id)
1455 {
1456 	struct acpi_device *adev = ACPI_COMPANION(dev);
1457 	const union acpi_object *obj;
1458 	const struct acpi_gpio_mapping *gm;
1459 	int count = -ENOENT;
1460 	int ret;
1461 	char propname[32];
1462 	unsigned int i;
1463 
1464 	/* Try first from _DSD */
1465 	for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
1466 		if (con_id)
1467 			snprintf(propname, sizeof(propname), "%s-%s",
1468 				 con_id, gpio_suffixes[i]);
1469 		else
1470 			snprintf(propname, sizeof(propname), "%s",
1471 				 gpio_suffixes[i]);
1472 
1473 		ret = acpi_dev_get_property(adev, propname, ACPI_TYPE_ANY,
1474 					    &obj);
1475 		if (ret == 0) {
1476 			if (obj->type == ACPI_TYPE_LOCAL_REFERENCE)
1477 				count = 1;
1478 			else if (obj->type == ACPI_TYPE_PACKAGE)
1479 				count = acpi_gpio_package_count(obj);
1480 		} else if (adev->driver_gpios) {
1481 			for (gm = adev->driver_gpios; gm->name; gm++)
1482 				if (strcmp(propname, gm->name) == 0) {
1483 					count = gm->size;
1484 					break;
1485 				}
1486 		}
1487 		if (count > 0)
1488 			break;
1489 	}
1490 
1491 	/* Then from plain _CRS GPIOs */
1492 	if (count < 0) {
1493 		struct list_head resource_list;
1494 		unsigned int crs_count = 0;
1495 
1496 		if (!acpi_can_fallback_to_crs(adev, con_id))
1497 			return count;
1498 
1499 		INIT_LIST_HEAD(&resource_list);
1500 		acpi_dev_get_resources(adev, &resource_list,
1501 				       acpi_find_gpio_count, &crs_count);
1502 		acpi_dev_free_resource_list(&resource_list);
1503 		if (crs_count > 0)
1504 			count = crs_count;
1505 	}
1506 	return count ? count : -ENOENT;
1507 }
1508 
1509 /* Run deferred acpi_gpiochip_request_irqs() */
1510 static int __init acpi_gpio_handle_deferred_request_irqs(void)
1511 {
1512 	struct acpi_gpio_chip *acpi_gpio, *tmp;
1513 
1514 	mutex_lock(&acpi_gpio_deferred_req_irqs_lock);
1515 	list_for_each_entry_safe(acpi_gpio, tmp,
1516 				 &acpi_gpio_deferred_req_irqs_list,
1517 				 deferred_req_irqs_list_entry)
1518 		acpi_gpiochip_request_irqs(acpi_gpio);
1519 
1520 	acpi_gpio_deferred_req_irqs_done = true;
1521 	mutex_unlock(&acpi_gpio_deferred_req_irqs_lock);
1522 
1523 	return 0;
1524 }
1525 /* We must use _sync so that this runs after the first deferred_probe run */
1526 late_initcall_sync(acpi_gpio_handle_deferred_request_irqs);
1527 
1528 static const struct dmi_system_id gpiolib_acpi_quirks[] __initconst = {
1529 	{
1530 		/*
1531 		 * The Minix Neo Z83-4 has a micro-USB-B id-pin handler for
1532 		 * a non existing micro-USB-B connector which puts the HDMI
1533 		 * DDC pins in GPIO mode, breaking HDMI support.
1534 		 */
1535 		.matches = {
1536 			DMI_MATCH(DMI_SYS_VENDOR, "MINIX"),
1537 			DMI_MATCH(DMI_PRODUCT_NAME, "Z83-4"),
1538 		},
1539 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1540 			.no_edge_events_on_boot = true,
1541 		},
1542 	},
1543 	{
1544 		/*
1545 		 * The Terra Pad 1061 has a micro-USB-B id-pin handler, which
1546 		 * instead of controlling the actual micro-USB-B turns the 5V
1547 		 * boost for its USB-A connector off. The actual micro-USB-B
1548 		 * connector is wired for charging only.
1549 		 */
1550 		.matches = {
1551 			DMI_MATCH(DMI_SYS_VENDOR, "Wortmann_AG"),
1552 			DMI_MATCH(DMI_PRODUCT_NAME, "TERRA_PAD_1061"),
1553 		},
1554 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1555 			.no_edge_events_on_boot = true,
1556 		},
1557 	},
1558 	{
1559 		/*
1560 		 * The Dell Venue 10 Pro 5055, with Bay Trail SoC + TI PMIC uses an
1561 		 * external embedded-controller connected via I2C + an ACPI GPIO
1562 		 * event handler on INT33FFC:02 pin 12, causing spurious wakeups.
1563 		 */
1564 		.matches = {
1565 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1566 			DMI_MATCH(DMI_PRODUCT_NAME, "Venue 10 Pro 5055"),
1567 		},
1568 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1569 			.ignore_wake = "INT33FC:02@12",
1570 		},
1571 	},
1572 	{
1573 		/*
1574 		 * HP X2 10 models with Cherry Trail SoC + TI PMIC use an
1575 		 * external embedded-controller connected via I2C + an ACPI GPIO
1576 		 * event handler on INT33FF:01 pin 0, causing spurious wakeups.
1577 		 * When suspending by closing the LID, the power to the USB
1578 		 * keyboard is turned off, causing INT0002 ACPI events to
1579 		 * trigger once the XHCI controller notices the keyboard is
1580 		 * gone. So INT0002 events cause spurious wakeups too. Ignoring
1581 		 * EC wakes breaks wakeup when opening the lid, the user needs
1582 		 * to press the power-button to wakeup the system. The
1583 		 * alternative is suspend simply not working, which is worse.
1584 		 */
1585 		.matches = {
1586 			DMI_MATCH(DMI_SYS_VENDOR, "HP"),
1587 			DMI_MATCH(DMI_PRODUCT_NAME, "HP x2 Detachable 10-p0XX"),
1588 		},
1589 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1590 			.ignore_wake = "INT33FF:01@0,INT0002:00@2",
1591 		},
1592 	},
1593 	{
1594 		/*
1595 		 * HP X2 10 models with Bay Trail SoC + AXP288 PMIC use an
1596 		 * external embedded-controller connected via I2C + an ACPI GPIO
1597 		 * event handler on INT33FC:02 pin 28, causing spurious wakeups.
1598 		 */
1599 		.matches = {
1600 			DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
1601 			DMI_MATCH(DMI_PRODUCT_NAME, "HP Pavilion x2 Detachable"),
1602 			DMI_MATCH(DMI_BOARD_NAME, "815D"),
1603 		},
1604 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1605 			.ignore_wake = "INT33FC:02@28",
1606 		},
1607 	},
1608 	{
1609 		/*
1610 		 * HP X2 10 models with Cherry Trail SoC + AXP288 PMIC use an
1611 		 * external embedded-controller connected via I2C + an ACPI GPIO
1612 		 * event handler on INT33FF:01 pin 0, causing spurious wakeups.
1613 		 */
1614 		.matches = {
1615 			DMI_MATCH(DMI_SYS_VENDOR, "HP"),
1616 			DMI_MATCH(DMI_PRODUCT_NAME, "HP Pavilion x2 Detachable"),
1617 			DMI_MATCH(DMI_BOARD_NAME, "813E"),
1618 		},
1619 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1620 			.ignore_wake = "INT33FF:01@0",
1621 		},
1622 	},
1623 	{
1624 		/*
1625 		 * Interrupt storm caused from edge triggered floating pin
1626 		 * Found in BIOS UX325UAZ.300
1627 		 * https://bugzilla.kernel.org/show_bug.cgi?id=216208
1628 		 */
1629 		.matches = {
1630 			DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK COMPUTER INC."),
1631 			DMI_MATCH(DMI_PRODUCT_NAME, "ZenBook UX325UAZ_UM325UAZ"),
1632 		},
1633 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1634 			.ignore_interrupt = "AMDI0030:00@18",
1635 		},
1636 	},
1637 	{
1638 		/*
1639 		 * Spurious wakeups from TP_ATTN# pin
1640 		 * Found in BIOS 1.7.8
1641 		 * https://gitlab.freedesktop.org/drm/amd/-/issues/1722#note_1720627
1642 		 */
1643 		.matches = {
1644 			DMI_MATCH(DMI_BOARD_NAME, "NL5xNU"),
1645 		},
1646 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1647 			.ignore_wake = "ELAN0415:00@9",
1648 		},
1649 	},
1650 	{
1651 		/*
1652 		 * Spurious wakeups from TP_ATTN# pin
1653 		 * Found in BIOS 1.7.8
1654 		 * https://gitlab.freedesktop.org/drm/amd/-/issues/1722#note_1720627
1655 		 */
1656 		.matches = {
1657 			DMI_MATCH(DMI_BOARD_NAME, "NL5xRU"),
1658 		},
1659 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1660 			.ignore_wake = "ELAN0415:00@9",
1661 		},
1662 	},
1663 	{
1664 		/*
1665 		 * Spurious wakeups from TP_ATTN# pin
1666 		 * Found in BIOS 1.7.7
1667 		 */
1668 		.matches = {
1669 			DMI_MATCH(DMI_BOARD_NAME, "NH5xAx"),
1670 		},
1671 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1672 			.ignore_wake = "SYNA1202:00@16",
1673 		},
1674 	},
1675 	{
1676 		/*
1677 		 * On the Peaq C1010 2-in-1 INT33FC:00 pin 3 is connected to
1678 		 * a "dolby" button. At the ACPI level an _AEI event-handler
1679 		 * is connected which sets an ACPI variable to 1 on both
1680 		 * edges. This variable can be polled + cleared to 0 using
1681 		 * WMI. But since the variable is set on both edges the WMI
1682 		 * interface is pretty useless even when polling.
1683 		 * So instead the x86-android-tablets code instantiates
1684 		 * a gpio-keys platform device for it.
1685 		 * Ignore the _AEI handler for the pin, so that it is not busy.
1686 		 */
1687 		.matches = {
1688 			DMI_MATCH(DMI_SYS_VENDOR, "PEAQ"),
1689 			DMI_MATCH(DMI_PRODUCT_NAME, "PEAQ PMM C1010 MD99187"),
1690 		},
1691 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1692 			.ignore_interrupt = "INT33FC:00@3",
1693 		},
1694 	},
1695 	{
1696 		/*
1697 		 * Spurious wakeups from TP_ATTN# pin
1698 		 * Found in BIOS 0.35
1699 		 * https://gitlab.freedesktop.org/drm/amd/-/issues/3073
1700 		 */
1701 		.matches = {
1702 			DMI_MATCH(DMI_SYS_VENDOR, "GPD"),
1703 			DMI_MATCH(DMI_PRODUCT_NAME, "G1619-04"),
1704 		},
1705 		.driver_data = &(struct acpi_gpiolib_dmi_quirk) {
1706 			.ignore_wake = "PNP0C50:00@8",
1707 		},
1708 	},
1709 	{} /* Terminating entry */
1710 };
1711 
1712 static int __init acpi_gpio_setup_params(void)
1713 {
1714 	const struct acpi_gpiolib_dmi_quirk *quirk = NULL;
1715 	const struct dmi_system_id *id;
1716 
1717 	id = dmi_first_match(gpiolib_acpi_quirks);
1718 	if (id)
1719 		quirk = id->driver_data;
1720 
1721 	if (run_edge_events_on_boot < 0) {
1722 		if (quirk && quirk->no_edge_events_on_boot)
1723 			run_edge_events_on_boot = 0;
1724 		else
1725 			run_edge_events_on_boot = 1;
1726 	}
1727 
1728 	if (ignore_wake == NULL && quirk && quirk->ignore_wake)
1729 		ignore_wake = quirk->ignore_wake;
1730 
1731 	if (ignore_interrupt == NULL && quirk && quirk->ignore_interrupt)
1732 		ignore_interrupt = quirk->ignore_interrupt;
1733 
1734 	return 0;
1735 }
1736 
1737 /* Directly after dmi_setup() which runs as core_initcall() */
1738 postcore_initcall(acpi_gpio_setup_params);
1739