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