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