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