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