xref: /linux/drivers/gpio/gpiolib-acpi-core.c (revision 07fdad3a93756b872da7b53647715c48d0f4a2d0)
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 /**
27  * struct acpi_gpio_event - ACPI GPIO event handler data
28  *
29  * @node:	  list-entry of the events list of the struct acpi_gpio_chip
30  * @handle:	  handle of ACPI method to execute when the IRQ triggers
31  * @handler:	  handler function to pass to request_irq() when requesting the IRQ
32  * @pin:	  GPIO pin number on the struct gpio_chip
33  * @irq:	  Linux IRQ number for the event, for request_irq() / free_irq()
34  * @irqflags:	  flags to pass to request_irq() when requesting the IRQ
35  * @irq_is_wake:  If the ACPI flags indicate the IRQ is a wakeup source
36  * @irq_requested:True if request_irq() has been done
37  * @desc:	  struct gpio_desc for the GPIO pin for this event
38  */
39 struct acpi_gpio_event {
40 	struct list_head node;
41 	acpi_handle handle;
42 	irq_handler_t handler;
43 	unsigned int pin;
44 	unsigned int irq;
45 	unsigned long irqflags;
46 	bool irq_is_wake;
47 	bool irq_requested;
48 	struct gpio_desc *desc;
49 };
50 
51 struct acpi_gpio_connection {
52 	struct list_head node;
53 	unsigned int pin;
54 	struct gpio_desc *desc;
55 };
56 
57 struct acpi_gpio_chip {
58 	/*
59 	 * ACPICA requires that the first field of the context parameter
60 	 * passed to acpi_install_address_space_handler() is large enough
61 	 * to hold struct acpi_connection_info.
62 	 */
63 	struct acpi_connection_info conn_info;
64 	struct list_head conns;
65 	struct mutex conn_lock;
66 	struct gpio_chip *chip;
67 	struct list_head events;
68 	struct list_head deferred_req_irqs_list_entry;
69 };
70 
71 /**
72  * struct acpi_gpio_info - ACPI GPIO specific information
73  * @adev: reference to ACPI device which consumes GPIO resource
74  * @flags: GPIO initialization flags
75  * @gpioint: if %true this GPIO is of type GpioInt otherwise type is GpioIo
76  * @wake_capable: wake capability as provided by ACPI
77  * @pin_config: pin bias as provided by ACPI
78  * @polarity: interrupt polarity as provided by ACPI
79  * @triggering: triggering type as provided by ACPI
80  * @debounce: debounce timeout as provided by ACPI
81  * @quirks: Linux specific quirks as provided by struct acpi_gpio_mapping
82  */
83 struct acpi_gpio_info {
84 	struct acpi_device *adev;
85 	enum gpiod_flags flags;
86 	bool gpioint;
87 	bool wake_capable;
88 	int pin_config;
89 	int polarity;
90 	int triggering;
91 	unsigned int debounce;
92 	unsigned int quirks;
93 };
94 
95 static int acpi_gpiochip_find(struct gpio_chip *gc, const void *data)
96 {
97 	/* First check the actual GPIO device */
98 	if (device_match_acpi_handle(&gc->gpiodev->dev, data))
99 		return true;
100 
101 	/*
102 	 * When the ACPI device is artificially split to the banks of GPIOs,
103 	 * where each of them is represented by a separate GPIO device,
104 	 * the firmware node of the physical device may not be shared among
105 	 * the banks as they may require different values for the same property,
106 	 * e.g., number of GPIOs in a certain bank. In such case the ACPI handle
107 	 * of a GPIO device is NULL and can not be used. Hence we have to check
108 	 * the parent device to be sure that there is no match before bailing
109 	 * out.
110 	 */
111 	if (gc->parent)
112 		return device_match_acpi_handle(gc->parent, data);
113 
114 	return false;
115 }
116 
117 /**
118  * acpi_get_gpiod() - Translate ACPI GPIO pin to GPIO descriptor usable with GPIO API
119  * @path:	ACPI GPIO controller full path name, (e.g. "\\_SB.GPO1")
120  * @pin:	ACPI GPIO pin number (0-based, controller-relative)
121  *
122  * Returns:
123  * GPIO descriptor to use with Linux generic GPIO API.
124  * If the GPIO cannot be translated or there is an error an ERR_PTR is
125  * returned.
126  *
127  * Specifically returns %-EPROBE_DEFER if the referenced GPIO
128  * controller does not have GPIO chip registered at the moment. This is to
129  * support probe deferral.
130  */
131 static struct gpio_desc *acpi_get_gpiod(char *path, unsigned int pin)
132 {
133 	acpi_handle handle;
134 	acpi_status status;
135 
136 	status = acpi_get_handle(NULL, path, &handle);
137 	if (ACPI_FAILURE(status))
138 		return ERR_PTR(-ENODEV);
139 
140 	struct gpio_device *gdev __free(gpio_device_put) =
141 				gpio_device_find(handle, acpi_gpiochip_find);
142 	if (!gdev)
143 		return ERR_PTR(-EPROBE_DEFER);
144 
145 	/*
146 	 * FIXME: keep track of the reference to the GPIO device somehow
147 	 * instead of putting it here.
148 	 */
149 	return gpio_device_get_desc(gdev, pin);
150 }
151 
152 static irqreturn_t acpi_gpio_irq_handler(int irq, void *data)
153 {
154 	struct acpi_gpio_event *event = data;
155 
156 	acpi_evaluate_object(event->handle, NULL, NULL, NULL);
157 
158 	return IRQ_HANDLED;
159 }
160 
161 static irqreturn_t acpi_gpio_irq_handler_evt(int irq, void *data)
162 {
163 	struct acpi_gpio_event *event = data;
164 
165 	acpi_execute_simple_method(event->handle, NULL, event->pin);
166 
167 	return IRQ_HANDLED;
168 }
169 
170 static void acpi_gpio_chip_dh(acpi_handle handle, void *data)
171 {
172 	/* The address of this function is used as a key. */
173 }
174 
175 bool acpi_gpio_get_irq_resource(struct acpi_resource *ares,
176 				struct acpi_resource_gpio **agpio)
177 {
178 	struct acpi_resource_gpio *gpio;
179 
180 	if (ares->type != ACPI_RESOURCE_TYPE_GPIO)
181 		return false;
182 
183 	gpio = &ares->data.gpio;
184 	if (gpio->connection_type != ACPI_RESOURCE_GPIO_TYPE_INT)
185 		return false;
186 
187 	*agpio = gpio;
188 	return true;
189 }
190 EXPORT_SYMBOL_GPL(acpi_gpio_get_irq_resource);
191 
192 /**
193  * acpi_gpio_get_io_resource - Fetch details of an ACPI resource if it is a GPIO
194  *			       I/O resource or return False if not.
195  * @ares:	Pointer to the ACPI resource to fetch
196  * @agpio:	Pointer to a &struct acpi_resource_gpio to store the output pointer
197  *
198  * Returns:
199  * %true if GpioIo resource is found, %false otherwise.
200  */
201 bool acpi_gpio_get_io_resource(struct acpi_resource *ares,
202 			       struct acpi_resource_gpio **agpio)
203 {
204 	struct acpi_resource_gpio *gpio;
205 
206 	if (ares->type != ACPI_RESOURCE_TYPE_GPIO)
207 		return false;
208 
209 	gpio = &ares->data.gpio;
210 	if (gpio->connection_type != ACPI_RESOURCE_GPIO_TYPE_IO)
211 		return false;
212 
213 	*agpio = gpio;
214 	return true;
215 }
216 EXPORT_SYMBOL_GPL(acpi_gpio_get_io_resource);
217 
218 static void acpi_gpiochip_request_irq(struct acpi_gpio_chip *acpi_gpio,
219 				      struct acpi_gpio_event *event)
220 {
221 	struct device *parent = acpi_gpio->chip->parent;
222 	int ret, value;
223 
224 	ret = request_threaded_irq(event->irq, NULL, event->handler,
225 				   event->irqflags | IRQF_ONESHOT, "ACPI:Event", event);
226 	if (ret) {
227 		dev_err(parent, "Failed to setup interrupt handler for %d\n", event->irq);
228 		return;
229 	}
230 
231 	if (event->irq_is_wake)
232 		enable_irq_wake(event->irq);
233 
234 	event->irq_requested = true;
235 
236 	/* Make sure we trigger the initial state of edge-triggered IRQs */
237 	if (acpi_gpio_need_run_edge_events_on_boot() &&
238 	    (event->irqflags & (IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING))) {
239 		value = gpiod_get_raw_value_cansleep(event->desc);
240 		if (((event->irqflags & IRQF_TRIGGER_RISING) && value == 1) ||
241 		    ((event->irqflags & IRQF_TRIGGER_FALLING) && value == 0))
242 			event->handler(event->irq, event);
243 	}
244 }
245 
246 static void acpi_gpiochip_request_irqs(struct acpi_gpio_chip *acpi_gpio)
247 {
248 	struct acpi_gpio_event *event;
249 
250 	list_for_each_entry(event, &acpi_gpio->events, node)
251 		acpi_gpiochip_request_irq(acpi_gpio, event);
252 }
253 
254 static enum gpiod_flags
255 acpi_gpio_to_gpiod_flags(const struct acpi_resource_gpio *agpio, int polarity)
256 {
257 	/* GpioInt() implies input configuration */
258 	if (agpio->connection_type == ACPI_RESOURCE_GPIO_TYPE_INT)
259 		return GPIOD_IN;
260 
261 	switch (agpio->io_restriction) {
262 	case ACPI_IO_RESTRICT_INPUT:
263 		return GPIOD_IN;
264 	case ACPI_IO_RESTRICT_OUTPUT:
265 		/*
266 		 * ACPI GPIO resources don't contain an initial value for the
267 		 * GPIO. Therefore we deduce that value from the pull field
268 		 * and the polarity instead. If the pin is pulled up we assume
269 		 * default to be high, if it is pulled down we assume default
270 		 * to be low, otherwise we leave pin untouched. For active low
271 		 * polarity values will be switched. See also
272 		 * Documentation/firmware-guide/acpi/gpio-properties.rst.
273 		 */
274 		switch (agpio->pin_config) {
275 		case ACPI_PIN_CONFIG_PULLUP:
276 			return polarity == GPIO_ACTIVE_LOW ? GPIOD_OUT_LOW : GPIOD_OUT_HIGH;
277 		case ACPI_PIN_CONFIG_PULLDOWN:
278 			return polarity == GPIO_ACTIVE_LOW ? GPIOD_OUT_HIGH : GPIOD_OUT_LOW;
279 		default:
280 			break;
281 		}
282 		break;
283 	default:
284 		break;
285 	}
286 
287 	/*
288 	 * Assume that the BIOS has configured the direction and pull
289 	 * accordingly.
290 	 */
291 	return GPIOD_ASIS;
292 }
293 
294 static struct gpio_desc *acpi_request_own_gpiod(struct gpio_chip *chip,
295 						struct acpi_resource_gpio *agpio,
296 						unsigned int index,
297 						const char *label)
298 {
299 	int polarity = GPIO_ACTIVE_HIGH;
300 	enum gpiod_flags flags = acpi_gpio_to_gpiod_flags(agpio, polarity);
301 	unsigned int pin = agpio->pin_table[index];
302 	struct gpio_desc *desc;
303 	int ret;
304 
305 	desc = gpiochip_request_own_desc(chip, pin, label, polarity, flags);
306 	if (IS_ERR(desc))
307 		return desc;
308 
309 	/* ACPI uses hundredths of milliseconds units */
310 	ret = gpio_set_debounce_timeout(desc, agpio->debounce_timeout * 10);
311 	if (ret)
312 		dev_warn(chip->parent,
313 			 "Failed to set debounce-timeout for pin 0x%04X, err %d\n",
314 			 pin, ret);
315 
316 	return desc;
317 }
318 
319 static bool acpi_gpio_irq_is_wake(struct device *parent,
320 				  const struct acpi_resource_gpio *agpio)
321 {
322 	unsigned int pin = agpio->pin_table[0];
323 
324 	if (agpio->wake_capable != ACPI_WAKE_CAPABLE)
325 		return false;
326 
327 	if (acpi_gpio_in_ignore_list(ACPI_GPIO_IGNORE_WAKE, dev_name(parent), pin)) {
328 		dev_info(parent, "Ignoring wakeup on pin %u\n", pin);
329 		return false;
330 	}
331 
332 	return true;
333 }
334 
335 /* Always returns AE_OK so that we keep looping over the resources */
336 static acpi_status acpi_gpiochip_alloc_event(struct acpi_resource *ares,
337 					     void *context)
338 {
339 	struct acpi_gpio_chip *acpi_gpio = context;
340 	struct gpio_chip *chip = acpi_gpio->chip;
341 	struct acpi_resource_gpio *agpio;
342 	acpi_handle handle, evt_handle;
343 	struct acpi_gpio_event *event;
344 	irq_handler_t handler = NULL;
345 	struct gpio_desc *desc;
346 	unsigned int pin;
347 	int ret, irq;
348 
349 	if (!acpi_gpio_get_irq_resource(ares, &agpio))
350 		return AE_OK;
351 
352 	handle = ACPI_HANDLE(chip->parent);
353 	pin = agpio->pin_table[0];
354 
355 	if (pin <= 255) {
356 		char ev_name[8];
357 		sprintf(ev_name, "_%c%02X",
358 			agpio->triggering == ACPI_EDGE_SENSITIVE ? 'E' : 'L',
359 			pin);
360 		if (ACPI_SUCCESS(acpi_get_handle(handle, ev_name, &evt_handle)))
361 			handler = acpi_gpio_irq_handler;
362 	}
363 	if (!handler) {
364 		if (ACPI_SUCCESS(acpi_get_handle(handle, "_EVT", &evt_handle)))
365 			handler = acpi_gpio_irq_handler_evt;
366 	}
367 	if (!handler)
368 		return AE_OK;
369 
370 	if (acpi_gpio_in_ignore_list(ACPI_GPIO_IGNORE_INTERRUPT, dev_name(chip->parent), pin)) {
371 		dev_info(chip->parent, "Ignoring interrupt on pin %u\n", pin);
372 		return AE_OK;
373 	}
374 
375 	desc = acpi_request_own_gpiod(chip, agpio, 0, "ACPI:Event");
376 	if (IS_ERR(desc)) {
377 		dev_err(chip->parent,
378 			"Failed to request GPIO for pin 0x%04X, err %ld\n",
379 			pin, PTR_ERR(desc));
380 		return AE_OK;
381 	}
382 
383 	ret = gpiochip_lock_as_irq(chip, pin);
384 	if (ret) {
385 		dev_err(chip->parent,
386 			"Failed to lock GPIO pin 0x%04X as interrupt, err %d\n",
387 			pin, ret);
388 		goto fail_free_desc;
389 	}
390 
391 	irq = gpiod_to_irq(desc);
392 	if (irq < 0) {
393 		dev_err(chip->parent,
394 			"Failed to translate GPIO pin 0x%04X to IRQ, err %d\n",
395 			pin, irq);
396 		goto fail_unlock_irq;
397 	}
398 
399 	event = kzalloc(sizeof(*event), GFP_KERNEL);
400 	if (!event)
401 		goto fail_unlock_irq;
402 
403 	event->irqflags = IRQF_ONESHOT;
404 	if (agpio->triggering == ACPI_LEVEL_SENSITIVE) {
405 		if (agpio->polarity == ACPI_ACTIVE_HIGH)
406 			event->irqflags |= IRQF_TRIGGER_HIGH;
407 		else
408 			event->irqflags |= IRQF_TRIGGER_LOW;
409 	} else {
410 		switch (agpio->polarity) {
411 		case ACPI_ACTIVE_HIGH:
412 			event->irqflags |= IRQF_TRIGGER_RISING;
413 			break;
414 		case ACPI_ACTIVE_LOW:
415 			event->irqflags |= IRQF_TRIGGER_FALLING;
416 			break;
417 		default:
418 			event->irqflags |= IRQF_TRIGGER_RISING |
419 					   IRQF_TRIGGER_FALLING;
420 			break;
421 		}
422 	}
423 
424 	event->handle = evt_handle;
425 	event->handler = handler;
426 	event->irq = irq;
427 	event->irq_is_wake = acpi_gpio_irq_is_wake(chip->parent, agpio);
428 	event->pin = pin;
429 	event->desc = desc;
430 
431 	list_add_tail(&event->node, &acpi_gpio->events);
432 
433 	return AE_OK;
434 
435 fail_unlock_irq:
436 	gpiochip_unlock_as_irq(chip, pin);
437 fail_free_desc:
438 	gpiochip_free_own_desc(desc);
439 
440 	return AE_OK;
441 }
442 
443 /**
444  * acpi_gpiochip_request_interrupts() - Register isr for gpio chip ACPI events
445  * @chip:      GPIO chip
446  *
447  * ACPI5 platforms can use GPIO signaled ACPI events. These GPIO interrupts are
448  * handled by ACPI event methods which need to be called from the GPIO
449  * chip's interrupt handler. acpi_gpiochip_request_interrupts() finds out which
450  * GPIO pins have ACPI event methods and assigns interrupt handlers that calls
451  * the ACPI event methods for those pins.
452  */
453 void acpi_gpiochip_request_interrupts(struct gpio_chip *chip)
454 {
455 	struct acpi_gpio_chip *acpi_gpio;
456 	acpi_handle handle;
457 	acpi_status status;
458 
459 	if (!chip->parent || !chip->to_irq)
460 		return;
461 
462 	handle = ACPI_HANDLE(chip->parent);
463 	if (!handle)
464 		return;
465 
466 	status = acpi_get_data(handle, acpi_gpio_chip_dh, (void **)&acpi_gpio);
467 	if (ACPI_FAILURE(status))
468 		return;
469 
470 	if (acpi_quirk_skip_gpio_event_handlers())
471 		return;
472 
473 	acpi_walk_resources(handle, METHOD_NAME__AEI,
474 			    acpi_gpiochip_alloc_event, acpi_gpio);
475 
476 	if (acpi_gpio_add_to_deferred_list(&acpi_gpio->deferred_req_irqs_list_entry))
477 		return;
478 
479 	acpi_gpiochip_request_irqs(acpi_gpio);
480 }
481 EXPORT_SYMBOL_GPL(acpi_gpiochip_request_interrupts);
482 
483 /**
484  * acpi_gpiochip_free_interrupts() - Free GPIO ACPI event interrupts.
485  * @chip:      GPIO chip
486  *
487  * Free interrupts associated with GPIO ACPI event method for the given
488  * GPIO chip.
489  */
490 void acpi_gpiochip_free_interrupts(struct gpio_chip *chip)
491 {
492 	struct acpi_gpio_chip *acpi_gpio;
493 	struct acpi_gpio_event *event, *ep;
494 	acpi_handle handle;
495 	acpi_status status;
496 
497 	if (!chip->parent || !chip->to_irq)
498 		return;
499 
500 	handle = ACPI_HANDLE(chip->parent);
501 	if (!handle)
502 		return;
503 
504 	status = acpi_get_data(handle, acpi_gpio_chip_dh, (void **)&acpi_gpio);
505 	if (ACPI_FAILURE(status))
506 		return;
507 
508 	acpi_gpio_remove_from_deferred_list(&acpi_gpio->deferred_req_irqs_list_entry);
509 
510 	list_for_each_entry_safe_reverse(event, ep, &acpi_gpio->events, node) {
511 		if (event->irq_requested) {
512 			if (event->irq_is_wake)
513 				disable_irq_wake(event->irq);
514 
515 			free_irq(event->irq, event);
516 		}
517 
518 		gpiochip_unlock_as_irq(chip, event->pin);
519 		gpiochip_free_own_desc(event->desc);
520 		list_del(&event->node);
521 		kfree(event);
522 	}
523 }
524 EXPORT_SYMBOL_GPL(acpi_gpiochip_free_interrupts);
525 
526 void __init acpi_gpio_process_deferred_list(struct list_head *list)
527 {
528 	struct acpi_gpio_chip *acpi_gpio, *tmp;
529 
530 	list_for_each_entry_safe(acpi_gpio, tmp, list, deferred_req_irqs_list_entry)
531 		acpi_gpiochip_request_irqs(acpi_gpio);
532 }
533 
534 int acpi_dev_add_driver_gpios(struct acpi_device *adev,
535 			      const struct acpi_gpio_mapping *gpios)
536 {
537 	if (adev && gpios) {
538 		adev->driver_gpios = gpios;
539 		return 0;
540 	}
541 	return -EINVAL;
542 }
543 EXPORT_SYMBOL_GPL(acpi_dev_add_driver_gpios);
544 
545 void acpi_dev_remove_driver_gpios(struct acpi_device *adev)
546 {
547 	if (adev)
548 		adev->driver_gpios = NULL;
549 }
550 EXPORT_SYMBOL_GPL(acpi_dev_remove_driver_gpios);
551 
552 static void acpi_dev_release_driver_gpios(void *adev)
553 {
554 	acpi_dev_remove_driver_gpios(adev);
555 }
556 
557 int devm_acpi_dev_add_driver_gpios(struct device *dev,
558 				   const struct acpi_gpio_mapping *gpios)
559 {
560 	struct acpi_device *adev = ACPI_COMPANION(dev);
561 	int ret;
562 
563 	ret = acpi_dev_add_driver_gpios(adev, gpios);
564 	if (ret)
565 		return ret;
566 
567 	return devm_add_action_or_reset(dev, acpi_dev_release_driver_gpios, adev);
568 }
569 EXPORT_SYMBOL_GPL(devm_acpi_dev_add_driver_gpios);
570 
571 static bool acpi_get_driver_gpio_data(struct acpi_device *adev,
572 				      const char *name, int index,
573 				      struct fwnode_reference_args *args,
574 				      unsigned int *quirks)
575 {
576 	const struct acpi_gpio_mapping *gm;
577 
578 	if (!adev || !adev->driver_gpios)
579 		return false;
580 
581 	for (gm = adev->driver_gpios; gm->name; gm++)
582 		if (!strcmp(name, gm->name) && gm->data && index < gm->size) {
583 			const struct acpi_gpio_params *params = gm->data + index;
584 
585 			args->fwnode = acpi_fwnode_handle(adev);
586 			args->args[0] = params->crs_entry_index;
587 			args->args[1] = params->line_index;
588 			args->args[2] = params->active_low;
589 			args->nargs = 3;
590 
591 			*quirks = gm->quirks;
592 			return true;
593 		}
594 
595 	return false;
596 }
597 
598 static int
599 __acpi_gpio_update_gpiod_flags(enum gpiod_flags *flags, enum gpiod_flags update)
600 {
601 	const enum gpiod_flags mask =
602 		GPIOD_FLAGS_BIT_DIR_SET | GPIOD_FLAGS_BIT_DIR_OUT |
603 		GPIOD_FLAGS_BIT_DIR_VAL;
604 	int ret = 0;
605 
606 	/*
607 	 * Check if the BIOS has IoRestriction with explicitly set direction
608 	 * and update @flags accordingly. Otherwise use whatever caller asked
609 	 * for.
610 	 */
611 	if (update & GPIOD_FLAGS_BIT_DIR_SET) {
612 		enum gpiod_flags diff = *flags ^ update;
613 
614 		/*
615 		 * Check if caller supplied incompatible GPIO initialization
616 		 * flags.
617 		 *
618 		 * Return %-EINVAL to notify that firmware has different
619 		 * settings and we are going to use them.
620 		 */
621 		if (((*flags & GPIOD_FLAGS_BIT_DIR_SET) && (diff & GPIOD_FLAGS_BIT_DIR_OUT)) ||
622 		    ((*flags & GPIOD_FLAGS_BIT_DIR_OUT) && (diff & GPIOD_FLAGS_BIT_DIR_VAL)))
623 			ret = -EINVAL;
624 		*flags = (*flags & ~mask) | (update & mask);
625 	}
626 	return ret;
627 }
628 
629 static int acpi_gpio_update_gpiod_flags(enum gpiod_flags *flags,
630 				        struct acpi_gpio_info *info)
631 {
632 	struct device *dev = &info->adev->dev;
633 	enum gpiod_flags old = *flags;
634 	int ret;
635 
636 	ret = __acpi_gpio_update_gpiod_flags(&old, info->flags);
637 	if (info->quirks & ACPI_GPIO_QUIRK_NO_IO_RESTRICTION) {
638 		if (ret)
639 			dev_warn(dev, FW_BUG "GPIO not in correct mode, fixing\n");
640 	} else {
641 		if (ret)
642 			dev_dbg(dev, "Override GPIO initialization flags\n");
643 		*flags = old;
644 	}
645 
646 	return ret;
647 }
648 
649 static int acpi_gpio_update_gpiod_lookup_flags(unsigned long *lookupflags,
650 					       struct acpi_gpio_info *info)
651 {
652 	switch (info->pin_config) {
653 	case ACPI_PIN_CONFIG_PULLUP:
654 		*lookupflags |= GPIO_PULL_UP;
655 		break;
656 	case ACPI_PIN_CONFIG_PULLDOWN:
657 		*lookupflags |= GPIO_PULL_DOWN;
658 		break;
659 	case ACPI_PIN_CONFIG_NOPULL:
660 		*lookupflags |= GPIO_PULL_DISABLE;
661 		break;
662 	default:
663 		break;
664 	}
665 
666 	if (info->polarity == GPIO_ACTIVE_LOW)
667 		*lookupflags |= GPIO_ACTIVE_LOW;
668 
669 	return 0;
670 }
671 
672 struct acpi_gpio_lookup {
673 	struct acpi_gpio_params params;
674 	struct acpi_gpio_info *info;
675 	struct gpio_desc *desc;
676 	int n;
677 };
678 
679 static int acpi_populate_gpio_lookup(struct acpi_resource *ares, void *data)
680 {
681 	struct acpi_gpio_lookup *lookup = data;
682 	struct acpi_gpio_params *params = &lookup->params;
683 	struct acpi_gpio_info *info = lookup->info;
684 
685 	if (ares->type != ACPI_RESOURCE_TYPE_GPIO)
686 		return 1;
687 
688 	if (!lookup->desc) {
689 		const struct acpi_resource_gpio *agpio = &ares->data.gpio;
690 		bool gpioint = agpio->connection_type == ACPI_RESOURCE_GPIO_TYPE_INT;
691 		struct gpio_desc *desc;
692 		u16 pin_index;
693 
694 		if (info->quirks & ACPI_GPIO_QUIRK_ONLY_GPIOIO && gpioint)
695 			params->crs_entry_index++;
696 
697 		if (lookup->n++ != params->crs_entry_index)
698 			return 1;
699 
700 		pin_index = params->line_index;
701 		if (pin_index >= agpio->pin_table_length)
702 			return 1;
703 
704 		if (info->quirks & ACPI_GPIO_QUIRK_ABSOLUTE_NUMBER)
705 			desc = gpio_to_desc(agpio->pin_table[pin_index]);
706 		else
707 			desc = acpi_get_gpiod(agpio->resource_source.string_ptr,
708 					      agpio->pin_table[pin_index]);
709 		lookup->desc = desc;
710 		info->pin_config = agpio->pin_config;
711 		info->debounce = agpio->debounce_timeout;
712 		info->gpioint = gpioint;
713 		info->wake_capable = acpi_gpio_irq_is_wake(&info->adev->dev, agpio);
714 
715 		/*
716 		 * Polarity and triggering are only specified for GpioInt
717 		 * resource.
718 		 * Note: we expect here:
719 		 * - ACPI_ACTIVE_LOW == GPIO_ACTIVE_LOW
720 		 * - ACPI_ACTIVE_HIGH == GPIO_ACTIVE_HIGH
721 		 */
722 		if (info->gpioint) {
723 			info->polarity = agpio->polarity;
724 			info->triggering = agpio->triggering;
725 		} else {
726 			info->polarity = params->active_low;
727 		}
728 
729 		info->flags = acpi_gpio_to_gpiod_flags(agpio, info->polarity);
730 	}
731 
732 	return 1;
733 }
734 
735 static int acpi_gpio_resource_lookup(struct acpi_gpio_lookup *lookup)
736 {
737 	struct acpi_gpio_info *info = lookup->info;
738 	struct acpi_device *adev = info->adev;
739 	struct list_head res_list;
740 	int ret;
741 
742 	INIT_LIST_HEAD(&res_list);
743 
744 	ret = acpi_dev_get_resources(adev, &res_list,
745 				     acpi_populate_gpio_lookup,
746 				     lookup);
747 	if (ret < 0)
748 		return ret;
749 
750 	acpi_dev_free_resource_list(&res_list);
751 
752 	if (!lookup->desc)
753 		return -ENOENT;
754 
755 	return 0;
756 }
757 
758 static int acpi_gpio_property_lookup(struct fwnode_handle *fwnode, const char *propname,
759 				     struct acpi_gpio_lookup *lookup)
760 {
761 	struct fwnode_reference_args args;
762 	struct acpi_gpio_params *params = &lookup->params;
763 	struct acpi_gpio_info *info = lookup->info;
764 	unsigned int index = params->crs_entry_index;
765 	unsigned int quirks = 0;
766 	int ret;
767 
768 	memset(&args, 0, sizeof(args));
769 
770 	ret = __acpi_node_get_property_reference(fwnode, propname, index, 3, &args);
771 	if (ret) {
772 		struct acpi_device *adev;
773 
774 		adev = to_acpi_device_node(fwnode);
775 		if (!acpi_get_driver_gpio_data(adev, propname, index, &args, &quirks))
776 			return ret;
777 	}
778 	/*
779 	 * The property was found and resolved, so need to lookup the GPIO based
780 	 * on returned args.
781 	 */
782 	if (!to_acpi_device_node(args.fwnode))
783 		return -EINVAL;
784 	if (args.nargs != 3)
785 		return -EPROTO;
786 
787 	params->crs_entry_index = args.args[0];
788 	params->line_index = args.args[1];
789 	params->active_low = !!args.args[2];
790 
791 	info->adev = to_acpi_device_node(args.fwnode);
792 	info->quirks = quirks;
793 
794 	return 0;
795 }
796 
797 /**
798  * acpi_get_gpiod_by_index() - get a GPIO descriptor from device resources
799  * @adev: pointer to a ACPI device to get GPIO from
800  * @propname: Property name of the GPIO (optional)
801  * @lookup: pointer to struct acpi_gpio_lookup to fill in
802  *
803  * Function goes through ACPI resources for @adev and based on @lookup.index looks
804  * up a GpioIo/GpioInt resource, translates it to the Linux GPIO descriptor,
805  * and returns it. @lookup.index matches GpioIo/GpioInt resources only so if there
806  * are total 3 GPIO resources, the index goes from 0 to 2.
807  *
808  * If @propname is specified the GPIO is looked using device property. In
809  * that case @index is used to select the GPIO entry in the property value
810  * (in case of multiple).
811  *
812  * Returns:
813  * 0 on success, negative errno on failure.
814  *
815  * The @lookup is filled with GPIO descriptor to use with Linux generic GPIO API.
816  * If the GPIO cannot be translated an error will be returned.
817  *
818  * Note: if the GPIO resource has multiple entries in the pin list, this
819  * function only returns the first.
820  */
821 static int acpi_get_gpiod_by_index(struct acpi_device *adev, const char *propname,
822 				   struct acpi_gpio_lookup *lookup)
823 {
824 	struct acpi_gpio_params *params = &lookup->params;
825 	struct acpi_gpio_info *info = lookup->info;
826 	int ret;
827 
828 	if (propname) {
829 		dev_dbg(&adev->dev, "GPIO: looking up %s\n", propname);
830 
831 		ret = acpi_gpio_property_lookup(acpi_fwnode_handle(adev), propname, lookup);
832 		if (ret)
833 			return ret;
834 
835 		dev_dbg(&adev->dev, "GPIO: _DSD returned %s %u %u %u\n",
836 			dev_name(&info->adev->dev),
837 			params->crs_entry_index, params->line_index, params->active_low);
838 	} else {
839 		dev_dbg(&adev->dev, "GPIO: looking up %u in _CRS\n", params->crs_entry_index);
840 		info->adev = adev;
841 	}
842 
843 	return acpi_gpio_resource_lookup(lookup);
844 }
845 
846 /**
847  * acpi_get_gpiod_from_data() - get a GPIO descriptor from ACPI data node
848  * @fwnode: pointer to an ACPI firmware node to get the GPIO information from
849  * @propname: Property name of the GPIO
850  * @lookup: pointer to struct acpi_gpio_lookup to fill in
851  *
852  * This function uses the property-based GPIO lookup to get to the GPIO
853  * resource with the relevant information from a data-only ACPI firmware node
854  * and uses that to obtain the GPIO descriptor to return.
855  *
856  * Returns:
857  * 0 on success, negative errno on failure.
858  *
859  * The @lookup is filled with GPIO descriptor to use with Linux generic GPIO API.
860  * If the GPIO cannot be translated an error will be returned.
861  */
862 static int acpi_get_gpiod_from_data(struct fwnode_handle *fwnode, const char *propname,
863 				    struct acpi_gpio_lookup *lookup)
864 {
865 	int ret;
866 
867 	if (!is_acpi_data_node(fwnode))
868 		return -ENODEV;
869 
870 	if (!propname)
871 		return -EINVAL;
872 
873 	ret = acpi_gpio_property_lookup(fwnode, propname, lookup);
874 	if (ret)
875 		return ret;
876 
877 	return acpi_gpio_resource_lookup(lookup);
878 }
879 
880 static bool acpi_can_fallback_to_crs(struct acpi_device *adev,
881 				     const char *con_id)
882 {
883 	/* If there is no ACPI device, there is no _CRS to fall back to */
884 	if (!adev)
885 		return false;
886 
887 	/* Never allow fallback if the device has properties */
888 	if (acpi_dev_has_props(adev) || adev->driver_gpios)
889 		return false;
890 
891 	return con_id == NULL;
892 }
893 
894 static struct gpio_desc *
895 __acpi_find_gpio(struct fwnode_handle *fwnode, const char *con_id, unsigned int idx,
896 		 bool can_fallback, struct acpi_gpio_info *info)
897 {
898 	struct acpi_device *adev = to_acpi_device_node(fwnode);
899 	struct acpi_gpio_lookup lookup;
900 	struct gpio_desc *desc;
901 	char propname[32];
902 	int ret;
903 
904 	memset(&lookup, 0, sizeof(lookup));
905 	lookup.params.crs_entry_index = idx;
906 	lookup.info = info;
907 
908 	/* Try first from _DSD */
909 	for_each_gpio_property_name(propname, con_id) {
910 		if (adev)
911 			ret = acpi_get_gpiod_by_index(adev, propname, &lookup);
912 		else
913 			ret = acpi_get_gpiod_from_data(fwnode, propname, &lookup);
914 		if (ret)
915 			continue;
916 
917 		desc = lookup.desc;
918 		if (PTR_ERR(desc) == -EPROBE_DEFER)
919 			return desc;
920 
921 		if (!IS_ERR(desc))
922 			return desc;
923 	}
924 
925 	/* Then from plain _CRS GPIOs */
926 	if (can_fallback) {
927 		ret = acpi_get_gpiod_by_index(adev, NULL, &lookup);
928 		if (ret)
929 			return ERR_PTR(ret);
930 
931 		return lookup.desc;
932 	}
933 
934 	return ERR_PTR(-ENOENT);
935 }
936 
937 struct gpio_desc *acpi_find_gpio(struct fwnode_handle *fwnode,
938 				 const char *con_id,
939 				 unsigned int idx,
940 				 enum gpiod_flags *dflags,
941 				 unsigned long *lookupflags)
942 {
943 	struct acpi_device *adev = to_acpi_device_node(fwnode);
944 	bool can_fallback = acpi_can_fallback_to_crs(adev, con_id);
945 	struct acpi_gpio_info info = {};
946 	struct gpio_desc *desc;
947 	int ret;
948 
949 	desc = __acpi_find_gpio(fwnode, con_id, idx, can_fallback, &info);
950 	if (IS_ERR(desc))
951 		return desc;
952 
953 	if (info.gpioint &&
954 	    (*dflags == GPIOD_OUT_LOW || *dflags == GPIOD_OUT_HIGH)) {
955 		dev_dbg(&adev->dev, "refusing GpioInt() entry when doing GPIOD_OUT_* lookup\n");
956 		return ERR_PTR(-ENOENT);
957 	}
958 
959 	acpi_gpio_update_gpiod_flags(dflags, &info);
960 	acpi_gpio_update_gpiod_lookup_flags(lookupflags, &info);
961 
962 	/* ACPI uses hundredths of milliseconds units */
963 	ret = gpio_set_debounce_timeout(desc, info.debounce * 10);
964 	if (ret)
965 		return ERR_PTR(ret);
966 
967 	return desc;
968 }
969 
970 /**
971  * acpi_dev_gpio_irq_wake_get_by() - Find GpioInt and translate it to Linux IRQ number
972  * @adev: pointer to a ACPI device to get IRQ from
973  * @con_id: optional name of GpioInt resource
974  * @index: index of GpioInt resource (starting from %0)
975  * @wake_capable: Set to true if the IRQ is wake capable
976  *
977  * If the device has one or more GpioInt resources, this function can be
978  * used to translate from the GPIO offset in the resource to the Linux IRQ
979  * number.
980  *
981  * The function is idempotent, though each time it runs it will configure GPIO
982  * pin direction according to the flags in GpioInt resource.
983  *
984  * The function takes optional @con_id parameter. If the resource has
985  * a @con_id in a property, then only those will be taken into account.
986  *
987  * The GPIO is considered wake capable if the GpioInt resource specifies
988  * SharedAndWake or ExclusiveAndWake.
989  *
990  * Returns:
991  * Linux IRQ number (> 0) on success, negative errno on failure.
992  */
993 int acpi_dev_gpio_irq_wake_get_by(struct acpi_device *adev, const char *con_id, int index,
994 				  bool *wake_capable)
995 {
996 	struct fwnode_handle *fwnode = acpi_fwnode_handle(adev);
997 	int idx, i;
998 	unsigned int irq_flags;
999 	int ret;
1000 
1001 	for (i = 0, idx = 0; idx <= index; i++) {
1002 		struct acpi_gpio_info info = {};
1003 		struct gpio_desc *desc;
1004 
1005 		/* Ignore -EPROBE_DEFER, it only matters if idx matches */
1006 		desc = __acpi_find_gpio(fwnode, con_id, i, true, &info);
1007 		if (IS_ERR(desc) && PTR_ERR(desc) != -EPROBE_DEFER)
1008 			return PTR_ERR(desc);
1009 
1010 		if (info.gpioint && idx++ == index) {
1011 			unsigned long lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
1012 			enum gpiod_flags dflags = GPIOD_ASIS;
1013 			char label[32];
1014 			int irq;
1015 
1016 			if (IS_ERR(desc))
1017 				return PTR_ERR(desc);
1018 
1019 			irq = gpiod_to_irq(desc);
1020 			if (irq < 0)
1021 				return irq;
1022 
1023 			acpi_gpio_update_gpiod_flags(&dflags, &info);
1024 			acpi_gpio_update_gpiod_lookup_flags(&lflags, &info);
1025 
1026 			snprintf(label, sizeof(label), "%pfwP GpioInt(%d)", fwnode, index);
1027 			ret = gpiod_set_consumer_name(desc, con_id ?: label);
1028 			if (ret)
1029 				return ret;
1030 
1031 			ret = gpiod_configure_flags(desc, label, lflags, dflags);
1032 			if (ret < 0)
1033 				return ret;
1034 
1035 			/* ACPI uses hundredths of milliseconds units */
1036 			ret = gpio_set_debounce_timeout(desc, info.debounce * 10);
1037 			if (ret)
1038 				return ret;
1039 
1040 			irq_flags = acpi_dev_get_irq_type(info.triggering,
1041 							  info.polarity);
1042 
1043 			/*
1044 			 * If the IRQ is not already in use then set type
1045 			 * if specified and different than the current one.
1046 			 */
1047 			if (can_request_irq(irq, irq_flags)) {
1048 				if (irq_flags != IRQ_TYPE_NONE &&
1049 				    irq_flags != irq_get_trigger_type(irq))
1050 					irq_set_irq_type(irq, irq_flags);
1051 			} else {
1052 				dev_dbg(&adev->dev, "IRQ %d already in use\n", irq);
1053 			}
1054 
1055 			/* avoid suspend issues with GPIOs when systems are using S3 */
1056 			if (wake_capable && acpi_gbl_FADT.flags & ACPI_FADT_LOW_POWER_S0)
1057 				*wake_capable = info.wake_capable;
1058 
1059 			return irq;
1060 		}
1061 
1062 	}
1063 	return -ENOENT;
1064 }
1065 EXPORT_SYMBOL_GPL(acpi_dev_gpio_irq_wake_get_by);
1066 
1067 static acpi_status
1068 acpi_gpio_adr_space_handler(u32 function, acpi_physical_address address,
1069 			    u32 bits, u64 *value, void *handler_context,
1070 			    void *region_context)
1071 {
1072 	struct acpi_gpio_chip *achip = region_context;
1073 	struct gpio_chip *chip = achip->chip;
1074 	struct acpi_resource_gpio *agpio;
1075 	struct acpi_resource *ares;
1076 	u16 pin_index = address;
1077 	acpi_status status;
1078 	int length;
1079 	int i;
1080 
1081 	status = acpi_buffer_to_resource(achip->conn_info.connection,
1082 					 achip->conn_info.length, &ares);
1083 	if (ACPI_FAILURE(status))
1084 		return status;
1085 
1086 	if (WARN_ON(ares->type != ACPI_RESOURCE_TYPE_GPIO)) {
1087 		ACPI_FREE(ares);
1088 		return AE_BAD_PARAMETER;
1089 	}
1090 
1091 	agpio = &ares->data.gpio;
1092 
1093 	if (WARN_ON(agpio->io_restriction == ACPI_IO_RESTRICT_INPUT &&
1094 	    function == ACPI_WRITE)) {
1095 		ACPI_FREE(ares);
1096 		return AE_BAD_PARAMETER;
1097 	}
1098 
1099 	length = min_t(u16, agpio->pin_table_length, pin_index + bits);
1100 	for (i = pin_index; i < length; ++i) {
1101 		unsigned int pin = agpio->pin_table[i];
1102 		struct acpi_gpio_connection *conn;
1103 		struct gpio_desc *desc;
1104 		bool found;
1105 
1106 		mutex_lock(&achip->conn_lock);
1107 
1108 		found = false;
1109 		list_for_each_entry(conn, &achip->conns, node) {
1110 			if (conn->pin == pin) {
1111 				found = true;
1112 				desc = conn->desc;
1113 				break;
1114 			}
1115 		}
1116 
1117 		/*
1118 		 * The same GPIO can be shared between operation region and
1119 		 * event but only if the access here is ACPI_READ. In that
1120 		 * case we "borrow" the event GPIO instead.
1121 		 */
1122 		if (!found && agpio->shareable == ACPI_SHARED &&
1123 		     function == ACPI_READ) {
1124 			struct acpi_gpio_event *event;
1125 
1126 			list_for_each_entry(event, &achip->events, node) {
1127 				if (event->pin == pin) {
1128 					desc = event->desc;
1129 					found = true;
1130 					break;
1131 				}
1132 			}
1133 		}
1134 
1135 		if (!found) {
1136 			desc = acpi_request_own_gpiod(chip, agpio, i, "ACPI:OpRegion");
1137 			if (IS_ERR(desc)) {
1138 				mutex_unlock(&achip->conn_lock);
1139 				status = AE_ERROR;
1140 				goto out;
1141 			}
1142 
1143 			conn = kzalloc(sizeof(*conn), GFP_KERNEL);
1144 			if (!conn) {
1145 				gpiochip_free_own_desc(desc);
1146 				mutex_unlock(&achip->conn_lock);
1147 				status = AE_NO_MEMORY;
1148 				goto out;
1149 			}
1150 
1151 			conn->pin = pin;
1152 			conn->desc = desc;
1153 			list_add_tail(&conn->node, &achip->conns);
1154 		}
1155 
1156 		mutex_unlock(&achip->conn_lock);
1157 
1158 		if (function == ACPI_WRITE)
1159 			gpiod_set_raw_value_cansleep(desc, !!(*value & BIT(i)));
1160 		else
1161 			*value |= (u64)gpiod_get_raw_value_cansleep(desc) << i;
1162 	}
1163 
1164 out:
1165 	ACPI_FREE(ares);
1166 	return status;
1167 }
1168 
1169 static void acpi_gpiochip_request_regions(struct acpi_gpio_chip *achip)
1170 {
1171 	struct gpio_chip *chip = achip->chip;
1172 	acpi_handle handle = ACPI_HANDLE(chip->parent);
1173 	acpi_status status;
1174 
1175 	INIT_LIST_HEAD(&achip->conns);
1176 	mutex_init(&achip->conn_lock);
1177 	status = acpi_install_address_space_handler(handle, ACPI_ADR_SPACE_GPIO,
1178 						    acpi_gpio_adr_space_handler,
1179 						    NULL, achip);
1180 	if (ACPI_FAILURE(status))
1181 		dev_err(chip->parent,
1182 		        "Failed to install GPIO OpRegion handler\n");
1183 }
1184 
1185 static void acpi_gpiochip_free_regions(struct acpi_gpio_chip *achip)
1186 {
1187 	struct gpio_chip *chip = achip->chip;
1188 	acpi_handle handle = ACPI_HANDLE(chip->parent);
1189 	struct acpi_gpio_connection *conn, *tmp;
1190 	acpi_status status;
1191 
1192 	status = acpi_remove_address_space_handler(handle, ACPI_ADR_SPACE_GPIO,
1193 						   acpi_gpio_adr_space_handler);
1194 	if (ACPI_FAILURE(status)) {
1195 		dev_err(chip->parent,
1196 			"Failed to remove GPIO OpRegion handler\n");
1197 		return;
1198 	}
1199 
1200 	list_for_each_entry_safe_reverse(conn, tmp, &achip->conns, node) {
1201 		gpiochip_free_own_desc(conn->desc);
1202 		list_del(&conn->node);
1203 		kfree(conn);
1204 	}
1205 }
1206 
1207 static struct gpio_desc *
1208 acpi_gpiochip_parse_own_gpio(struct acpi_gpio_chip *achip,
1209 			     struct fwnode_handle *fwnode,
1210 			     const char **name,
1211 			     unsigned long *lflags,
1212 			     enum gpiod_flags *dflags)
1213 {
1214 	struct gpio_chip *chip = achip->chip;
1215 	struct gpio_desc *desc;
1216 	u32 gpios[2];
1217 	int ret;
1218 
1219 	*lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
1220 	*dflags = GPIOD_ASIS;
1221 	*name = NULL;
1222 
1223 	ret = fwnode_property_read_u32_array(fwnode, "gpios", gpios,
1224 					     ARRAY_SIZE(gpios));
1225 	if (ret < 0)
1226 		return ERR_PTR(ret);
1227 
1228 	desc = gpiochip_get_desc(chip, gpios[0]);
1229 	if (IS_ERR(desc))
1230 		return desc;
1231 
1232 	if (gpios[1])
1233 		*lflags |= GPIO_ACTIVE_LOW;
1234 
1235 	if (fwnode_property_present(fwnode, "input"))
1236 		*dflags |= GPIOD_IN;
1237 	else if (fwnode_property_present(fwnode, "output-low"))
1238 		*dflags |= GPIOD_OUT_LOW;
1239 	else if (fwnode_property_present(fwnode, "output-high"))
1240 		*dflags |= GPIOD_OUT_HIGH;
1241 	else
1242 		return ERR_PTR(-EINVAL);
1243 
1244 	fwnode_property_read_string(fwnode, "line-name", name);
1245 
1246 	return desc;
1247 }
1248 
1249 static void acpi_gpiochip_scan_gpios(struct acpi_gpio_chip *achip)
1250 {
1251 	struct gpio_chip *chip = achip->chip;
1252 
1253 	device_for_each_child_node_scoped(chip->parent, fwnode) {
1254 		unsigned long lflags;
1255 		enum gpiod_flags dflags;
1256 		struct gpio_desc *desc;
1257 		const char *name;
1258 		int ret;
1259 
1260 		if (!fwnode_property_present(fwnode, "gpio-hog"))
1261 			continue;
1262 
1263 		desc = acpi_gpiochip_parse_own_gpio(achip, fwnode, &name,
1264 						    &lflags, &dflags);
1265 		if (IS_ERR(desc))
1266 			continue;
1267 
1268 		ret = gpiod_hog(desc, name, lflags, dflags);
1269 		if (ret) {
1270 			dev_err(chip->parent, "Failed to hog GPIO\n");
1271 			return;
1272 		}
1273 	}
1274 }
1275 
1276 void acpi_gpiochip_add(struct gpio_chip *chip)
1277 {
1278 	struct acpi_gpio_chip *acpi_gpio;
1279 	struct acpi_device *adev;
1280 	acpi_status status;
1281 
1282 	if (!chip || !chip->parent)
1283 		return;
1284 
1285 	adev = ACPI_COMPANION(chip->parent);
1286 	if (!adev)
1287 		return;
1288 
1289 	acpi_gpio = kzalloc(sizeof(*acpi_gpio), GFP_KERNEL);
1290 	if (!acpi_gpio) {
1291 		dev_err(chip->parent,
1292 			"Failed to allocate memory for ACPI GPIO chip\n");
1293 		return;
1294 	}
1295 
1296 	acpi_gpio->chip = chip;
1297 	INIT_LIST_HEAD(&acpi_gpio->events);
1298 	INIT_LIST_HEAD(&acpi_gpio->deferred_req_irqs_list_entry);
1299 
1300 	status = acpi_attach_data(adev->handle, acpi_gpio_chip_dh, acpi_gpio);
1301 	if (ACPI_FAILURE(status)) {
1302 		dev_err(chip->parent, "Failed to attach ACPI GPIO chip\n");
1303 		kfree(acpi_gpio);
1304 		return;
1305 	}
1306 
1307 	acpi_gpiochip_request_regions(acpi_gpio);
1308 	acpi_gpiochip_scan_gpios(acpi_gpio);
1309 	acpi_dev_clear_dependencies(adev);
1310 }
1311 
1312 void acpi_gpiochip_remove(struct gpio_chip *chip)
1313 {
1314 	struct acpi_gpio_chip *acpi_gpio;
1315 	acpi_handle handle;
1316 	acpi_status status;
1317 
1318 	if (!chip || !chip->parent)
1319 		return;
1320 
1321 	handle = ACPI_HANDLE(chip->parent);
1322 	if (!handle)
1323 		return;
1324 
1325 	status = acpi_get_data(handle, acpi_gpio_chip_dh, (void **)&acpi_gpio);
1326 	if (ACPI_FAILURE(status)) {
1327 		dev_warn(chip->parent, "Failed to retrieve ACPI GPIO chip\n");
1328 		return;
1329 	}
1330 
1331 	acpi_gpiochip_free_regions(acpi_gpio);
1332 
1333 	acpi_detach_data(handle, acpi_gpio_chip_dh);
1334 	kfree(acpi_gpio);
1335 }
1336 
1337 static int acpi_gpio_package_count(const union acpi_object *obj)
1338 {
1339 	const union acpi_object *element = obj->package.elements;
1340 	const union acpi_object *end = element + obj->package.count;
1341 	unsigned int count = 0;
1342 
1343 	while (element < end) {
1344 		switch (element->type) {
1345 		case ACPI_TYPE_LOCAL_REFERENCE:
1346 			element += 3;
1347 			fallthrough;
1348 		case ACPI_TYPE_INTEGER:
1349 			element++;
1350 			count++;
1351 			break;
1352 
1353 		default:
1354 			return -EPROTO;
1355 		}
1356 	}
1357 
1358 	return count;
1359 }
1360 
1361 static int acpi_find_gpio_count(struct acpi_resource *ares, void *data)
1362 {
1363 	unsigned int *count = data;
1364 
1365 	if (ares->type == ACPI_RESOURCE_TYPE_GPIO)
1366 		*count += ares->data.gpio.pin_table_length;
1367 
1368 	return 1;
1369 }
1370 
1371 /**
1372  * acpi_gpio_count - count the GPIOs associated with a firmware node / function
1373  * @fwnode:	firmware node of the GPIO consumer
1374  * @con_id:	function within the GPIO consumer
1375  *
1376  * Returns:
1377  * The number of GPIOs associated with a firmware node / function or %-ENOENT,
1378  * if no GPIO has been assigned to the requested function.
1379  */
1380 int acpi_gpio_count(const struct fwnode_handle *fwnode, const char *con_id)
1381 {
1382 	struct acpi_device *adev = to_acpi_device_node(fwnode);
1383 	const union acpi_object *obj;
1384 	const struct acpi_gpio_mapping *gm;
1385 	int count = -ENOENT;
1386 	int ret;
1387 	char propname[32];
1388 
1389 	/* Try first from _DSD */
1390 	for_each_gpio_property_name(propname, con_id) {
1391 		ret = acpi_dev_get_property(adev, propname, ACPI_TYPE_ANY, &obj);
1392 		if (ret == 0) {
1393 			if (obj->type == ACPI_TYPE_LOCAL_REFERENCE)
1394 				count = 1;
1395 			else if (obj->type == ACPI_TYPE_PACKAGE)
1396 				count = acpi_gpio_package_count(obj);
1397 		} else if (adev->driver_gpios) {
1398 			for (gm = adev->driver_gpios; gm->name; gm++)
1399 				if (strcmp(propname, gm->name) == 0) {
1400 					count = gm->size;
1401 					break;
1402 				}
1403 		}
1404 		if (count > 0)
1405 			break;
1406 	}
1407 
1408 	/* Then from plain _CRS GPIOs */
1409 	if (count < 0) {
1410 		struct list_head resource_list;
1411 		unsigned int crs_count = 0;
1412 
1413 		if (!acpi_can_fallback_to_crs(adev, con_id))
1414 			return count;
1415 
1416 		INIT_LIST_HEAD(&resource_list);
1417 		acpi_dev_get_resources(adev, &resource_list,
1418 				       acpi_find_gpio_count, &crs_count);
1419 		acpi_dev_free_resource_list(&resource_list);
1420 		if (crs_count > 0)
1421 			count = crs_count;
1422 	}
1423 	return count ? count : -ENOENT;
1424 }
1425