xref: /openbmc/linux/drivers/gpio/gpiolib-acpi.c (revision 83268fa6)
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/errno.h>
11 #include <linux/gpio/consumer.h>
12 #include <linux/gpio/driver.h>
13 #include <linux/gpio/machine.h>
14 #include <linux/export.h>
15 #include <linux/acpi.h>
16 #include <linux/interrupt.h>
17 #include <linux/mutex.h>
18 #include <linux/pinctrl/pinctrl.h>
19 
20 #include "gpiolib.h"
21 
22 struct acpi_gpio_event {
23 	struct list_head node;
24 	acpi_handle handle;
25 	unsigned int pin;
26 	unsigned int irq;
27 	struct gpio_desc *desc;
28 };
29 
30 struct acpi_gpio_connection {
31 	struct list_head node;
32 	unsigned int pin;
33 	struct gpio_desc *desc;
34 };
35 
36 struct acpi_gpio_chip {
37 	/*
38 	 * ACPICA requires that the first field of the context parameter
39 	 * passed to acpi_install_address_space_handler() is large enough
40 	 * to hold struct acpi_connection_info.
41 	 */
42 	struct acpi_connection_info conn_info;
43 	struct list_head conns;
44 	struct mutex conn_lock;
45 	struct gpio_chip *chip;
46 	struct list_head events;
47 	struct list_head deferred_req_irqs_list_entry;
48 };
49 
50 /*
51  * For gpiochips which call acpi_gpiochip_request_interrupts() before late_init
52  * (so builtin drivers) we register the ACPI GpioInt event handlers from a
53  * late_initcall_sync handler, so that other builtin drivers can register their
54  * OpRegions before the event handlers can run.  This list contains gpiochips
55  * for which the acpi_gpiochip_request_interrupts() has been deferred.
56  */
57 static DEFINE_MUTEX(acpi_gpio_deferred_req_irqs_lock);
58 static LIST_HEAD(acpi_gpio_deferred_req_irqs_list);
59 static bool acpi_gpio_deferred_req_irqs_done;
60 
61 static int acpi_gpiochip_find(struct gpio_chip *gc, void *data)
62 {
63 	if (!gc->parent)
64 		return false;
65 
66 	return ACPI_HANDLE(gc->parent) == data;
67 }
68 
69 /**
70  * acpi_get_gpiod() - Translate ACPI GPIO pin to GPIO descriptor usable with GPIO API
71  * @path:	ACPI GPIO controller full path name, (e.g. "\\_SB.GPO1")
72  * @pin:	ACPI GPIO pin number (0-based, controller-relative)
73  *
74  * Return: GPIO descriptor to use with Linux generic GPIO API, or ERR_PTR
75  * error value. Specifically returns %-EPROBE_DEFER if the referenced GPIO
76  * controller does not have gpiochip registered at the moment. This is to
77  * support probe deferral.
78  */
79 static struct gpio_desc *acpi_get_gpiod(char *path, int pin)
80 {
81 	struct gpio_chip *chip;
82 	acpi_handle handle;
83 	acpi_status status;
84 
85 	status = acpi_get_handle(NULL, path, &handle);
86 	if (ACPI_FAILURE(status))
87 		return ERR_PTR(-ENODEV);
88 
89 	chip = gpiochip_find(handle, acpi_gpiochip_find);
90 	if (!chip)
91 		return ERR_PTR(-EPROBE_DEFER);
92 
93 	return gpiochip_get_desc(chip, pin);
94 }
95 
96 static irqreturn_t acpi_gpio_irq_handler(int irq, void *data)
97 {
98 	struct acpi_gpio_event *event = data;
99 
100 	acpi_evaluate_object(event->handle, NULL, NULL, NULL);
101 
102 	return IRQ_HANDLED;
103 }
104 
105 static irqreturn_t acpi_gpio_irq_handler_evt(int irq, void *data)
106 {
107 	struct acpi_gpio_event *event = data;
108 
109 	acpi_execute_simple_method(event->handle, NULL, event->pin);
110 
111 	return IRQ_HANDLED;
112 }
113 
114 static void acpi_gpio_chip_dh(acpi_handle handle, void *data)
115 {
116 	/* The address of this function is used as a key. */
117 }
118 
119 bool acpi_gpio_get_irq_resource(struct acpi_resource *ares,
120 				struct acpi_resource_gpio **agpio)
121 {
122 	struct acpi_resource_gpio *gpio;
123 
124 	if (ares->type != ACPI_RESOURCE_TYPE_GPIO)
125 		return false;
126 
127 	gpio = &ares->data.gpio;
128 	if (gpio->connection_type != ACPI_RESOURCE_GPIO_TYPE_INT)
129 		return false;
130 
131 	*agpio = gpio;
132 	return true;
133 }
134 EXPORT_SYMBOL_GPL(acpi_gpio_get_irq_resource);
135 
136 static acpi_status acpi_gpiochip_request_interrupt(struct acpi_resource *ares,
137 						   void *context)
138 {
139 	struct acpi_gpio_chip *acpi_gpio = context;
140 	struct gpio_chip *chip = acpi_gpio->chip;
141 	struct acpi_resource_gpio *agpio;
142 	acpi_handle handle, evt_handle;
143 	struct acpi_gpio_event *event;
144 	irq_handler_t handler = NULL;
145 	struct gpio_desc *desc;
146 	unsigned long irqflags;
147 	int ret, pin, irq, value;
148 
149 	if (!acpi_gpio_get_irq_resource(ares, &agpio))
150 		return AE_OK;
151 
152 	handle = ACPI_HANDLE(chip->parent);
153 	pin = agpio->pin_table[0];
154 
155 	if (pin <= 255) {
156 		char ev_name[5];
157 		sprintf(ev_name, "_%c%02hhX",
158 			agpio->triggering == ACPI_EDGE_SENSITIVE ? 'E' : 'L',
159 			pin);
160 		if (ACPI_SUCCESS(acpi_get_handle(handle, ev_name, &evt_handle)))
161 			handler = acpi_gpio_irq_handler;
162 	}
163 	if (!handler) {
164 		if (ACPI_SUCCESS(acpi_get_handle(handle, "_EVT", &evt_handle)))
165 			handler = acpi_gpio_irq_handler_evt;
166 	}
167 	if (!handler)
168 		return AE_OK;
169 
170 	desc = gpiochip_request_own_desc(chip, pin, "ACPI:Event");
171 	if (IS_ERR(desc)) {
172 		dev_err(chip->parent, "Failed to request GPIO\n");
173 		return AE_ERROR;
174 	}
175 
176 	gpiod_direction_input(desc);
177 
178 	value = gpiod_get_value_cansleep(desc);
179 
180 	ret = gpiochip_lock_as_irq(chip, pin);
181 	if (ret) {
182 		dev_err(chip->parent, "Failed to lock GPIO as interrupt\n");
183 		goto fail_free_desc;
184 	}
185 
186 	irq = gpiod_to_irq(desc);
187 	if (irq < 0) {
188 		dev_err(chip->parent, "Failed to translate GPIO to IRQ\n");
189 		goto fail_unlock_irq;
190 	}
191 
192 	irqflags = IRQF_ONESHOT;
193 	if (agpio->triggering == ACPI_LEVEL_SENSITIVE) {
194 		if (agpio->polarity == ACPI_ACTIVE_HIGH)
195 			irqflags |= IRQF_TRIGGER_HIGH;
196 		else
197 			irqflags |= IRQF_TRIGGER_LOW;
198 	} else {
199 		switch (agpio->polarity) {
200 		case ACPI_ACTIVE_HIGH:
201 			irqflags |= IRQF_TRIGGER_RISING;
202 			break;
203 		case ACPI_ACTIVE_LOW:
204 			irqflags |= IRQF_TRIGGER_FALLING;
205 			break;
206 		default:
207 			irqflags |= IRQF_TRIGGER_RISING |
208 				    IRQF_TRIGGER_FALLING;
209 			break;
210 		}
211 	}
212 
213 	event = kzalloc(sizeof(*event), GFP_KERNEL);
214 	if (!event)
215 		goto fail_unlock_irq;
216 
217 	event->handle = evt_handle;
218 	event->irq = irq;
219 	event->pin = pin;
220 	event->desc = desc;
221 
222 	ret = request_threaded_irq(event->irq, NULL, handler, irqflags,
223 				   "ACPI:Event", event);
224 	if (ret) {
225 		dev_err(chip->parent,
226 			"Failed to setup interrupt handler for %d\n",
227 			event->irq);
228 		goto fail_free_event;
229 	}
230 
231 	if (agpio->wake_capable == ACPI_WAKE_CAPABLE)
232 		enable_irq_wake(irq);
233 
234 	list_add_tail(&event->node, &acpi_gpio->events);
235 
236 	/*
237 	 * Make sure we trigger the initial state of the IRQ when using RISING
238 	 * or FALLING.  Note we run the handlers on late_init, the AML code
239 	 * may refer to OperationRegions from other (builtin) drivers which
240 	 * may be probed after us.
241 	 */
242 	if (((irqflags & IRQF_TRIGGER_RISING) && value == 1) ||
243 	    ((irqflags & IRQF_TRIGGER_FALLING) && value == 0))
244 		handler(event->irq, event);
245 
246 	return AE_OK;
247 
248 fail_free_event:
249 	kfree(event);
250 fail_unlock_irq:
251 	gpiochip_unlock_as_irq(chip, pin);
252 fail_free_desc:
253 	gpiochip_free_own_desc(desc);
254 
255 	return AE_ERROR;
256 }
257 
258 /**
259  * acpi_gpiochip_request_interrupts() - Register isr for gpio chip ACPI events
260  * @chip:      GPIO chip
261  *
262  * ACPI5 platforms can use GPIO signaled ACPI events. These GPIO interrupts are
263  * handled by ACPI event methods which need to be called from the GPIO
264  * chip's interrupt handler. acpi_gpiochip_request_interrupts finds out which
265  * gpio pins have acpi event methods and assigns interrupt handlers that calls
266  * the acpi event methods for those pins.
267  */
268 void acpi_gpiochip_request_interrupts(struct gpio_chip *chip)
269 {
270 	struct acpi_gpio_chip *acpi_gpio;
271 	acpi_handle handle;
272 	acpi_status status;
273 	bool defer;
274 
275 	if (!chip->parent || !chip->to_irq)
276 		return;
277 
278 	handle = ACPI_HANDLE(chip->parent);
279 	if (!handle)
280 		return;
281 
282 	status = acpi_get_data(handle, acpi_gpio_chip_dh, (void **)&acpi_gpio);
283 	if (ACPI_FAILURE(status))
284 		return;
285 
286 	mutex_lock(&acpi_gpio_deferred_req_irqs_lock);
287 	defer = !acpi_gpio_deferred_req_irqs_done;
288 	if (defer)
289 		list_add(&acpi_gpio->deferred_req_irqs_list_entry,
290 			 &acpi_gpio_deferred_req_irqs_list);
291 	mutex_unlock(&acpi_gpio_deferred_req_irqs_lock);
292 
293 	if (defer)
294 		return;
295 
296 	acpi_walk_resources(handle, "_AEI",
297 			    acpi_gpiochip_request_interrupt, acpi_gpio);
298 }
299 EXPORT_SYMBOL_GPL(acpi_gpiochip_request_interrupts);
300 
301 /**
302  * acpi_gpiochip_free_interrupts() - Free GPIO ACPI event interrupts.
303  * @chip:      GPIO chip
304  *
305  * Free interrupts associated with GPIO ACPI event method for the given
306  * GPIO chip.
307  */
308 void acpi_gpiochip_free_interrupts(struct gpio_chip *chip)
309 {
310 	struct acpi_gpio_chip *acpi_gpio;
311 	struct acpi_gpio_event *event, *ep;
312 	acpi_handle handle;
313 	acpi_status status;
314 
315 	if (!chip->parent || !chip->to_irq)
316 		return;
317 
318 	handle = ACPI_HANDLE(chip->parent);
319 	if (!handle)
320 		return;
321 
322 	status = acpi_get_data(handle, acpi_gpio_chip_dh, (void **)&acpi_gpio);
323 	if (ACPI_FAILURE(status))
324 		return;
325 
326 	mutex_lock(&acpi_gpio_deferred_req_irqs_lock);
327 	if (!list_empty(&acpi_gpio->deferred_req_irqs_list_entry))
328 		list_del_init(&acpi_gpio->deferred_req_irqs_list_entry);
329 	mutex_unlock(&acpi_gpio_deferred_req_irqs_lock);
330 
331 	list_for_each_entry_safe_reverse(event, ep, &acpi_gpio->events, node) {
332 		struct gpio_desc *desc;
333 
334 		if (irqd_is_wakeup_set(irq_get_irq_data(event->irq)))
335 			disable_irq_wake(event->irq);
336 
337 		free_irq(event->irq, event);
338 		desc = event->desc;
339 		if (WARN_ON(IS_ERR(desc)))
340 			continue;
341 		gpiochip_unlock_as_irq(chip, event->pin);
342 		gpiochip_free_own_desc(desc);
343 		list_del(&event->node);
344 		kfree(event);
345 	}
346 }
347 EXPORT_SYMBOL_GPL(acpi_gpiochip_free_interrupts);
348 
349 int acpi_dev_add_driver_gpios(struct acpi_device *adev,
350 			      const struct acpi_gpio_mapping *gpios)
351 {
352 	if (adev && gpios) {
353 		adev->driver_gpios = gpios;
354 		return 0;
355 	}
356 	return -EINVAL;
357 }
358 EXPORT_SYMBOL_GPL(acpi_dev_add_driver_gpios);
359 
360 static void devm_acpi_dev_release_driver_gpios(struct device *dev, void *res)
361 {
362 	acpi_dev_remove_driver_gpios(ACPI_COMPANION(dev));
363 }
364 
365 int devm_acpi_dev_add_driver_gpios(struct device *dev,
366 				   const struct acpi_gpio_mapping *gpios)
367 {
368 	void *res;
369 	int ret;
370 
371 	res = devres_alloc(devm_acpi_dev_release_driver_gpios, 0, GFP_KERNEL);
372 	if (!res)
373 		return -ENOMEM;
374 
375 	ret = acpi_dev_add_driver_gpios(ACPI_COMPANION(dev), gpios);
376 	if (ret) {
377 		devres_free(res);
378 		return ret;
379 	}
380 	devres_add(dev, res);
381 	return 0;
382 }
383 EXPORT_SYMBOL_GPL(devm_acpi_dev_add_driver_gpios);
384 
385 void devm_acpi_dev_remove_driver_gpios(struct device *dev)
386 {
387 	WARN_ON(devres_release(dev, devm_acpi_dev_release_driver_gpios, NULL, NULL));
388 }
389 EXPORT_SYMBOL_GPL(devm_acpi_dev_remove_driver_gpios);
390 
391 static bool acpi_get_driver_gpio_data(struct acpi_device *adev,
392 				      const char *name, int index,
393 				      struct fwnode_reference_args *args,
394 				      unsigned int *quirks)
395 {
396 	const struct acpi_gpio_mapping *gm;
397 
398 	if (!adev->driver_gpios)
399 		return false;
400 
401 	for (gm = adev->driver_gpios; gm->name; gm++)
402 		if (!strcmp(name, gm->name) && gm->data && index < gm->size) {
403 			const struct acpi_gpio_params *par = gm->data + index;
404 
405 			args->fwnode = acpi_fwnode_handle(adev);
406 			args->args[0] = par->crs_entry_index;
407 			args->args[1] = par->line_index;
408 			args->args[2] = par->active_low;
409 			args->nargs = 3;
410 
411 			*quirks = gm->quirks;
412 			return true;
413 		}
414 
415 	return false;
416 }
417 
418 static enum gpiod_flags
419 acpi_gpio_to_gpiod_flags(const struct acpi_resource_gpio *agpio)
420 {
421 	bool pull_up = agpio->pin_config == ACPI_PIN_CONFIG_PULLUP;
422 
423 	switch (agpio->io_restriction) {
424 	case ACPI_IO_RESTRICT_INPUT:
425 		return GPIOD_IN;
426 	case ACPI_IO_RESTRICT_OUTPUT:
427 		/*
428 		 * ACPI GPIO resources don't contain an initial value for the
429 		 * GPIO. Therefore we deduce that value from the pull field
430 		 * instead. If the pin is pulled up we assume default to be
431 		 * high, otherwise low.
432 		 */
433 		return pull_up ? GPIOD_OUT_HIGH : GPIOD_OUT_LOW;
434 	default:
435 		/*
436 		 * Assume that the BIOS has configured the direction and pull
437 		 * accordingly.
438 		 */
439 		return GPIOD_ASIS;
440 	}
441 }
442 
443 static int
444 __acpi_gpio_update_gpiod_flags(enum gpiod_flags *flags, enum gpiod_flags update)
445 {
446 	int ret = 0;
447 
448 	/*
449 	 * Check if the BIOS has IoRestriction with explicitly set direction
450 	 * and update @flags accordingly. Otherwise use whatever caller asked
451 	 * for.
452 	 */
453 	if (update & GPIOD_FLAGS_BIT_DIR_SET) {
454 		enum gpiod_flags diff = *flags ^ update;
455 
456 		/*
457 		 * Check if caller supplied incompatible GPIO initialization
458 		 * flags.
459 		 *
460 		 * Return %-EINVAL to notify that firmware has different
461 		 * settings and we are going to use them.
462 		 */
463 		if (((*flags & GPIOD_FLAGS_BIT_DIR_SET) && (diff & GPIOD_FLAGS_BIT_DIR_OUT)) ||
464 		    ((*flags & GPIOD_FLAGS_BIT_DIR_OUT) && (diff & GPIOD_FLAGS_BIT_DIR_VAL)))
465 			ret = -EINVAL;
466 		*flags = update;
467 	}
468 	return ret;
469 }
470 
471 int
472 acpi_gpio_update_gpiod_flags(enum gpiod_flags *flags, struct acpi_gpio_info *info)
473 {
474 	struct device *dev = &info->adev->dev;
475 	enum gpiod_flags old = *flags;
476 	int ret;
477 
478 	ret = __acpi_gpio_update_gpiod_flags(&old, info->flags);
479 	if (info->quirks & ACPI_GPIO_QUIRK_NO_IO_RESTRICTION) {
480 		if (ret)
481 			dev_warn(dev, FW_BUG "GPIO not in correct mode, fixing\n");
482 	} else {
483 		if (ret)
484 			dev_dbg(dev, "Override GPIO initialization flags\n");
485 		*flags = old;
486 	}
487 
488 	return ret;
489 }
490 
491 struct acpi_gpio_lookup {
492 	struct acpi_gpio_info info;
493 	int index;
494 	int pin_index;
495 	bool active_low;
496 	struct gpio_desc *desc;
497 	int n;
498 };
499 
500 static int acpi_populate_gpio_lookup(struct acpi_resource *ares, void *data)
501 {
502 	struct acpi_gpio_lookup *lookup = data;
503 
504 	if (ares->type != ACPI_RESOURCE_TYPE_GPIO)
505 		return 1;
506 
507 	if (lookup->n++ == lookup->index && !lookup->desc) {
508 		const struct acpi_resource_gpio *agpio = &ares->data.gpio;
509 		int pin_index = lookup->pin_index;
510 
511 		if (pin_index >= agpio->pin_table_length)
512 			return 1;
513 
514 		lookup->desc = acpi_get_gpiod(agpio->resource_source.string_ptr,
515 					      agpio->pin_table[pin_index]);
516 		lookup->info.gpioint =
517 			agpio->connection_type == ACPI_RESOURCE_GPIO_TYPE_INT;
518 
519 		/*
520 		 * Polarity and triggering are only specified for GpioInt
521 		 * resource.
522 		 * Note: we expect here:
523 		 * - ACPI_ACTIVE_LOW == GPIO_ACTIVE_LOW
524 		 * - ACPI_ACTIVE_HIGH == GPIO_ACTIVE_HIGH
525 		 */
526 		if (lookup->info.gpioint) {
527 			lookup->info.flags = GPIOD_IN;
528 			lookup->info.polarity = agpio->polarity;
529 			lookup->info.triggering = agpio->triggering;
530 		} else {
531 			lookup->info.flags = acpi_gpio_to_gpiod_flags(agpio);
532 			lookup->info.polarity = lookup->active_low;
533 		}
534 	}
535 
536 	return 1;
537 }
538 
539 static int acpi_gpio_resource_lookup(struct acpi_gpio_lookup *lookup,
540 				     struct acpi_gpio_info *info)
541 {
542 	struct acpi_device *adev = lookup->info.adev;
543 	struct list_head res_list;
544 	int ret;
545 
546 	INIT_LIST_HEAD(&res_list);
547 
548 	ret = acpi_dev_get_resources(adev, &res_list,
549 				     acpi_populate_gpio_lookup,
550 				     lookup);
551 	if (ret < 0)
552 		return ret;
553 
554 	acpi_dev_free_resource_list(&res_list);
555 
556 	if (!lookup->desc)
557 		return -ENOENT;
558 
559 	if (info)
560 		*info = lookup->info;
561 	return 0;
562 }
563 
564 static int acpi_gpio_property_lookup(struct fwnode_handle *fwnode,
565 				     const char *propname, int index,
566 				     struct acpi_gpio_lookup *lookup)
567 {
568 	struct fwnode_reference_args args;
569 	unsigned int quirks = 0;
570 	int ret;
571 
572 	memset(&args, 0, sizeof(args));
573 	ret = __acpi_node_get_property_reference(fwnode, propname, index, 3,
574 						 &args);
575 	if (ret) {
576 		struct acpi_device *adev = to_acpi_device_node(fwnode);
577 
578 		if (!adev)
579 			return ret;
580 
581 		if (!acpi_get_driver_gpio_data(adev, propname, index, &args,
582 					       &quirks))
583 			return ret;
584 	}
585 	/*
586 	 * The property was found and resolved, so need to lookup the GPIO based
587 	 * on returned args.
588 	 */
589 	if (!to_acpi_device_node(args.fwnode))
590 		return -EINVAL;
591 	if (args.nargs != 3)
592 		return -EPROTO;
593 
594 	lookup->index = args.args[0];
595 	lookup->pin_index = args.args[1];
596 	lookup->active_low = !!args.args[2];
597 
598 	lookup->info.adev = to_acpi_device_node(args.fwnode);
599 	lookup->info.quirks = quirks;
600 
601 	return 0;
602 }
603 
604 /**
605  * acpi_get_gpiod_by_index() - get a GPIO descriptor from device resources
606  * @adev: pointer to a ACPI device to get GPIO from
607  * @propname: Property name of the GPIO (optional)
608  * @index: index of GpioIo/GpioInt resource (starting from %0)
609  * @info: info pointer to fill in (optional)
610  *
611  * Function goes through ACPI resources for @adev and based on @index looks
612  * up a GpioIo/GpioInt resource, translates it to the Linux GPIO descriptor,
613  * and returns it. @index matches GpioIo/GpioInt resources only so if there
614  * are total %3 GPIO resources, the index goes from %0 to %2.
615  *
616  * If @propname is specified the GPIO is looked using device property. In
617  * that case @index is used to select the GPIO entry in the property value
618  * (in case of multiple).
619  *
620  * If the GPIO cannot be translated or there is an error an ERR_PTR is
621  * returned.
622  *
623  * Note: if the GPIO resource has multiple entries in the pin list, this
624  * function only returns the first.
625  */
626 static struct gpio_desc *acpi_get_gpiod_by_index(struct acpi_device *adev,
627 					  const char *propname, int index,
628 					  struct acpi_gpio_info *info)
629 {
630 	struct acpi_gpio_lookup lookup;
631 	int ret;
632 
633 	if (!adev)
634 		return ERR_PTR(-ENODEV);
635 
636 	memset(&lookup, 0, sizeof(lookup));
637 	lookup.index = index;
638 
639 	if (propname) {
640 		dev_dbg(&adev->dev, "GPIO: looking up %s\n", propname);
641 
642 		ret = acpi_gpio_property_lookup(acpi_fwnode_handle(adev),
643 						propname, index, &lookup);
644 		if (ret)
645 			return ERR_PTR(ret);
646 
647 		dev_dbg(&adev->dev, "GPIO: _DSD returned %s %d %d %u\n",
648 			dev_name(&lookup.info.adev->dev), lookup.index,
649 			lookup.pin_index, lookup.active_low);
650 	} else {
651 		dev_dbg(&adev->dev, "GPIO: looking up %d in _CRS\n", index);
652 		lookup.info.adev = adev;
653 	}
654 
655 	ret = acpi_gpio_resource_lookup(&lookup, info);
656 	return ret ? ERR_PTR(ret) : lookup.desc;
657 }
658 
659 struct gpio_desc *acpi_find_gpio(struct device *dev,
660 				 const char *con_id,
661 				 unsigned int idx,
662 				 enum gpiod_flags *dflags,
663 				 enum gpio_lookup_flags *lookupflags)
664 {
665 	struct acpi_device *adev = ACPI_COMPANION(dev);
666 	struct acpi_gpio_info info;
667 	struct gpio_desc *desc;
668 	char propname[32];
669 	int i;
670 
671 	/* Try first from _DSD */
672 	for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
673 		if (con_id) {
674 			snprintf(propname, sizeof(propname), "%s-%s",
675 				 con_id, gpio_suffixes[i]);
676 		} else {
677 			snprintf(propname, sizeof(propname), "%s",
678 				 gpio_suffixes[i]);
679 		}
680 
681 		desc = acpi_get_gpiod_by_index(adev, propname, idx, &info);
682 		if (!IS_ERR(desc))
683 			break;
684 		if (PTR_ERR(desc) == -EPROBE_DEFER)
685 			return ERR_CAST(desc);
686 	}
687 
688 	/* Then from plain _CRS GPIOs */
689 	if (IS_ERR(desc)) {
690 		if (!acpi_can_fallback_to_crs(adev, con_id))
691 			return ERR_PTR(-ENOENT);
692 
693 		desc = acpi_get_gpiod_by_index(adev, NULL, idx, &info);
694 		if (IS_ERR(desc))
695 			return desc;
696 	}
697 
698 	if (info.gpioint &&
699 	    (*dflags == GPIOD_OUT_LOW || *dflags == GPIOD_OUT_HIGH)) {
700 		dev_dbg(dev, "refusing GpioInt() entry when doing GPIOD_OUT_* lookup\n");
701 		return ERR_PTR(-ENOENT);
702 	}
703 
704 	if (info.polarity == GPIO_ACTIVE_LOW)
705 		*lookupflags |= GPIO_ACTIVE_LOW;
706 
707 	acpi_gpio_update_gpiod_flags(dflags, &info);
708 	return desc;
709 }
710 
711 /**
712  * acpi_node_get_gpiod() - get a GPIO descriptor from ACPI resources
713  * @fwnode: pointer to an ACPI firmware node to get the GPIO information from
714  * @propname: Property name of the GPIO
715  * @index: index of GpioIo/GpioInt resource (starting from %0)
716  * @info: info pointer to fill in (optional)
717  *
718  * If @fwnode is an ACPI device object, call %acpi_get_gpiod_by_index() for it.
719  * Otherwise (ie. it is a data-only non-device object), use the property-based
720  * GPIO lookup to get to the GPIO resource with the relevant information and use
721  * that to obtain the GPIO descriptor to return.
722  */
723 struct gpio_desc *acpi_node_get_gpiod(struct fwnode_handle *fwnode,
724 				      const char *propname, int index,
725 				      struct acpi_gpio_info *info)
726 {
727 	struct acpi_gpio_lookup lookup;
728 	struct acpi_device *adev;
729 	int ret;
730 
731 	adev = to_acpi_device_node(fwnode);
732 	if (adev)
733 		return acpi_get_gpiod_by_index(adev, propname, index, info);
734 
735 	if (!is_acpi_data_node(fwnode))
736 		return ERR_PTR(-ENODEV);
737 
738 	if (!propname)
739 		return ERR_PTR(-EINVAL);
740 
741 	memset(&lookup, 0, sizeof(lookup));
742 	lookup.index = index;
743 
744 	ret = acpi_gpio_property_lookup(fwnode, propname, index, &lookup);
745 	if (ret)
746 		return ERR_PTR(ret);
747 
748 	ret = acpi_gpio_resource_lookup(&lookup, info);
749 	return ret ? ERR_PTR(ret) : lookup.desc;
750 }
751 
752 /**
753  * acpi_dev_gpio_irq_get() - Find GpioInt and translate it to Linux IRQ number
754  * @adev: pointer to a ACPI device to get IRQ from
755  * @index: index of GpioInt resource (starting from %0)
756  *
757  * If the device has one or more GpioInt resources, this function can be
758  * used to translate from the GPIO offset in the resource to the Linux IRQ
759  * number.
760  *
761  * The function is idempotent, though each time it runs it will configure GPIO
762  * pin direction according to the flags in GpioInt resource.
763  *
764  * Return: Linux IRQ number (> %0) on success, negative errno on failure.
765  */
766 int acpi_dev_gpio_irq_get(struct acpi_device *adev, int index)
767 {
768 	int idx, i;
769 	unsigned int irq_flags;
770 	int ret;
771 
772 	for (i = 0, idx = 0; idx <= index; i++) {
773 		struct acpi_gpio_info info;
774 		struct gpio_desc *desc;
775 
776 		desc = acpi_get_gpiod_by_index(adev, NULL, i, &info);
777 
778 		/* Ignore -EPROBE_DEFER, it only matters if idx matches */
779 		if (IS_ERR(desc) && PTR_ERR(desc) != -EPROBE_DEFER)
780 			return PTR_ERR(desc);
781 
782 		if (info.gpioint && idx++ == index) {
783 			char label[32];
784 			int irq;
785 
786 			if (IS_ERR(desc))
787 				return PTR_ERR(desc);
788 
789 			irq = gpiod_to_irq(desc);
790 			if (irq < 0)
791 				return irq;
792 
793 			snprintf(label, sizeof(label), "GpioInt() %d", index);
794 			ret = gpiod_configure_flags(desc, label, 0, info.flags);
795 			if (ret < 0)
796 				return ret;
797 
798 			irq_flags = acpi_dev_get_irq_type(info.triggering,
799 							  info.polarity);
800 
801 			/* Set type if specified and different than the current one */
802 			if (irq_flags != IRQ_TYPE_NONE &&
803 			    irq_flags != irq_get_trigger_type(irq))
804 				irq_set_irq_type(irq, irq_flags);
805 
806 			return irq;
807 		}
808 
809 	}
810 	return -ENOENT;
811 }
812 EXPORT_SYMBOL_GPL(acpi_dev_gpio_irq_get);
813 
814 static acpi_status
815 acpi_gpio_adr_space_handler(u32 function, acpi_physical_address address,
816 			    u32 bits, u64 *value, void *handler_context,
817 			    void *region_context)
818 {
819 	struct acpi_gpio_chip *achip = region_context;
820 	struct gpio_chip *chip = achip->chip;
821 	struct acpi_resource_gpio *agpio;
822 	struct acpi_resource *ares;
823 	int pin_index = (int)address;
824 	acpi_status status;
825 	int length;
826 	int i;
827 
828 	status = acpi_buffer_to_resource(achip->conn_info.connection,
829 					 achip->conn_info.length, &ares);
830 	if (ACPI_FAILURE(status))
831 		return status;
832 
833 	if (WARN_ON(ares->type != ACPI_RESOURCE_TYPE_GPIO)) {
834 		ACPI_FREE(ares);
835 		return AE_BAD_PARAMETER;
836 	}
837 
838 	agpio = &ares->data.gpio;
839 
840 	if (WARN_ON(agpio->io_restriction == ACPI_IO_RESTRICT_INPUT &&
841 	    function == ACPI_WRITE)) {
842 		ACPI_FREE(ares);
843 		return AE_BAD_PARAMETER;
844 	}
845 
846 	length = min(agpio->pin_table_length, (u16)(pin_index + bits));
847 	for (i = pin_index; i < length; ++i) {
848 		int pin = agpio->pin_table[i];
849 		struct acpi_gpio_connection *conn;
850 		struct gpio_desc *desc;
851 		bool found;
852 
853 		mutex_lock(&achip->conn_lock);
854 
855 		found = false;
856 		list_for_each_entry(conn, &achip->conns, node) {
857 			if (conn->pin == pin) {
858 				found = true;
859 				desc = conn->desc;
860 				break;
861 			}
862 		}
863 
864 		/*
865 		 * The same GPIO can be shared between operation region and
866 		 * event but only if the access here is ACPI_READ. In that
867 		 * case we "borrow" the event GPIO instead.
868 		 */
869 		if (!found && agpio->sharable == ACPI_SHARED &&
870 		     function == ACPI_READ) {
871 			struct acpi_gpio_event *event;
872 
873 			list_for_each_entry(event, &achip->events, node) {
874 				if (event->pin == pin) {
875 					desc = event->desc;
876 					found = true;
877 					break;
878 				}
879 			}
880 		}
881 
882 		if (!found) {
883 			enum gpiod_flags flags = acpi_gpio_to_gpiod_flags(agpio);
884 			const char *label = "ACPI:OpRegion";
885 			int err;
886 
887 			desc = gpiochip_request_own_desc(chip, pin, label);
888 			if (IS_ERR(desc)) {
889 				status = AE_ERROR;
890 				mutex_unlock(&achip->conn_lock);
891 				goto out;
892 			}
893 
894 			err = gpiod_configure_flags(desc, label, 0, flags);
895 			if (err < 0) {
896 				status = AE_NOT_CONFIGURED;
897 				gpiochip_free_own_desc(desc);
898 				mutex_unlock(&achip->conn_lock);
899 				goto out;
900 			}
901 
902 			conn = kzalloc(sizeof(*conn), GFP_KERNEL);
903 			if (!conn) {
904 				status = AE_NO_MEMORY;
905 				gpiochip_free_own_desc(desc);
906 				mutex_unlock(&achip->conn_lock);
907 				goto out;
908 			}
909 
910 			conn->pin = pin;
911 			conn->desc = desc;
912 			list_add_tail(&conn->node, &achip->conns);
913 		}
914 
915 		mutex_unlock(&achip->conn_lock);
916 
917 		if (function == ACPI_WRITE)
918 			gpiod_set_raw_value_cansleep(desc,
919 						     !!((1 << i) & *value));
920 		else
921 			*value |= (u64)gpiod_get_raw_value_cansleep(desc) << i;
922 	}
923 
924 out:
925 	ACPI_FREE(ares);
926 	return status;
927 }
928 
929 static void acpi_gpiochip_request_regions(struct acpi_gpio_chip *achip)
930 {
931 	struct gpio_chip *chip = achip->chip;
932 	acpi_handle handle = ACPI_HANDLE(chip->parent);
933 	acpi_status status;
934 
935 	INIT_LIST_HEAD(&achip->conns);
936 	mutex_init(&achip->conn_lock);
937 	status = acpi_install_address_space_handler(handle, ACPI_ADR_SPACE_GPIO,
938 						    acpi_gpio_adr_space_handler,
939 						    NULL, achip);
940 	if (ACPI_FAILURE(status))
941 		dev_err(chip->parent,
942 		        "Failed to install GPIO OpRegion handler\n");
943 }
944 
945 static void acpi_gpiochip_free_regions(struct acpi_gpio_chip *achip)
946 {
947 	struct gpio_chip *chip = achip->chip;
948 	acpi_handle handle = ACPI_HANDLE(chip->parent);
949 	struct acpi_gpio_connection *conn, *tmp;
950 	acpi_status status;
951 
952 	status = acpi_remove_address_space_handler(handle, ACPI_ADR_SPACE_GPIO,
953 						   acpi_gpio_adr_space_handler);
954 	if (ACPI_FAILURE(status)) {
955 		dev_err(chip->parent,
956 			"Failed to remove GPIO OpRegion handler\n");
957 		return;
958 	}
959 
960 	list_for_each_entry_safe_reverse(conn, tmp, &achip->conns, node) {
961 		gpiochip_free_own_desc(conn->desc);
962 		list_del(&conn->node);
963 		kfree(conn);
964 	}
965 }
966 
967 static struct gpio_desc *acpi_gpiochip_parse_own_gpio(
968 	struct acpi_gpio_chip *achip, struct fwnode_handle *fwnode,
969 	const char **name, unsigned int *lflags, unsigned int *dflags)
970 {
971 	struct gpio_chip *chip = achip->chip;
972 	struct gpio_desc *desc;
973 	u32 gpios[2];
974 	int ret;
975 
976 	*lflags = 0;
977 	*dflags = 0;
978 	*name = NULL;
979 
980 	ret = fwnode_property_read_u32_array(fwnode, "gpios", gpios,
981 					     ARRAY_SIZE(gpios));
982 	if (ret < 0)
983 		return ERR_PTR(ret);
984 
985 	desc = gpiochip_get_desc(chip, gpios[0]);
986 	if (IS_ERR(desc))
987 		return desc;
988 
989 	if (gpios[1])
990 		*lflags |= GPIO_ACTIVE_LOW;
991 
992 	if (fwnode_property_present(fwnode, "input"))
993 		*dflags |= GPIOD_IN;
994 	else if (fwnode_property_present(fwnode, "output-low"))
995 		*dflags |= GPIOD_OUT_LOW;
996 	else if (fwnode_property_present(fwnode, "output-high"))
997 		*dflags |= GPIOD_OUT_HIGH;
998 	else
999 		return ERR_PTR(-EINVAL);
1000 
1001 	fwnode_property_read_string(fwnode, "line-name", name);
1002 
1003 	return desc;
1004 }
1005 
1006 static void acpi_gpiochip_scan_gpios(struct acpi_gpio_chip *achip)
1007 {
1008 	struct gpio_chip *chip = achip->chip;
1009 	struct fwnode_handle *fwnode;
1010 
1011 	device_for_each_child_node(chip->parent, fwnode) {
1012 		unsigned int lflags, dflags;
1013 		struct gpio_desc *desc;
1014 		const char *name;
1015 		int ret;
1016 
1017 		if (!fwnode_property_present(fwnode, "gpio-hog"))
1018 			continue;
1019 
1020 		desc = acpi_gpiochip_parse_own_gpio(achip, fwnode, &name,
1021 						    &lflags, &dflags);
1022 		if (IS_ERR(desc))
1023 			continue;
1024 
1025 		ret = gpiod_hog(desc, name, lflags, dflags);
1026 		if (ret) {
1027 			dev_err(chip->parent, "Failed to hog GPIO\n");
1028 			fwnode_handle_put(fwnode);
1029 			return;
1030 		}
1031 	}
1032 }
1033 
1034 void acpi_gpiochip_add(struct gpio_chip *chip)
1035 {
1036 	struct acpi_gpio_chip *acpi_gpio;
1037 	acpi_handle handle;
1038 	acpi_status status;
1039 
1040 	if (!chip || !chip->parent)
1041 		return;
1042 
1043 	handle = ACPI_HANDLE(chip->parent);
1044 	if (!handle)
1045 		return;
1046 
1047 	acpi_gpio = kzalloc(sizeof(*acpi_gpio), GFP_KERNEL);
1048 	if (!acpi_gpio) {
1049 		dev_err(chip->parent,
1050 			"Failed to allocate memory for ACPI GPIO chip\n");
1051 		return;
1052 	}
1053 
1054 	acpi_gpio->chip = chip;
1055 	INIT_LIST_HEAD(&acpi_gpio->events);
1056 	INIT_LIST_HEAD(&acpi_gpio->deferred_req_irqs_list_entry);
1057 
1058 	status = acpi_attach_data(handle, acpi_gpio_chip_dh, acpi_gpio);
1059 	if (ACPI_FAILURE(status)) {
1060 		dev_err(chip->parent, "Failed to attach ACPI GPIO chip\n");
1061 		kfree(acpi_gpio);
1062 		return;
1063 	}
1064 
1065 	if (!chip->names)
1066 		devprop_gpiochip_set_names(chip, dev_fwnode(chip->parent));
1067 
1068 	acpi_gpiochip_request_regions(acpi_gpio);
1069 	acpi_gpiochip_scan_gpios(acpi_gpio);
1070 	acpi_walk_dep_device_list(handle);
1071 }
1072 
1073 void acpi_gpiochip_remove(struct gpio_chip *chip)
1074 {
1075 	struct acpi_gpio_chip *acpi_gpio;
1076 	acpi_handle handle;
1077 	acpi_status status;
1078 
1079 	if (!chip || !chip->parent)
1080 		return;
1081 
1082 	handle = ACPI_HANDLE(chip->parent);
1083 	if (!handle)
1084 		return;
1085 
1086 	status = acpi_get_data(handle, acpi_gpio_chip_dh, (void **)&acpi_gpio);
1087 	if (ACPI_FAILURE(status)) {
1088 		dev_warn(chip->parent, "Failed to retrieve ACPI GPIO chip\n");
1089 		return;
1090 	}
1091 
1092 	acpi_gpiochip_free_regions(acpi_gpio);
1093 
1094 	acpi_detach_data(handle, acpi_gpio_chip_dh);
1095 	kfree(acpi_gpio);
1096 }
1097 
1098 static int acpi_gpio_package_count(const union acpi_object *obj)
1099 {
1100 	const union acpi_object *element = obj->package.elements;
1101 	const union acpi_object *end = element + obj->package.count;
1102 	unsigned int count = 0;
1103 
1104 	while (element < end) {
1105 		switch (element->type) {
1106 		case ACPI_TYPE_LOCAL_REFERENCE:
1107 			element += 3;
1108 			/* Fallthrough */
1109 		case ACPI_TYPE_INTEGER:
1110 			element++;
1111 			count++;
1112 			break;
1113 
1114 		default:
1115 			return -EPROTO;
1116 		}
1117 	}
1118 
1119 	return count;
1120 }
1121 
1122 static int acpi_find_gpio_count(struct acpi_resource *ares, void *data)
1123 {
1124 	unsigned int *count = data;
1125 
1126 	if (ares->type == ACPI_RESOURCE_TYPE_GPIO)
1127 		*count += ares->data.gpio.pin_table_length;
1128 
1129 	return 1;
1130 }
1131 
1132 /**
1133  * acpi_gpio_count - return the number of GPIOs associated with a
1134  *		device / function or -ENOENT if no GPIO has been
1135  *		assigned to the requested function.
1136  * @dev:	GPIO consumer, can be NULL for system-global GPIOs
1137  * @con_id:	function within the GPIO consumer
1138  */
1139 int acpi_gpio_count(struct device *dev, const char *con_id)
1140 {
1141 	struct acpi_device *adev = ACPI_COMPANION(dev);
1142 	const union acpi_object *obj;
1143 	const struct acpi_gpio_mapping *gm;
1144 	int count = -ENOENT;
1145 	int ret;
1146 	char propname[32];
1147 	unsigned int i;
1148 
1149 	/* Try first from _DSD */
1150 	for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
1151 		if (con_id)
1152 			snprintf(propname, sizeof(propname), "%s-%s",
1153 				 con_id, gpio_suffixes[i]);
1154 		else
1155 			snprintf(propname, sizeof(propname), "%s",
1156 				 gpio_suffixes[i]);
1157 
1158 		ret = acpi_dev_get_property(adev, propname, ACPI_TYPE_ANY,
1159 					    &obj);
1160 		if (ret == 0) {
1161 			if (obj->type == ACPI_TYPE_LOCAL_REFERENCE)
1162 				count = 1;
1163 			else if (obj->type == ACPI_TYPE_PACKAGE)
1164 				count = acpi_gpio_package_count(obj);
1165 		} else if (adev->driver_gpios) {
1166 			for (gm = adev->driver_gpios; gm->name; gm++)
1167 				if (strcmp(propname, gm->name) == 0) {
1168 					count = gm->size;
1169 					break;
1170 				}
1171 		}
1172 		if (count > 0)
1173 			break;
1174 	}
1175 
1176 	/* Then from plain _CRS GPIOs */
1177 	if (count < 0) {
1178 		struct list_head resource_list;
1179 		unsigned int crs_count = 0;
1180 
1181 		if (!acpi_can_fallback_to_crs(adev, con_id))
1182 			return count;
1183 
1184 		INIT_LIST_HEAD(&resource_list);
1185 		acpi_dev_get_resources(adev, &resource_list,
1186 				       acpi_find_gpio_count, &crs_count);
1187 		acpi_dev_free_resource_list(&resource_list);
1188 		if (crs_count > 0)
1189 			count = crs_count;
1190 	}
1191 	return count ? count : -ENOENT;
1192 }
1193 
1194 bool acpi_can_fallback_to_crs(struct acpi_device *adev, const char *con_id)
1195 {
1196 	/* Never allow fallback if the device has properties */
1197 	if (acpi_dev_has_props(adev) || adev->driver_gpios)
1198 		return false;
1199 
1200 	return con_id == NULL;
1201 }
1202 
1203 /* Run deferred acpi_gpiochip_request_interrupts() */
1204 static int acpi_gpio_handle_deferred_request_interrupts(void)
1205 {
1206 	struct acpi_gpio_chip *acpi_gpio, *tmp;
1207 
1208 	mutex_lock(&acpi_gpio_deferred_req_irqs_lock);
1209 	list_for_each_entry_safe(acpi_gpio, tmp,
1210 				 &acpi_gpio_deferred_req_irqs_list,
1211 				 deferred_req_irqs_list_entry) {
1212 		acpi_handle handle;
1213 
1214 		handle = ACPI_HANDLE(acpi_gpio->chip->parent);
1215 		acpi_walk_resources(handle, "_AEI",
1216 				    acpi_gpiochip_request_interrupt, acpi_gpio);
1217 
1218 		list_del_init(&acpi_gpio->deferred_req_irqs_list_entry);
1219 	}
1220 
1221 	acpi_gpio_deferred_req_irqs_done = true;
1222 	mutex_unlock(&acpi_gpio_deferred_req_irqs_lock);
1223 
1224 	return 0;
1225 }
1226 /* We must use _sync so that this runs after the first deferred_probe run */
1227 late_initcall_sync(acpi_gpio_handle_deferred_request_interrupts);
1228