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