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