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