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