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