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