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