gpiolib: split character device into gpiolib-cdev
[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                 if (bitmap_full(array_info->get_mask, array_size))
2598                         return 0;
2599
2600                 i = find_first_zero_bit(array_info->get_mask, array_size);
2601         } else {
2602                 array_info = NULL;
2603         }
2604
2605         while (i < array_size) {
2606                 struct gpio_chip *gc = desc_array[i]->gdev->chip;
2607                 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
2608                 unsigned long *mask, *bits;
2609                 int first, j, ret;
2610
2611                 if (likely(gc->ngpio <= FASTPATH_NGPIO)) {
2612                         mask = fastpath;
2613                 } else {
2614                         mask = kmalloc_array(2 * BITS_TO_LONGS(gc->ngpio),
2615                                            sizeof(*mask),
2616                                            can_sleep ? GFP_KERNEL : GFP_ATOMIC);
2617                         if (!mask)
2618                                 return -ENOMEM;
2619                 }
2620
2621                 bits = mask + BITS_TO_LONGS(gc->ngpio);
2622                 bitmap_zero(mask, gc->ngpio);
2623
2624                 if (!can_sleep)
2625                         WARN_ON(gc->can_sleep);
2626
2627                 /* collect all inputs belonging to the same chip */
2628                 first = i;
2629                 do {
2630                         const struct gpio_desc *desc = desc_array[i];
2631                         int hwgpio = gpio_chip_hwgpio(desc);
2632
2633                         __set_bit(hwgpio, mask);
2634                         i++;
2635
2636                         if (array_info)
2637                                 i = find_next_zero_bit(array_info->get_mask,
2638                                                        array_size, i);
2639                 } while ((i < array_size) &&
2640                          (desc_array[i]->gdev->chip == gc));
2641
2642                 ret = gpio_chip_get_multiple(gc, mask, bits);
2643                 if (ret) {
2644                         if (mask != fastpath)
2645                                 kfree(mask);
2646                         return ret;
2647                 }
2648
2649                 for (j = first; j < i; ) {
2650                         const struct gpio_desc *desc = desc_array[j];
2651                         int hwgpio = gpio_chip_hwgpio(desc);
2652                         int value = test_bit(hwgpio, bits);
2653
2654                         if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2655                                 value = !value;
2656                         __assign_bit(j, value_bitmap, value);
2657                         trace_gpio_value(desc_to_gpio(desc), 1, value);
2658                         j++;
2659
2660                         if (array_info)
2661                                 j = find_next_zero_bit(array_info->get_mask, i,
2662                                                        j);
2663                 }
2664
2665                 if (mask != fastpath)
2666                         kfree(mask);
2667         }
2668         return 0;
2669 }
2670
2671 /**
2672  * gpiod_get_raw_value() - return a gpio's raw value
2673  * @desc: gpio whose value will be returned
2674  *
2675  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2676  * its ACTIVE_LOW status, or negative errno on failure.
2677  *
2678  * This function can be called from contexts where we cannot sleep, and will
2679  * complain if the GPIO chip functions potentially sleep.
2680  */
2681 int gpiod_get_raw_value(const struct gpio_desc *desc)
2682 {
2683         VALIDATE_DESC(desc);
2684         /* Should be using gpiod_get_raw_value_cansleep() */
2685         WARN_ON(desc->gdev->chip->can_sleep);
2686         return gpiod_get_raw_value_commit(desc);
2687 }
2688 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
2689
2690 /**
2691  * gpiod_get_value() - return a gpio's value
2692  * @desc: gpio whose value will be returned
2693  *
2694  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2695  * account, or negative errno on failure.
2696  *
2697  * This function can be called from contexts where we cannot sleep, and will
2698  * complain if the GPIO chip functions potentially sleep.
2699  */
2700 int gpiod_get_value(const struct gpio_desc *desc)
2701 {
2702         int value;
2703
2704         VALIDATE_DESC(desc);
2705         /* Should be using gpiod_get_value_cansleep() */
2706         WARN_ON(desc->gdev->chip->can_sleep);
2707
2708         value = gpiod_get_raw_value_commit(desc);
2709         if (value < 0)
2710                 return value;
2711
2712         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2713                 value = !value;
2714
2715         return value;
2716 }
2717 EXPORT_SYMBOL_GPL(gpiod_get_value);
2718
2719 /**
2720  * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
2721  * @array_size: number of elements in the descriptor array / value bitmap
2722  * @desc_array: array of GPIO descriptors whose values will be read
2723  * @array_info: information on applicability of fast bitmap processing path
2724  * @value_bitmap: bitmap to store the read values
2725  *
2726  * Read the raw values of the GPIOs, i.e. the values of the physical lines
2727  * without regard for their ACTIVE_LOW status.  Return 0 in case of success,
2728  * else an error code.
2729  *
2730  * This function can be called from contexts where we cannot sleep,
2731  * and it will complain if the GPIO chip functions potentially sleep.
2732  */
2733 int gpiod_get_raw_array_value(unsigned int array_size,
2734                               struct gpio_desc **desc_array,
2735                               struct gpio_array *array_info,
2736                               unsigned long *value_bitmap)
2737 {
2738         if (!desc_array)
2739                 return -EINVAL;
2740         return gpiod_get_array_value_complex(true, false, array_size,
2741                                              desc_array, array_info,
2742                                              value_bitmap);
2743 }
2744 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
2745
2746 /**
2747  * gpiod_get_array_value() - read values from an array of GPIOs
2748  * @array_size: number of elements in the descriptor array / value bitmap
2749  * @desc_array: array of GPIO descriptors whose values will be read
2750  * @array_info: information on applicability of fast bitmap processing path
2751  * @value_bitmap: bitmap to store the read values
2752  *
2753  * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
2754  * into account.  Return 0 in case of success, else an error code.
2755  *
2756  * This function can be called from contexts where we cannot sleep,
2757  * and it will complain if the GPIO chip functions potentially sleep.
2758  */
2759 int gpiod_get_array_value(unsigned int array_size,
2760                           struct gpio_desc **desc_array,
2761                           struct gpio_array *array_info,
2762                           unsigned long *value_bitmap)
2763 {
2764         if (!desc_array)
2765                 return -EINVAL;
2766         return gpiod_get_array_value_complex(false, false, array_size,
2767                                              desc_array, array_info,
2768                                              value_bitmap);
2769 }
2770 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
2771
2772 /*
2773  *  gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
2774  * @desc: gpio descriptor whose state need to be set.
2775  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2776  */
2777 static void gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
2778 {
2779         int ret = 0;
2780         struct gpio_chip *gc = desc->gdev->chip;
2781         int offset = gpio_chip_hwgpio(desc);
2782
2783         if (value) {
2784                 ret = gc->direction_input(gc, offset);
2785         } else {
2786                 ret = gc->direction_output(gc, offset, 0);
2787                 if (!ret)
2788                         set_bit(FLAG_IS_OUT, &desc->flags);
2789         }
2790         trace_gpio_direction(desc_to_gpio(desc), value, ret);
2791         if (ret < 0)
2792                 gpiod_err(desc,
2793                           "%s: Error in set_value for open drain err %d\n",
2794                           __func__, ret);
2795 }
2796
2797 /*
2798  *  _gpio_set_open_source_value() - Set the open source gpio's value.
2799  * @desc: gpio descriptor whose state need to be set.
2800  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2801  */
2802 static void gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
2803 {
2804         int ret = 0;
2805         struct gpio_chip *gc = desc->gdev->chip;
2806         int offset = gpio_chip_hwgpio(desc);
2807
2808         if (value) {
2809                 ret = gc->direction_output(gc, offset, 1);
2810                 if (!ret)
2811                         set_bit(FLAG_IS_OUT, &desc->flags);
2812         } else {
2813                 ret = gc->direction_input(gc, offset);
2814         }
2815         trace_gpio_direction(desc_to_gpio(desc), !value, ret);
2816         if (ret < 0)
2817                 gpiod_err(desc,
2818                           "%s: Error in set_value for open source err %d\n",
2819                           __func__, ret);
2820 }
2821
2822 static void gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
2823 {
2824         struct gpio_chip        *gc;
2825
2826         gc = desc->gdev->chip;
2827         trace_gpio_value(desc_to_gpio(desc), 0, value);
2828         gc->set(gc, gpio_chip_hwgpio(desc), value);
2829 }
2830
2831 /*
2832  * set multiple outputs on the same chip;
2833  * use the chip's set_multiple function if available;
2834  * otherwise set the outputs sequentially;
2835  * @chip: the GPIO chip we operate on
2836  * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
2837  *        defines which outputs are to be changed
2838  * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
2839  *        defines the values the outputs specified by mask are to be set to
2840  */
2841 static void gpio_chip_set_multiple(struct gpio_chip *gc,
2842                                    unsigned long *mask, unsigned long *bits)
2843 {
2844         if (gc->set_multiple) {
2845                 gc->set_multiple(gc, mask, bits);
2846         } else {
2847                 unsigned int i;
2848
2849                 /* set outputs if the corresponding mask bit is set */
2850                 for_each_set_bit(i, mask, gc->ngpio)
2851                         gc->set(gc, i, test_bit(i, bits));
2852         }
2853 }
2854
2855 int gpiod_set_array_value_complex(bool raw, bool can_sleep,
2856                                   unsigned int array_size,
2857                                   struct gpio_desc **desc_array,
2858                                   struct gpio_array *array_info,
2859                                   unsigned long *value_bitmap)
2860 {
2861         int i = 0;
2862
2863         /*
2864          * Validate array_info against desc_array and its size.
2865          * It should immediately follow desc_array if both
2866          * have been obtained from the same gpiod_get_array() call.
2867          */
2868         if (array_info && array_info->desc == desc_array &&
2869             array_size <= array_info->size &&
2870             (void *)array_info == desc_array + array_info->size) {
2871                 if (!can_sleep)
2872                         WARN_ON(array_info->chip->can_sleep);
2873
2874                 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
2875                         bitmap_xor(value_bitmap, value_bitmap,
2876                                    array_info->invert_mask, array_size);
2877
2878                 gpio_chip_set_multiple(array_info->chip, array_info->set_mask,
2879                                        value_bitmap);
2880
2881                 if (bitmap_full(array_info->set_mask, array_size))
2882                         return 0;
2883
2884                 i = find_first_zero_bit(array_info->set_mask, array_size);
2885         } else {
2886                 array_info = NULL;
2887         }
2888
2889         while (i < array_size) {
2890                 struct gpio_chip *gc = desc_array[i]->gdev->chip;
2891                 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
2892                 unsigned long *mask, *bits;
2893                 int count = 0;
2894
2895                 if (likely(gc->ngpio <= FASTPATH_NGPIO)) {
2896                         mask = fastpath;
2897                 } else {
2898                         mask = kmalloc_array(2 * BITS_TO_LONGS(gc->ngpio),
2899                                            sizeof(*mask),
2900                                            can_sleep ? GFP_KERNEL : GFP_ATOMIC);
2901                         if (!mask)
2902                                 return -ENOMEM;
2903                 }
2904
2905                 bits = mask + BITS_TO_LONGS(gc->ngpio);
2906                 bitmap_zero(mask, gc->ngpio);
2907
2908                 if (!can_sleep)
2909                         WARN_ON(gc->can_sleep);
2910
2911                 do {
2912                         struct gpio_desc *desc = desc_array[i];
2913                         int hwgpio = gpio_chip_hwgpio(desc);
2914                         int value = test_bit(i, value_bitmap);
2915
2916                         /*
2917                          * Pins applicable for fast input but not for
2918                          * fast output processing may have been already
2919                          * inverted inside the fast path, skip them.
2920                          */
2921                         if (!raw && !(array_info &&
2922                             test_bit(i, array_info->invert_mask)) &&
2923                             test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2924                                 value = !value;
2925                         trace_gpio_value(desc_to_gpio(desc), 0, value);
2926                         /*
2927                          * collect all normal outputs belonging to the same chip
2928                          * open drain and open source outputs are set individually
2929                          */
2930                         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
2931                                 gpio_set_open_drain_value_commit(desc, value);
2932                         } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
2933                                 gpio_set_open_source_value_commit(desc, value);
2934                         } else {
2935                                 __set_bit(hwgpio, mask);
2936                                 __assign_bit(hwgpio, bits, value);
2937                                 count++;
2938                         }
2939                         i++;
2940
2941                         if (array_info)
2942                                 i = find_next_zero_bit(array_info->set_mask,
2943                                                        array_size, i);
2944                 } while ((i < array_size) &&
2945                          (desc_array[i]->gdev->chip == gc));
2946                 /* push collected bits to outputs */
2947                 if (count != 0)
2948                         gpio_chip_set_multiple(gc, mask, bits);
2949
2950                 if (mask != fastpath)
2951                         kfree(mask);
2952         }
2953         return 0;
2954 }
2955
2956 /**
2957  * gpiod_set_raw_value() - assign a gpio's raw value
2958  * @desc: gpio whose value will be assigned
2959  * @value: value to assign
2960  *
2961  * Set the raw value of the GPIO, i.e. the value of its physical line without
2962  * regard for its ACTIVE_LOW status.
2963  *
2964  * This function can be called from contexts where we cannot sleep, and will
2965  * complain if the GPIO chip functions potentially sleep.
2966  */
2967 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
2968 {
2969         VALIDATE_DESC_VOID(desc);
2970         /* Should be using gpiod_set_raw_value_cansleep() */
2971         WARN_ON(desc->gdev->chip->can_sleep);
2972         gpiod_set_raw_value_commit(desc, value);
2973 }
2974 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
2975
2976 /**
2977  * gpiod_set_value_nocheck() - set a GPIO line value without checking
2978  * @desc: the descriptor to set the value on
2979  * @value: value to set
2980  *
2981  * This sets the value of a GPIO line backing a descriptor, applying
2982  * different semantic quirks like active low and open drain/source
2983  * handling.
2984  */
2985 static void gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
2986 {
2987         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2988                 value = !value;
2989         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2990                 gpio_set_open_drain_value_commit(desc, value);
2991         else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2992                 gpio_set_open_source_value_commit(desc, value);
2993         else
2994                 gpiod_set_raw_value_commit(desc, value);
2995 }
2996
2997 /**
2998  * gpiod_set_value() - assign a gpio's value
2999  * @desc: gpio whose value will be assigned
3000  * @value: value to assign
3001  *
3002  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
3003  * OPEN_DRAIN and OPEN_SOURCE flags into account.
3004  *
3005  * This function can be called from contexts where we cannot sleep, and will
3006  * complain if the GPIO chip functions potentially sleep.
3007  */
3008 void gpiod_set_value(struct gpio_desc *desc, int value)
3009 {
3010         VALIDATE_DESC_VOID(desc);
3011         /* Should be using gpiod_set_value_cansleep() */
3012         WARN_ON(desc->gdev->chip->can_sleep);
3013         gpiod_set_value_nocheck(desc, value);
3014 }
3015 EXPORT_SYMBOL_GPL(gpiod_set_value);
3016
3017 /**
3018  * gpiod_set_raw_array_value() - assign values to an array of GPIOs
3019  * @array_size: number of elements in the descriptor array / value bitmap
3020  * @desc_array: array of GPIO descriptors whose values will be assigned
3021  * @array_info: information on applicability of fast bitmap processing path
3022  * @value_bitmap: bitmap of values to assign
3023  *
3024  * Set the raw values of the GPIOs, i.e. the values of the physical lines
3025  * without regard for their ACTIVE_LOW status.
3026  *
3027  * This function can be called from contexts where we cannot sleep, and will
3028  * complain if the GPIO chip functions potentially sleep.
3029  */
3030 int gpiod_set_raw_array_value(unsigned int array_size,
3031                               struct gpio_desc **desc_array,
3032                               struct gpio_array *array_info,
3033                               unsigned long *value_bitmap)
3034 {
3035         if (!desc_array)
3036                 return -EINVAL;
3037         return gpiod_set_array_value_complex(true, false, array_size,
3038                                         desc_array, array_info, value_bitmap);
3039 }
3040 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
3041
3042 /**
3043  * gpiod_set_array_value() - assign values to an array of GPIOs
3044  * @array_size: number of elements in the descriptor array / value bitmap
3045  * @desc_array: array of GPIO descriptors whose values will be assigned
3046  * @array_info: information on applicability of fast bitmap processing path
3047  * @value_bitmap: bitmap of values to assign
3048  *
3049  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3050  * into account.
3051  *
3052  * This function can be called from contexts where we cannot sleep, and will
3053  * complain if the GPIO chip functions potentially sleep.
3054  */
3055 int gpiod_set_array_value(unsigned int array_size,
3056                           struct gpio_desc **desc_array,
3057                           struct gpio_array *array_info,
3058                           unsigned long *value_bitmap)
3059 {
3060         if (!desc_array)
3061                 return -EINVAL;
3062         return gpiod_set_array_value_complex(false, false, array_size,
3063                                              desc_array, array_info,
3064                                              value_bitmap);
3065 }
3066 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
3067
3068 /**
3069  * gpiod_cansleep() - report whether gpio value access may sleep
3070  * @desc: gpio to check
3071  *
3072  */
3073 int gpiod_cansleep(const struct gpio_desc *desc)
3074 {
3075         VALIDATE_DESC(desc);
3076         return desc->gdev->chip->can_sleep;
3077 }
3078 EXPORT_SYMBOL_GPL(gpiod_cansleep);
3079
3080 /**
3081  * gpiod_set_consumer_name() - set the consumer name for the descriptor
3082  * @desc: gpio to set the consumer name on
3083  * @name: the new consumer name
3084  */
3085 int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
3086 {
3087         VALIDATE_DESC(desc);
3088         if (name) {
3089                 name = kstrdup_const(name, GFP_KERNEL);
3090                 if (!name)
3091                         return -ENOMEM;
3092         }
3093
3094         kfree_const(desc->label);
3095         desc_set_label(desc, name);
3096
3097         return 0;
3098 }
3099 EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
3100
3101 /**
3102  * gpiod_to_irq() - return the IRQ corresponding to a GPIO
3103  * @desc: gpio whose IRQ will be returned (already requested)
3104  *
3105  * Return the IRQ corresponding to the passed GPIO, or an error code in case of
3106  * error.
3107  */
3108 int gpiod_to_irq(const struct gpio_desc *desc)
3109 {
3110         struct gpio_chip *gc;
3111         int offset;
3112
3113         /*
3114          * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
3115          * requires this function to not return zero on an invalid descriptor
3116          * but rather a negative error number.
3117          */
3118         if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
3119                 return -EINVAL;
3120
3121         gc = desc->gdev->chip;
3122         offset = gpio_chip_hwgpio(desc);
3123         if (gc->to_irq) {
3124                 int retirq = gc->to_irq(gc, offset);
3125
3126                 /* Zero means NO_IRQ */
3127                 if (!retirq)
3128                         return -ENXIO;
3129
3130                 return retirq;
3131         }
3132         return -ENXIO;
3133 }
3134 EXPORT_SYMBOL_GPL(gpiod_to_irq);
3135
3136 /**
3137  * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
3138  * @gc: the chip the GPIO to lock belongs to
3139  * @offset: the offset of the GPIO to lock as IRQ
3140  *
3141  * This is used directly by GPIO drivers that want to lock down
3142  * a certain GPIO line to be used for IRQs.
3143  */
3144 int gpiochip_lock_as_irq(struct gpio_chip *gc, unsigned int offset)
3145 {
3146         struct gpio_desc *desc;
3147
3148         desc = gpiochip_get_desc(gc, offset);
3149         if (IS_ERR(desc))
3150                 return PTR_ERR(desc);
3151
3152         /*
3153          * If it's fast: flush the direction setting if something changed
3154          * behind our back
3155          */
3156         if (!gc->can_sleep && gc->get_direction) {
3157                 int dir = gpiod_get_direction(desc);
3158
3159                 if (dir < 0) {
3160                         chip_err(gc, "%s: cannot get GPIO direction\n",
3161                                  __func__);
3162                         return dir;
3163                 }
3164         }
3165
3166         /* To be valid for IRQ the line needs to be input or open drain */
3167         if (test_bit(FLAG_IS_OUT, &desc->flags) &&
3168             !test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
3169                 chip_err(gc,
3170                          "%s: tried to flag a GPIO set as output for IRQ\n",
3171                          __func__);
3172                 return -EIO;
3173         }
3174
3175         set_bit(FLAG_USED_AS_IRQ, &desc->flags);
3176         set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3177
3178         /*
3179          * If the consumer has not set up a label (such as when the
3180          * IRQ is referenced from .to_irq()) we set up a label here
3181          * so it is clear this is used as an interrupt.
3182          */
3183         if (!desc->label)
3184                 desc_set_label(desc, "interrupt");
3185
3186         return 0;
3187 }
3188 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
3189
3190 /**
3191  * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
3192  * @gc: the chip the GPIO to lock belongs to
3193  * @offset: the offset of the GPIO to lock as IRQ
3194  *
3195  * This is used directly by GPIO drivers that want to indicate
3196  * that a certain GPIO is no longer used exclusively for IRQ.
3197  */
3198 void gpiochip_unlock_as_irq(struct gpio_chip *gc, unsigned int offset)
3199 {
3200         struct gpio_desc *desc;
3201
3202         desc = gpiochip_get_desc(gc, offset);
3203         if (IS_ERR(desc))
3204                 return;
3205
3206         clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
3207         clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3208
3209         /* If we only had this marking, erase it */
3210         if (desc->label && !strcmp(desc->label, "interrupt"))
3211                 desc_set_label(desc, NULL);
3212 }
3213 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
3214
3215 void gpiochip_disable_irq(struct gpio_chip *gc, unsigned int offset)
3216 {
3217         struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
3218
3219         if (!IS_ERR(desc) &&
3220             !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags)))
3221                 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3222 }
3223 EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
3224
3225 void gpiochip_enable_irq(struct gpio_chip *gc, unsigned int offset)
3226 {
3227         struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
3228
3229         if (!IS_ERR(desc) &&
3230             !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags))) {
3231                 /*
3232                  * We must not be output when using IRQ UNLESS we are
3233                  * open drain.
3234                  */
3235                 WARN_ON(test_bit(FLAG_IS_OUT, &desc->flags) &&
3236                         !test_bit(FLAG_OPEN_DRAIN, &desc->flags));
3237                 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3238         }
3239 }
3240 EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
3241
3242 bool gpiochip_line_is_irq(struct gpio_chip *gc, unsigned int offset)
3243 {
3244         if (offset >= gc->ngpio)
3245                 return false;
3246
3247         return test_bit(FLAG_USED_AS_IRQ, &gc->gpiodev->descs[offset].flags);
3248 }
3249 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
3250
3251 int gpiochip_reqres_irq(struct gpio_chip *gc, unsigned int offset)
3252 {
3253         int ret;
3254
3255         if (!try_module_get(gc->gpiodev->owner))
3256                 return -ENODEV;
3257
3258         ret = gpiochip_lock_as_irq(gc, offset);
3259         if (ret) {
3260                 chip_err(gc, "unable to lock HW IRQ %u for IRQ\n", offset);
3261                 module_put(gc->gpiodev->owner);
3262                 return ret;
3263         }
3264         return 0;
3265 }
3266 EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
3267
3268 void gpiochip_relres_irq(struct gpio_chip *gc, unsigned int offset)
3269 {
3270         gpiochip_unlock_as_irq(gc, offset);
3271         module_put(gc->gpiodev->owner);
3272 }
3273 EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
3274
3275 bool gpiochip_line_is_open_drain(struct gpio_chip *gc, unsigned int offset)
3276 {
3277         if (offset >= gc->ngpio)
3278                 return false;
3279
3280         return test_bit(FLAG_OPEN_DRAIN, &gc->gpiodev->descs[offset].flags);
3281 }
3282 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
3283
3284 bool gpiochip_line_is_open_source(struct gpio_chip *gc, unsigned int offset)
3285 {
3286         if (offset >= gc->ngpio)
3287                 return false;
3288
3289         return test_bit(FLAG_OPEN_SOURCE, &gc->gpiodev->descs[offset].flags);
3290 }
3291 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
3292
3293 bool gpiochip_line_is_persistent(struct gpio_chip *gc, unsigned int offset)
3294 {
3295         if (offset >= gc->ngpio)
3296                 return false;
3297
3298         return !test_bit(FLAG_TRANSITORY, &gc->gpiodev->descs[offset].flags);
3299 }
3300 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
3301
3302 /**
3303  * gpiod_get_raw_value_cansleep() - return a gpio's raw value
3304  * @desc: gpio whose value will be returned
3305  *
3306  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
3307  * its ACTIVE_LOW status, or negative errno on failure.
3308  *
3309  * This function is to be called from contexts that can sleep.
3310  */
3311 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
3312 {
3313         might_sleep_if(extra_checks);
3314         VALIDATE_DESC(desc);
3315         return gpiod_get_raw_value_commit(desc);
3316 }
3317 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
3318
3319 /**
3320  * gpiod_get_value_cansleep() - return a gpio's value
3321  * @desc: gpio whose value will be returned
3322  *
3323  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3324  * account, or negative errno on failure.
3325  *
3326  * This function is to be called from contexts that can sleep.
3327  */
3328 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
3329 {
3330         int value;
3331
3332         might_sleep_if(extra_checks);
3333         VALIDATE_DESC(desc);
3334         value = gpiod_get_raw_value_commit(desc);
3335         if (value < 0)
3336                 return value;
3337
3338         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3339                 value = !value;
3340
3341         return value;
3342 }
3343 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
3344
3345 /**
3346  * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
3347  * @array_size: number of elements in the descriptor array / value bitmap
3348  * @desc_array: array of GPIO descriptors whose values will be read
3349  * @array_info: information on applicability of fast bitmap processing path
3350  * @value_bitmap: bitmap to store the read values
3351  *
3352  * Read the raw values of the GPIOs, i.e. the values of the physical lines
3353  * without regard for their ACTIVE_LOW status.  Return 0 in case of success,
3354  * else an error code.
3355  *
3356  * This function is to be called from contexts that can sleep.
3357  */
3358 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
3359                                        struct gpio_desc **desc_array,
3360                                        struct gpio_array *array_info,
3361                                        unsigned long *value_bitmap)
3362 {
3363         might_sleep_if(extra_checks);
3364         if (!desc_array)
3365                 return -EINVAL;
3366         return gpiod_get_array_value_complex(true, true, array_size,
3367                                              desc_array, array_info,
3368                                              value_bitmap);
3369 }
3370 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
3371
3372 /**
3373  * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
3374  * @array_size: number of elements in the descriptor array / value bitmap
3375  * @desc_array: array of GPIO descriptors whose values will be read
3376  * @array_info: information on applicability of fast bitmap processing path
3377  * @value_bitmap: bitmap to store the read values
3378  *
3379  * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3380  * into account.  Return 0 in case of success, else an error code.
3381  *
3382  * This function is to be called from contexts that can sleep.
3383  */
3384 int gpiod_get_array_value_cansleep(unsigned int array_size,
3385                                    struct gpio_desc **desc_array,
3386                                    struct gpio_array *array_info,
3387                                    unsigned long *value_bitmap)
3388 {
3389         might_sleep_if(extra_checks);
3390         if (!desc_array)
3391                 return -EINVAL;
3392         return gpiod_get_array_value_complex(false, true, array_size,
3393                                              desc_array, array_info,
3394                                              value_bitmap);
3395 }
3396 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
3397
3398 /**
3399  * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
3400  * @desc: gpio whose value will be assigned
3401  * @value: value to assign
3402  *
3403  * Set the raw value of the GPIO, i.e. the value of its physical line without
3404  * regard for its ACTIVE_LOW status.
3405  *
3406  * This function is to be called from contexts that can sleep.
3407  */
3408 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
3409 {
3410         might_sleep_if(extra_checks);
3411         VALIDATE_DESC_VOID(desc);
3412         gpiod_set_raw_value_commit(desc, value);
3413 }
3414 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
3415
3416 /**
3417  * gpiod_set_value_cansleep() - assign a gpio's value
3418  * @desc: gpio whose value will be assigned
3419  * @value: value to assign
3420  *
3421  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3422  * account
3423  *
3424  * This function is to be called from contexts that can sleep.
3425  */
3426 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
3427 {
3428         might_sleep_if(extra_checks);
3429         VALIDATE_DESC_VOID(desc);
3430         gpiod_set_value_nocheck(desc, value);
3431 }
3432 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
3433
3434 /**
3435  * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
3436  * @array_size: number of elements in the descriptor array / value bitmap
3437  * @desc_array: array of GPIO descriptors whose values will be assigned
3438  * @array_info: information on applicability of fast bitmap processing path
3439  * @value_bitmap: bitmap of values to assign
3440  *
3441  * Set the raw values of the GPIOs, i.e. the values of the physical lines
3442  * without regard for their ACTIVE_LOW status.
3443  *
3444  * This function is to be called from contexts that can sleep.
3445  */
3446 int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
3447                                        struct gpio_desc **desc_array,
3448                                        struct gpio_array *array_info,
3449                                        unsigned long *value_bitmap)
3450 {
3451         might_sleep_if(extra_checks);
3452         if (!desc_array)
3453                 return -EINVAL;
3454         return gpiod_set_array_value_complex(true, true, array_size, desc_array,
3455                                       array_info, value_bitmap);
3456 }
3457 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
3458
3459 /**
3460  * gpiod_add_lookup_tables() - register GPIO device consumers
3461  * @tables: list of tables of consumers to register
3462  * @n: number of tables in the list
3463  */
3464 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
3465 {
3466         unsigned int i;
3467
3468         mutex_lock(&gpio_lookup_lock);
3469
3470         for (i = 0; i < n; i++)
3471                 list_add_tail(&tables[i]->list, &gpio_lookup_list);
3472
3473         mutex_unlock(&gpio_lookup_lock);
3474 }
3475
3476 /**
3477  * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
3478  * @array_size: number of elements in the descriptor array / value bitmap
3479  * @desc_array: array of GPIO descriptors whose values will be assigned
3480  * @array_info: information on applicability of fast bitmap processing path
3481  * @value_bitmap: bitmap of values to assign
3482  *
3483  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3484  * into account.
3485  *
3486  * This function is to be called from contexts that can sleep.
3487  */
3488 int gpiod_set_array_value_cansleep(unsigned int array_size,
3489                                    struct gpio_desc **desc_array,
3490                                    struct gpio_array *array_info,
3491                                    unsigned long *value_bitmap)
3492 {
3493         might_sleep_if(extra_checks);
3494         if (!desc_array)
3495                 return -EINVAL;
3496         return gpiod_set_array_value_complex(false, true, array_size,
3497                                              desc_array, array_info,
3498                                              value_bitmap);
3499 }
3500 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
3501
3502 /**
3503  * gpiod_add_lookup_table() - register GPIO device consumers
3504  * @table: table of consumers to register
3505  */
3506 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
3507 {
3508         mutex_lock(&gpio_lookup_lock);
3509
3510         list_add_tail(&table->list, &gpio_lookup_list);
3511
3512         mutex_unlock(&gpio_lookup_lock);
3513 }
3514 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
3515
3516 /**
3517  * gpiod_remove_lookup_table() - unregister GPIO device consumers
3518  * @table: table of consumers to unregister
3519  */
3520 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
3521 {
3522         mutex_lock(&gpio_lookup_lock);
3523
3524         list_del(&table->list);
3525
3526         mutex_unlock(&gpio_lookup_lock);
3527 }
3528 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
3529
3530 /**
3531  * gpiod_add_hogs() - register a set of GPIO hogs from machine code
3532  * @hogs: table of gpio hog entries with a zeroed sentinel at the end
3533  */
3534 void gpiod_add_hogs(struct gpiod_hog *hogs)
3535 {
3536         struct gpio_chip *gc;
3537         struct gpiod_hog *hog;
3538
3539         mutex_lock(&gpio_machine_hogs_mutex);
3540
3541         for (hog = &hogs[0]; hog->chip_label; hog++) {
3542                 list_add_tail(&hog->list, &gpio_machine_hogs);
3543
3544                 /*
3545                  * The chip may have been registered earlier, so check if it
3546                  * exists and, if so, try to hog the line now.
3547                  */
3548                 gc = find_chip_by_name(hog->chip_label);
3549                 if (gc)
3550                         gpiochip_machine_hog(gc, hog);
3551         }
3552
3553         mutex_unlock(&gpio_machine_hogs_mutex);
3554 }
3555 EXPORT_SYMBOL_GPL(gpiod_add_hogs);
3556
3557 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
3558 {
3559         const char *dev_id = dev ? dev_name(dev) : NULL;
3560         struct gpiod_lookup_table *table;
3561
3562         mutex_lock(&gpio_lookup_lock);
3563
3564         list_for_each_entry(table, &gpio_lookup_list, list) {
3565                 if (table->dev_id && dev_id) {
3566                         /*
3567                          * Valid strings on both ends, must be identical to have
3568                          * a match
3569                          */
3570                         if (!strcmp(table->dev_id, dev_id))
3571                                 goto found;
3572                 } else {
3573                         /*
3574                          * One of the pointers is NULL, so both must be to have
3575                          * a match
3576                          */
3577                         if (dev_id == table->dev_id)
3578                                 goto found;
3579                 }
3580         }
3581         table = NULL;
3582
3583 found:
3584         mutex_unlock(&gpio_lookup_lock);
3585         return table;
3586 }
3587
3588 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
3589                                     unsigned int idx, unsigned long *flags)
3590 {
3591         struct gpio_desc *desc = ERR_PTR(-ENOENT);
3592         struct gpiod_lookup_table *table;
3593         struct gpiod_lookup *p;
3594
3595         table = gpiod_find_lookup_table(dev);
3596         if (!table)
3597                 return desc;
3598
3599         for (p = &table->table[0]; p->key; p++) {
3600                 struct gpio_chip *gc;
3601
3602                 /* idx must always match exactly */
3603                 if (p->idx != idx)
3604                         continue;
3605
3606                 /* If the lookup entry has a con_id, require exact match */
3607                 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
3608                         continue;
3609
3610                 if (p->chip_hwnum == U16_MAX) {
3611                         desc = gpio_name_to_desc(p->key);
3612                         if (desc) {
3613                                 *flags = p->flags;
3614                                 return desc;
3615                         }
3616
3617                         dev_warn(dev, "cannot find GPIO line %s, deferring\n",
3618                                  p->key);
3619                         return ERR_PTR(-EPROBE_DEFER);
3620                 }
3621
3622                 gc = find_chip_by_name(p->key);
3623
3624                 if (!gc) {
3625                         /*
3626                          * As the lookup table indicates a chip with
3627                          * p->key should exist, assume it may
3628                          * still appear later and let the interested
3629                          * consumer be probed again or let the Deferred
3630                          * Probe infrastructure handle the error.
3631                          */
3632                         dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
3633                                  p->key);
3634                         return ERR_PTR(-EPROBE_DEFER);
3635                 }
3636
3637                 if (gc->ngpio <= p->chip_hwnum) {
3638                         dev_err(dev,
3639                                 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
3640                                 idx, p->chip_hwnum, gc->ngpio - 1,
3641                                 gc->label);
3642                         return ERR_PTR(-EINVAL);
3643                 }
3644
3645                 desc = gpiochip_get_desc(gc, p->chip_hwnum);
3646                 *flags = p->flags;
3647
3648                 return desc;
3649         }
3650
3651         return desc;
3652 }
3653
3654 static int platform_gpio_count(struct device *dev, const char *con_id)
3655 {
3656         struct gpiod_lookup_table *table;
3657         struct gpiod_lookup *p;
3658         unsigned int count = 0;
3659
3660         table = gpiod_find_lookup_table(dev);
3661         if (!table)
3662                 return -ENOENT;
3663
3664         for (p = &table->table[0]; p->key; p++) {
3665                 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
3666                     (!con_id && !p->con_id))
3667                         count++;
3668         }
3669         if (!count)
3670                 return -ENOENT;
3671
3672         return count;
3673 }
3674
3675 /**
3676  * fwnode_gpiod_get_index - obtain a GPIO from firmware node
3677  * @fwnode:     handle of the firmware node
3678  * @con_id:     function within the GPIO consumer
3679  * @index:      index of the GPIO to obtain for the consumer
3680  * @flags:      GPIO initialization flags
3681  * @label:      label to attach to the requested GPIO
3682  *
3683  * This function can be used for drivers that get their configuration
3684  * from opaque firmware.
3685  *
3686  * The function properly finds the corresponding GPIO using whatever is the
3687  * underlying firmware interface and then makes sure that the GPIO
3688  * descriptor is requested before it is returned to the caller.
3689  *
3690  * Returns:
3691  * On successful request the GPIO pin is configured in accordance with
3692  * provided @flags.
3693  *
3694  * In case of error an ERR_PTR() is returned.
3695  */
3696 struct gpio_desc *fwnode_gpiod_get_index(struct fwnode_handle *fwnode,
3697                                          const char *con_id, int index,
3698                                          enum gpiod_flags flags,
3699                                          const char *label)
3700 {
3701         struct gpio_desc *desc;
3702         char prop_name[32]; /* 32 is max size of property name */
3703         unsigned int i;
3704
3705         for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
3706                 if (con_id)
3707                         snprintf(prop_name, sizeof(prop_name), "%s-%s",
3708                                             con_id, gpio_suffixes[i]);
3709                 else
3710                         snprintf(prop_name, sizeof(prop_name), "%s",
3711                                             gpio_suffixes[i]);
3712
3713                 desc = fwnode_get_named_gpiod(fwnode, prop_name, index, flags,
3714                                               label);
3715                 if (!IS_ERR(desc) || (PTR_ERR(desc) != -ENOENT))
3716                         break;
3717         }
3718
3719         return desc;
3720 }
3721 EXPORT_SYMBOL_GPL(fwnode_gpiod_get_index);
3722
3723 /**
3724  * gpiod_count - return the number of GPIOs associated with a device / function
3725  *              or -ENOENT if no GPIO has been assigned to the requested function
3726  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3727  * @con_id:     function within the GPIO consumer
3728  */
3729 int gpiod_count(struct device *dev, const char *con_id)
3730 {
3731         int count = -ENOENT;
3732
3733         if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
3734                 count = of_gpio_get_count(dev, con_id);
3735         else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
3736                 count = acpi_gpio_count(dev, con_id);
3737
3738         if (count < 0)
3739                 count = platform_gpio_count(dev, con_id);
3740
3741         return count;
3742 }
3743 EXPORT_SYMBOL_GPL(gpiod_count);
3744
3745 /**
3746  * gpiod_get - obtain a GPIO for a given GPIO function
3747  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3748  * @con_id:     function within the GPIO consumer
3749  * @flags:      optional GPIO initialization flags
3750  *
3751  * Return the GPIO descriptor corresponding to the function con_id of device
3752  * dev, -ENOENT if no GPIO has been assigned to the requested function, or
3753  * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
3754  */
3755 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
3756                                          enum gpiod_flags flags)
3757 {
3758         return gpiod_get_index(dev, con_id, 0, flags);
3759 }
3760 EXPORT_SYMBOL_GPL(gpiod_get);
3761
3762 /**
3763  * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
3764  * @dev: GPIO consumer, can be NULL for system-global GPIOs
3765  * @con_id: function within the GPIO consumer
3766  * @flags: optional GPIO initialization flags
3767  *
3768  * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
3769  * the requested function it will return NULL. This is convenient for drivers
3770  * that need to handle optional GPIOs.
3771  */
3772 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
3773                                                   const char *con_id,
3774                                                   enum gpiod_flags flags)
3775 {
3776         return gpiod_get_index_optional(dev, con_id, 0, flags);
3777 }
3778 EXPORT_SYMBOL_GPL(gpiod_get_optional);
3779
3780
3781 /**
3782  * gpiod_configure_flags - helper function to configure a given GPIO
3783  * @desc:       gpio whose value will be assigned
3784  * @con_id:     function within the GPIO consumer
3785  * @lflags:     bitmask of gpio_lookup_flags GPIO_* values - returned from
3786  *              of_find_gpio() or of_get_gpio_hog()
3787  * @dflags:     gpiod_flags - optional GPIO initialization flags
3788  *
3789  * Return 0 on success, -ENOENT if no GPIO has been assigned to the
3790  * requested function and/or index, or another IS_ERR() code if an error
3791  * occurred while trying to acquire the GPIO.
3792  */
3793 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
3794                 unsigned long lflags, enum gpiod_flags dflags)
3795 {
3796         int ret;
3797
3798         if (lflags & GPIO_ACTIVE_LOW)
3799                 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
3800
3801         if (lflags & GPIO_OPEN_DRAIN)
3802                 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3803         else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
3804                 /*
3805                  * This enforces open drain mode from the consumer side.
3806                  * This is necessary for some busses like I2C, but the lookup
3807                  * should *REALLY* have specified them as open drain in the
3808                  * first place, so print a little warning here.
3809                  */
3810                 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3811                 gpiod_warn(desc,
3812                            "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
3813         }
3814
3815         if (lflags & GPIO_OPEN_SOURCE)
3816                 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
3817
3818         if ((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DOWN)) {
3819                 gpiod_err(desc,
3820                           "both pull-up and pull-down enabled, invalid configuration\n");
3821                 return -EINVAL;
3822         }
3823
3824         if (lflags & GPIO_PULL_UP)
3825                 set_bit(FLAG_PULL_UP, &desc->flags);
3826         else if (lflags & GPIO_PULL_DOWN)
3827                 set_bit(FLAG_PULL_DOWN, &desc->flags);
3828
3829         ret = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
3830         if (ret < 0)
3831                 return ret;
3832
3833         /* No particular flag request, return here... */
3834         if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
3835                 gpiod_dbg(desc, "no flags found for %s\n", con_id);
3836                 return 0;
3837         }
3838
3839         /* Process flags */
3840         if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
3841                 ret = gpiod_direction_output(desc,
3842                                 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
3843         else
3844                 ret = gpiod_direction_input(desc);
3845
3846         return ret;
3847 }
3848
3849 /**
3850  * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
3851  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3852  * @con_id:     function within the GPIO consumer
3853  * @idx:        index of the GPIO to obtain in the consumer
3854  * @flags:      optional GPIO initialization flags
3855  *
3856  * This variant of gpiod_get() allows to access GPIOs other than the first
3857  * defined one for functions that define several GPIOs.
3858  *
3859  * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
3860  * requested function and/or index, or another IS_ERR() code if an error
3861  * occurred while trying to acquire the GPIO.
3862  */
3863 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
3864                                                const char *con_id,
3865                                                unsigned int idx,
3866                                                enum gpiod_flags flags)
3867 {
3868         unsigned long lookupflags = GPIO_LOOKUP_FLAGS_DEFAULT;
3869         struct gpio_desc *desc = NULL;
3870         int ret;
3871         /* Maybe we have a device name, maybe not */
3872         const char *devname = dev ? dev_name(dev) : "?";
3873
3874         dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
3875
3876         if (dev) {
3877                 /* Using device tree? */
3878                 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
3879                         dev_dbg(dev, "using device tree for GPIO lookup\n");
3880                         desc = of_find_gpio(dev, con_id, idx, &lookupflags);
3881                 } else if (ACPI_COMPANION(dev)) {
3882                         dev_dbg(dev, "using ACPI for GPIO lookup\n");
3883                         desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
3884                 }
3885         }
3886
3887         /*
3888          * Either we are not using DT or ACPI, or their lookup did not return
3889          * a result. In that case, use platform lookup as a fallback.
3890          */
3891         if (!desc || desc == ERR_PTR(-ENOENT)) {
3892                 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
3893                 desc = gpiod_find(dev, con_id, idx, &lookupflags);
3894         }
3895
3896         if (IS_ERR(desc)) {
3897                 dev_dbg(dev, "No GPIO consumer %s found\n", con_id);
3898                 return desc;
3899         }
3900
3901         /*
3902          * If a connection label was passed use that, else attempt to use
3903          * the device name as label
3904          */
3905         ret = gpiod_request(desc, con_id ? con_id : devname);
3906         if (ret < 0) {
3907                 if (ret == -EBUSY && flags & GPIOD_FLAGS_BIT_NONEXCLUSIVE) {
3908                         /*
3909                          * This happens when there are several consumers for
3910                          * the same GPIO line: we just return here without
3911                          * further initialization. It is a bit if a hack.
3912                          * This is necessary to support fixed regulators.
3913                          *
3914                          * FIXME: Make this more sane and safe.
3915                          */
3916                         dev_info(dev, "nonexclusive access to GPIO for %s\n",
3917                                  con_id ? con_id : devname);
3918                         return desc;
3919                 } else {
3920                         return ERR_PTR(ret);
3921                 }
3922         }
3923
3924         ret = gpiod_configure_flags(desc, con_id, lookupflags, flags);
3925         if (ret < 0) {
3926                 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
3927                 gpiod_put(desc);
3928                 return ERR_PTR(ret);
3929         }
3930
3931         atomic_notifier_call_chain(&desc->gdev->notifier,
3932                                    GPIOLINE_CHANGED_REQUESTED, desc);
3933
3934         return desc;
3935 }
3936 EXPORT_SYMBOL_GPL(gpiod_get_index);
3937
3938 /**
3939  * fwnode_get_named_gpiod - obtain a GPIO from firmware node
3940  * @fwnode:     handle of the firmware node
3941  * @propname:   name of the firmware property representing the GPIO
3942  * @index:      index of the GPIO to obtain for the consumer
3943  * @dflags:     GPIO initialization flags
3944  * @label:      label to attach to the requested GPIO
3945  *
3946  * This function can be used for drivers that get their configuration
3947  * from opaque firmware.
3948  *
3949  * The function properly finds the corresponding GPIO using whatever is the
3950  * underlying firmware interface and then makes sure that the GPIO
3951  * descriptor is requested before it is returned to the caller.
3952  *
3953  * Returns:
3954  * On successful request the GPIO pin is configured in accordance with
3955  * provided @dflags.
3956  *
3957  * In case of error an ERR_PTR() is returned.
3958  */
3959 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
3960                                          const char *propname, int index,
3961                                          enum gpiod_flags dflags,
3962                                          const char *label)
3963 {
3964         unsigned long lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
3965         struct gpio_desc *desc = ERR_PTR(-ENODEV);
3966         int ret;
3967
3968         if (!fwnode)
3969                 return ERR_PTR(-EINVAL);
3970
3971         if (is_of_node(fwnode)) {
3972                 desc = gpiod_get_from_of_node(to_of_node(fwnode),
3973                                               propname, index,
3974                                               dflags,
3975                                               label);
3976                 return desc;
3977         } else if (is_acpi_node(fwnode)) {
3978                 struct acpi_gpio_info info;
3979
3980                 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
3981                 if (IS_ERR(desc))
3982                         return desc;
3983
3984                 acpi_gpio_update_gpiod_flags(&dflags, &info);
3985                 acpi_gpio_update_gpiod_lookup_flags(&lflags, &info);
3986         }
3987
3988         /* Currently only ACPI takes this path */
3989         ret = gpiod_request(desc, label);
3990         if (ret)
3991                 return ERR_PTR(ret);
3992
3993         ret = gpiod_configure_flags(desc, propname, lflags, dflags);
3994         if (ret < 0) {
3995                 gpiod_put(desc);
3996                 return ERR_PTR(ret);
3997         }
3998
3999         atomic_notifier_call_chain(&desc->gdev->notifier,
4000                                    GPIOLINE_CHANGED_REQUESTED, desc);
4001
4002         return desc;
4003 }
4004 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
4005
4006 /**
4007  * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
4008  *                            function
4009  * @dev: GPIO consumer, can be NULL for system-global GPIOs
4010  * @con_id: function within the GPIO consumer
4011  * @index: index of the GPIO to obtain in the consumer
4012  * @flags: optional GPIO initialization flags
4013  *
4014  * This is equivalent to gpiod_get_index(), except that when no GPIO with the
4015  * specified index was assigned to the requested function it will return NULL.
4016  * This is convenient for drivers that need to handle optional GPIOs.
4017  */
4018 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
4019                                                         const char *con_id,
4020                                                         unsigned int index,
4021                                                         enum gpiod_flags flags)
4022 {
4023         struct gpio_desc *desc;
4024
4025         desc = gpiod_get_index(dev, con_id, index, flags);
4026         if (IS_ERR(desc)) {
4027                 if (PTR_ERR(desc) == -ENOENT)
4028                         return NULL;
4029         }
4030
4031         return desc;
4032 }
4033 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
4034
4035 /**
4036  * gpiod_hog - Hog the specified GPIO desc given the provided flags
4037  * @desc:       gpio whose value will be assigned
4038  * @name:       gpio line name
4039  * @lflags:     bitmask of gpio_lookup_flags GPIO_* values - returned from
4040  *              of_find_gpio() or of_get_gpio_hog()
4041  * @dflags:     gpiod_flags - optional GPIO initialization flags
4042  */
4043 int gpiod_hog(struct gpio_desc *desc, const char *name,
4044               unsigned long lflags, enum gpiod_flags dflags)
4045 {
4046         struct gpio_chip *gc;
4047         struct gpio_desc *local_desc;
4048         int hwnum;
4049         int ret;
4050
4051         gc = gpiod_to_chip(desc);
4052         hwnum = gpio_chip_hwgpio(desc);
4053
4054         local_desc = gpiochip_request_own_desc(gc, hwnum, name,
4055                                                lflags, dflags);
4056         if (IS_ERR(local_desc)) {
4057                 ret = PTR_ERR(local_desc);
4058                 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
4059                        name, gc->label, hwnum, ret);
4060                 return ret;
4061         }
4062
4063         /* Mark GPIO as hogged so it can be identified and removed later */
4064         set_bit(FLAG_IS_HOGGED, &desc->flags);
4065
4066         gpiod_info(desc, "hogged as %s%s\n",
4067                 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
4068                 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ?
4069                   (dflags & GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low" : "");
4070
4071         return 0;
4072 }
4073
4074 /**
4075  * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
4076  * @gc: gpio chip to act on
4077  */
4078 static void gpiochip_free_hogs(struct gpio_chip *gc)
4079 {
4080         int id;
4081
4082         for (id = 0; id < gc->ngpio; id++) {
4083                 if (test_bit(FLAG_IS_HOGGED, &gc->gpiodev->descs[id].flags))
4084                         gpiochip_free_own_desc(&gc->gpiodev->descs[id]);
4085         }
4086 }
4087
4088 /**
4089  * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
4090  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
4091  * @con_id:     function within the GPIO consumer
4092  * @flags:      optional GPIO initialization flags
4093  *
4094  * This function acquires all the GPIOs defined under a given function.
4095  *
4096  * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
4097  * no GPIO has been assigned to the requested function, or another IS_ERR()
4098  * code if an error occurred while trying to acquire the GPIOs.
4099  */
4100 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
4101                                                 const char *con_id,
4102                                                 enum gpiod_flags flags)
4103 {
4104         struct gpio_desc *desc;
4105         struct gpio_descs *descs;
4106         struct gpio_array *array_info = NULL;
4107         struct gpio_chip *gc;
4108         int count, bitmap_size;
4109
4110         count = gpiod_count(dev, con_id);
4111         if (count < 0)
4112                 return ERR_PTR(count);
4113
4114         descs = kzalloc(struct_size(descs, desc, count), GFP_KERNEL);
4115         if (!descs)
4116                 return ERR_PTR(-ENOMEM);
4117
4118         for (descs->ndescs = 0; descs->ndescs < count; ) {
4119                 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
4120                 if (IS_ERR(desc)) {
4121                         gpiod_put_array(descs);
4122                         return ERR_CAST(desc);
4123                 }
4124
4125                 descs->desc[descs->ndescs] = desc;
4126
4127                 gc = gpiod_to_chip(desc);
4128                 /*
4129                  * If pin hardware number of array member 0 is also 0, select
4130                  * its chip as a candidate for fast bitmap processing path.
4131                  */
4132                 if (descs->ndescs == 0 && gpio_chip_hwgpio(desc) == 0) {
4133                         struct gpio_descs *array;
4134
4135                         bitmap_size = BITS_TO_LONGS(gc->ngpio > count ?
4136                                                     gc->ngpio : count);
4137
4138                         array = kzalloc(struct_size(descs, desc, count) +
4139                                         struct_size(array_info, invert_mask,
4140                                         3 * bitmap_size), GFP_KERNEL);
4141                         if (!array) {
4142                                 gpiod_put_array(descs);
4143                                 return ERR_PTR(-ENOMEM);
4144                         }
4145
4146                         memcpy(array, descs,
4147                                struct_size(descs, desc, descs->ndescs + 1));
4148                         kfree(descs);
4149
4150                         descs = array;
4151                         array_info = (void *)(descs->desc + count);
4152                         array_info->get_mask = array_info->invert_mask +
4153                                                   bitmap_size;
4154                         array_info->set_mask = array_info->get_mask +
4155                                                   bitmap_size;
4156
4157                         array_info->desc = descs->desc;
4158                         array_info->size = count;
4159                         array_info->chip = gc;
4160                         bitmap_set(array_info->get_mask, descs->ndescs,
4161                                    count - descs->ndescs);
4162                         bitmap_set(array_info->set_mask, descs->ndescs,
4163                                    count - descs->ndescs);
4164                         descs->info = array_info;
4165                 }
4166                 /* Unmark array members which don't belong to the 'fast' chip */
4167                 if (array_info && array_info->chip != gc) {
4168                         __clear_bit(descs->ndescs, array_info->get_mask);
4169                         __clear_bit(descs->ndescs, array_info->set_mask);
4170                 }
4171                 /*
4172                  * Detect array members which belong to the 'fast' chip
4173                  * but their pins are not in hardware order.
4174                  */
4175                 else if (array_info &&
4176                            gpio_chip_hwgpio(desc) != descs->ndescs) {
4177                         /*
4178                          * Don't use fast path if all array members processed so
4179                          * far belong to the same chip as this one but its pin
4180                          * hardware number is different from its array index.
4181                          */
4182                         if (bitmap_full(array_info->get_mask, descs->ndescs)) {
4183                                 array_info = NULL;
4184                         } else {
4185                                 __clear_bit(descs->ndescs,
4186                                             array_info->get_mask);
4187                                 __clear_bit(descs->ndescs,
4188                                             array_info->set_mask);
4189                         }
4190                 } else if (array_info) {
4191                         /* Exclude open drain or open source from fast output */
4192                         if (gpiochip_line_is_open_drain(gc, descs->ndescs) ||
4193                             gpiochip_line_is_open_source(gc, descs->ndescs))
4194                                 __clear_bit(descs->ndescs,
4195                                             array_info->set_mask);
4196                         /* Identify 'fast' pins which require invertion */
4197                         if (gpiod_is_active_low(desc))
4198                                 __set_bit(descs->ndescs,
4199                                           array_info->invert_mask);
4200                 }
4201
4202                 descs->ndescs++;
4203         }
4204         if (array_info)
4205                 dev_dbg(dev,
4206                         "GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
4207                         array_info->chip->label, array_info->size,
4208                         *array_info->get_mask, *array_info->set_mask,
4209                         *array_info->invert_mask);
4210         return descs;
4211 }
4212 EXPORT_SYMBOL_GPL(gpiod_get_array);
4213
4214 /**
4215  * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
4216  *                            function
4217  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
4218  * @con_id:     function within the GPIO consumer
4219  * @flags:      optional GPIO initialization flags
4220  *
4221  * This is equivalent to gpiod_get_array(), except that when no GPIO was
4222  * assigned to the requested function it will return NULL.
4223  */
4224 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
4225                                                         const char *con_id,
4226                                                         enum gpiod_flags flags)
4227 {
4228         struct gpio_descs *descs;
4229
4230         descs = gpiod_get_array(dev, con_id, flags);
4231         if (PTR_ERR(descs) == -ENOENT)
4232                 return NULL;
4233
4234         return descs;
4235 }
4236 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
4237
4238 /**
4239  * gpiod_put - dispose of a GPIO descriptor
4240  * @desc:       GPIO descriptor to dispose of
4241  *
4242  * No descriptor can be used after gpiod_put() has been called on it.
4243  */
4244 void gpiod_put(struct gpio_desc *desc)
4245 {
4246         if (desc)
4247                 gpiod_free(desc);
4248 }
4249 EXPORT_SYMBOL_GPL(gpiod_put);
4250
4251 /**
4252  * gpiod_put_array - dispose of multiple GPIO descriptors
4253  * @descs:      struct gpio_descs containing an array of descriptors
4254  */
4255 void gpiod_put_array(struct gpio_descs *descs)
4256 {
4257         unsigned int i;
4258
4259         for (i = 0; i < descs->ndescs; i++)
4260                 gpiod_put(descs->desc[i]);
4261
4262         kfree(descs);
4263 }
4264 EXPORT_SYMBOL_GPL(gpiod_put_array);
4265
4266 static int __init gpiolib_dev_init(void)
4267 {
4268         int ret;
4269
4270         /* Register GPIO sysfs bus */
4271         ret = bus_register(&gpio_bus_type);
4272         if (ret < 0) {
4273                 pr_err("gpiolib: could not register GPIO bus type\n");
4274                 return ret;
4275         }
4276
4277         ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, GPIOCHIP_NAME);
4278         if (ret < 0) {
4279                 pr_err("gpiolib: failed to allocate char dev region\n");
4280                 bus_unregister(&gpio_bus_type);
4281                 return ret;
4282         }
4283
4284         gpiolib_initialized = true;
4285         gpiochip_setup_devs();
4286
4287 #if IS_ENABLED(CONFIG_OF_DYNAMIC) && IS_ENABLED(CONFIG_OF_GPIO)
4288         WARN_ON(of_reconfig_notifier_register(&gpio_of_notifier));
4289 #endif /* CONFIG_OF_DYNAMIC && CONFIG_OF_GPIO */
4290
4291         return ret;
4292 }
4293 core_initcall(gpiolib_dev_init);
4294
4295 #ifdef CONFIG_DEBUG_FS
4296
4297 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
4298 {
4299         unsigned                i;
4300         struct gpio_chip        *gc = gdev->chip;
4301         unsigned                gpio = gdev->base;
4302         struct gpio_desc        *gdesc = &gdev->descs[0];
4303         bool                    is_out;
4304         bool                    is_irq;
4305         bool                    active_low;
4306
4307         for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
4308                 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
4309                         if (gdesc->name) {
4310                                 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
4311                                            gpio, gdesc->name);
4312                         }
4313                         continue;
4314                 }
4315
4316                 gpiod_get_direction(gdesc);
4317                 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
4318                 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
4319                 active_low = test_bit(FLAG_ACTIVE_LOW, &gdesc->flags);
4320                 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s%s",
4321                         gpio, gdesc->name ? gdesc->name : "", gdesc->label,
4322                         is_out ? "out" : "in ",
4323                         gc->get ? (gc->get(gc, i) ? "hi" : "lo") : "?  ",
4324                         is_irq ? "IRQ " : "",
4325                         active_low ? "ACTIVE LOW" : "");
4326                 seq_printf(s, "\n");
4327         }
4328 }
4329
4330 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
4331 {
4332         unsigned long flags;
4333         struct gpio_device *gdev = NULL;
4334         loff_t index = *pos;
4335
4336         s->private = "";
4337
4338         spin_lock_irqsave(&gpio_lock, flags);
4339         list_for_each_entry(gdev, &gpio_devices, list)
4340                 if (index-- == 0) {
4341                         spin_unlock_irqrestore(&gpio_lock, flags);
4342                         return gdev;
4343                 }
4344         spin_unlock_irqrestore(&gpio_lock, flags);
4345
4346         return NULL;
4347 }
4348
4349 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
4350 {
4351         unsigned long flags;
4352         struct gpio_device *gdev = v;
4353         void *ret = NULL;
4354
4355         spin_lock_irqsave(&gpio_lock, flags);
4356         if (list_is_last(&gdev->list, &gpio_devices))
4357                 ret = NULL;
4358         else
4359                 ret = list_entry(gdev->list.next, struct gpio_device, list);
4360         spin_unlock_irqrestore(&gpio_lock, flags);
4361
4362         s->private = "\n";
4363         ++*pos;
4364
4365         return ret;
4366 }
4367
4368 static void gpiolib_seq_stop(struct seq_file *s, void *v)
4369 {
4370 }
4371
4372 static int gpiolib_seq_show(struct seq_file *s, void *v)
4373 {
4374         struct gpio_device *gdev = v;
4375         struct gpio_chip *gc = gdev->chip;
4376         struct device *parent;
4377
4378         if (!gc) {
4379                 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
4380                            dev_name(&gdev->dev));
4381                 return 0;
4382         }
4383
4384         seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
4385                    dev_name(&gdev->dev),
4386                    gdev->base, gdev->base + gdev->ngpio - 1);
4387         parent = gc->parent;
4388         if (parent)
4389                 seq_printf(s, ", parent: %s/%s",
4390                            parent->bus ? parent->bus->name : "no-bus",
4391                            dev_name(parent));
4392         if (gc->label)
4393                 seq_printf(s, ", %s", gc->label);
4394         if (gc->can_sleep)
4395                 seq_printf(s, ", can sleep");
4396         seq_printf(s, ":\n");
4397
4398         if (gc->dbg_show)
4399                 gc->dbg_show(s, gc);
4400         else
4401                 gpiolib_dbg_show(s, gdev);
4402
4403         return 0;
4404 }
4405
4406 static const struct seq_operations gpiolib_seq_ops = {
4407         .start = gpiolib_seq_start,
4408         .next = gpiolib_seq_next,
4409         .stop = gpiolib_seq_stop,
4410         .show = gpiolib_seq_show,
4411 };
4412
4413 static int gpiolib_open(struct inode *inode, struct file *file)
4414 {
4415         return seq_open(file, &gpiolib_seq_ops);
4416 }
4417
4418 static const struct file_operations gpiolib_operations = {
4419         .owner          = THIS_MODULE,
4420         .open           = gpiolib_open,
4421         .read           = seq_read,
4422         .llseek         = seq_lseek,
4423         .release        = seq_release,
4424 };
4425
4426 static int __init gpiolib_debugfs_init(void)
4427 {
4428         /* /sys/kernel/debug/gpio */
4429         debugfs_create_file("gpio", S_IFREG | S_IRUGO, NULL, NULL,
4430                             &gpiolib_operations);
4431         return 0;
4432 }
4433 subsys_initcall(gpiolib_debugfs_init);
4434
4435 #endif  /* DEBUG_FS */