gpiolib: unexport devprop_gpiochip_set_names()
[linux-2.6-microblaze.git] / drivers / gpio / gpiolib.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/bitmap.h>
3 #include <linux/kernel.h>
4 #include <linux/module.h>
5 #include <linux/interrupt.h>
6 #include <linux/irq.h>
7 #include <linux/spinlock.h>
8 #include <linux/list.h>
9 #include <linux/device.h>
10 #include <linux/err.h>
11 #include <linux/debugfs.h>
12 #include <linux/seq_file.h>
13 #include <linux/gpio.h>
14 #include <linux/idr.h>
15 #include <linux/slab.h>
16 #include <linux/acpi.h>
17 #include <linux/gpio/driver.h>
18 #include <linux/gpio/machine.h>
19 #include <linux/pinctrl/consumer.h>
20 #include <linux/fs.h>
21 #include <linux/compat.h>
22 #include <linux/file.h>
23 #include <uapi/linux/gpio.h>
24
25 #include "gpiolib.h"
26 #include "gpiolib-of.h"
27 #include "gpiolib-acpi.h"
28 #include "gpiolib-cdev.h"
29 #include "gpiolib-sysfs.h"
30
31 #define CREATE_TRACE_POINTS
32 #include <trace/events/gpio.h>
33
34 /* Implementation infrastructure for GPIO interfaces.
35  *
36  * The GPIO programming interface allows for inlining speed-critical
37  * get/set operations for common cases, so that access to SOC-integrated
38  * GPIOs can sometimes cost only an instruction or two per bit.
39  */
40
41
42 /* When debugging, extend minimal trust to callers and platform code.
43  * Also emit diagnostic messages that may help initial bringup, when
44  * board setup or driver bugs are most common.
45  *
46  * Otherwise, minimize overhead in what may be bitbanging codepaths.
47  */
48 #ifdef  DEBUG
49 #define extra_checks    1
50 #else
51 #define extra_checks    0
52 #endif
53
54 /* Device and char device-related information */
55 static DEFINE_IDA(gpio_ida);
56 static dev_t gpio_devt;
57 #define GPIO_DEV_MAX 256 /* 256 GPIO chip devices supported */
58 static struct bus_type gpio_bus_type = {
59         .name = "gpio",
60 };
61
62 /*
63  * Number of GPIOs to use for the fast path in set array
64  */
65 #define FASTPATH_NGPIO CONFIG_GPIOLIB_FASTPATH_LIMIT
66
67 /* gpio_lock prevents conflicts during gpio_desc[] table updates.
68  * While any GPIO is requested, its gpio_chip is not removable;
69  * each GPIO's "requested" flag serves as a lock and refcount.
70  */
71 DEFINE_SPINLOCK(gpio_lock);
72
73 static DEFINE_MUTEX(gpio_lookup_lock);
74 static LIST_HEAD(gpio_lookup_list);
75 LIST_HEAD(gpio_devices);
76
77 static DEFINE_MUTEX(gpio_machine_hogs_mutex);
78 static LIST_HEAD(gpio_machine_hogs);
79
80 static void gpiochip_free_hogs(struct gpio_chip *gc);
81 static int gpiochip_add_irqchip(struct gpio_chip *gc,
82                                 struct lock_class_key *lock_key,
83                                 struct lock_class_key *request_key);
84 static void gpiochip_irqchip_remove(struct gpio_chip *gc);
85 static int gpiochip_irqchip_init_hw(struct gpio_chip *gc);
86 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc);
87 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc);
88
89 static bool gpiolib_initialized;
90
91 static inline void desc_set_label(struct gpio_desc *d, const char *label)
92 {
93         d->label = label;
94 }
95
96 /**
97  * gpio_to_desc - Convert a GPIO number to its descriptor
98  * @gpio: global GPIO number
99  *
100  * Returns:
101  * The GPIO descriptor associated with the given GPIO, or %NULL if no GPIO
102  * with the given number exists in the system.
103  */
104 struct gpio_desc *gpio_to_desc(unsigned gpio)
105 {
106         struct gpio_device *gdev;
107         unsigned long flags;
108
109         spin_lock_irqsave(&gpio_lock, flags);
110
111         list_for_each_entry(gdev, &gpio_devices, list) {
112                 if (gdev->base <= gpio &&
113                     gdev->base + gdev->ngpio > gpio) {
114                         spin_unlock_irqrestore(&gpio_lock, flags);
115                         return &gdev->descs[gpio - gdev->base];
116                 }
117         }
118
119         spin_unlock_irqrestore(&gpio_lock, flags);
120
121         if (!gpio_is_valid(gpio))
122                 WARN(1, "invalid GPIO %d\n", gpio);
123
124         return NULL;
125 }
126 EXPORT_SYMBOL_GPL(gpio_to_desc);
127
128 /**
129  * gpiochip_get_desc - get the GPIO descriptor corresponding to the given
130  *                     hardware number for this chip
131  * @gc: GPIO chip
132  * @hwnum: hardware number of the GPIO for this chip
133  *
134  * Returns:
135  * A pointer to the GPIO descriptor or ``ERR_PTR(-EINVAL)`` if no GPIO exists
136  * in the given chip for the specified hardware number.
137  */
138 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *gc,
139                                     unsigned int hwnum)
140 {
141         struct gpio_device *gdev = gc->gpiodev;
142
143         if (hwnum >= gdev->ngpio)
144                 return ERR_PTR(-EINVAL);
145
146         return &gdev->descs[hwnum];
147 }
148 EXPORT_SYMBOL_GPL(gpiochip_get_desc);
149
150 /**
151  * desc_to_gpio - convert a GPIO descriptor to the integer namespace
152  * @desc: GPIO descriptor
153  *
154  * This should disappear in the future but is needed since we still
155  * use GPIO numbers for error messages and sysfs nodes.
156  *
157  * Returns:
158  * The global GPIO number for the GPIO specified by its descriptor.
159  */
160 int desc_to_gpio(const struct gpio_desc *desc)
161 {
162         return desc->gdev->base + (desc - &desc->gdev->descs[0]);
163 }
164 EXPORT_SYMBOL_GPL(desc_to_gpio);
165
166
167 /**
168  * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
169  * @desc:       descriptor to return the chip of
170  */
171 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
172 {
173         if (!desc || !desc->gdev)
174                 return NULL;
175         return desc->gdev->chip;
176 }
177 EXPORT_SYMBOL_GPL(gpiod_to_chip);
178
179 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
180 static int gpiochip_find_base(int ngpio)
181 {
182         struct gpio_device *gdev;
183         int base = ARCH_NR_GPIOS - ngpio;
184
185         list_for_each_entry_reverse(gdev, &gpio_devices, list) {
186                 /* found a free space? */
187                 if (gdev->base + gdev->ngpio <= base)
188                         break;
189                 else
190                         /* nope, check the space right before the chip */
191                         base = gdev->base - ngpio;
192         }
193
194         if (gpio_is_valid(base)) {
195                 pr_debug("%s: found new base at %d\n", __func__, base);
196                 return base;
197         } else {
198                 pr_err("%s: cannot find free range\n", __func__);
199                 return -ENOSPC;
200         }
201 }
202
203 /**
204  * gpiod_get_direction - return the current direction of a GPIO
205  * @desc:       GPIO to get the direction of
206  *
207  * Returns 0 for output, 1 for input, or an error code in case of error.
208  *
209  * This function may sleep if gpiod_cansleep() is true.
210  */
211 int gpiod_get_direction(struct gpio_desc *desc)
212 {
213         struct gpio_chip *gc;
214         unsigned offset;
215         int ret;
216
217         gc = gpiod_to_chip(desc);
218         offset = gpio_chip_hwgpio(desc);
219
220         /*
221          * Open drain emulation using input mode may incorrectly report
222          * input here, fix that up.
223          */
224         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) &&
225             test_bit(FLAG_IS_OUT, &desc->flags))
226                 return 0;
227
228         if (!gc->get_direction)
229                 return -ENOTSUPP;
230
231         ret = gc->get_direction(gc, offset);
232         if (ret < 0)
233                 return ret;
234
235         /* GPIOF_DIR_IN or other positive, otherwise GPIOF_DIR_OUT */
236         if (ret > 0)
237                 ret = 1;
238
239         assign_bit(FLAG_IS_OUT, &desc->flags, !ret);
240
241         return ret;
242 }
243 EXPORT_SYMBOL_GPL(gpiod_get_direction);
244
245 /*
246  * Add a new chip to the global chips list, keeping the list of chips sorted
247  * by range(means [base, base + ngpio - 1]) order.
248  *
249  * Return -EBUSY if the new chip overlaps with some other chip's integer
250  * space.
251  */
252 static int gpiodev_add_to_list(struct gpio_device *gdev)
253 {
254         struct gpio_device *prev, *next;
255
256         if (list_empty(&gpio_devices)) {
257                 /* initial entry in list */
258                 list_add_tail(&gdev->list, &gpio_devices);
259                 return 0;
260         }
261
262         next = list_entry(gpio_devices.next, struct gpio_device, list);
263         if (gdev->base + gdev->ngpio <= next->base) {
264                 /* add before first entry */
265                 list_add(&gdev->list, &gpio_devices);
266                 return 0;
267         }
268
269         prev = list_entry(gpio_devices.prev, struct gpio_device, list);
270         if (prev->base + prev->ngpio <= gdev->base) {
271                 /* add behind last entry */
272                 list_add_tail(&gdev->list, &gpio_devices);
273                 return 0;
274         }
275
276         list_for_each_entry_safe(prev, next, &gpio_devices, list) {
277                 /* at the end of the list */
278                 if (&next->list == &gpio_devices)
279                         break;
280
281                 /* add between prev and next */
282                 if (prev->base + prev->ngpio <= gdev->base
283                                 && gdev->base + gdev->ngpio <= next->base) {
284                         list_add(&gdev->list, &prev->list);
285                         return 0;
286                 }
287         }
288
289         dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
290         return -EBUSY;
291 }
292
293 /*
294  * Convert a GPIO name to its descriptor
295  * Note that there is no guarantee that GPIO names are globally unique!
296  * Hence this function will return, if it exists, a reference to the first GPIO
297  * line found that matches the given name.
298  */
299 static struct gpio_desc *gpio_name_to_desc(const char * const name)
300 {
301         struct gpio_device *gdev;
302         unsigned long flags;
303
304         if (!name)
305                 return NULL;
306
307         spin_lock_irqsave(&gpio_lock, flags);
308
309         list_for_each_entry(gdev, &gpio_devices, list) {
310                 int i;
311
312                 for (i = 0; i != gdev->ngpio; ++i) {
313                         struct gpio_desc *desc = &gdev->descs[i];
314
315                         if (!desc->name)
316                                 continue;
317
318                         if (!strcmp(desc->name, name)) {
319                                 spin_unlock_irqrestore(&gpio_lock, flags);
320                                 return desc;
321                         }
322                 }
323         }
324
325         spin_unlock_irqrestore(&gpio_lock, flags);
326
327         return NULL;
328 }
329
330 /*
331  * Take the names from gc->names and assign them to their GPIO descriptors.
332  * Warn if a name is already used for a GPIO line on a different GPIO chip.
333  *
334  * Note that:
335  *   1. Non-unique names are still accepted,
336  *   2. Name collisions within the same GPIO chip are not reported.
337  */
338 static int gpiochip_set_desc_names(struct gpio_chip *gc)
339 {
340         struct gpio_device *gdev = gc->gpiodev;
341         int i;
342
343         /* First check all names if they are unique */
344         for (i = 0; i != gc->ngpio; ++i) {
345                 struct gpio_desc *gpio;
346
347                 gpio = gpio_name_to_desc(gc->names[i]);
348                 if (gpio)
349                         dev_warn(&gdev->dev,
350                                  "Detected name collision for GPIO name '%s'\n",
351                                  gc->names[i]);
352         }
353
354         /* Then add all names to the GPIO descriptors */
355         for (i = 0; i != gc->ngpio; ++i)
356                 gdev->descs[i].name = gc->names[i];
357
358         return 0;
359 }
360
361 /*
362  * devprop_gpiochip_set_names - Set GPIO line names using device properties
363  * @chip: GPIO chip whose lines should be named, if possible
364  *
365  * Looks for device property "gpio-line-names" and if it exists assigns
366  * GPIO line names for the chip. The memory allocated for the assigned
367  * names belong to the underlying software node and should not be released
368  * by the caller.
369  */
370 static int devprop_gpiochip_set_names(struct gpio_chip *chip)
371 {
372         struct gpio_device *gdev = chip->gpiodev;
373         struct device *dev = chip->parent;
374         const char **names;
375         int ret, i;
376         int count;
377
378         count = device_property_string_array_count(dev, "gpio-line-names");
379         if (count < 0)
380                 return 0;
381
382         if (count > gdev->ngpio) {
383                 dev_warn(&gdev->dev, "gpio-line-names is length %d but should be at most length %d",
384                          count, gdev->ngpio);
385                 count = gdev->ngpio;
386         }
387
388         names = kcalloc(count, sizeof(*names), GFP_KERNEL);
389         if (!names)
390                 return -ENOMEM;
391
392         ret = device_property_read_string_array(dev, "gpio-line-names",
393                                                 names, count);
394         if (ret < 0) {
395                 dev_warn(&gdev->dev, "failed to read GPIO line names\n");
396                 kfree(names);
397                 return ret;
398         }
399
400         for (i = 0; i < count; i++)
401                 gdev->descs[i].name = names[i];
402
403         kfree(names);
404
405         return 0;
406 }
407
408 static unsigned long *gpiochip_allocate_mask(struct gpio_chip *gc)
409 {
410         unsigned long *p;
411
412         p = bitmap_alloc(gc->ngpio, GFP_KERNEL);
413         if (!p)
414                 return NULL;
415
416         /* Assume by default all GPIOs are valid */
417         bitmap_fill(p, gc->ngpio);
418
419         return p;
420 }
421
422 static int gpiochip_alloc_valid_mask(struct gpio_chip *gc)
423 {
424         if (!(of_gpio_need_valid_mask(gc) || gc->init_valid_mask))
425                 return 0;
426
427         gc->valid_mask = gpiochip_allocate_mask(gc);
428         if (!gc->valid_mask)
429                 return -ENOMEM;
430
431         return 0;
432 }
433
434 static int gpiochip_init_valid_mask(struct gpio_chip *gc)
435 {
436         if (gc->init_valid_mask)
437                 return gc->init_valid_mask(gc,
438                                            gc->valid_mask,
439                                            gc->ngpio);
440
441         return 0;
442 }
443
444 static void gpiochip_free_valid_mask(struct gpio_chip *gc)
445 {
446         bitmap_free(gc->valid_mask);
447         gc->valid_mask = NULL;
448 }
449
450 static int gpiochip_add_pin_ranges(struct gpio_chip *gc)
451 {
452         if (gc->add_pin_ranges)
453                 return gc->add_pin_ranges(gc);
454
455         return 0;
456 }
457
458 bool gpiochip_line_is_valid(const struct gpio_chip *gc,
459                                 unsigned int offset)
460 {
461         /* No mask means all valid */
462         if (likely(!gc->valid_mask))
463                 return true;
464         return test_bit(offset, gc->valid_mask);
465 }
466 EXPORT_SYMBOL_GPL(gpiochip_line_is_valid);
467
468 static void gpiodevice_release(struct device *dev)
469 {
470         struct gpio_device *gdev = dev_get_drvdata(dev);
471
472         list_del(&gdev->list);
473         ida_free(&gpio_ida, gdev->id);
474         kfree_const(gdev->label);
475         kfree(gdev->descs);
476         kfree(gdev);
477 }
478
479 static int gpiochip_setup_dev(struct gpio_device *gdev)
480 {
481         int ret;
482
483         ret = gpiolib_cdev_register(gdev, gpio_devt);
484         if (ret)
485                 return ret;
486
487         ret = gpiochip_sysfs_register(gdev);
488         if (ret)
489                 goto err_remove_device;
490
491         /* From this point, the .release() function cleans up gpio_device */
492         gdev->dev.release = gpiodevice_release;
493         dev_dbg(&gdev->dev, "registered GPIOs %d to %d on %s\n", gdev->base,
494                 gdev->base + gdev->ngpio - 1, gdev->chip->label ? : "generic");
495
496         return 0;
497
498 err_remove_device:
499         gpiolib_cdev_unregister(gdev);
500         return ret;
501 }
502
503 static void gpiochip_machine_hog(struct gpio_chip *gc, struct gpiod_hog *hog)
504 {
505         struct gpio_desc *desc;
506         int rv;
507
508         desc = gpiochip_get_desc(gc, hog->chip_hwnum);
509         if (IS_ERR(desc)) {
510                 chip_err(gc, "%s: unable to get GPIO desc: %ld\n", __func__,
511                          PTR_ERR(desc));
512                 return;
513         }
514
515         if (test_bit(FLAG_IS_HOGGED, &desc->flags))
516                 return;
517
518         rv = gpiod_hog(desc, hog->line_name, hog->lflags, hog->dflags);
519         if (rv)
520                 gpiod_err(desc, "%s: unable to hog GPIO line (%s:%u): %d\n",
521                           __func__, gc->label, hog->chip_hwnum, rv);
522 }
523
524 static void machine_gpiochip_add(struct gpio_chip *gc)
525 {
526         struct gpiod_hog *hog;
527
528         mutex_lock(&gpio_machine_hogs_mutex);
529
530         list_for_each_entry(hog, &gpio_machine_hogs, list) {
531                 if (!strcmp(gc->label, hog->chip_label))
532                         gpiochip_machine_hog(gc, hog);
533         }
534
535         mutex_unlock(&gpio_machine_hogs_mutex);
536 }
537
538 static void gpiochip_setup_devs(void)
539 {
540         struct gpio_device *gdev;
541         int ret;
542
543         list_for_each_entry(gdev, &gpio_devices, list) {
544                 ret = gpiochip_setup_dev(gdev);
545                 if (ret)
546                         dev_err(&gdev->dev,
547                                 "Failed to initialize gpio device (%d)\n", ret);
548         }
549 }
550
551 int gpiochip_add_data_with_key(struct gpio_chip *gc, void *data,
552                                struct lock_class_key *lock_key,
553                                struct lock_class_key *request_key)
554 {
555         unsigned long   flags;
556         int             ret = 0;
557         unsigned        i;
558         int             base = gc->base;
559         struct gpio_device *gdev;
560
561         /*
562          * First: allocate and populate the internal stat container, and
563          * set up the struct device.
564          */
565         gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
566         if (!gdev)
567                 return -ENOMEM;
568         gdev->dev.bus = &gpio_bus_type;
569         gdev->chip = gc;
570         gc->gpiodev = gdev;
571         if (gc->parent) {
572                 gdev->dev.parent = gc->parent;
573                 gdev->dev.of_node = gc->parent->of_node;
574         }
575
576 #ifdef CONFIG_OF_GPIO
577         /* If the gpiochip has an assigned OF node this takes precedence */
578         if (gc->of_node)
579                 gdev->dev.of_node = gc->of_node;
580         else
581                 gc->of_node = gdev->dev.of_node;
582 #endif
583
584         gdev->id = ida_alloc(&gpio_ida, GFP_KERNEL);
585         if (gdev->id < 0) {
586                 ret = gdev->id;
587                 goto err_free_gdev;
588         }
589         dev_set_name(&gdev->dev, GPIOCHIP_NAME "%d", gdev->id);
590         device_initialize(&gdev->dev);
591         dev_set_drvdata(&gdev->dev, gdev);
592         if (gc->parent && gc->parent->driver)
593                 gdev->owner = gc->parent->driver->owner;
594         else if (gc->owner)
595                 /* TODO: remove chip->owner */
596                 gdev->owner = gc->owner;
597         else
598                 gdev->owner = THIS_MODULE;
599
600         gdev->descs = kcalloc(gc->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
601         if (!gdev->descs) {
602                 ret = -ENOMEM;
603                 goto err_free_ida;
604         }
605
606         if (gc->ngpio == 0) {
607                 chip_err(gc, "tried to insert a GPIO chip with zero lines\n");
608                 ret = -EINVAL;
609                 goto err_free_descs;
610         }
611
612         if (gc->ngpio > FASTPATH_NGPIO)
613                 chip_warn(gc, "line cnt %u is greater than fast path cnt %u\n",
614                           gc->ngpio, FASTPATH_NGPIO);
615
616         gdev->label = kstrdup_const(gc->label ?: "unknown", GFP_KERNEL);
617         if (!gdev->label) {
618                 ret = -ENOMEM;
619                 goto err_free_descs;
620         }
621
622         gdev->ngpio = gc->ngpio;
623         gdev->data = data;
624
625         spin_lock_irqsave(&gpio_lock, flags);
626
627         /*
628          * TODO: this allocates a Linux GPIO number base in the global
629          * GPIO numberspace for this chip. In the long run we want to
630          * get *rid* of this numberspace and use only descriptors, but
631          * it may be a pipe dream. It will not happen before we get rid
632          * of the sysfs interface anyways.
633          */
634         if (base < 0) {
635                 base = gpiochip_find_base(gc->ngpio);
636                 if (base < 0) {
637                         ret = base;
638                         spin_unlock_irqrestore(&gpio_lock, flags);
639                         goto err_free_label;
640                 }
641                 /*
642                  * TODO: it should not be necessary to reflect the assigned
643                  * base outside of the GPIO subsystem. Go over drivers and
644                  * see if anyone makes use of this, else drop this and assign
645                  * a poison instead.
646                  */
647                 gc->base = base;
648         }
649         gdev->base = base;
650
651         ret = gpiodev_add_to_list(gdev);
652         if (ret) {
653                 spin_unlock_irqrestore(&gpio_lock, flags);
654                 goto err_free_label;
655         }
656
657         for (i = 0; i < gc->ngpio; i++)
658                 gdev->descs[i].gdev = gdev;
659
660         spin_unlock_irqrestore(&gpio_lock, flags);
661
662         BLOCKING_INIT_NOTIFIER_HEAD(&gdev->notifier);
663
664 #ifdef CONFIG_PINCTRL
665         INIT_LIST_HEAD(&gdev->pin_ranges);
666 #endif
667
668         if (gc->names)
669                 ret = gpiochip_set_desc_names(gc);
670         else
671                 ret = devprop_gpiochip_set_names(gc);
672         if (ret)
673                 goto err_remove_from_list;
674
675         ret = gpiochip_alloc_valid_mask(gc);
676         if (ret)
677                 goto err_remove_from_list;
678
679         ret = of_gpiochip_add(gc);
680         if (ret)
681                 goto err_free_gpiochip_mask;
682
683         ret = gpiochip_init_valid_mask(gc);
684         if (ret)
685                 goto err_remove_of_chip;
686
687         for (i = 0; i < gc->ngpio; i++) {
688                 struct gpio_desc *desc = &gdev->descs[i];
689
690                 if (gc->get_direction && gpiochip_line_is_valid(gc, i)) {
691                         assign_bit(FLAG_IS_OUT,
692                                    &desc->flags, !gc->get_direction(gc, i));
693                 } else {
694                         assign_bit(FLAG_IS_OUT,
695                                    &desc->flags, !gc->direction_input);
696                 }
697         }
698
699         ret = gpiochip_add_pin_ranges(gc);
700         if (ret)
701                 goto err_remove_of_chip;
702
703         acpi_gpiochip_add(gc);
704
705         machine_gpiochip_add(gc);
706
707         ret = gpiochip_irqchip_init_valid_mask(gc);
708         if (ret)
709                 goto err_remove_acpi_chip;
710
711         ret = gpiochip_irqchip_init_hw(gc);
712         if (ret)
713                 goto err_remove_acpi_chip;
714
715         ret = gpiochip_add_irqchip(gc, lock_key, request_key);
716         if (ret)
717                 goto err_remove_irqchip_mask;
718
719         /*
720          * By first adding the chardev, and then adding the device,
721          * we get a device node entry in sysfs under
722          * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
723          * coldplug of device nodes and other udev business.
724          * We can do this only if gpiolib has been initialized.
725          * Otherwise, defer until later.
726          */
727         if (gpiolib_initialized) {
728                 ret = gpiochip_setup_dev(gdev);
729                 if (ret)
730                         goto err_remove_irqchip;
731         }
732         return 0;
733
734 err_remove_irqchip:
735         gpiochip_irqchip_remove(gc);
736 err_remove_irqchip_mask:
737         gpiochip_irqchip_free_valid_mask(gc);
738 err_remove_acpi_chip:
739         acpi_gpiochip_remove(gc);
740 err_remove_of_chip:
741         gpiochip_free_hogs(gc);
742         of_gpiochip_remove(gc);
743 err_free_gpiochip_mask:
744         gpiochip_remove_pin_ranges(gc);
745         gpiochip_free_valid_mask(gc);
746 err_remove_from_list:
747         spin_lock_irqsave(&gpio_lock, flags);
748         list_del(&gdev->list);
749         spin_unlock_irqrestore(&gpio_lock, flags);
750 err_free_label:
751         kfree_const(gdev->label);
752 err_free_descs:
753         kfree(gdev->descs);
754 err_free_ida:
755         ida_free(&gpio_ida, gdev->id);
756 err_free_gdev:
757         /* failures here can mean systems won't boot... */
758         pr_err("%s: GPIOs %d..%d (%s) failed to register, %d\n", __func__,
759                gdev->base, gdev->base + gdev->ngpio - 1,
760                gc->label ? : "generic", ret);
761         kfree(gdev);
762         return ret;
763 }
764 EXPORT_SYMBOL_GPL(gpiochip_add_data_with_key);
765
766 /**
767  * gpiochip_get_data() - get per-subdriver data for the chip
768  * @gc: GPIO chip
769  *
770  * Returns:
771  * The per-subdriver data for the chip.
772  */
773 void *gpiochip_get_data(struct gpio_chip *gc)
774 {
775         return gc->gpiodev->data;
776 }
777 EXPORT_SYMBOL_GPL(gpiochip_get_data);
778
779 /**
780  * gpiochip_remove() - unregister a gpio_chip
781  * @gc: the chip to unregister
782  *
783  * A gpio_chip with any GPIOs still requested may not be removed.
784  */
785 void gpiochip_remove(struct gpio_chip *gc)
786 {
787         struct gpio_device *gdev = gc->gpiodev;
788         unsigned long   flags;
789         unsigned int    i;
790
791         /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
792         gpiochip_sysfs_unregister(gdev);
793         gpiochip_free_hogs(gc);
794         /* Numb the device, cancelling all outstanding operations */
795         gdev->chip = NULL;
796         gpiochip_irqchip_remove(gc);
797         acpi_gpiochip_remove(gc);
798         of_gpiochip_remove(gc);
799         gpiochip_remove_pin_ranges(gc);
800         gpiochip_free_valid_mask(gc);
801         /*
802          * We accept no more calls into the driver from this point, so
803          * NULL the driver data pointer
804          */
805         gdev->data = NULL;
806
807         spin_lock_irqsave(&gpio_lock, flags);
808         for (i = 0; i < gdev->ngpio; i++) {
809                 if (gpiochip_is_requested(gc, i))
810                         break;
811         }
812         spin_unlock_irqrestore(&gpio_lock, flags);
813
814         if (i != gdev->ngpio)
815                 dev_crit(&gdev->dev,
816                          "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
817
818         /*
819          * The gpiochip side puts its use of the device to rest here:
820          * if there are no userspace clients, the chardev and device will
821          * be removed, else it will be dangling until the last user is
822          * gone.
823          */
824         gpiolib_cdev_unregister(gdev);
825         put_device(&gdev->dev);
826 }
827 EXPORT_SYMBOL_GPL(gpiochip_remove);
828
829 /**
830  * gpiochip_find() - iterator for locating a specific gpio_chip
831  * @data: data to pass to match function
832  * @match: Callback function to check gpio_chip
833  *
834  * Similar to bus_find_device.  It returns a reference to a gpio_chip as
835  * determined by a user supplied @match callback.  The callback should return
836  * 0 if the device doesn't match and non-zero if it does.  If the callback is
837  * non-zero, this function will return to the caller and not iterate over any
838  * more gpio_chips.
839  */
840 struct gpio_chip *gpiochip_find(void *data,
841                                 int (*match)(struct gpio_chip *gc,
842                                              void *data))
843 {
844         struct gpio_device *gdev;
845         struct gpio_chip *gc = NULL;
846         unsigned long flags;
847
848         spin_lock_irqsave(&gpio_lock, flags);
849         list_for_each_entry(gdev, &gpio_devices, list)
850                 if (gdev->chip && match(gdev->chip, data)) {
851                         gc = gdev->chip;
852                         break;
853                 }
854
855         spin_unlock_irqrestore(&gpio_lock, flags);
856
857         return gc;
858 }
859 EXPORT_SYMBOL_GPL(gpiochip_find);
860
861 static int gpiochip_match_name(struct gpio_chip *gc, void *data)
862 {
863         const char *name = data;
864
865         return !strcmp(gc->label, name);
866 }
867
868 static struct gpio_chip *find_chip_by_name(const char *name)
869 {
870         return gpiochip_find((void *)name, gpiochip_match_name);
871 }
872
873 #ifdef CONFIG_GPIOLIB_IRQCHIP
874
875 /*
876  * The following is irqchip helper code for gpiochips.
877  */
878
879 static int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
880 {
881         struct gpio_irq_chip *girq = &gc->irq;
882
883         if (!girq->init_hw)
884                 return 0;
885
886         return girq->init_hw(gc);
887 }
888
889 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
890 {
891         struct gpio_irq_chip *girq = &gc->irq;
892
893         if (!girq->init_valid_mask)
894                 return 0;
895
896         girq->valid_mask = gpiochip_allocate_mask(gc);
897         if (!girq->valid_mask)
898                 return -ENOMEM;
899
900         girq->init_valid_mask(gc, girq->valid_mask, gc->ngpio);
901
902         return 0;
903 }
904
905 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc)
906 {
907         bitmap_free(gc->irq.valid_mask);
908         gc->irq.valid_mask = NULL;
909 }
910
911 bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gc,
912                                 unsigned int offset)
913 {
914         if (!gpiochip_line_is_valid(gc, offset))
915                 return false;
916         /* No mask means all valid */
917         if (likely(!gc->irq.valid_mask))
918                 return true;
919         return test_bit(offset, gc->irq.valid_mask);
920 }
921 EXPORT_SYMBOL_GPL(gpiochip_irqchip_irq_valid);
922
923 /**
924  * gpiochip_set_cascaded_irqchip() - connects a cascaded irqchip to a gpiochip
925  * @gc: the gpiochip to set the irqchip chain to
926  * @parent_irq: the irq number corresponding to the parent IRQ for this
927  * cascaded irqchip
928  * @parent_handler: the parent interrupt handler for the accumulated IRQ
929  * coming out of the gpiochip. If the interrupt is nested rather than
930  * cascaded, pass NULL in this handler argument
931  */
932 static void gpiochip_set_cascaded_irqchip(struct gpio_chip *gc,
933                                           unsigned int parent_irq,
934                                           irq_flow_handler_t parent_handler)
935 {
936         struct gpio_irq_chip *girq = &gc->irq;
937         struct device *dev = &gc->gpiodev->dev;
938
939         if (!girq->domain) {
940                 chip_err(gc, "called %s before setting up irqchip\n",
941                          __func__);
942                 return;
943         }
944
945         if (parent_handler) {
946                 if (gc->can_sleep) {
947                         chip_err(gc,
948                                  "you cannot have chained interrupts on a chip that may sleep\n");
949                         return;
950                 }
951                 girq->parents = devm_kcalloc(dev, 1,
952                                              sizeof(*girq->parents),
953                                              GFP_KERNEL);
954                 if (!girq->parents) {
955                         chip_err(gc, "out of memory allocating parent IRQ\n");
956                         return;
957                 }
958                 girq->parents[0] = parent_irq;
959                 girq->num_parents = 1;
960                 /*
961                  * The parent irqchip is already using the chip_data for this
962                  * irqchip, so our callbacks simply use the handler_data.
963                  */
964                 irq_set_chained_handler_and_data(parent_irq, parent_handler,
965                                                  gc);
966         }
967 }
968
969 /**
970  * gpiochip_set_nested_irqchip() - connects a nested irqchip to a gpiochip
971  * @gc: the gpiochip to set the irqchip nested handler to
972  * @irqchip: the irqchip to nest to the gpiochip
973  * @parent_irq: the irq number corresponding to the parent IRQ for this
974  * nested irqchip
975  */
976 void gpiochip_set_nested_irqchip(struct gpio_chip *gc,
977                                  struct irq_chip *irqchip,
978                                  unsigned int parent_irq)
979 {
980         gpiochip_set_cascaded_irqchip(gc, parent_irq, NULL);
981 }
982 EXPORT_SYMBOL_GPL(gpiochip_set_nested_irqchip);
983
984 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
985
986 /**
987  * gpiochip_set_hierarchical_irqchip() - connects a hierarchical irqchip
988  * to a gpiochip
989  * @gc: the gpiochip to set the irqchip hierarchical handler to
990  * @irqchip: the irqchip to handle this level of the hierarchy, the interrupt
991  * will then percolate up to the parent
992  */
993 static void gpiochip_set_hierarchical_irqchip(struct gpio_chip *gc,
994                                               struct irq_chip *irqchip)
995 {
996         /* DT will deal with mapping each IRQ as we go along */
997         if (is_of_node(gc->irq.fwnode))
998                 return;
999
1000         /*
1001          * This is for legacy and boardfile "irqchip" fwnodes: allocate
1002          * irqs upfront instead of dynamically since we don't have the
1003          * dynamic type of allocation that hardware description languages
1004          * provide. Once all GPIO drivers using board files are gone from
1005          * the kernel we can delete this code, but for a transitional period
1006          * it is necessary to keep this around.
1007          */
1008         if (is_fwnode_irqchip(gc->irq.fwnode)) {
1009                 int i;
1010                 int ret;
1011
1012                 for (i = 0; i < gc->ngpio; i++) {
1013                         struct irq_fwspec fwspec;
1014                         unsigned int parent_hwirq;
1015                         unsigned int parent_type;
1016                         struct gpio_irq_chip *girq = &gc->irq;
1017
1018                         /*
1019                          * We call the child to parent translation function
1020                          * only to check if the child IRQ is valid or not.
1021                          * Just pick the rising edge type here as that is what
1022                          * we likely need to support.
1023                          */
1024                         ret = girq->child_to_parent_hwirq(gc, i,
1025                                                           IRQ_TYPE_EDGE_RISING,
1026                                                           &parent_hwirq,
1027                                                           &parent_type);
1028                         if (ret) {
1029                                 chip_err(gc, "skip set-up on hwirq %d\n",
1030                                          i);
1031                                 continue;
1032                         }
1033
1034                         fwspec.fwnode = gc->irq.fwnode;
1035                         /* This is the hwirq for the GPIO line side of things */
1036                         fwspec.param[0] = girq->child_offset_to_irq(gc, i);
1037                         /* Just pick something */
1038                         fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
1039                         fwspec.param_count = 2;
1040                         ret = __irq_domain_alloc_irqs(gc->irq.domain,
1041                                                       /* just pick something */
1042                                                       -1,
1043                                                       1,
1044                                                       NUMA_NO_NODE,
1045                                                       &fwspec,
1046                                                       false,
1047                                                       NULL);
1048                         if (ret < 0) {
1049                                 chip_err(gc,
1050                                          "can not allocate irq for GPIO line %d parent hwirq %d in hierarchy domain: %d\n",
1051                                          i, parent_hwirq,
1052                                          ret);
1053                         }
1054                 }
1055         }
1056
1057         chip_err(gc, "%s unknown fwnode type proceed anyway\n", __func__);
1058
1059         return;
1060 }
1061
1062 static int gpiochip_hierarchy_irq_domain_translate(struct irq_domain *d,
1063                                                    struct irq_fwspec *fwspec,
1064                                                    unsigned long *hwirq,
1065                                                    unsigned int *type)
1066 {
1067         /* We support standard DT translation */
1068         if (is_of_node(fwspec->fwnode) && fwspec->param_count == 2) {
1069                 return irq_domain_translate_twocell(d, fwspec, hwirq, type);
1070         }
1071
1072         /* This is for board files and others not using DT */
1073         if (is_fwnode_irqchip(fwspec->fwnode)) {
1074                 int ret;
1075
1076                 ret = irq_domain_translate_twocell(d, fwspec, hwirq, type);
1077                 if (ret)
1078                         return ret;
1079                 WARN_ON(*type == IRQ_TYPE_NONE);
1080                 return 0;
1081         }
1082         return -EINVAL;
1083 }
1084
1085 static int gpiochip_hierarchy_irq_domain_alloc(struct irq_domain *d,
1086                                                unsigned int irq,
1087                                                unsigned int nr_irqs,
1088                                                void *data)
1089 {
1090         struct gpio_chip *gc = d->host_data;
1091         irq_hw_number_t hwirq;
1092         unsigned int type = IRQ_TYPE_NONE;
1093         struct irq_fwspec *fwspec = data;
1094         void *parent_arg;
1095         unsigned int parent_hwirq;
1096         unsigned int parent_type;
1097         struct gpio_irq_chip *girq = &gc->irq;
1098         int ret;
1099
1100         /*
1101          * The nr_irqs parameter is always one except for PCI multi-MSI
1102          * so this should not happen.
1103          */
1104         WARN_ON(nr_irqs != 1);
1105
1106         ret = gc->irq.child_irq_domain_ops.translate(d, fwspec, &hwirq, &type);
1107         if (ret)
1108                 return ret;
1109
1110         chip_dbg(gc, "allocate IRQ %d, hwirq %lu\n", irq,  hwirq);
1111
1112         ret = girq->child_to_parent_hwirq(gc, hwirq, type,
1113                                           &parent_hwirq, &parent_type);
1114         if (ret) {
1115                 chip_err(gc, "can't look up hwirq %lu\n", hwirq);
1116                 return ret;
1117         }
1118         chip_dbg(gc, "found parent hwirq %u\n", parent_hwirq);
1119
1120         /*
1121          * We set handle_bad_irq because the .set_type() should
1122          * always be invoked and set the right type of handler.
1123          */
1124         irq_domain_set_info(d,
1125                             irq,
1126                             hwirq,
1127                             gc->irq.chip,
1128                             gc,
1129                             girq->handler,
1130                             NULL, NULL);
1131         irq_set_probe(irq);
1132
1133         /* This parent only handles asserted level IRQs */
1134         parent_arg = girq->populate_parent_alloc_arg(gc, parent_hwirq, parent_type);
1135         if (!parent_arg)
1136                 return -ENOMEM;
1137
1138         chip_dbg(gc, "alloc_irqs_parent for %d parent hwirq %d\n",
1139                   irq, parent_hwirq);
1140         irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
1141         ret = irq_domain_alloc_irqs_parent(d, irq, 1, parent_arg);
1142         /*
1143          * If the parent irqdomain is msi, the interrupts have already
1144          * been allocated, so the EEXIST is good.
1145          */
1146         if (irq_domain_is_msi(d->parent) && (ret == -EEXIST))
1147                 ret = 0;
1148         if (ret)
1149                 chip_err(gc,
1150                          "failed to allocate parent hwirq %d for hwirq %lu\n",
1151                          parent_hwirq, hwirq);
1152
1153         kfree(parent_arg);
1154         return ret;
1155 }
1156
1157 static unsigned int gpiochip_child_offset_to_irq_noop(struct gpio_chip *gc,
1158                                                       unsigned int offset)
1159 {
1160         return offset;
1161 }
1162
1163 static void gpiochip_hierarchy_setup_domain_ops(struct irq_domain_ops *ops)
1164 {
1165         ops->activate = gpiochip_irq_domain_activate;
1166         ops->deactivate = gpiochip_irq_domain_deactivate;
1167         ops->alloc = gpiochip_hierarchy_irq_domain_alloc;
1168         ops->free = irq_domain_free_irqs_common;
1169
1170         /*
1171          * We only allow overriding the translate() function for
1172          * hierarchical chips, and this should only be done if the user
1173          * really need something other than 1:1 translation.
1174          */
1175         if (!ops->translate)
1176                 ops->translate = gpiochip_hierarchy_irq_domain_translate;
1177 }
1178
1179 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
1180 {
1181         if (!gc->irq.child_to_parent_hwirq ||
1182             !gc->irq.fwnode) {
1183                 chip_err(gc, "missing irqdomain vital data\n");
1184                 return -EINVAL;
1185         }
1186
1187         if (!gc->irq.child_offset_to_irq)
1188                 gc->irq.child_offset_to_irq = gpiochip_child_offset_to_irq_noop;
1189
1190         if (!gc->irq.populate_parent_alloc_arg)
1191                 gc->irq.populate_parent_alloc_arg =
1192                         gpiochip_populate_parent_fwspec_twocell;
1193
1194         gpiochip_hierarchy_setup_domain_ops(&gc->irq.child_irq_domain_ops);
1195
1196         gc->irq.domain = irq_domain_create_hierarchy(
1197                 gc->irq.parent_domain,
1198                 0,
1199                 gc->ngpio,
1200                 gc->irq.fwnode,
1201                 &gc->irq.child_irq_domain_ops,
1202                 gc);
1203
1204         if (!gc->irq.domain)
1205                 return -ENOMEM;
1206
1207         gpiochip_set_hierarchical_irqchip(gc, gc->irq.chip);
1208
1209         return 0;
1210 }
1211
1212 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
1213 {
1214         return !!gc->irq.parent_domain;
1215 }
1216
1217 void *gpiochip_populate_parent_fwspec_twocell(struct gpio_chip *gc,
1218                                              unsigned int parent_hwirq,
1219                                              unsigned int parent_type)
1220 {
1221         struct irq_fwspec *fwspec;
1222
1223         fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
1224         if (!fwspec)
1225                 return NULL;
1226
1227         fwspec->fwnode = gc->irq.parent_domain->fwnode;
1228         fwspec->param_count = 2;
1229         fwspec->param[0] = parent_hwirq;
1230         fwspec->param[1] = parent_type;
1231
1232         return fwspec;
1233 }
1234 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_twocell);
1235
1236 void *gpiochip_populate_parent_fwspec_fourcell(struct gpio_chip *gc,
1237                                               unsigned int parent_hwirq,
1238                                               unsigned int parent_type)
1239 {
1240         struct irq_fwspec *fwspec;
1241
1242         fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
1243         if (!fwspec)
1244                 return NULL;
1245
1246         fwspec->fwnode = gc->irq.parent_domain->fwnode;
1247         fwspec->param_count = 4;
1248         fwspec->param[0] = 0;
1249         fwspec->param[1] = parent_hwirq;
1250         fwspec->param[2] = 0;
1251         fwspec->param[3] = parent_type;
1252
1253         return fwspec;
1254 }
1255 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_fourcell);
1256
1257 #else
1258
1259 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
1260 {
1261         return -EINVAL;
1262 }
1263
1264 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
1265 {
1266         return false;
1267 }
1268
1269 #endif /* CONFIG_IRQ_DOMAIN_HIERARCHY */
1270
1271 /**
1272  * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
1273  * @d: the irqdomain used by this irqchip
1274  * @irq: the global irq number used by this GPIO irqchip irq
1275  * @hwirq: the local IRQ/GPIO line offset on this gpiochip
1276  *
1277  * This function will set up the mapping for a certain IRQ line on a
1278  * gpiochip by assigning the gpiochip as chip data, and using the irqchip
1279  * stored inside the gpiochip.
1280  */
1281 int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
1282                      irq_hw_number_t hwirq)
1283 {
1284         struct gpio_chip *gc = d->host_data;
1285         int ret = 0;
1286
1287         if (!gpiochip_irqchip_irq_valid(gc, hwirq))
1288                 return -ENXIO;
1289
1290         irq_set_chip_data(irq, gc);
1291         /*
1292          * This lock class tells lockdep that GPIO irqs are in a different
1293          * category than their parents, so it won't report false recursion.
1294          */
1295         irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
1296         irq_set_chip_and_handler(irq, gc->irq.chip, gc->irq.handler);
1297         /* Chips that use nested thread handlers have them marked */
1298         if (gc->irq.threaded)
1299                 irq_set_nested_thread(irq, 1);
1300         irq_set_noprobe(irq);
1301
1302         if (gc->irq.num_parents == 1)
1303                 ret = irq_set_parent(irq, gc->irq.parents[0]);
1304         else if (gc->irq.map)
1305                 ret = irq_set_parent(irq, gc->irq.map[hwirq]);
1306
1307         if (ret < 0)
1308                 return ret;
1309
1310         /*
1311          * No set-up of the hardware will happen if IRQ_TYPE_NONE
1312          * is passed as default type.
1313          */
1314         if (gc->irq.default_type != IRQ_TYPE_NONE)
1315                 irq_set_irq_type(irq, gc->irq.default_type);
1316
1317         return 0;
1318 }
1319 EXPORT_SYMBOL_GPL(gpiochip_irq_map);
1320
1321 void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
1322 {
1323         struct gpio_chip *gc = d->host_data;
1324
1325         if (gc->irq.threaded)
1326                 irq_set_nested_thread(irq, 0);
1327         irq_set_chip_and_handler(irq, NULL, NULL);
1328         irq_set_chip_data(irq, NULL);
1329 }
1330 EXPORT_SYMBOL_GPL(gpiochip_irq_unmap);
1331
1332 static const struct irq_domain_ops gpiochip_domain_ops = {
1333         .map    = gpiochip_irq_map,
1334         .unmap  = gpiochip_irq_unmap,
1335         /* Virtually all GPIO irqchips are twocell:ed */
1336         .xlate  = irq_domain_xlate_twocell,
1337 };
1338
1339 /*
1340  * TODO: move these activate/deactivate in under the hierarchicial
1341  * irqchip implementation as static once SPMI and SSBI (all external
1342  * users) are phased over.
1343  */
1344 /**
1345  * gpiochip_irq_domain_activate() - Lock a GPIO to be used as an IRQ
1346  * @domain: The IRQ domain used by this IRQ chip
1347  * @data: Outermost irq_data associated with the IRQ
1348  * @reserve: If set, only reserve an interrupt vector instead of assigning one
1349  *
1350  * This function is a wrapper that calls gpiochip_lock_as_irq() and is to be
1351  * used as the activate function for the &struct irq_domain_ops. The host_data
1352  * for the IRQ domain must be the &struct gpio_chip.
1353  */
1354 int gpiochip_irq_domain_activate(struct irq_domain *domain,
1355                                  struct irq_data *data, bool reserve)
1356 {
1357         struct gpio_chip *gc = domain->host_data;
1358
1359         return gpiochip_lock_as_irq(gc, data->hwirq);
1360 }
1361 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_activate);
1362
1363 /**
1364  * gpiochip_irq_domain_deactivate() - Unlock a GPIO used as an IRQ
1365  * @domain: The IRQ domain used by this IRQ chip
1366  * @data: Outermost irq_data associated with the IRQ
1367  *
1368  * This function is a wrapper that will call gpiochip_unlock_as_irq() and is to
1369  * be used as the deactivate function for the &struct irq_domain_ops. The
1370  * host_data for the IRQ domain must be the &struct gpio_chip.
1371  */
1372 void gpiochip_irq_domain_deactivate(struct irq_domain *domain,
1373                                     struct irq_data *data)
1374 {
1375         struct gpio_chip *gc = domain->host_data;
1376
1377         return gpiochip_unlock_as_irq(gc, data->hwirq);
1378 }
1379 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_deactivate);
1380
1381 static int gpiochip_to_irq(struct gpio_chip *gc, unsigned offset)
1382 {
1383         struct irq_domain *domain = gc->irq.domain;
1384
1385         if (!gpiochip_irqchip_irq_valid(gc, offset))
1386                 return -ENXIO;
1387
1388 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
1389         if (irq_domain_is_hierarchy(domain)) {
1390                 struct irq_fwspec spec;
1391
1392                 spec.fwnode = domain->fwnode;
1393                 spec.param_count = 2;
1394                 spec.param[0] = gc->irq.child_offset_to_irq(gc, offset);
1395                 spec.param[1] = IRQ_TYPE_NONE;
1396
1397                 return irq_create_fwspec_mapping(&spec);
1398         }
1399 #endif
1400
1401         return irq_create_mapping(domain, offset);
1402 }
1403
1404 static int gpiochip_irq_reqres(struct irq_data *d)
1405 {
1406         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1407
1408         return gpiochip_reqres_irq(gc, d->hwirq);
1409 }
1410
1411 static void gpiochip_irq_relres(struct irq_data *d)
1412 {
1413         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1414
1415         gpiochip_relres_irq(gc, d->hwirq);
1416 }
1417
1418 static void gpiochip_irq_mask(struct irq_data *d)
1419 {
1420         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1421
1422         if (gc->irq.irq_mask)
1423                 gc->irq.irq_mask(d);
1424         gpiochip_disable_irq(gc, d->hwirq);
1425 }
1426
1427 static void gpiochip_irq_unmask(struct irq_data *d)
1428 {
1429         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1430
1431         gpiochip_enable_irq(gc, d->hwirq);
1432         if (gc->irq.irq_unmask)
1433                 gc->irq.irq_unmask(d);
1434 }
1435
1436 static void gpiochip_irq_enable(struct irq_data *d)
1437 {
1438         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1439
1440         gpiochip_enable_irq(gc, d->hwirq);
1441         gc->irq.irq_enable(d);
1442 }
1443
1444 static void gpiochip_irq_disable(struct irq_data *d)
1445 {
1446         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1447
1448         gc->irq.irq_disable(d);
1449         gpiochip_disable_irq(gc, d->hwirq);
1450 }
1451
1452 static void gpiochip_set_irq_hooks(struct gpio_chip *gc)
1453 {
1454         struct irq_chip *irqchip = gc->irq.chip;
1455
1456         if (!irqchip->irq_request_resources &&
1457             !irqchip->irq_release_resources) {
1458                 irqchip->irq_request_resources = gpiochip_irq_reqres;
1459                 irqchip->irq_release_resources = gpiochip_irq_relres;
1460         }
1461         if (WARN_ON(gc->irq.irq_enable))
1462                 return;
1463         /* Check if the irqchip already has this hook... */
1464         if (irqchip->irq_enable == gpiochip_irq_enable) {
1465                 /*
1466                  * ...and if so, give a gentle warning that this is bad
1467                  * practice.
1468                  */
1469                 chip_info(gc,
1470                           "detected irqchip that is shared with multiple gpiochips: please fix the driver.\n");
1471                 return;
1472         }
1473
1474         if (irqchip->irq_disable) {
1475                 gc->irq.irq_disable = irqchip->irq_disable;
1476                 irqchip->irq_disable = gpiochip_irq_disable;
1477         } else {
1478                 gc->irq.irq_mask = irqchip->irq_mask;
1479                 irqchip->irq_mask = gpiochip_irq_mask;
1480         }
1481
1482         if (irqchip->irq_enable) {
1483                 gc->irq.irq_enable = irqchip->irq_enable;
1484                 irqchip->irq_enable = gpiochip_irq_enable;
1485         } else {
1486                 gc->irq.irq_unmask = irqchip->irq_unmask;
1487                 irqchip->irq_unmask = gpiochip_irq_unmask;
1488         }
1489 }
1490
1491 /**
1492  * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
1493  * @gc: the GPIO chip to add the IRQ chip to
1494  * @lock_key: lockdep class for IRQ lock
1495  * @request_key: lockdep class for IRQ request
1496  */
1497 static int gpiochip_add_irqchip(struct gpio_chip *gc,
1498                                 struct lock_class_key *lock_key,
1499                                 struct lock_class_key *request_key)
1500 {
1501         struct irq_chip *irqchip = gc->irq.chip;
1502         const struct irq_domain_ops *ops = NULL;
1503         struct device_node *np;
1504         unsigned int type;
1505         unsigned int i;
1506
1507         if (!irqchip)
1508                 return 0;
1509
1510         if (gc->irq.parent_handler && gc->can_sleep) {
1511                 chip_err(gc, "you cannot have chained interrupts on a chip that may sleep\n");
1512                 return -EINVAL;
1513         }
1514
1515         np = gc->gpiodev->dev.of_node;
1516         type = gc->irq.default_type;
1517
1518         /*
1519          * Specifying a default trigger is a terrible idea if DT or ACPI is
1520          * used to configure the interrupts, as you may end up with
1521          * conflicting triggers. Tell the user, and reset to NONE.
1522          */
1523         if (WARN(np && type != IRQ_TYPE_NONE,
1524                  "%s: Ignoring %u default trigger\n", np->full_name, type))
1525                 type = IRQ_TYPE_NONE;
1526
1527         if (has_acpi_companion(gc->parent) && type != IRQ_TYPE_NONE) {
1528                 acpi_handle_warn(ACPI_HANDLE(gc->parent),
1529                                  "Ignoring %u default trigger\n", type);
1530                 type = IRQ_TYPE_NONE;
1531         }
1532
1533         gc->to_irq = gpiochip_to_irq;
1534         gc->irq.default_type = type;
1535         gc->irq.lock_key = lock_key;
1536         gc->irq.request_key = request_key;
1537
1538         /* If a parent irqdomain is provided, let's build a hierarchy */
1539         if (gpiochip_hierarchy_is_hierarchical(gc)) {
1540                 int ret = gpiochip_hierarchy_add_domain(gc);
1541                 if (ret)
1542                         return ret;
1543         } else {
1544                 /* Some drivers provide custom irqdomain ops */
1545                 if (gc->irq.domain_ops)
1546                         ops = gc->irq.domain_ops;
1547
1548                 if (!ops)
1549                         ops = &gpiochip_domain_ops;
1550                 gc->irq.domain = irq_domain_add_simple(np,
1551                         gc->ngpio,
1552                         gc->irq.first,
1553                         ops, gc);
1554                 if (!gc->irq.domain)
1555                         return -EINVAL;
1556         }
1557
1558         if (gc->irq.parent_handler) {
1559                 void *data = gc->irq.parent_handler_data ?: gc;
1560
1561                 for (i = 0; i < gc->irq.num_parents; i++) {
1562                         /*
1563                          * The parent IRQ chip is already using the chip_data
1564                          * for this IRQ chip, so our callbacks simply use the
1565                          * handler_data.
1566                          */
1567                         irq_set_chained_handler_and_data(gc->irq.parents[i],
1568                                                          gc->irq.parent_handler,
1569                                                          data);
1570                 }
1571         }
1572
1573         gpiochip_set_irq_hooks(gc);
1574
1575         acpi_gpiochip_request_interrupts(gc);
1576
1577         return 0;
1578 }
1579
1580 /**
1581  * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
1582  * @gc: the gpiochip to remove the irqchip from
1583  *
1584  * This is called only from gpiochip_remove()
1585  */
1586 static void gpiochip_irqchip_remove(struct gpio_chip *gc)
1587 {
1588         struct irq_chip *irqchip = gc->irq.chip;
1589         unsigned int offset;
1590
1591         acpi_gpiochip_free_interrupts(gc);
1592
1593         if (irqchip && gc->irq.parent_handler) {
1594                 struct gpio_irq_chip *irq = &gc->irq;
1595                 unsigned int i;
1596
1597                 for (i = 0; i < irq->num_parents; i++)
1598                         irq_set_chained_handler_and_data(irq->parents[i],
1599                                                          NULL, NULL);
1600         }
1601
1602         /* Remove all IRQ mappings and delete the domain */
1603         if (gc->irq.domain) {
1604                 unsigned int irq;
1605
1606                 for (offset = 0; offset < gc->ngpio; offset++) {
1607                         if (!gpiochip_irqchip_irq_valid(gc, offset))
1608                                 continue;
1609
1610                         irq = irq_find_mapping(gc->irq.domain, offset);
1611                         irq_dispose_mapping(irq);
1612                 }
1613
1614                 irq_domain_remove(gc->irq.domain);
1615         }
1616
1617         if (irqchip) {
1618                 if (irqchip->irq_request_resources == gpiochip_irq_reqres) {
1619                         irqchip->irq_request_resources = NULL;
1620                         irqchip->irq_release_resources = NULL;
1621                 }
1622                 if (irqchip->irq_enable == gpiochip_irq_enable) {
1623                         irqchip->irq_enable = gc->irq.irq_enable;
1624                         irqchip->irq_disable = gc->irq.irq_disable;
1625                 }
1626         }
1627         gc->irq.irq_enable = NULL;
1628         gc->irq.irq_disable = NULL;
1629         gc->irq.chip = NULL;
1630
1631         gpiochip_irqchip_free_valid_mask(gc);
1632 }
1633
1634 /**
1635  * gpiochip_irqchip_add_key() - adds an irqchip to a gpiochip
1636  * @gc: the gpiochip to add the irqchip to
1637  * @irqchip: the irqchip to add to the gpiochip
1638  * @first_irq: if not dynamically assigned, the base (first) IRQ to
1639  * allocate gpiochip irqs from
1640  * @handler: the irq handler to use (often a predefined irq core function)
1641  * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
1642  * to have the core avoid setting up any default type in the hardware.
1643  * @threaded: whether this irqchip uses a nested thread handler
1644  * @lock_key: lockdep class for IRQ lock
1645  * @request_key: lockdep class for IRQ request
1646  *
1647  * This function closely associates a certain irqchip with a certain
1648  * gpiochip, providing an irq domain to translate the local IRQs to
1649  * global irqs in the gpiolib core, and making sure that the gpiochip
1650  * is passed as chip data to all related functions. Driver callbacks
1651  * need to use gpiochip_get_data() to get their local state containers back
1652  * from the gpiochip passed as chip data. An irqdomain will be stored
1653  * in the gpiochip that shall be used by the driver to handle IRQ number
1654  * translation. The gpiochip will need to be initialized and registered
1655  * before calling this function.
1656  *
1657  * This function will handle two cell:ed simple IRQs and assumes all
1658  * the pins on the gpiochip can generate a unique IRQ. Everything else
1659  * need to be open coded.
1660  */
1661 int gpiochip_irqchip_add_key(struct gpio_chip *gc,
1662                              struct irq_chip *irqchip,
1663                              unsigned int first_irq,
1664                              irq_flow_handler_t handler,
1665                              unsigned int type,
1666                              bool threaded,
1667                              struct lock_class_key *lock_key,
1668                              struct lock_class_key *request_key)
1669 {
1670         struct device_node *of_node;
1671
1672         if (!gc || !irqchip)
1673                 return -EINVAL;
1674
1675         if (!gc->parent) {
1676                 chip_err(gc, "missing gpiochip .dev parent pointer\n");
1677                 return -EINVAL;
1678         }
1679         gc->irq.threaded = threaded;
1680         of_node = gc->parent->of_node;
1681 #ifdef CONFIG_OF_GPIO
1682         /*
1683          * If the gpiochip has an assigned OF node this takes precedence
1684          * FIXME: get rid of this and use gc->parent->of_node
1685          * everywhere
1686          */
1687         if (gc->of_node)
1688                 of_node = gc->of_node;
1689 #endif
1690         /*
1691          * Specifying a default trigger is a terrible idea if DT or ACPI is
1692          * used to configure the interrupts, as you may end-up with
1693          * conflicting triggers. Tell the user, and reset to NONE.
1694          */
1695         if (WARN(of_node && type != IRQ_TYPE_NONE,
1696                  "%pOF: Ignoring %d default trigger\n", of_node, type))
1697                 type = IRQ_TYPE_NONE;
1698         if (has_acpi_companion(gc->parent) && type != IRQ_TYPE_NONE) {
1699                 acpi_handle_warn(ACPI_HANDLE(gc->parent),
1700                                  "Ignoring %d default trigger\n", type);
1701                 type = IRQ_TYPE_NONE;
1702         }
1703
1704         gc->irq.chip = irqchip;
1705         gc->irq.handler = handler;
1706         gc->irq.default_type = type;
1707         gc->to_irq = gpiochip_to_irq;
1708         gc->irq.lock_key = lock_key;
1709         gc->irq.request_key = request_key;
1710         gc->irq.domain = irq_domain_add_simple(of_node,
1711                                         gc->ngpio, first_irq,
1712                                         &gpiochip_domain_ops, gc);
1713         if (!gc->irq.domain) {
1714                 gc->irq.chip = NULL;
1715                 return -EINVAL;
1716         }
1717
1718         gpiochip_set_irq_hooks(gc);
1719
1720         acpi_gpiochip_request_interrupts(gc);
1721
1722         return 0;
1723 }
1724 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_key);
1725
1726 /**
1727  * gpiochip_irqchip_add_domain() - adds an irqdomain to a gpiochip
1728  * @gc: the gpiochip to add the irqchip to
1729  * @domain: the irqdomain to add to the gpiochip
1730  *
1731  * This function adds an IRQ domain to the gpiochip.
1732  */
1733 int gpiochip_irqchip_add_domain(struct gpio_chip *gc,
1734                                 struct irq_domain *domain)
1735 {
1736         if (!domain)
1737                 return -EINVAL;
1738
1739         gc->to_irq = gpiochip_to_irq;
1740         gc->irq.domain = domain;
1741
1742         return 0;
1743 }
1744 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_domain);
1745
1746 #else /* CONFIG_GPIOLIB_IRQCHIP */
1747
1748 static inline int gpiochip_add_irqchip(struct gpio_chip *gc,
1749                                        struct lock_class_key *lock_key,
1750                                        struct lock_class_key *request_key)
1751 {
1752         return 0;
1753 }
1754 static void gpiochip_irqchip_remove(struct gpio_chip *gc) {}
1755
1756 static inline int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
1757 {
1758         return 0;
1759 }
1760
1761 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
1762 {
1763         return 0;
1764 }
1765 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc)
1766 { }
1767
1768 #endif /* CONFIG_GPIOLIB_IRQCHIP */
1769
1770 /**
1771  * gpiochip_generic_request() - request the gpio function for a pin
1772  * @gc: the gpiochip owning the GPIO
1773  * @offset: the offset of the GPIO to request for GPIO function
1774  */
1775 int gpiochip_generic_request(struct gpio_chip *gc, unsigned offset)
1776 {
1777 #ifdef CONFIG_PINCTRL
1778         if (list_empty(&gc->gpiodev->pin_ranges))
1779                 return 0;
1780 #endif
1781
1782         return pinctrl_gpio_request(gc->gpiodev->base + offset);
1783 }
1784 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
1785
1786 /**
1787  * gpiochip_generic_free() - free the gpio function from a pin
1788  * @gc: the gpiochip to request the gpio function for
1789  * @offset: the offset of the GPIO to free from GPIO function
1790  */
1791 void gpiochip_generic_free(struct gpio_chip *gc, unsigned offset)
1792 {
1793         pinctrl_gpio_free(gc->gpiodev->base + offset);
1794 }
1795 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
1796
1797 /**
1798  * gpiochip_generic_config() - apply configuration for a pin
1799  * @gc: the gpiochip owning the GPIO
1800  * @offset: the offset of the GPIO to apply the configuration
1801  * @config: the configuration to be applied
1802  */
1803 int gpiochip_generic_config(struct gpio_chip *gc, unsigned offset,
1804                             unsigned long config)
1805 {
1806         return pinctrl_gpio_set_config(gc->gpiodev->base + offset, config);
1807 }
1808 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
1809
1810 #ifdef CONFIG_PINCTRL
1811
1812 /**
1813  * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
1814  * @gc: the gpiochip to add the range for
1815  * @pctldev: the pin controller to map to
1816  * @gpio_offset: the start offset in the current gpio_chip number space
1817  * @pin_group: name of the pin group inside the pin controller
1818  *
1819  * Calling this function directly from a DeviceTree-supported
1820  * pinctrl driver is DEPRECATED. Please see Section 2.1 of
1821  * Documentation/devicetree/bindings/gpio/gpio.txt on how to
1822  * bind pinctrl and gpio drivers via the "gpio-ranges" property.
1823  */
1824 int gpiochip_add_pingroup_range(struct gpio_chip *gc,
1825                         struct pinctrl_dev *pctldev,
1826                         unsigned int gpio_offset, const char *pin_group)
1827 {
1828         struct gpio_pin_range *pin_range;
1829         struct gpio_device *gdev = gc->gpiodev;
1830         int ret;
1831
1832         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1833         if (!pin_range) {
1834                 chip_err(gc, "failed to allocate pin ranges\n");
1835                 return -ENOMEM;
1836         }
1837
1838         /* Use local offset as range ID */
1839         pin_range->range.id = gpio_offset;
1840         pin_range->range.gc = gc;
1841         pin_range->range.name = gc->label;
1842         pin_range->range.base = gdev->base + gpio_offset;
1843         pin_range->pctldev = pctldev;
1844
1845         ret = pinctrl_get_group_pins(pctldev, pin_group,
1846                                         &pin_range->range.pins,
1847                                         &pin_range->range.npins);
1848         if (ret < 0) {
1849                 kfree(pin_range);
1850                 return ret;
1851         }
1852
1853         pinctrl_add_gpio_range(pctldev, &pin_range->range);
1854
1855         chip_dbg(gc, "created GPIO range %d->%d ==> %s PINGRP %s\n",
1856                  gpio_offset, gpio_offset + pin_range->range.npins - 1,
1857                  pinctrl_dev_get_devname(pctldev), pin_group);
1858
1859         list_add_tail(&pin_range->node, &gdev->pin_ranges);
1860
1861         return 0;
1862 }
1863 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
1864
1865 /**
1866  * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
1867  * @gc: the gpiochip to add the range for
1868  * @pinctl_name: the dev_name() of the pin controller to map to
1869  * @gpio_offset: the start offset in the current gpio_chip number space
1870  * @pin_offset: the start offset in the pin controller number space
1871  * @npins: the number of pins from the offset of each pin space (GPIO and
1872  *      pin controller) to accumulate in this range
1873  *
1874  * Returns:
1875  * 0 on success, or a negative error-code on failure.
1876  *
1877  * Calling this function directly from a DeviceTree-supported
1878  * pinctrl driver is DEPRECATED. Please see Section 2.1 of
1879  * Documentation/devicetree/bindings/gpio/gpio.txt on how to
1880  * bind pinctrl and gpio drivers via the "gpio-ranges" property.
1881  */
1882 int gpiochip_add_pin_range(struct gpio_chip *gc, const char *pinctl_name,
1883                            unsigned int gpio_offset, unsigned int pin_offset,
1884                            unsigned int npins)
1885 {
1886         struct gpio_pin_range *pin_range;
1887         struct gpio_device *gdev = gc->gpiodev;
1888         int ret;
1889
1890         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1891         if (!pin_range) {
1892                 chip_err(gc, "failed to allocate pin ranges\n");
1893                 return -ENOMEM;
1894         }
1895
1896         /* Use local offset as range ID */
1897         pin_range->range.id = gpio_offset;
1898         pin_range->range.gc = gc;
1899         pin_range->range.name = gc->label;
1900         pin_range->range.base = gdev->base + gpio_offset;
1901         pin_range->range.pin_base = pin_offset;
1902         pin_range->range.npins = npins;
1903         pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
1904                         &pin_range->range);
1905         if (IS_ERR(pin_range->pctldev)) {
1906                 ret = PTR_ERR(pin_range->pctldev);
1907                 chip_err(gc, "could not create pin range\n");
1908                 kfree(pin_range);
1909                 return ret;
1910         }
1911         chip_dbg(gc, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
1912                  gpio_offset, gpio_offset + npins - 1,
1913                  pinctl_name,
1914                  pin_offset, pin_offset + npins - 1);
1915
1916         list_add_tail(&pin_range->node, &gdev->pin_ranges);
1917
1918         return 0;
1919 }
1920 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
1921
1922 /**
1923  * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
1924  * @gc: the chip to remove all the mappings for
1925  */
1926 void gpiochip_remove_pin_ranges(struct gpio_chip *gc)
1927 {
1928         struct gpio_pin_range *pin_range, *tmp;
1929         struct gpio_device *gdev = gc->gpiodev;
1930
1931         list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
1932                 list_del(&pin_range->node);
1933                 pinctrl_remove_gpio_range(pin_range->pctldev,
1934                                 &pin_range->range);
1935                 kfree(pin_range);
1936         }
1937 }
1938 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
1939
1940 #endif /* CONFIG_PINCTRL */
1941
1942 /* These "optional" allocation calls help prevent drivers from stomping
1943  * on each other, and help provide better diagnostics in debugfs.
1944  * They're called even less than the "set direction" calls.
1945  */
1946 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
1947 {
1948         struct gpio_chip        *gc = desc->gdev->chip;
1949         int                     ret;
1950         unsigned long           flags;
1951         unsigned                offset;
1952
1953         if (label) {
1954                 label = kstrdup_const(label, GFP_KERNEL);
1955                 if (!label)
1956                         return -ENOMEM;
1957         }
1958
1959         spin_lock_irqsave(&gpio_lock, flags);
1960
1961         /* NOTE:  gpio_request() can be called in early boot,
1962          * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
1963          */
1964
1965         if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
1966                 desc_set_label(desc, label ? : "?");
1967                 ret = 0;
1968         } else {
1969                 kfree_const(label);
1970                 ret = -EBUSY;
1971                 goto done;
1972         }
1973
1974         if (gc->request) {
1975                 /* gc->request may sleep */
1976                 spin_unlock_irqrestore(&gpio_lock, flags);
1977                 offset = gpio_chip_hwgpio(desc);
1978                 if (gpiochip_line_is_valid(gc, offset))
1979                         ret = gc->request(gc, offset);
1980                 else
1981                         ret = -EINVAL;
1982                 spin_lock_irqsave(&gpio_lock, flags);
1983
1984                 if (ret < 0) {
1985                         desc_set_label(desc, NULL);
1986                         kfree_const(label);
1987                         clear_bit(FLAG_REQUESTED, &desc->flags);
1988                         goto done;
1989                 }
1990         }
1991         if (gc->get_direction) {
1992                 /* gc->get_direction may sleep */
1993                 spin_unlock_irqrestore(&gpio_lock, flags);
1994                 gpiod_get_direction(desc);
1995                 spin_lock_irqsave(&gpio_lock, flags);
1996         }
1997 done:
1998         spin_unlock_irqrestore(&gpio_lock, flags);
1999         return ret;
2000 }
2001
2002 /*
2003  * This descriptor validation needs to be inserted verbatim into each
2004  * function taking a descriptor, so we need to use a preprocessor
2005  * macro to avoid endless duplication. If the desc is NULL it is an
2006  * optional GPIO and calls should just bail out.
2007  */
2008 static int validate_desc(const struct gpio_desc *desc, const char *func)
2009 {
2010         if (!desc)
2011                 return 0;
2012         if (IS_ERR(desc)) {
2013                 pr_warn("%s: invalid GPIO (errorpointer)\n", func);
2014                 return PTR_ERR(desc);
2015         }
2016         if (!desc->gdev) {
2017                 pr_warn("%s: invalid GPIO (no device)\n", func);
2018                 return -EINVAL;
2019         }
2020         if (!desc->gdev->chip) {
2021                 dev_warn(&desc->gdev->dev,
2022                          "%s: backing chip is gone\n", func);
2023                 return 0;
2024         }
2025         return 1;
2026 }
2027
2028 #define VALIDATE_DESC(desc) do { \
2029         int __valid = validate_desc(desc, __func__); \
2030         if (__valid <= 0) \
2031                 return __valid; \
2032         } while (0)
2033
2034 #define VALIDATE_DESC_VOID(desc) do { \
2035         int __valid = validate_desc(desc, __func__); \
2036         if (__valid <= 0) \
2037                 return; \
2038         } while (0)
2039
2040 int gpiod_request(struct gpio_desc *desc, const char *label)
2041 {
2042         int ret = -EPROBE_DEFER;
2043         struct gpio_device *gdev;
2044
2045         VALIDATE_DESC(desc);
2046         gdev = desc->gdev;
2047
2048         if (try_module_get(gdev->owner)) {
2049                 ret = gpiod_request_commit(desc, label);
2050                 if (ret < 0)
2051                         module_put(gdev->owner);
2052                 else
2053                         get_device(&gdev->dev);
2054         }
2055
2056         if (ret)
2057                 gpiod_dbg(desc, "%s: status %d\n", __func__, ret);
2058
2059         return ret;
2060 }
2061
2062 static bool gpiod_free_commit(struct gpio_desc *desc)
2063 {
2064         bool                    ret = false;
2065         unsigned long           flags;
2066         struct gpio_chip        *gc;
2067
2068         might_sleep();
2069
2070         gpiod_unexport(desc);
2071
2072         spin_lock_irqsave(&gpio_lock, flags);
2073
2074         gc = desc->gdev->chip;
2075         if (gc && test_bit(FLAG_REQUESTED, &desc->flags)) {
2076                 if (gc->free) {
2077                         spin_unlock_irqrestore(&gpio_lock, flags);
2078                         might_sleep_if(gc->can_sleep);
2079                         gc->free(gc, gpio_chip_hwgpio(desc));
2080                         spin_lock_irqsave(&gpio_lock, flags);
2081                 }
2082                 kfree_const(desc->label);
2083                 desc_set_label(desc, NULL);
2084                 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
2085                 clear_bit(FLAG_REQUESTED, &desc->flags);
2086                 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
2087                 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
2088                 clear_bit(FLAG_PULL_UP, &desc->flags);
2089                 clear_bit(FLAG_PULL_DOWN, &desc->flags);
2090                 clear_bit(FLAG_BIAS_DISABLE, &desc->flags);
2091                 clear_bit(FLAG_IS_HOGGED, &desc->flags);
2092 #ifdef CONFIG_OF_DYNAMIC
2093                 desc->hog = NULL;
2094 #endif
2095                 ret = true;
2096         }
2097
2098         spin_unlock_irqrestore(&gpio_lock, flags);
2099         blocking_notifier_call_chain(&desc->gdev->notifier,
2100                                      GPIOLINE_CHANGED_RELEASED, desc);
2101
2102         return ret;
2103 }
2104
2105 void gpiod_free(struct gpio_desc *desc)
2106 {
2107         if (desc && desc->gdev && gpiod_free_commit(desc)) {
2108                 module_put(desc->gdev->owner);
2109                 put_device(&desc->gdev->dev);
2110         } else {
2111                 WARN_ON(extra_checks);
2112         }
2113 }
2114
2115 /**
2116  * gpiochip_is_requested - return string iff signal was requested
2117  * @gc: controller managing the signal
2118  * @offset: of signal within controller's 0..(ngpio - 1) range
2119  *
2120  * Returns NULL if the GPIO is not currently requested, else a string.
2121  * The string returned is the label passed to gpio_request(); if none has been
2122  * passed it is a meaningless, non-NULL constant.
2123  *
2124  * This function is for use by GPIO controller drivers.  The label can
2125  * help with diagnostics, and knowing that the signal is used as a GPIO
2126  * can help avoid accidentally multiplexing it to another controller.
2127  */
2128 const char *gpiochip_is_requested(struct gpio_chip *gc, unsigned offset)
2129 {
2130         struct gpio_desc *desc;
2131
2132         if (offset >= gc->ngpio)
2133                 return NULL;
2134
2135         desc = gpiochip_get_desc(gc, offset);
2136         if (IS_ERR(desc))
2137                 return NULL;
2138
2139         if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
2140                 return NULL;
2141         return desc->label;
2142 }
2143 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
2144
2145 /**
2146  * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2147  * @gc: GPIO chip
2148  * @hwnum: hardware number of the GPIO for which to request the descriptor
2149  * @label: label for the GPIO
2150  * @lflags: lookup flags for this GPIO or 0 if default, this can be used to
2151  * specify things like line inversion semantics with the machine flags
2152  * such as GPIO_OUT_LOW
2153  * @dflags: descriptor request flags for this GPIO or 0 if default, this
2154  * can be used to specify consumer semantics such as open drain
2155  *
2156  * Function allows GPIO chip drivers to request and use their own GPIO
2157  * descriptors via gpiolib API. Difference to gpiod_request() is that this
2158  * function will not increase reference count of the GPIO chip module. This
2159  * allows the GPIO chip module to be unloaded as needed (we assume that the
2160  * GPIO chip driver handles freeing the GPIOs it has requested).
2161  *
2162  * Returns:
2163  * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
2164  * code on failure.
2165  */
2166 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *gc,
2167                                             unsigned int hwnum,
2168                                             const char *label,
2169                                             enum gpio_lookup_flags lflags,
2170                                             enum gpiod_flags dflags)
2171 {
2172         struct gpio_desc *desc = gpiochip_get_desc(gc, hwnum);
2173         int ret;
2174
2175         if (IS_ERR(desc)) {
2176                 chip_err(gc, "failed to get GPIO descriptor\n");
2177                 return desc;
2178         }
2179
2180         ret = gpiod_request_commit(desc, label);
2181         if (ret < 0)
2182                 return ERR_PTR(ret);
2183
2184         ret = gpiod_configure_flags(desc, label, lflags, dflags);
2185         if (ret) {
2186                 chip_err(gc, "setup of own GPIO %s failed\n", label);
2187                 gpiod_free_commit(desc);
2188                 return ERR_PTR(ret);
2189         }
2190
2191         return desc;
2192 }
2193 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
2194
2195 /**
2196  * gpiochip_free_own_desc - Free GPIO requested by the chip driver
2197  * @desc: GPIO descriptor to free
2198  *
2199  * Function frees the given GPIO requested previously with
2200  * gpiochip_request_own_desc().
2201  */
2202 void gpiochip_free_own_desc(struct gpio_desc *desc)
2203 {
2204         if (desc)
2205                 gpiod_free_commit(desc);
2206 }
2207 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
2208
2209 /*
2210  * Drivers MUST set GPIO direction before making get/set calls.  In
2211  * some cases this is done in early boot, before IRQs are enabled.
2212  *
2213  * As a rule these aren't called more than once (except for drivers
2214  * using the open-drain emulation idiom) so these are natural places
2215  * to accumulate extra debugging checks.  Note that we can't (yet)
2216  * rely on gpio_request() having been called beforehand.
2217  */
2218
2219 static int gpio_do_set_config(struct gpio_chip *gc, unsigned int offset,
2220                               unsigned long config)
2221 {
2222         if (!gc->set_config)
2223                 return -ENOTSUPP;
2224
2225         return gc->set_config(gc, offset, config);
2226 }
2227
2228 static int gpio_set_config(struct gpio_desc *desc, enum pin_config_param mode)
2229 {
2230         struct gpio_chip *gc = desc->gdev->chip;
2231         unsigned long config;
2232         unsigned arg;
2233
2234         switch (mode) {
2235         case PIN_CONFIG_BIAS_PULL_DOWN:
2236         case PIN_CONFIG_BIAS_PULL_UP:
2237                 arg = 1;
2238                 break;
2239
2240         default:
2241                 arg = 0;
2242         }
2243
2244         config = PIN_CONF_PACKED(mode, arg);
2245         return gpio_do_set_config(gc, gpio_chip_hwgpio(desc), config);
2246 }
2247
2248 static int gpio_set_bias(struct gpio_desc *desc)
2249 {
2250         int bias = 0;
2251         int ret = 0;
2252
2253         if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
2254                 bias = PIN_CONFIG_BIAS_DISABLE;
2255         else if (test_bit(FLAG_PULL_UP, &desc->flags))
2256                 bias = PIN_CONFIG_BIAS_PULL_UP;
2257         else if (test_bit(FLAG_PULL_DOWN, &desc->flags))
2258                 bias = PIN_CONFIG_BIAS_PULL_DOWN;
2259
2260         if (bias) {
2261                 ret = gpio_set_config(desc, bias);
2262                 if (ret != -ENOTSUPP)
2263                         return ret;
2264         }
2265         return 0;
2266 }
2267
2268 /**
2269  * gpiod_direction_input - set the GPIO direction to input
2270  * @desc:       GPIO to set to input
2271  *
2272  * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2273  * be called safely on it.
2274  *
2275  * Return 0 in case of success, else an error code.
2276  */
2277 int gpiod_direction_input(struct gpio_desc *desc)
2278 {
2279         struct gpio_chip        *gc;
2280         int                     ret = 0;
2281
2282         VALIDATE_DESC(desc);
2283         gc = desc->gdev->chip;
2284
2285         /*
2286          * It is legal to have no .get() and .direction_input() specified if
2287          * the chip is output-only, but you can't specify .direction_input()
2288          * and not support the .get() operation, that doesn't make sense.
2289          */
2290         if (!gc->get && gc->direction_input) {
2291                 gpiod_warn(desc,
2292                            "%s: missing get() but have direction_input()\n",
2293                            __func__);
2294                 return -EIO;
2295         }
2296
2297         /*
2298          * If we have a .direction_input() callback, things are simple,
2299          * just call it. Else we are some input-only chip so try to check the
2300          * direction (if .get_direction() is supported) else we silently
2301          * assume we are in input mode after this.
2302          */
2303         if (gc->direction_input) {
2304                 ret = gc->direction_input(gc, gpio_chip_hwgpio(desc));
2305         } else if (gc->get_direction &&
2306                   (gc->get_direction(gc, gpio_chip_hwgpio(desc)) != 1)) {
2307                 gpiod_warn(desc,
2308                            "%s: missing direction_input() operation and line is output\n",
2309                            __func__);
2310                 return -EIO;
2311         }
2312         if (ret == 0) {
2313                 clear_bit(FLAG_IS_OUT, &desc->flags);
2314                 ret = gpio_set_bias(desc);
2315         }
2316
2317         trace_gpio_direction(desc_to_gpio(desc), 1, ret);
2318
2319         return ret;
2320 }
2321 EXPORT_SYMBOL_GPL(gpiod_direction_input);
2322
2323 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
2324 {
2325         struct gpio_chip *gc = desc->gdev->chip;
2326         int val = !!value;
2327         int ret = 0;
2328
2329         /*
2330          * It's OK not to specify .direction_output() if the gpiochip is
2331          * output-only, but if there is then not even a .set() operation it
2332          * is pretty tricky to drive the output line.
2333          */
2334         if (!gc->set && !gc->direction_output) {
2335                 gpiod_warn(desc,
2336                            "%s: missing set() and direction_output() operations\n",
2337                            __func__);
2338                 return -EIO;
2339         }
2340
2341         if (gc->direction_output) {
2342                 ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
2343         } else {
2344                 /* Check that we are in output mode if we can */
2345                 if (gc->get_direction &&
2346                     gc->get_direction(gc, gpio_chip_hwgpio(desc))) {
2347                         gpiod_warn(desc,
2348                                 "%s: missing direction_output() operation\n",
2349                                 __func__);
2350                         return -EIO;
2351                 }
2352                 /*
2353                  * If we can't actively set the direction, we are some
2354                  * output-only chip, so just drive the output as desired.
2355                  */
2356                 gc->set(gc, gpio_chip_hwgpio(desc), val);
2357         }
2358
2359         if (!ret)
2360                 set_bit(FLAG_IS_OUT, &desc->flags);
2361         trace_gpio_value(desc_to_gpio(desc), 0, val);
2362         trace_gpio_direction(desc_to_gpio(desc), 0, ret);
2363         return ret;
2364 }
2365
2366 /**
2367  * gpiod_direction_output_raw - set the GPIO direction to output
2368  * @desc:       GPIO to set to output
2369  * @value:      initial output value of the GPIO
2370  *
2371  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2372  * be called safely on it. The initial value of the output must be specified
2373  * as raw value on the physical line without regard for the ACTIVE_LOW status.
2374  *
2375  * Return 0 in case of success, else an error code.
2376  */
2377 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2378 {
2379         VALIDATE_DESC(desc);
2380         return gpiod_direction_output_raw_commit(desc, value);
2381 }
2382 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
2383
2384 /**
2385  * gpiod_direction_output - set the GPIO direction to output
2386  * @desc:       GPIO to set to output
2387  * @value:      initial output value of the GPIO
2388  *
2389  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2390  * be called safely on it. The initial value of the output must be specified
2391  * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2392  * account.
2393  *
2394  * Return 0 in case of success, else an error code.
2395  */
2396 int gpiod_direction_output(struct gpio_desc *desc, int value)
2397 {
2398         int ret;
2399
2400         VALIDATE_DESC(desc);
2401         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2402                 value = !value;
2403         else
2404                 value = !!value;
2405
2406         /* GPIOs used for enabled IRQs shall not be set as output */
2407         if (test_bit(FLAG_USED_AS_IRQ, &desc->flags) &&
2408             test_bit(FLAG_IRQ_IS_ENABLED, &desc->flags)) {
2409                 gpiod_err(desc,
2410                           "%s: tried to set a GPIO tied to an IRQ as output\n",
2411                           __func__);
2412                 return -EIO;
2413         }
2414
2415         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
2416                 /* First see if we can enable open drain in hardware */
2417                 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_DRAIN);
2418                 if (!ret)
2419                         goto set_output_value;
2420                 /* Emulate open drain by not actively driving the line high */
2421                 if (value) {
2422                         ret = gpiod_direction_input(desc);
2423                         goto set_output_flag;
2424                 }
2425         }
2426         else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
2427                 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_SOURCE);
2428                 if (!ret)
2429                         goto set_output_value;
2430                 /* Emulate open source by not actively driving the line low */
2431                 if (!value) {
2432                         ret = gpiod_direction_input(desc);
2433                         goto set_output_flag;
2434                 }
2435         } else {
2436                 gpio_set_config(desc, PIN_CONFIG_DRIVE_PUSH_PULL);
2437         }
2438
2439 set_output_value:
2440         ret = gpio_set_bias(desc);
2441         if (ret)
2442                 return ret;
2443         return gpiod_direction_output_raw_commit(desc, value);
2444
2445 set_output_flag:
2446         /*
2447          * When emulating open-source or open-drain functionalities by not
2448          * actively driving the line (setting mode to input) we still need to
2449          * set the IS_OUT flag or otherwise we won't be able to set the line
2450          * value anymore.
2451          */
2452         if (ret == 0)
2453                 set_bit(FLAG_IS_OUT, &desc->flags);
2454         return ret;
2455 }
2456 EXPORT_SYMBOL_GPL(gpiod_direction_output);
2457
2458 /**
2459  * gpiod_set_config - sets @config for a GPIO
2460  * @desc: descriptor of the GPIO for which to set the configuration
2461  * @config: Same packed config format as generic pinconf
2462  *
2463  * Returns:
2464  * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
2465  * configuration.
2466  */
2467 int gpiod_set_config(struct gpio_desc *desc, unsigned long config)
2468 {
2469         struct gpio_chip *gc;
2470
2471         VALIDATE_DESC(desc);
2472         gc = desc->gdev->chip;
2473
2474         return gpio_do_set_config(gc, gpio_chip_hwgpio(desc), config);
2475 }
2476 EXPORT_SYMBOL_GPL(gpiod_set_config);
2477
2478 /**
2479  * gpiod_set_debounce - sets @debounce time for a GPIO
2480  * @desc: descriptor of the GPIO for which to set debounce time
2481  * @debounce: debounce time in microseconds
2482  *
2483  * Returns:
2484  * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
2485  * debounce time.
2486  */
2487 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
2488 {
2489         unsigned long config;
2490
2491         config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
2492         return gpiod_set_config(desc, config);
2493 }
2494 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
2495
2496 /**
2497  * gpiod_set_transitory - Lose or retain GPIO state on suspend or reset
2498  * @desc: descriptor of the GPIO for which to configure persistence
2499  * @transitory: True to lose state on suspend or reset, false for persistence
2500  *
2501  * Returns:
2502  * 0 on success, otherwise a negative error code.
2503  */
2504 int gpiod_set_transitory(struct gpio_desc *desc, bool transitory)
2505 {
2506         struct gpio_chip *gc;
2507         unsigned long packed;
2508         int gpio;
2509         int rc;
2510
2511         VALIDATE_DESC(desc);
2512         /*
2513          * Handle FLAG_TRANSITORY first, enabling queries to gpiolib for
2514          * persistence state.
2515          */
2516         assign_bit(FLAG_TRANSITORY, &desc->flags, transitory);
2517
2518         /* If the driver supports it, set the persistence state now */
2519         gc = desc->gdev->chip;
2520         if (!gc->set_config)
2521                 return 0;
2522
2523         packed = pinconf_to_config_packed(PIN_CONFIG_PERSIST_STATE,
2524                                           !transitory);
2525         gpio = gpio_chip_hwgpio(desc);
2526         rc = gpio_do_set_config(gc, gpio, packed);
2527         if (rc == -ENOTSUPP) {
2528                 dev_dbg(&desc->gdev->dev, "Persistence not supported for GPIO %d\n",
2529                                 gpio);
2530                 return 0;
2531         }
2532
2533         return rc;
2534 }
2535 EXPORT_SYMBOL_GPL(gpiod_set_transitory);
2536
2537 /**
2538  * gpiod_is_active_low - test whether a GPIO is active-low or not
2539  * @desc: the gpio descriptor to test
2540  *
2541  * Returns 1 if the GPIO is active-low, 0 otherwise.
2542  */
2543 int gpiod_is_active_low(const struct gpio_desc *desc)
2544 {
2545         VALIDATE_DESC(desc);
2546         return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
2547 }
2548 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
2549
2550 /**
2551  * gpiod_toggle_active_low - toggle whether a GPIO is active-low or not
2552  * @desc: the gpio descriptor to change
2553  */
2554 void gpiod_toggle_active_low(struct gpio_desc *desc)
2555 {
2556         VALIDATE_DESC_VOID(desc);
2557         change_bit(FLAG_ACTIVE_LOW, &desc->flags);
2558 }
2559 EXPORT_SYMBOL_GPL(gpiod_toggle_active_low);
2560
2561 /* I/O calls are only valid after configuration completed; the relevant
2562  * "is this a valid GPIO" error checks should already have been done.
2563  *
2564  * "Get" operations are often inlinable as reading a pin value register,
2565  * and masking the relevant bit in that register.
2566  *
2567  * When "set" operations are inlinable, they involve writing that mask to
2568  * one register to set a low value, or a different register to set it high.
2569  * Otherwise locking is needed, so there may be little value to inlining.
2570  *
2571  *------------------------------------------------------------------------
2572  *
2573  * IMPORTANT!!!  The hot paths -- get/set value -- assume that callers
2574  * have requested the GPIO.  That can include implicit requesting by
2575  * a direction setting call.  Marking a gpio as requested locks its chip
2576  * in memory, guaranteeing that these table lookups need no more locking
2577  * and that gpiochip_remove() will fail.
2578  *
2579  * REVISIT when debugging, consider adding some instrumentation to ensure
2580  * that the GPIO was actually requested.
2581  */
2582
2583 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
2584 {
2585         struct gpio_chip        *gc;
2586         int offset;
2587         int value;
2588
2589         gc = desc->gdev->chip;
2590         offset = gpio_chip_hwgpio(desc);
2591         value = gc->get ? gc->get(gc, offset) : -EIO;
2592         value = value < 0 ? value : !!value;
2593         trace_gpio_value(desc_to_gpio(desc), 1, value);
2594         return value;
2595 }
2596
2597 static int gpio_chip_get_multiple(struct gpio_chip *gc,
2598                                   unsigned long *mask, unsigned long *bits)
2599 {
2600         if (gc->get_multiple) {
2601                 return gc->get_multiple(gc, mask, bits);
2602         } else if (gc->get) {
2603                 int i, value;
2604
2605                 for_each_set_bit(i, mask, gc->ngpio) {
2606                         value = gc->get(gc, i);
2607                         if (value < 0)
2608                                 return value;
2609                         __assign_bit(i, bits, value);
2610                 }
2611                 return 0;
2612         }
2613         return -EIO;
2614 }
2615
2616 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
2617                                   unsigned int array_size,
2618                                   struct gpio_desc **desc_array,
2619                                   struct gpio_array *array_info,
2620                                   unsigned long *value_bitmap)
2621 {
2622         int ret, i = 0;
2623
2624         /*
2625          * Validate array_info against desc_array and its size.
2626          * It should immediately follow desc_array if both
2627          * have been obtained from the same gpiod_get_array() call.
2628          */
2629         if (array_info && array_info->desc == desc_array &&
2630             array_size <= array_info->size &&
2631             (void *)array_info == desc_array + array_info->size) {
2632                 if (!can_sleep)
2633                         WARN_ON(array_info->chip->can_sleep);
2634
2635                 ret = gpio_chip_get_multiple(array_info->chip,
2636                                              array_info->get_mask,
2637                                              value_bitmap);
2638                 if (ret)
2639                         return ret;
2640
2641                 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
2642                         bitmap_xor(value_bitmap, value_bitmap,
2643                                    array_info->invert_mask, array_size);
2644
2645                 i = find_first_zero_bit(array_info->get_mask, array_size);
2646                 if (i == array_size)
2647                         return 0;
2648         } else {
2649                 array_info = NULL;
2650         }
2651
2652         while (i < array_size) {
2653                 struct gpio_chip *gc = desc_array[i]->gdev->chip;
2654                 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
2655                 unsigned long *mask, *bits;
2656                 int first, j, ret;
2657
2658                 if (likely(gc->ngpio <= FASTPATH_NGPIO)) {
2659                         mask = fastpath;
2660                 } else {
2661                         mask = kmalloc_array(2 * BITS_TO_LONGS(gc->ngpio),
2662                                            sizeof(*mask),
2663                                            can_sleep ? GFP_KERNEL : GFP_ATOMIC);
2664                         if (!mask)
2665                                 return -ENOMEM;
2666                 }
2667
2668                 bits = mask + BITS_TO_LONGS(gc->ngpio);
2669                 bitmap_zero(mask, gc->ngpio);
2670
2671                 if (!can_sleep)
2672                         WARN_ON(gc->can_sleep);
2673
2674                 /* collect all inputs belonging to the same chip */
2675                 first = i;
2676                 do {
2677                         const struct gpio_desc *desc = desc_array[i];
2678                         int hwgpio = gpio_chip_hwgpio(desc);
2679
2680                         __set_bit(hwgpio, mask);
2681                         i++;
2682
2683                         if (array_info)
2684                                 i = find_next_zero_bit(array_info->get_mask,
2685                                                        array_size, i);
2686                 } while ((i < array_size) &&
2687                          (desc_array[i]->gdev->chip == gc));
2688
2689                 ret = gpio_chip_get_multiple(gc, mask, bits);
2690                 if (ret) {
2691                         if (mask != fastpath)
2692                                 kfree(mask);
2693                         return ret;
2694                 }
2695
2696                 for (j = first; j < i; ) {
2697                         const struct gpio_desc *desc = desc_array[j];
2698                         int hwgpio = gpio_chip_hwgpio(desc);
2699                         int value = test_bit(hwgpio, bits);
2700
2701                         if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2702                                 value = !value;
2703                         __assign_bit(j, value_bitmap, value);
2704                         trace_gpio_value(desc_to_gpio(desc), 1, value);
2705                         j++;
2706
2707                         if (array_info)
2708                                 j = find_next_zero_bit(array_info->get_mask, i,
2709                                                        j);
2710                 }
2711
2712                 if (mask != fastpath)
2713                         kfree(mask);
2714         }
2715         return 0;
2716 }
2717
2718 /**
2719  * gpiod_get_raw_value() - return a gpio's raw value
2720  * @desc: gpio whose value will be returned
2721  *
2722  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2723  * its ACTIVE_LOW status, or negative errno on failure.
2724  *
2725  * This function can be called from contexts where we cannot sleep, and will
2726  * complain if the GPIO chip functions potentially sleep.
2727  */
2728 int gpiod_get_raw_value(const struct gpio_desc *desc)
2729 {
2730         VALIDATE_DESC(desc);
2731         /* Should be using gpiod_get_raw_value_cansleep() */
2732         WARN_ON(desc->gdev->chip->can_sleep);
2733         return gpiod_get_raw_value_commit(desc);
2734 }
2735 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
2736
2737 /**
2738  * gpiod_get_value() - return a gpio's value
2739  * @desc: gpio whose value will be returned
2740  *
2741  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2742  * account, or negative errno on failure.
2743  *
2744  * This function can be called from contexts where we cannot sleep, and will
2745  * complain if the GPIO chip functions potentially sleep.
2746  */
2747 int gpiod_get_value(const struct gpio_desc *desc)
2748 {
2749         int value;
2750
2751         VALIDATE_DESC(desc);
2752         /* Should be using gpiod_get_value_cansleep() */
2753         WARN_ON(desc->gdev->chip->can_sleep);
2754
2755         value = gpiod_get_raw_value_commit(desc);
2756         if (value < 0)
2757                 return value;
2758
2759         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2760                 value = !value;
2761
2762         return value;
2763 }
2764 EXPORT_SYMBOL_GPL(gpiod_get_value);
2765
2766 /**
2767  * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
2768  * @array_size: number of elements in the descriptor array / value bitmap
2769  * @desc_array: array of GPIO descriptors whose values will be read
2770  * @array_info: information on applicability of fast bitmap processing path
2771  * @value_bitmap: bitmap to store the read values
2772  *
2773  * Read the raw values of the GPIOs, i.e. the values of the physical lines
2774  * without regard for their ACTIVE_LOW status.  Return 0 in case of success,
2775  * else an error code.
2776  *
2777  * This function can be called from contexts where we cannot sleep,
2778  * and it will complain if the GPIO chip functions potentially sleep.
2779  */
2780 int gpiod_get_raw_array_value(unsigned int array_size,
2781                               struct gpio_desc **desc_array,
2782                               struct gpio_array *array_info,
2783                               unsigned long *value_bitmap)
2784 {
2785         if (!desc_array)
2786                 return -EINVAL;
2787         return gpiod_get_array_value_complex(true, false, array_size,
2788                                              desc_array, array_info,
2789                                              value_bitmap);
2790 }
2791 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
2792
2793 /**
2794  * gpiod_get_array_value() - read values from an array of GPIOs
2795  * @array_size: number of elements in the descriptor array / value bitmap
2796  * @desc_array: array of GPIO descriptors whose values will be read
2797  * @array_info: information on applicability of fast bitmap processing path
2798  * @value_bitmap: bitmap to store the read values
2799  *
2800  * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
2801  * into account.  Return 0 in case of success, else an error code.
2802  *
2803  * This function can be called from contexts where we cannot sleep,
2804  * and it will complain if the GPIO chip functions potentially sleep.
2805  */
2806 int gpiod_get_array_value(unsigned int array_size,
2807                           struct gpio_desc **desc_array,
2808                           struct gpio_array *array_info,
2809                           unsigned long *value_bitmap)
2810 {
2811         if (!desc_array)
2812                 return -EINVAL;
2813         return gpiod_get_array_value_complex(false, false, array_size,
2814                                              desc_array, array_info,
2815                                              value_bitmap);
2816 }
2817 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
2818
2819 /*
2820  *  gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
2821  * @desc: gpio descriptor whose state need to be set.
2822  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2823  */
2824 static void gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
2825 {
2826         int ret = 0;
2827         struct gpio_chip *gc = desc->gdev->chip;
2828         int offset = gpio_chip_hwgpio(desc);
2829
2830         if (value) {
2831                 ret = gc->direction_input(gc, offset);
2832         } else {
2833                 ret = gc->direction_output(gc, offset, 0);
2834                 if (!ret)
2835                         set_bit(FLAG_IS_OUT, &desc->flags);
2836         }
2837         trace_gpio_direction(desc_to_gpio(desc), value, ret);
2838         if (ret < 0)
2839                 gpiod_err(desc,
2840                           "%s: Error in set_value for open drain err %d\n",
2841                           __func__, ret);
2842 }
2843
2844 /*
2845  *  _gpio_set_open_source_value() - Set the open source gpio's value.
2846  * @desc: gpio descriptor whose state need to be set.
2847  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2848  */
2849 static void gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
2850 {
2851         int ret = 0;
2852         struct gpio_chip *gc = desc->gdev->chip;
2853         int offset = gpio_chip_hwgpio(desc);
2854
2855         if (value) {
2856                 ret = gc->direction_output(gc, offset, 1);
2857                 if (!ret)
2858                         set_bit(FLAG_IS_OUT, &desc->flags);
2859         } else {
2860                 ret = gc->direction_input(gc, offset);
2861         }
2862         trace_gpio_direction(desc_to_gpio(desc), !value, ret);
2863         if (ret < 0)
2864                 gpiod_err(desc,
2865                           "%s: Error in set_value for open source err %d\n",
2866                           __func__, ret);
2867 }
2868
2869 static void gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
2870 {
2871         struct gpio_chip        *gc;
2872
2873         gc = desc->gdev->chip;
2874         trace_gpio_value(desc_to_gpio(desc), 0, value);
2875         gc->set(gc, gpio_chip_hwgpio(desc), value);
2876 }
2877
2878 /*
2879  * set multiple outputs on the same chip;
2880  * use the chip's set_multiple function if available;
2881  * otherwise set the outputs sequentially;
2882  * @chip: the GPIO chip we operate on
2883  * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
2884  *        defines which outputs are to be changed
2885  * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
2886  *        defines the values the outputs specified by mask are to be set to
2887  */
2888 static void gpio_chip_set_multiple(struct gpio_chip *gc,
2889                                    unsigned long *mask, unsigned long *bits)
2890 {
2891         if (gc->set_multiple) {
2892                 gc->set_multiple(gc, mask, bits);
2893         } else {
2894                 unsigned int i;
2895
2896                 /* set outputs if the corresponding mask bit is set */
2897                 for_each_set_bit(i, mask, gc->ngpio)
2898                         gc->set(gc, i, test_bit(i, bits));
2899         }
2900 }
2901
2902 int gpiod_set_array_value_complex(bool raw, bool can_sleep,
2903                                   unsigned int array_size,
2904                                   struct gpio_desc **desc_array,
2905                                   struct gpio_array *array_info,
2906                                   unsigned long *value_bitmap)
2907 {
2908         int i = 0;
2909
2910         /*
2911          * Validate array_info against desc_array and its size.
2912          * It should immediately follow desc_array if both
2913          * have been obtained from the same gpiod_get_array() call.
2914          */
2915         if (array_info && array_info->desc == desc_array &&
2916             array_size <= array_info->size &&
2917             (void *)array_info == desc_array + array_info->size) {
2918                 if (!can_sleep)
2919                         WARN_ON(array_info->chip->can_sleep);
2920
2921                 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
2922                         bitmap_xor(value_bitmap, value_bitmap,
2923                                    array_info->invert_mask, array_size);
2924
2925                 gpio_chip_set_multiple(array_info->chip, array_info->set_mask,
2926                                        value_bitmap);
2927
2928                 i = find_first_zero_bit(array_info->set_mask, array_size);
2929                 if (i == array_size)
2930                         return 0;
2931         } else {
2932                 array_info = NULL;
2933         }
2934
2935         while (i < array_size) {
2936                 struct gpio_chip *gc = desc_array[i]->gdev->chip;
2937                 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
2938                 unsigned long *mask, *bits;
2939                 int count = 0;
2940
2941                 if (likely(gc->ngpio <= FASTPATH_NGPIO)) {
2942                         mask = fastpath;
2943                 } else {
2944                         mask = kmalloc_array(2 * BITS_TO_LONGS(gc->ngpio),
2945                                            sizeof(*mask),
2946                                            can_sleep ? GFP_KERNEL : GFP_ATOMIC);
2947                         if (!mask)
2948                                 return -ENOMEM;
2949                 }
2950
2951                 bits = mask + BITS_TO_LONGS(gc->ngpio);
2952                 bitmap_zero(mask, gc->ngpio);
2953
2954                 if (!can_sleep)
2955                         WARN_ON(gc->can_sleep);
2956
2957                 do {
2958                         struct gpio_desc *desc = desc_array[i];
2959                         int hwgpio = gpio_chip_hwgpio(desc);
2960                         int value = test_bit(i, value_bitmap);
2961
2962                         /*
2963                          * Pins applicable for fast input but not for
2964                          * fast output processing may have been already
2965                          * inverted inside the fast path, skip them.
2966                          */
2967                         if (!raw && !(array_info &&
2968                             test_bit(i, array_info->invert_mask)) &&
2969                             test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2970                                 value = !value;
2971                         trace_gpio_value(desc_to_gpio(desc), 0, value);
2972                         /*
2973                          * collect all normal outputs belonging to the same chip
2974                          * open drain and open source outputs are set individually
2975                          */
2976                         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
2977                                 gpio_set_open_drain_value_commit(desc, value);
2978                         } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
2979                                 gpio_set_open_source_value_commit(desc, value);
2980                         } else {
2981                                 __set_bit(hwgpio, mask);
2982                                 __assign_bit(hwgpio, bits, value);
2983                                 count++;
2984                         }
2985                         i++;
2986
2987                         if (array_info)
2988                                 i = find_next_zero_bit(array_info->set_mask,
2989                                                        array_size, i);
2990                 } while ((i < array_size) &&
2991                          (desc_array[i]->gdev->chip == gc));
2992                 /* push collected bits to outputs */
2993                 if (count != 0)
2994                         gpio_chip_set_multiple(gc, mask, bits);
2995
2996                 if (mask != fastpath)
2997                         kfree(mask);
2998         }
2999         return 0;
3000 }
3001
3002 /**
3003  * gpiod_set_raw_value() - assign a gpio's raw value
3004  * @desc: gpio whose value will be assigned
3005  * @value: value to assign
3006  *
3007  * Set the raw value of the GPIO, i.e. the value of its physical line without
3008  * regard for its ACTIVE_LOW status.
3009  *
3010  * This function can be called from contexts where we cannot sleep, and will
3011  * complain if the GPIO chip functions potentially sleep.
3012  */
3013 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
3014 {
3015         VALIDATE_DESC_VOID(desc);
3016         /* Should be using gpiod_set_raw_value_cansleep() */
3017         WARN_ON(desc->gdev->chip->can_sleep);
3018         gpiod_set_raw_value_commit(desc, value);
3019 }
3020 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
3021
3022 /**
3023  * gpiod_set_value_nocheck() - set a GPIO line value without checking
3024  * @desc: the descriptor to set the value on
3025  * @value: value to set
3026  *
3027  * This sets the value of a GPIO line backing a descriptor, applying
3028  * different semantic quirks like active low and open drain/source
3029  * handling.
3030  */
3031 static void gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
3032 {
3033         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3034                 value = !value;
3035         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
3036                 gpio_set_open_drain_value_commit(desc, value);
3037         else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
3038                 gpio_set_open_source_value_commit(desc, value);
3039         else
3040                 gpiod_set_raw_value_commit(desc, value);
3041 }
3042
3043 /**
3044  * gpiod_set_value() - assign a gpio's value
3045  * @desc: gpio whose value will be assigned
3046  * @value: value to assign
3047  *
3048  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
3049  * OPEN_DRAIN and OPEN_SOURCE flags into account.
3050  *
3051  * This function can be called from contexts where we cannot sleep, and will
3052  * complain if the GPIO chip functions potentially sleep.
3053  */
3054 void gpiod_set_value(struct gpio_desc *desc, int value)
3055 {
3056         VALIDATE_DESC_VOID(desc);
3057         /* Should be using gpiod_set_value_cansleep() */
3058         WARN_ON(desc->gdev->chip->can_sleep);
3059         gpiod_set_value_nocheck(desc, value);
3060 }
3061 EXPORT_SYMBOL_GPL(gpiod_set_value);
3062
3063 /**
3064  * gpiod_set_raw_array_value() - assign values to an array of GPIOs
3065  * @array_size: number of elements in the descriptor array / value bitmap
3066  * @desc_array: array of GPIO descriptors whose values will be assigned
3067  * @array_info: information on applicability of fast bitmap processing path
3068  * @value_bitmap: bitmap of values to assign
3069  *
3070  * Set the raw values of the GPIOs, i.e. the values of the physical lines
3071  * without regard for their ACTIVE_LOW status.
3072  *
3073  * This function can be called from contexts where we cannot sleep, and will
3074  * complain if the GPIO chip functions potentially sleep.
3075  */
3076 int gpiod_set_raw_array_value(unsigned int array_size,
3077                               struct gpio_desc **desc_array,
3078                               struct gpio_array *array_info,
3079                               unsigned long *value_bitmap)
3080 {
3081         if (!desc_array)
3082                 return -EINVAL;
3083         return gpiod_set_array_value_complex(true, false, array_size,
3084                                         desc_array, array_info, value_bitmap);
3085 }
3086 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
3087
3088 /**
3089  * gpiod_set_array_value() - assign values to an array of GPIOs
3090  * @array_size: number of elements in the descriptor array / value bitmap
3091  * @desc_array: array of GPIO descriptors whose values will be assigned
3092  * @array_info: information on applicability of fast bitmap processing path
3093  * @value_bitmap: bitmap of values to assign
3094  *
3095  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3096  * into account.
3097  *
3098  * This function can be called from contexts where we cannot sleep, and will
3099  * complain if the GPIO chip functions potentially sleep.
3100  */
3101 int gpiod_set_array_value(unsigned int array_size,
3102                           struct gpio_desc **desc_array,
3103                           struct gpio_array *array_info,
3104                           unsigned long *value_bitmap)
3105 {
3106         if (!desc_array)
3107                 return -EINVAL;
3108         return gpiod_set_array_value_complex(false, false, array_size,
3109                                              desc_array, array_info,
3110                                              value_bitmap);
3111 }
3112 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
3113
3114 /**
3115  * gpiod_cansleep() - report whether gpio value access may sleep
3116  * @desc: gpio to check
3117  *
3118  */
3119 int gpiod_cansleep(const struct gpio_desc *desc)
3120 {
3121         VALIDATE_DESC(desc);
3122         return desc->gdev->chip->can_sleep;
3123 }
3124 EXPORT_SYMBOL_GPL(gpiod_cansleep);
3125
3126 /**
3127  * gpiod_set_consumer_name() - set the consumer name for the descriptor
3128  * @desc: gpio to set the consumer name on
3129  * @name: the new consumer name
3130  */
3131 int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
3132 {
3133         VALIDATE_DESC(desc);
3134         if (name) {
3135                 name = kstrdup_const(name, GFP_KERNEL);
3136                 if (!name)
3137                         return -ENOMEM;
3138         }
3139
3140         kfree_const(desc->label);
3141         desc_set_label(desc, name);
3142
3143         return 0;
3144 }
3145 EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
3146
3147 /**
3148  * gpiod_to_irq() - return the IRQ corresponding to a GPIO
3149  * @desc: gpio whose IRQ will be returned (already requested)
3150  *
3151  * Return the IRQ corresponding to the passed GPIO, or an error code in case of
3152  * error.
3153  */
3154 int gpiod_to_irq(const struct gpio_desc *desc)
3155 {
3156         struct gpio_chip *gc;
3157         int offset;
3158
3159         /*
3160          * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
3161          * requires this function to not return zero on an invalid descriptor
3162          * but rather a negative error number.
3163          */
3164         if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
3165                 return -EINVAL;
3166
3167         gc = desc->gdev->chip;
3168         offset = gpio_chip_hwgpio(desc);
3169         if (gc->to_irq) {
3170                 int retirq = gc->to_irq(gc, offset);
3171
3172                 /* Zero means NO_IRQ */
3173                 if (!retirq)
3174                         return -ENXIO;
3175
3176                 return retirq;
3177         }
3178         return -ENXIO;
3179 }
3180 EXPORT_SYMBOL_GPL(gpiod_to_irq);
3181
3182 /**
3183  * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
3184  * @gc: the chip the GPIO to lock belongs to
3185  * @offset: the offset of the GPIO to lock as IRQ
3186  *
3187  * This is used directly by GPIO drivers that want to lock down
3188  * a certain GPIO line to be used for IRQs.
3189  */
3190 int gpiochip_lock_as_irq(struct gpio_chip *gc, unsigned int offset)
3191 {
3192         struct gpio_desc *desc;
3193
3194         desc = gpiochip_get_desc(gc, offset);
3195         if (IS_ERR(desc))
3196                 return PTR_ERR(desc);
3197
3198         /*
3199          * If it's fast: flush the direction setting if something changed
3200          * behind our back
3201          */
3202         if (!gc->can_sleep && gc->get_direction) {
3203                 int dir = gpiod_get_direction(desc);
3204
3205                 if (dir < 0) {
3206                         chip_err(gc, "%s: cannot get GPIO direction\n",
3207                                  __func__);
3208                         return dir;
3209                 }
3210         }
3211
3212         /* To be valid for IRQ the line needs to be input or open drain */
3213         if (test_bit(FLAG_IS_OUT, &desc->flags) &&
3214             !test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
3215                 chip_err(gc,
3216                          "%s: tried to flag a GPIO set as output for IRQ\n",
3217                          __func__);
3218                 return -EIO;
3219         }
3220
3221         set_bit(FLAG_USED_AS_IRQ, &desc->flags);
3222         set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3223
3224         /*
3225          * If the consumer has not set up a label (such as when the
3226          * IRQ is referenced from .to_irq()) we set up a label here
3227          * so it is clear this is used as an interrupt.
3228          */
3229         if (!desc->label)
3230                 desc_set_label(desc, "interrupt");
3231
3232         return 0;
3233 }
3234 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
3235
3236 /**
3237  * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
3238  * @gc: the chip the GPIO to lock belongs to
3239  * @offset: the offset of the GPIO to lock as IRQ
3240  *
3241  * This is used directly by GPIO drivers that want to indicate
3242  * that a certain GPIO is no longer used exclusively for IRQ.
3243  */
3244 void gpiochip_unlock_as_irq(struct gpio_chip *gc, unsigned int offset)
3245 {
3246         struct gpio_desc *desc;
3247
3248         desc = gpiochip_get_desc(gc, offset);
3249         if (IS_ERR(desc))
3250                 return;
3251
3252         clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
3253         clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3254
3255         /* If we only had this marking, erase it */
3256         if (desc->label && !strcmp(desc->label, "interrupt"))
3257                 desc_set_label(desc, NULL);
3258 }
3259 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
3260
3261 void gpiochip_disable_irq(struct gpio_chip *gc, unsigned int offset)
3262 {
3263         struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
3264
3265         if (!IS_ERR(desc) &&
3266             !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags)))
3267                 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3268 }
3269 EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
3270
3271 void gpiochip_enable_irq(struct gpio_chip *gc, unsigned int offset)
3272 {
3273         struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
3274
3275         if (!IS_ERR(desc) &&
3276             !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags))) {
3277                 /*
3278                  * We must not be output when using IRQ UNLESS we are
3279                  * open drain.
3280                  */
3281                 WARN_ON(test_bit(FLAG_IS_OUT, &desc->flags) &&
3282                         !test_bit(FLAG_OPEN_DRAIN, &desc->flags));
3283                 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3284         }
3285 }
3286 EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
3287
3288 bool gpiochip_line_is_irq(struct gpio_chip *gc, unsigned int offset)
3289 {
3290         if (offset >= gc->ngpio)
3291                 return false;
3292
3293         return test_bit(FLAG_USED_AS_IRQ, &gc->gpiodev->descs[offset].flags);
3294 }
3295 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
3296
3297 int gpiochip_reqres_irq(struct gpio_chip *gc, unsigned int offset)
3298 {
3299         int ret;
3300
3301         if (!try_module_get(gc->gpiodev->owner))
3302                 return -ENODEV;
3303
3304         ret = gpiochip_lock_as_irq(gc, offset);
3305         if (ret) {
3306                 chip_err(gc, "unable to lock HW IRQ %u for IRQ\n", offset);
3307                 module_put(gc->gpiodev->owner);
3308                 return ret;
3309         }
3310         return 0;
3311 }
3312 EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
3313
3314 void gpiochip_relres_irq(struct gpio_chip *gc, unsigned int offset)
3315 {
3316         gpiochip_unlock_as_irq(gc, offset);
3317         module_put(gc->gpiodev->owner);
3318 }
3319 EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
3320
3321 bool gpiochip_line_is_open_drain(struct gpio_chip *gc, unsigned int offset)
3322 {
3323         if (offset >= gc->ngpio)
3324                 return false;
3325
3326         return test_bit(FLAG_OPEN_DRAIN, &gc->gpiodev->descs[offset].flags);
3327 }
3328 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
3329
3330 bool gpiochip_line_is_open_source(struct gpio_chip *gc, unsigned int offset)
3331 {
3332         if (offset >= gc->ngpio)
3333                 return false;
3334
3335         return test_bit(FLAG_OPEN_SOURCE, &gc->gpiodev->descs[offset].flags);
3336 }
3337 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
3338
3339 bool gpiochip_line_is_persistent(struct gpio_chip *gc, unsigned int offset)
3340 {
3341         if (offset >= gc->ngpio)
3342                 return false;
3343
3344         return !test_bit(FLAG_TRANSITORY, &gc->gpiodev->descs[offset].flags);
3345 }
3346 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
3347
3348 /**
3349  * gpiod_get_raw_value_cansleep() - return a gpio's raw value
3350  * @desc: gpio whose value will be returned
3351  *
3352  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
3353  * its ACTIVE_LOW status, or negative errno on failure.
3354  *
3355  * This function is to be called from contexts that can sleep.
3356  */
3357 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
3358 {
3359         might_sleep_if(extra_checks);
3360         VALIDATE_DESC(desc);
3361         return gpiod_get_raw_value_commit(desc);
3362 }
3363 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
3364
3365 /**
3366  * gpiod_get_value_cansleep() - return a gpio's value
3367  * @desc: gpio whose value will be returned
3368  *
3369  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3370  * account, or negative errno on failure.
3371  *
3372  * This function is to be called from contexts that can sleep.
3373  */
3374 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
3375 {
3376         int value;
3377
3378         might_sleep_if(extra_checks);
3379         VALIDATE_DESC(desc);
3380         value = gpiod_get_raw_value_commit(desc);
3381         if (value < 0)
3382                 return value;
3383
3384         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3385                 value = !value;
3386
3387         return value;
3388 }
3389 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
3390
3391 /**
3392  * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
3393  * @array_size: number of elements in the descriptor array / value bitmap
3394  * @desc_array: array of GPIO descriptors whose values will be read
3395  * @array_info: information on applicability of fast bitmap processing path
3396  * @value_bitmap: bitmap to store the read values
3397  *
3398  * Read the raw values of the GPIOs, i.e. the values of the physical lines
3399  * without regard for their ACTIVE_LOW status.  Return 0 in case of success,
3400  * else an error code.
3401  *
3402  * This function is to be called from contexts that can sleep.
3403  */
3404 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
3405                                        struct gpio_desc **desc_array,
3406                                        struct gpio_array *array_info,
3407                                        unsigned long *value_bitmap)
3408 {
3409         might_sleep_if(extra_checks);
3410         if (!desc_array)
3411                 return -EINVAL;
3412         return gpiod_get_array_value_complex(true, true, array_size,
3413                                              desc_array, array_info,
3414                                              value_bitmap);
3415 }
3416 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
3417
3418 /**
3419  * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
3420  * @array_size: number of elements in the descriptor array / value bitmap
3421  * @desc_array: array of GPIO descriptors whose values will be read
3422  * @array_info: information on applicability of fast bitmap processing path
3423  * @value_bitmap: bitmap to store the read values
3424  *
3425  * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3426  * into account.  Return 0 in case of success, else an error code.
3427  *
3428  * This function is to be called from contexts that can sleep.
3429  */
3430 int gpiod_get_array_value_cansleep(unsigned int array_size,
3431                                    struct gpio_desc **desc_array,
3432                                    struct gpio_array *array_info,
3433                                    unsigned long *value_bitmap)
3434 {
3435         might_sleep_if(extra_checks);
3436         if (!desc_array)
3437                 return -EINVAL;
3438         return gpiod_get_array_value_complex(false, true, array_size,
3439                                              desc_array, array_info,
3440                                              value_bitmap);
3441 }
3442 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
3443
3444 /**
3445  * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
3446  * @desc: gpio whose value will be assigned
3447  * @value: value to assign
3448  *
3449  * Set the raw value of the GPIO, i.e. the value of its physical line without
3450  * regard for its ACTIVE_LOW status.
3451  *
3452  * This function is to be called from contexts that can sleep.
3453  */
3454 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
3455 {
3456         might_sleep_if(extra_checks);
3457         VALIDATE_DESC_VOID(desc);
3458         gpiod_set_raw_value_commit(desc, value);
3459 }
3460 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
3461
3462 /**
3463  * gpiod_set_value_cansleep() - assign a gpio's value
3464  * @desc: gpio whose value will be assigned
3465  * @value: value to assign
3466  *
3467  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3468  * account
3469  *
3470  * This function is to be called from contexts that can sleep.
3471  */
3472 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
3473 {
3474         might_sleep_if(extra_checks);
3475         VALIDATE_DESC_VOID(desc);
3476         gpiod_set_value_nocheck(desc, value);
3477 }
3478 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
3479
3480 /**
3481  * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
3482  * @array_size: number of elements in the descriptor array / value bitmap
3483  * @desc_array: array of GPIO descriptors whose values will be assigned
3484  * @array_info: information on applicability of fast bitmap processing path
3485  * @value_bitmap: bitmap of values to assign
3486  *
3487  * Set the raw values of the GPIOs, i.e. the values of the physical lines
3488  * without regard for their ACTIVE_LOW status.
3489  *
3490  * This function is to be called from contexts that can sleep.
3491  */
3492 int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
3493                                        struct gpio_desc **desc_array,
3494                                        struct gpio_array *array_info,
3495                                        unsigned long *value_bitmap)
3496 {
3497         might_sleep_if(extra_checks);
3498         if (!desc_array)
3499                 return -EINVAL;
3500         return gpiod_set_array_value_complex(true, true, array_size, desc_array,
3501                                       array_info, value_bitmap);
3502 }
3503 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
3504
3505 /**
3506  * gpiod_add_lookup_tables() - register GPIO device consumers
3507  * @tables: list of tables of consumers to register
3508  * @n: number of tables in the list
3509  */
3510 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
3511 {
3512         unsigned int i;
3513
3514         mutex_lock(&gpio_lookup_lock);
3515
3516         for (i = 0; i < n; i++)
3517                 list_add_tail(&tables[i]->list, &gpio_lookup_list);
3518
3519         mutex_unlock(&gpio_lookup_lock);
3520 }
3521
3522 /**
3523  * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
3524  * @array_size: number of elements in the descriptor array / value bitmap
3525  * @desc_array: array of GPIO descriptors whose values will be assigned
3526  * @array_info: information on applicability of fast bitmap processing path
3527  * @value_bitmap: bitmap of values to assign
3528  *
3529  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3530  * into account.
3531  *
3532  * This function is to be called from contexts that can sleep.
3533  */
3534 int gpiod_set_array_value_cansleep(unsigned int array_size,
3535                                    struct gpio_desc **desc_array,
3536                                    struct gpio_array *array_info,
3537                                    unsigned long *value_bitmap)
3538 {
3539         might_sleep_if(extra_checks);
3540         if (!desc_array)
3541                 return -EINVAL;
3542         return gpiod_set_array_value_complex(false, true, array_size,
3543                                              desc_array, array_info,
3544                                              value_bitmap);
3545 }
3546 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
3547
3548 /**
3549  * gpiod_add_lookup_table() - register GPIO device consumers
3550  * @table: table of consumers to register
3551  */
3552 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
3553 {
3554         mutex_lock(&gpio_lookup_lock);
3555
3556         list_add_tail(&table->list, &gpio_lookup_list);
3557
3558         mutex_unlock(&gpio_lookup_lock);
3559 }
3560 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
3561
3562 /**
3563  * gpiod_remove_lookup_table() - unregister GPIO device consumers
3564  * @table: table of consumers to unregister
3565  */
3566 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
3567 {
3568         mutex_lock(&gpio_lookup_lock);
3569
3570         list_del(&table->list);
3571
3572         mutex_unlock(&gpio_lookup_lock);
3573 }
3574 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
3575
3576 /**
3577  * gpiod_add_hogs() - register a set of GPIO hogs from machine code
3578  * @hogs: table of gpio hog entries with a zeroed sentinel at the end
3579  */
3580 void gpiod_add_hogs(struct gpiod_hog *hogs)
3581 {
3582         struct gpio_chip *gc;
3583         struct gpiod_hog *hog;
3584
3585         mutex_lock(&gpio_machine_hogs_mutex);
3586
3587         for (hog = &hogs[0]; hog->chip_label; hog++) {
3588                 list_add_tail(&hog->list, &gpio_machine_hogs);
3589
3590                 /*
3591                  * The chip may have been registered earlier, so check if it
3592                  * exists and, if so, try to hog the line now.
3593                  */
3594                 gc = find_chip_by_name(hog->chip_label);
3595                 if (gc)
3596                         gpiochip_machine_hog(gc, hog);
3597         }
3598
3599         mutex_unlock(&gpio_machine_hogs_mutex);
3600 }
3601 EXPORT_SYMBOL_GPL(gpiod_add_hogs);
3602
3603 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
3604 {
3605         const char *dev_id = dev ? dev_name(dev) : NULL;
3606         struct gpiod_lookup_table *table;
3607
3608         mutex_lock(&gpio_lookup_lock);
3609
3610         list_for_each_entry(table, &gpio_lookup_list, list) {
3611                 if (table->dev_id && dev_id) {
3612                         /*
3613                          * Valid strings on both ends, must be identical to have
3614                          * a match
3615                          */
3616                         if (!strcmp(table->dev_id, dev_id))
3617                                 goto found;
3618                 } else {
3619                         /*
3620                          * One of the pointers is NULL, so both must be to have
3621                          * a match
3622                          */
3623                         if (dev_id == table->dev_id)
3624                                 goto found;
3625                 }
3626         }
3627         table = NULL;
3628
3629 found:
3630         mutex_unlock(&gpio_lookup_lock);
3631         return table;
3632 }
3633
3634 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
3635                                     unsigned int idx, unsigned long *flags)
3636 {
3637         struct gpio_desc *desc = ERR_PTR(-ENOENT);
3638         struct gpiod_lookup_table *table;
3639         struct gpiod_lookup *p;
3640
3641         table = gpiod_find_lookup_table(dev);
3642         if (!table)
3643                 return desc;
3644
3645         for (p = &table->table[0]; p->key; p++) {
3646                 struct gpio_chip *gc;
3647
3648                 /* idx must always match exactly */
3649                 if (p->idx != idx)
3650                         continue;
3651
3652                 /* If the lookup entry has a con_id, require exact match */
3653                 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
3654                         continue;
3655
3656                 if (p->chip_hwnum == U16_MAX) {
3657                         desc = gpio_name_to_desc(p->key);
3658                         if (desc) {
3659                                 *flags = p->flags;
3660                                 return desc;
3661                         }
3662
3663                         dev_warn(dev, "cannot find GPIO line %s, deferring\n",
3664                                  p->key);
3665                         return ERR_PTR(-EPROBE_DEFER);
3666                 }
3667
3668                 gc = find_chip_by_name(p->key);
3669
3670                 if (!gc) {
3671                         /*
3672                          * As the lookup table indicates a chip with
3673                          * p->key should exist, assume it may
3674                          * still appear later and let the interested
3675                          * consumer be probed again or let the Deferred
3676                          * Probe infrastructure handle the error.
3677                          */
3678                         dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
3679                                  p->key);
3680                         return ERR_PTR(-EPROBE_DEFER);
3681                 }
3682
3683                 if (gc->ngpio <= p->chip_hwnum) {
3684                         dev_err(dev,
3685                                 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
3686                                 idx, p->chip_hwnum, gc->ngpio - 1,
3687                                 gc->label);
3688                         return ERR_PTR(-EINVAL);
3689                 }
3690
3691                 desc = gpiochip_get_desc(gc, p->chip_hwnum);
3692                 *flags = p->flags;
3693
3694                 return desc;
3695         }
3696
3697         return desc;
3698 }
3699
3700 static int platform_gpio_count(struct device *dev, const char *con_id)
3701 {
3702         struct gpiod_lookup_table *table;
3703         struct gpiod_lookup *p;
3704         unsigned int count = 0;
3705
3706         table = gpiod_find_lookup_table(dev);
3707         if (!table)
3708                 return -ENOENT;
3709
3710         for (p = &table->table[0]; p->key; p++) {
3711                 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
3712                     (!con_id && !p->con_id))
3713                         count++;
3714         }
3715         if (!count)
3716                 return -ENOENT;
3717
3718         return count;
3719 }
3720
3721 /**
3722  * fwnode_gpiod_get_index - obtain a GPIO from firmware node
3723  * @fwnode:     handle of the firmware node
3724  * @con_id:     function within the GPIO consumer
3725  * @index:      index of the GPIO to obtain for the consumer
3726  * @flags:      GPIO initialization flags
3727  * @label:      label to attach to the requested GPIO
3728  *
3729  * This function can be used for drivers that get their configuration
3730  * from opaque firmware.
3731  *
3732  * The function properly finds the corresponding GPIO using whatever is the
3733  * underlying firmware interface and then makes sure that the GPIO
3734  * descriptor is requested before it is returned to the caller.
3735  *
3736  * Returns:
3737  * On successful request the GPIO pin is configured in accordance with
3738  * provided @flags.
3739  *
3740  * In case of error an ERR_PTR() is returned.
3741  */
3742 struct gpio_desc *fwnode_gpiod_get_index(struct fwnode_handle *fwnode,
3743                                          const char *con_id, int index,
3744                                          enum gpiod_flags flags,
3745                                          const char *label)
3746 {
3747         struct gpio_desc *desc;
3748         char prop_name[32]; /* 32 is max size of property name */
3749         unsigned int i;
3750
3751         for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
3752                 if (con_id)
3753                         snprintf(prop_name, sizeof(prop_name), "%s-%s",
3754                                             con_id, gpio_suffixes[i]);
3755                 else
3756                         snprintf(prop_name, sizeof(prop_name), "%s",
3757                                             gpio_suffixes[i]);
3758
3759                 desc = fwnode_get_named_gpiod(fwnode, prop_name, index, flags,
3760                                               label);
3761                 if (!IS_ERR(desc) || (PTR_ERR(desc) != -ENOENT))
3762                         break;
3763         }
3764
3765         return desc;
3766 }
3767 EXPORT_SYMBOL_GPL(fwnode_gpiod_get_index);
3768
3769 /**
3770  * gpiod_count - return the number of GPIOs associated with a device / function
3771  *              or -ENOENT if no GPIO has been assigned to the requested function
3772  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3773  * @con_id:     function within the GPIO consumer
3774  */
3775 int gpiod_count(struct device *dev, const char *con_id)
3776 {
3777         int count = -ENOENT;
3778
3779         if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
3780                 count = of_gpio_get_count(dev, con_id);
3781         else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
3782                 count = acpi_gpio_count(dev, con_id);
3783
3784         if (count < 0)
3785                 count = platform_gpio_count(dev, con_id);
3786
3787         return count;
3788 }
3789 EXPORT_SYMBOL_GPL(gpiod_count);
3790
3791 /**
3792  * gpiod_get - obtain a GPIO for a given GPIO function
3793  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3794  * @con_id:     function within the GPIO consumer
3795  * @flags:      optional GPIO initialization flags
3796  *
3797  * Return the GPIO descriptor corresponding to the function con_id of device
3798  * dev, -ENOENT if no GPIO has been assigned to the requested function, or
3799  * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
3800  */
3801 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
3802                                          enum gpiod_flags flags)
3803 {
3804         return gpiod_get_index(dev, con_id, 0, flags);
3805 }
3806 EXPORT_SYMBOL_GPL(gpiod_get);
3807
3808 /**
3809  * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
3810  * @dev: GPIO consumer, can be NULL for system-global GPIOs
3811  * @con_id: function within the GPIO consumer
3812  * @flags: optional GPIO initialization flags
3813  *
3814  * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
3815  * the requested function it will return NULL. This is convenient for drivers
3816  * that need to handle optional GPIOs.
3817  */
3818 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
3819                                                   const char *con_id,
3820                                                   enum gpiod_flags flags)
3821 {
3822         return gpiod_get_index_optional(dev, con_id, 0, flags);
3823 }
3824 EXPORT_SYMBOL_GPL(gpiod_get_optional);
3825
3826
3827 /**
3828  * gpiod_configure_flags - helper function to configure a given GPIO
3829  * @desc:       gpio whose value will be assigned
3830  * @con_id:     function within the GPIO consumer
3831  * @lflags:     bitmask of gpio_lookup_flags GPIO_* values - returned from
3832  *              of_find_gpio() or of_get_gpio_hog()
3833  * @dflags:     gpiod_flags - optional GPIO initialization flags
3834  *
3835  * Return 0 on success, -ENOENT if no GPIO has been assigned to the
3836  * requested function and/or index, or another IS_ERR() code if an error
3837  * occurred while trying to acquire the GPIO.
3838  */
3839 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
3840                 unsigned long lflags, enum gpiod_flags dflags)
3841 {
3842         int ret;
3843
3844         if (lflags & GPIO_ACTIVE_LOW)
3845                 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
3846
3847         if (lflags & GPIO_OPEN_DRAIN)
3848                 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3849         else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
3850                 /*
3851                  * This enforces open drain mode from the consumer side.
3852                  * This is necessary for some busses like I2C, but the lookup
3853                  * should *REALLY* have specified them as open drain in the
3854                  * first place, so print a little warning here.
3855                  */
3856                 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3857                 gpiod_warn(desc,
3858                            "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
3859         }
3860
3861         if (lflags & GPIO_OPEN_SOURCE)
3862                 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
3863
3864         if ((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DOWN)) {
3865                 gpiod_err(desc,
3866                           "both pull-up and pull-down enabled, invalid configuration\n");
3867                 return -EINVAL;
3868         }
3869
3870         if (lflags & GPIO_PULL_UP)
3871                 set_bit(FLAG_PULL_UP, &desc->flags);
3872         else if (lflags & GPIO_PULL_DOWN)
3873                 set_bit(FLAG_PULL_DOWN, &desc->flags);
3874
3875         ret = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
3876         if (ret < 0)
3877                 return ret;
3878
3879         /* No particular flag request, return here... */
3880         if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
3881                 gpiod_dbg(desc, "no flags found for %s\n", con_id);
3882                 return 0;
3883         }
3884
3885         /* Process flags */
3886         if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
3887                 ret = gpiod_direction_output(desc,
3888                                 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
3889         else
3890                 ret = gpiod_direction_input(desc);
3891
3892         return ret;
3893 }
3894
3895 /**
3896  * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
3897  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3898  * @con_id:     function within the GPIO consumer
3899  * @idx:        index of the GPIO to obtain in the consumer
3900  * @flags:      optional GPIO initialization flags
3901  *
3902  * This variant of gpiod_get() allows to access GPIOs other than the first
3903  * defined one for functions that define several GPIOs.
3904  *
3905  * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
3906  * requested function and/or index, or another IS_ERR() code if an error
3907  * occurred while trying to acquire the GPIO.
3908  */
3909 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
3910                                                const char *con_id,
3911                                                unsigned int idx,
3912                                                enum gpiod_flags flags)
3913 {
3914         unsigned long lookupflags = GPIO_LOOKUP_FLAGS_DEFAULT;
3915         struct gpio_desc *desc = NULL;
3916         int ret;
3917         /* Maybe we have a device name, maybe not */
3918         const char *devname = dev ? dev_name(dev) : "?";
3919
3920         dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
3921
3922         if (dev) {
3923                 /* Using device tree? */
3924                 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
3925                         dev_dbg(dev, "using device tree for GPIO lookup\n");
3926                         desc = of_find_gpio(dev, con_id, idx, &lookupflags);
3927                 } else if (ACPI_COMPANION(dev)) {
3928                         dev_dbg(dev, "using ACPI for GPIO lookup\n");
3929                         desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
3930                 }
3931         }
3932
3933         /*
3934          * Either we are not using DT or ACPI, or their lookup did not return
3935          * a result. In that case, use platform lookup as a fallback.
3936          */
3937         if (!desc || desc == ERR_PTR(-ENOENT)) {
3938                 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
3939                 desc = gpiod_find(dev, con_id, idx, &lookupflags);
3940         }
3941
3942         if (IS_ERR(desc)) {
3943                 dev_dbg(dev, "No GPIO consumer %s found\n", con_id);
3944                 return desc;
3945         }
3946
3947         /*
3948          * If a connection label was passed use that, else attempt to use
3949          * the device name as label
3950          */
3951         ret = gpiod_request(desc, con_id ? con_id : devname);
3952         if (ret < 0) {
3953                 if (ret == -EBUSY && flags & GPIOD_FLAGS_BIT_NONEXCLUSIVE) {
3954                         /*
3955                          * This happens when there are several consumers for
3956                          * the same GPIO line: we just return here without
3957                          * further initialization. It is a bit if a hack.
3958                          * This is necessary to support fixed regulators.
3959                          *
3960                          * FIXME: Make this more sane and safe.
3961                          */
3962                         dev_info(dev, "nonexclusive access to GPIO for %s\n",
3963                                  con_id ? con_id : devname);
3964                         return desc;
3965                 } else {
3966                         return ERR_PTR(ret);
3967                 }
3968         }
3969
3970         ret = gpiod_configure_flags(desc, con_id, lookupflags, flags);
3971         if (ret < 0) {
3972                 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
3973                 gpiod_put(desc);
3974                 return ERR_PTR(ret);
3975         }
3976
3977         blocking_notifier_call_chain(&desc->gdev->notifier,
3978                                      GPIOLINE_CHANGED_REQUESTED, desc);
3979
3980         return desc;
3981 }
3982 EXPORT_SYMBOL_GPL(gpiod_get_index);
3983
3984 /**
3985  * fwnode_get_named_gpiod - obtain a GPIO from firmware node
3986  * @fwnode:     handle of the firmware node
3987  * @propname:   name of the firmware property representing the GPIO
3988  * @index:      index of the GPIO to obtain for the consumer
3989  * @dflags:     GPIO initialization flags
3990  * @label:      label to attach to the requested GPIO
3991  *
3992  * This function can be used for drivers that get their configuration
3993  * from opaque firmware.
3994  *
3995  * The function properly finds the corresponding GPIO using whatever is the
3996  * underlying firmware interface and then makes sure that the GPIO
3997  * descriptor is requested before it is returned to the caller.
3998  *
3999  * Returns:
4000  * On successful request the GPIO pin is configured in accordance with
4001  * provided @dflags.
4002  *
4003  * In case of error an ERR_PTR() is returned.
4004  */
4005 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
4006                                          const char *propname, int index,
4007                                          enum gpiod_flags dflags,
4008                                          const char *label)
4009 {
4010         unsigned long lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4011         struct gpio_desc *desc = ERR_PTR(-ENODEV);
4012         int ret;
4013
4014         if (!fwnode)
4015                 return ERR_PTR(-EINVAL);
4016
4017         if (is_of_node(fwnode)) {
4018                 desc = gpiod_get_from_of_node(to_of_node(fwnode),
4019                                               propname, index,
4020                                               dflags,
4021                                               label);
4022                 return desc;
4023         } else if (is_acpi_node(fwnode)) {
4024                 struct acpi_gpio_info info;
4025
4026                 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
4027                 if (IS_ERR(desc))
4028                         return desc;
4029
4030                 acpi_gpio_update_gpiod_flags(&dflags, &info);
4031                 acpi_gpio_update_gpiod_lookup_flags(&lflags, &info);
4032         }
4033
4034         /* Currently only ACPI takes this path */
4035         ret = gpiod_request(desc, label);
4036         if (ret)
4037                 return ERR_PTR(ret);
4038
4039         ret = gpiod_configure_flags(desc, propname, lflags, dflags);
4040         if (ret < 0) {
4041                 gpiod_put(desc);
4042                 return ERR_PTR(ret);
4043         }
4044
4045         blocking_notifier_call_chain(&desc->gdev->notifier,
4046                                      GPIOLINE_CHANGED_REQUESTED, desc);
4047
4048         return desc;
4049 }
4050 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
4051
4052 /**
4053  * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
4054  *                            function
4055  * @dev: GPIO consumer, can be NULL for system-global GPIOs
4056  * @con_id: function within the GPIO consumer
4057  * @index: index of the GPIO to obtain in the consumer
4058  * @flags: optional GPIO initialization flags
4059  *
4060  * This is equivalent to gpiod_get_index(), except that when no GPIO with the
4061  * specified index was assigned to the requested function it will return NULL.
4062  * This is convenient for drivers that need to handle optional GPIOs.
4063  */
4064 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
4065                                                         const char *con_id,
4066                                                         unsigned int index,
4067                                                         enum gpiod_flags flags)
4068 {
4069         struct gpio_desc *desc;
4070
4071         desc = gpiod_get_index(dev, con_id, index, flags);
4072         if (IS_ERR(desc)) {
4073                 if (PTR_ERR(desc) == -ENOENT)
4074                         return NULL;
4075         }
4076
4077         return desc;
4078 }
4079 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
4080
4081 /**
4082  * gpiod_hog - Hog the specified GPIO desc given the provided flags
4083  * @desc:       gpio whose value will be assigned
4084  * @name:       gpio line name
4085  * @lflags:     bitmask of gpio_lookup_flags GPIO_* values - returned from
4086  *              of_find_gpio() or of_get_gpio_hog()
4087  * @dflags:     gpiod_flags - optional GPIO initialization flags
4088  */
4089 int gpiod_hog(struct gpio_desc *desc, const char *name,
4090               unsigned long lflags, enum gpiod_flags dflags)
4091 {
4092         struct gpio_chip *gc;
4093         struct gpio_desc *local_desc;
4094         int hwnum;
4095         int ret;
4096
4097         gc = gpiod_to_chip(desc);
4098         hwnum = gpio_chip_hwgpio(desc);
4099
4100         local_desc = gpiochip_request_own_desc(gc, hwnum, name,
4101                                                lflags, dflags);
4102         if (IS_ERR(local_desc)) {
4103                 ret = PTR_ERR(local_desc);
4104                 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
4105                        name, gc->label, hwnum, ret);
4106                 return ret;
4107         }
4108
4109         /* Mark GPIO as hogged so it can be identified and removed later */
4110         set_bit(FLAG_IS_HOGGED, &desc->flags);
4111
4112         gpiod_info(desc, "hogged as %s%s\n",
4113                 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
4114                 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ?
4115                   (dflags & GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low" : "");
4116
4117         return 0;
4118 }
4119
4120 /**
4121  * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
4122  * @gc: gpio chip to act on
4123  */
4124 static void gpiochip_free_hogs(struct gpio_chip *gc)
4125 {
4126         int id;
4127
4128         for (id = 0; id < gc->ngpio; id++) {
4129                 if (test_bit(FLAG_IS_HOGGED, &gc->gpiodev->descs[id].flags))
4130                         gpiochip_free_own_desc(&gc->gpiodev->descs[id]);
4131         }
4132 }
4133
4134 /**
4135  * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
4136  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
4137  * @con_id:     function within the GPIO consumer
4138  * @flags:      optional GPIO initialization flags
4139  *
4140  * This function acquires all the GPIOs defined under a given function.
4141  *
4142  * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
4143  * no GPIO has been assigned to the requested function, or another IS_ERR()
4144  * code if an error occurred while trying to acquire the GPIOs.
4145  */
4146 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
4147                                                 const char *con_id,
4148                                                 enum gpiod_flags flags)
4149 {
4150         struct gpio_desc *desc;
4151         struct gpio_descs *descs;
4152         struct gpio_array *array_info = NULL;
4153         struct gpio_chip *gc;
4154         int count, bitmap_size;
4155
4156         count = gpiod_count(dev, con_id);
4157         if (count < 0)
4158                 return ERR_PTR(count);
4159
4160         descs = kzalloc(struct_size(descs, desc, count), GFP_KERNEL);
4161         if (!descs)
4162                 return ERR_PTR(-ENOMEM);
4163
4164         for (descs->ndescs = 0; descs->ndescs < count; ) {
4165                 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
4166                 if (IS_ERR(desc)) {
4167                         gpiod_put_array(descs);
4168                         return ERR_CAST(desc);
4169                 }
4170
4171                 descs->desc[descs->ndescs] = desc;
4172
4173                 gc = gpiod_to_chip(desc);
4174                 /*
4175                  * If pin hardware number of array member 0 is also 0, select
4176                  * its chip as a candidate for fast bitmap processing path.
4177                  */
4178                 if (descs->ndescs == 0 && gpio_chip_hwgpio(desc) == 0) {
4179                         struct gpio_descs *array;
4180
4181                         bitmap_size = BITS_TO_LONGS(gc->ngpio > count ?
4182                                                     gc->ngpio : count);
4183
4184                         array = kzalloc(struct_size(descs, desc, count) +
4185                                         struct_size(array_info, invert_mask,
4186                                         3 * bitmap_size), GFP_KERNEL);
4187                         if (!array) {
4188                                 gpiod_put_array(descs);
4189                                 return ERR_PTR(-ENOMEM);
4190                         }
4191
4192                         memcpy(array, descs,
4193                                struct_size(descs, desc, descs->ndescs + 1));
4194                         kfree(descs);
4195
4196                         descs = array;
4197                         array_info = (void *)(descs->desc + count);
4198                         array_info->get_mask = array_info->invert_mask +
4199                                                   bitmap_size;
4200                         array_info->set_mask = array_info->get_mask +
4201                                                   bitmap_size;
4202
4203                         array_info->desc = descs->desc;
4204                         array_info->size = count;
4205                         array_info->chip = gc;
4206                         bitmap_set(array_info->get_mask, descs->ndescs,
4207                                    count - descs->ndescs);
4208                         bitmap_set(array_info->set_mask, descs->ndescs,
4209                                    count - descs->ndescs);
4210                         descs->info = array_info;
4211                 }
4212                 /* Unmark array members which don't belong to the 'fast' chip */
4213                 if (array_info && array_info->chip != gc) {
4214                         __clear_bit(descs->ndescs, array_info->get_mask);
4215                         __clear_bit(descs->ndescs, array_info->set_mask);
4216                 }
4217                 /*
4218                  * Detect array members which belong to the 'fast' chip
4219                  * but their pins are not in hardware order.
4220                  */
4221                 else if (array_info &&
4222                            gpio_chip_hwgpio(desc) != descs->ndescs) {
4223                         /*
4224                          * Don't use fast path if all array members processed so
4225                          * far belong to the same chip as this one but its pin
4226                          * hardware number is different from its array index.
4227                          */
4228                         if (bitmap_full(array_info->get_mask, descs->ndescs)) {
4229                                 array_info = NULL;
4230                         } else {
4231                                 __clear_bit(descs->ndescs,
4232                                             array_info->get_mask);
4233                                 __clear_bit(descs->ndescs,
4234                                             array_info->set_mask);
4235                         }
4236                 } else if (array_info) {
4237                         /* Exclude open drain or open source from fast output */
4238                         if (gpiochip_line_is_open_drain(gc, descs->ndescs) ||
4239                             gpiochip_line_is_open_source(gc, descs->ndescs))
4240                                 __clear_bit(descs->ndescs,
4241                                             array_info->set_mask);
4242                         /* Identify 'fast' pins which require invertion */
4243                         if (gpiod_is_active_low(desc))
4244                                 __set_bit(descs->ndescs,
4245                                           array_info->invert_mask);
4246                 }
4247
4248                 descs->ndescs++;
4249         }
4250         if (array_info)
4251                 dev_dbg(dev,
4252                         "GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
4253                         array_info->chip->label, array_info->size,
4254                         *array_info->get_mask, *array_info->set_mask,
4255                         *array_info->invert_mask);
4256         return descs;
4257 }
4258 EXPORT_SYMBOL_GPL(gpiod_get_array);
4259
4260 /**
4261  * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
4262  *                            function
4263  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
4264  * @con_id:     function within the GPIO consumer
4265  * @flags:      optional GPIO initialization flags
4266  *
4267  * This is equivalent to gpiod_get_array(), except that when no GPIO was
4268  * assigned to the requested function it will return NULL.
4269  */
4270 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
4271                                                         const char *con_id,
4272                                                         enum gpiod_flags flags)
4273 {
4274         struct gpio_descs *descs;
4275
4276         descs = gpiod_get_array(dev, con_id, flags);
4277         if (PTR_ERR(descs) == -ENOENT)
4278                 return NULL;
4279
4280         return descs;
4281 }
4282 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
4283
4284 /**
4285  * gpiod_put - dispose of a GPIO descriptor
4286  * @desc:       GPIO descriptor to dispose of
4287  *
4288  * No descriptor can be used after gpiod_put() has been called on it.
4289  */
4290 void gpiod_put(struct gpio_desc *desc)
4291 {
4292         if (desc)
4293                 gpiod_free(desc);
4294 }
4295 EXPORT_SYMBOL_GPL(gpiod_put);
4296
4297 /**
4298  * gpiod_put_array - dispose of multiple GPIO descriptors
4299  * @descs:      struct gpio_descs containing an array of descriptors
4300  */
4301 void gpiod_put_array(struct gpio_descs *descs)
4302 {
4303         unsigned int i;
4304
4305         for (i = 0; i < descs->ndescs; i++)
4306                 gpiod_put(descs->desc[i]);
4307
4308         kfree(descs);
4309 }
4310 EXPORT_SYMBOL_GPL(gpiod_put_array);
4311
4312 static int __init gpiolib_dev_init(void)
4313 {
4314         int ret;
4315
4316         /* Register GPIO sysfs bus */
4317         ret = bus_register(&gpio_bus_type);
4318         if (ret < 0) {
4319                 pr_err("gpiolib: could not register GPIO bus type\n");
4320                 return ret;
4321         }
4322
4323         ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, GPIOCHIP_NAME);
4324         if (ret < 0) {
4325                 pr_err("gpiolib: failed to allocate char dev region\n");
4326                 bus_unregister(&gpio_bus_type);
4327                 return ret;
4328         }
4329
4330         gpiolib_initialized = true;
4331         gpiochip_setup_devs();
4332
4333 #if IS_ENABLED(CONFIG_OF_DYNAMIC) && IS_ENABLED(CONFIG_OF_GPIO)
4334         WARN_ON(of_reconfig_notifier_register(&gpio_of_notifier));
4335 #endif /* CONFIG_OF_DYNAMIC && CONFIG_OF_GPIO */
4336
4337         return ret;
4338 }
4339 core_initcall(gpiolib_dev_init);
4340
4341 #ifdef CONFIG_DEBUG_FS
4342
4343 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
4344 {
4345         unsigned                i;
4346         struct gpio_chip        *gc = gdev->chip;
4347         unsigned                gpio = gdev->base;
4348         struct gpio_desc        *gdesc = &gdev->descs[0];
4349         bool                    is_out;
4350         bool                    is_irq;
4351         bool                    active_low;
4352
4353         for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
4354                 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
4355                         if (gdesc->name) {
4356                                 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
4357                                            gpio, gdesc->name);
4358                         }
4359                         continue;
4360                 }
4361
4362                 gpiod_get_direction(gdesc);
4363                 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
4364                 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
4365                 active_low = test_bit(FLAG_ACTIVE_LOW, &gdesc->flags);
4366                 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s%s",
4367                         gpio, gdesc->name ? gdesc->name : "", gdesc->label,
4368                         is_out ? "out" : "in ",
4369                         gc->get ? (gc->get(gc, i) ? "hi" : "lo") : "?  ",
4370                         is_irq ? "IRQ " : "",
4371                         active_low ? "ACTIVE LOW" : "");
4372                 seq_printf(s, "\n");
4373         }
4374 }
4375
4376 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
4377 {
4378         unsigned long flags;
4379         struct gpio_device *gdev = NULL;
4380         loff_t index = *pos;
4381
4382         s->private = "";
4383
4384         spin_lock_irqsave(&gpio_lock, flags);
4385         list_for_each_entry(gdev, &gpio_devices, list)
4386                 if (index-- == 0) {
4387                         spin_unlock_irqrestore(&gpio_lock, flags);
4388                         return gdev;
4389                 }
4390         spin_unlock_irqrestore(&gpio_lock, flags);
4391
4392         return NULL;
4393 }
4394
4395 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
4396 {
4397         unsigned long flags;
4398         struct gpio_device *gdev = v;
4399         void *ret = NULL;
4400
4401         spin_lock_irqsave(&gpio_lock, flags);
4402         if (list_is_last(&gdev->list, &gpio_devices))
4403                 ret = NULL;
4404         else
4405                 ret = list_entry(gdev->list.next, struct gpio_device, list);
4406         spin_unlock_irqrestore(&gpio_lock, flags);
4407
4408         s->private = "\n";
4409         ++*pos;
4410
4411         return ret;
4412 }
4413
4414 static void gpiolib_seq_stop(struct seq_file *s, void *v)
4415 {
4416 }
4417
4418 static int gpiolib_seq_show(struct seq_file *s, void *v)
4419 {
4420         struct gpio_device *gdev = v;
4421         struct gpio_chip *gc = gdev->chip;
4422         struct device *parent;
4423
4424         if (!gc) {
4425                 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
4426                            dev_name(&gdev->dev));
4427                 return 0;
4428         }
4429
4430         seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
4431                    dev_name(&gdev->dev),
4432                    gdev->base, gdev->base + gdev->ngpio - 1);
4433         parent = gc->parent;
4434         if (parent)
4435                 seq_printf(s, ", parent: %s/%s",
4436                            parent->bus ? parent->bus->name : "no-bus",
4437                            dev_name(parent));
4438         if (gc->label)
4439                 seq_printf(s, ", %s", gc->label);
4440         if (gc->can_sleep)
4441                 seq_printf(s, ", can sleep");
4442         seq_printf(s, ":\n");
4443
4444         if (gc->dbg_show)
4445                 gc->dbg_show(s, gc);
4446         else
4447                 gpiolib_dbg_show(s, gdev);
4448
4449         return 0;
4450 }
4451
4452 static const struct seq_operations gpiolib_sops = {
4453         .start = gpiolib_seq_start,
4454         .next = gpiolib_seq_next,
4455         .stop = gpiolib_seq_stop,
4456         .show = gpiolib_seq_show,
4457 };
4458 DEFINE_SEQ_ATTRIBUTE(gpiolib);
4459
4460 static int __init gpiolib_debugfs_init(void)
4461 {
4462         /* /sys/kernel/debug/gpio */
4463         debugfs_create_file("gpio", 0444, NULL, NULL, &gpiolib_fops);
4464         return 0;
4465 }
4466 subsys_initcall(gpiolib_debugfs_init);
4467
4468 #endif  /* DEBUG_FS */