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