gpiolib: add missed break statement
[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 int 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 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
940
941 /**
942  * gpiochip_set_hierarchical_irqchip() - connects a hierarchical irqchip
943  * to a gpiochip
944  * @gc: the gpiochip to set the irqchip hierarchical handler to
945  * @irqchip: the irqchip to handle this level of the hierarchy, the interrupt
946  * will then percolate up to the parent
947  */
948 static void gpiochip_set_hierarchical_irqchip(struct gpio_chip *gc,
949                                               struct irq_chip *irqchip)
950 {
951         /* DT will deal with mapping each IRQ as we go along */
952         if (is_of_node(gc->irq.fwnode))
953                 return;
954
955         /*
956          * This is for legacy and boardfile "irqchip" fwnodes: allocate
957          * irqs upfront instead of dynamically since we don't have the
958          * dynamic type of allocation that hardware description languages
959          * provide. Once all GPIO drivers using board files are gone from
960          * the kernel we can delete this code, but for a transitional period
961          * it is necessary to keep this around.
962          */
963         if (is_fwnode_irqchip(gc->irq.fwnode)) {
964                 int i;
965                 int ret;
966
967                 for (i = 0; i < gc->ngpio; i++) {
968                         struct irq_fwspec fwspec;
969                         unsigned int parent_hwirq;
970                         unsigned int parent_type;
971                         struct gpio_irq_chip *girq = &gc->irq;
972
973                         /*
974                          * We call the child to parent translation function
975                          * only to check if the child IRQ is valid or not.
976                          * Just pick the rising edge type here as that is what
977                          * we likely need to support.
978                          */
979                         ret = girq->child_to_parent_hwirq(gc, i,
980                                                           IRQ_TYPE_EDGE_RISING,
981                                                           &parent_hwirq,
982                                                           &parent_type);
983                         if (ret) {
984                                 chip_err(gc, "skip set-up on hwirq %d\n",
985                                          i);
986                                 continue;
987                         }
988
989                         fwspec.fwnode = gc->irq.fwnode;
990                         /* This is the hwirq for the GPIO line side of things */
991                         fwspec.param[0] = girq->child_offset_to_irq(gc, i);
992                         /* Just pick something */
993                         fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
994                         fwspec.param_count = 2;
995                         ret = __irq_domain_alloc_irqs(gc->irq.domain,
996                                                       /* just pick something */
997                                                       -1,
998                                                       1,
999                                                       NUMA_NO_NODE,
1000                                                       &fwspec,
1001                                                       false,
1002                                                       NULL);
1003                         if (ret < 0) {
1004                                 chip_err(gc,
1005                                          "can not allocate irq for GPIO line %d parent hwirq %d in hierarchy domain: %d\n",
1006                                          i, parent_hwirq,
1007                                          ret);
1008                         }
1009                 }
1010         }
1011
1012         chip_err(gc, "%s unknown fwnode type proceed anyway\n", __func__);
1013
1014         return;
1015 }
1016
1017 static int gpiochip_hierarchy_irq_domain_translate(struct irq_domain *d,
1018                                                    struct irq_fwspec *fwspec,
1019                                                    unsigned long *hwirq,
1020                                                    unsigned int *type)
1021 {
1022         /* We support standard DT translation */
1023         if (is_of_node(fwspec->fwnode) && fwspec->param_count == 2) {
1024                 return irq_domain_translate_twocell(d, fwspec, hwirq, type);
1025         }
1026
1027         /* This is for board files and others not using DT */
1028         if (is_fwnode_irqchip(fwspec->fwnode)) {
1029                 int ret;
1030
1031                 ret = irq_domain_translate_twocell(d, fwspec, hwirq, type);
1032                 if (ret)
1033                         return ret;
1034                 WARN_ON(*type == IRQ_TYPE_NONE);
1035                 return 0;
1036         }
1037         return -EINVAL;
1038 }
1039
1040 static int gpiochip_hierarchy_irq_domain_alloc(struct irq_domain *d,
1041                                                unsigned int irq,
1042                                                unsigned int nr_irqs,
1043                                                void *data)
1044 {
1045         struct gpio_chip *gc = d->host_data;
1046         irq_hw_number_t hwirq;
1047         unsigned int type = IRQ_TYPE_NONE;
1048         struct irq_fwspec *fwspec = data;
1049         void *parent_arg;
1050         unsigned int parent_hwirq;
1051         unsigned int parent_type;
1052         struct gpio_irq_chip *girq = &gc->irq;
1053         int ret;
1054
1055         /*
1056          * The nr_irqs parameter is always one except for PCI multi-MSI
1057          * so this should not happen.
1058          */
1059         WARN_ON(nr_irqs != 1);
1060
1061         ret = gc->irq.child_irq_domain_ops.translate(d, fwspec, &hwirq, &type);
1062         if (ret)
1063                 return ret;
1064
1065         chip_dbg(gc, "allocate IRQ %d, hwirq %lu\n", irq,  hwirq);
1066
1067         ret = girq->child_to_parent_hwirq(gc, hwirq, type,
1068                                           &parent_hwirq, &parent_type);
1069         if (ret) {
1070                 chip_err(gc, "can't look up hwirq %lu\n", hwirq);
1071                 return ret;
1072         }
1073         chip_dbg(gc, "found parent hwirq %u\n", parent_hwirq);
1074
1075         /*
1076          * We set handle_bad_irq because the .set_type() should
1077          * always be invoked and set the right type of handler.
1078          */
1079         irq_domain_set_info(d,
1080                             irq,
1081                             hwirq,
1082                             gc->irq.chip,
1083                             gc,
1084                             girq->handler,
1085                             NULL, NULL);
1086         irq_set_probe(irq);
1087
1088         /* This parent only handles asserted level IRQs */
1089         parent_arg = girq->populate_parent_alloc_arg(gc, parent_hwirq, parent_type);
1090         if (!parent_arg)
1091                 return -ENOMEM;
1092
1093         chip_dbg(gc, "alloc_irqs_parent for %d parent hwirq %d\n",
1094                   irq, parent_hwirq);
1095         irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
1096         ret = irq_domain_alloc_irqs_parent(d, irq, 1, parent_arg);
1097         /*
1098          * If the parent irqdomain is msi, the interrupts have already
1099          * been allocated, so the EEXIST is good.
1100          */
1101         if (irq_domain_is_msi(d->parent) && (ret == -EEXIST))
1102                 ret = 0;
1103         if (ret)
1104                 chip_err(gc,
1105                          "failed to allocate parent hwirq %d for hwirq %lu\n",
1106                          parent_hwirq, hwirq);
1107
1108         kfree(parent_arg);
1109         return ret;
1110 }
1111
1112 static unsigned int gpiochip_child_offset_to_irq_noop(struct gpio_chip *gc,
1113                                                       unsigned int offset)
1114 {
1115         return offset;
1116 }
1117
1118 static void gpiochip_hierarchy_setup_domain_ops(struct irq_domain_ops *ops)
1119 {
1120         ops->activate = gpiochip_irq_domain_activate;
1121         ops->deactivate = gpiochip_irq_domain_deactivate;
1122         ops->alloc = gpiochip_hierarchy_irq_domain_alloc;
1123         ops->free = irq_domain_free_irqs_common;
1124
1125         /*
1126          * We only allow overriding the translate() function for
1127          * hierarchical chips, and this should only be done if the user
1128          * really need something other than 1:1 translation.
1129          */
1130         if (!ops->translate)
1131                 ops->translate = gpiochip_hierarchy_irq_domain_translate;
1132 }
1133
1134 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
1135 {
1136         if (!gc->irq.child_to_parent_hwirq ||
1137             !gc->irq.fwnode) {
1138                 chip_err(gc, "missing irqdomain vital data\n");
1139                 return -EINVAL;
1140         }
1141
1142         if (!gc->irq.child_offset_to_irq)
1143                 gc->irq.child_offset_to_irq = gpiochip_child_offset_to_irq_noop;
1144
1145         if (!gc->irq.populate_parent_alloc_arg)
1146                 gc->irq.populate_parent_alloc_arg =
1147                         gpiochip_populate_parent_fwspec_twocell;
1148
1149         gpiochip_hierarchy_setup_domain_ops(&gc->irq.child_irq_domain_ops);
1150
1151         gc->irq.domain = irq_domain_create_hierarchy(
1152                 gc->irq.parent_domain,
1153                 0,
1154                 gc->ngpio,
1155                 gc->irq.fwnode,
1156                 &gc->irq.child_irq_domain_ops,
1157                 gc);
1158
1159         if (!gc->irq.domain)
1160                 return -ENOMEM;
1161
1162         gpiochip_set_hierarchical_irqchip(gc, gc->irq.chip);
1163
1164         return 0;
1165 }
1166
1167 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
1168 {
1169         return !!gc->irq.parent_domain;
1170 }
1171
1172 void *gpiochip_populate_parent_fwspec_twocell(struct gpio_chip *gc,
1173                                              unsigned int parent_hwirq,
1174                                              unsigned int parent_type)
1175 {
1176         struct irq_fwspec *fwspec;
1177
1178         fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
1179         if (!fwspec)
1180                 return NULL;
1181
1182         fwspec->fwnode = gc->irq.parent_domain->fwnode;
1183         fwspec->param_count = 2;
1184         fwspec->param[0] = parent_hwirq;
1185         fwspec->param[1] = parent_type;
1186
1187         return fwspec;
1188 }
1189 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_twocell);
1190
1191 void *gpiochip_populate_parent_fwspec_fourcell(struct gpio_chip *gc,
1192                                               unsigned int parent_hwirq,
1193                                               unsigned int parent_type)
1194 {
1195         struct irq_fwspec *fwspec;
1196
1197         fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
1198         if (!fwspec)
1199                 return NULL;
1200
1201         fwspec->fwnode = gc->irq.parent_domain->fwnode;
1202         fwspec->param_count = 4;
1203         fwspec->param[0] = 0;
1204         fwspec->param[1] = parent_hwirq;
1205         fwspec->param[2] = 0;
1206         fwspec->param[3] = parent_type;
1207
1208         return fwspec;
1209 }
1210 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_fourcell);
1211
1212 #else
1213
1214 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
1215 {
1216         return -EINVAL;
1217 }
1218
1219 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
1220 {
1221         return false;
1222 }
1223
1224 #endif /* CONFIG_IRQ_DOMAIN_HIERARCHY */
1225
1226 /**
1227  * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
1228  * @d: the irqdomain used by this irqchip
1229  * @irq: the global irq number used by this GPIO irqchip irq
1230  * @hwirq: the local IRQ/GPIO line offset on this gpiochip
1231  *
1232  * This function will set up the mapping for a certain IRQ line on a
1233  * gpiochip by assigning the gpiochip as chip data, and using the irqchip
1234  * stored inside the gpiochip.
1235  */
1236 int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
1237                      irq_hw_number_t hwirq)
1238 {
1239         struct gpio_chip *gc = d->host_data;
1240         int ret = 0;
1241
1242         if (!gpiochip_irqchip_irq_valid(gc, hwirq))
1243                 return -ENXIO;
1244
1245         irq_set_chip_data(irq, gc);
1246         /*
1247          * This lock class tells lockdep that GPIO irqs are in a different
1248          * category than their parents, so it won't report false recursion.
1249          */
1250         irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
1251         irq_set_chip_and_handler(irq, gc->irq.chip, gc->irq.handler);
1252         /* Chips that use nested thread handlers have them marked */
1253         if (gc->irq.threaded)
1254                 irq_set_nested_thread(irq, 1);
1255         irq_set_noprobe(irq);
1256
1257         if (gc->irq.num_parents == 1)
1258                 ret = irq_set_parent(irq, gc->irq.parents[0]);
1259         else if (gc->irq.map)
1260                 ret = irq_set_parent(irq, gc->irq.map[hwirq]);
1261
1262         if (ret < 0)
1263                 return ret;
1264
1265         /*
1266          * No set-up of the hardware will happen if IRQ_TYPE_NONE
1267          * is passed as default type.
1268          */
1269         if (gc->irq.default_type != IRQ_TYPE_NONE)
1270                 irq_set_irq_type(irq, gc->irq.default_type);
1271
1272         return 0;
1273 }
1274 EXPORT_SYMBOL_GPL(gpiochip_irq_map);
1275
1276 void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
1277 {
1278         struct gpio_chip *gc = d->host_data;
1279
1280         if (gc->irq.threaded)
1281                 irq_set_nested_thread(irq, 0);
1282         irq_set_chip_and_handler(irq, NULL, NULL);
1283         irq_set_chip_data(irq, NULL);
1284 }
1285 EXPORT_SYMBOL_GPL(gpiochip_irq_unmap);
1286
1287 static const struct irq_domain_ops gpiochip_domain_ops = {
1288         .map    = gpiochip_irq_map,
1289         .unmap  = gpiochip_irq_unmap,
1290         /* Virtually all GPIO irqchips are twocell:ed */
1291         .xlate  = irq_domain_xlate_twocell,
1292 };
1293
1294 /*
1295  * TODO: move these activate/deactivate in under the hierarchicial
1296  * irqchip implementation as static once SPMI and SSBI (all external
1297  * users) are phased over.
1298  */
1299 /**
1300  * gpiochip_irq_domain_activate() - Lock a GPIO to be used as an IRQ
1301  * @domain: The IRQ domain used by this IRQ chip
1302  * @data: Outermost irq_data associated with the IRQ
1303  * @reserve: If set, only reserve an interrupt vector instead of assigning one
1304  *
1305  * This function is a wrapper that calls gpiochip_lock_as_irq() and is to be
1306  * used as the activate function for the &struct irq_domain_ops. The host_data
1307  * for the IRQ domain must be the &struct gpio_chip.
1308  */
1309 int gpiochip_irq_domain_activate(struct irq_domain *domain,
1310                                  struct irq_data *data, bool reserve)
1311 {
1312         struct gpio_chip *gc = domain->host_data;
1313
1314         return gpiochip_lock_as_irq(gc, data->hwirq);
1315 }
1316 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_activate);
1317
1318 /**
1319  * gpiochip_irq_domain_deactivate() - Unlock a GPIO used as an IRQ
1320  * @domain: The IRQ domain used by this IRQ chip
1321  * @data: Outermost irq_data associated with the IRQ
1322  *
1323  * This function is a wrapper that will call gpiochip_unlock_as_irq() and is to
1324  * be used as the deactivate function for the &struct irq_domain_ops. The
1325  * host_data for the IRQ domain must be the &struct gpio_chip.
1326  */
1327 void gpiochip_irq_domain_deactivate(struct irq_domain *domain,
1328                                     struct irq_data *data)
1329 {
1330         struct gpio_chip *gc = domain->host_data;
1331
1332         return gpiochip_unlock_as_irq(gc, data->hwirq);
1333 }
1334 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_deactivate);
1335
1336 static int gpiochip_to_irq(struct gpio_chip *gc, unsigned int offset)
1337 {
1338         struct irq_domain *domain = gc->irq.domain;
1339
1340         if (!gpiochip_irqchip_irq_valid(gc, offset))
1341                 return -ENXIO;
1342
1343 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
1344         if (irq_domain_is_hierarchy(domain)) {
1345                 struct irq_fwspec spec;
1346
1347                 spec.fwnode = domain->fwnode;
1348                 spec.param_count = 2;
1349                 spec.param[0] = gc->irq.child_offset_to_irq(gc, offset);
1350                 spec.param[1] = IRQ_TYPE_NONE;
1351
1352                 return irq_create_fwspec_mapping(&spec);
1353         }
1354 #endif
1355
1356         return irq_create_mapping(domain, offset);
1357 }
1358
1359 static int gpiochip_irq_reqres(struct irq_data *d)
1360 {
1361         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1362
1363         return gpiochip_reqres_irq(gc, d->hwirq);
1364 }
1365
1366 static void gpiochip_irq_relres(struct irq_data *d)
1367 {
1368         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1369
1370         gpiochip_relres_irq(gc, d->hwirq);
1371 }
1372
1373 static void gpiochip_irq_mask(struct irq_data *d)
1374 {
1375         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1376
1377         if (gc->irq.irq_mask)
1378                 gc->irq.irq_mask(d);
1379         gpiochip_disable_irq(gc, d->hwirq);
1380 }
1381
1382 static void gpiochip_irq_unmask(struct irq_data *d)
1383 {
1384         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1385
1386         gpiochip_enable_irq(gc, d->hwirq);
1387         if (gc->irq.irq_unmask)
1388                 gc->irq.irq_unmask(d);
1389 }
1390
1391 static void gpiochip_irq_enable(struct irq_data *d)
1392 {
1393         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1394
1395         gpiochip_enable_irq(gc, d->hwirq);
1396         gc->irq.irq_enable(d);
1397 }
1398
1399 static void gpiochip_irq_disable(struct irq_data *d)
1400 {
1401         struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1402
1403         gc->irq.irq_disable(d);
1404         gpiochip_disable_irq(gc, d->hwirq);
1405 }
1406
1407 static void gpiochip_set_irq_hooks(struct gpio_chip *gc)
1408 {
1409         struct irq_chip *irqchip = gc->irq.chip;
1410
1411         if (!irqchip->irq_request_resources &&
1412             !irqchip->irq_release_resources) {
1413                 irqchip->irq_request_resources = gpiochip_irq_reqres;
1414                 irqchip->irq_release_resources = gpiochip_irq_relres;
1415         }
1416         if (WARN_ON(gc->irq.irq_enable))
1417                 return;
1418         /* Check if the irqchip already has this hook... */
1419         if (irqchip->irq_enable == gpiochip_irq_enable) {
1420                 /*
1421                  * ...and if so, give a gentle warning that this is bad
1422                  * practice.
1423                  */
1424                 chip_info(gc,
1425                           "detected irqchip that is shared with multiple gpiochips: please fix the driver.\n");
1426                 return;
1427         }
1428
1429         if (irqchip->irq_disable) {
1430                 gc->irq.irq_disable = irqchip->irq_disable;
1431                 irqchip->irq_disable = gpiochip_irq_disable;
1432         } else {
1433                 gc->irq.irq_mask = irqchip->irq_mask;
1434                 irqchip->irq_mask = gpiochip_irq_mask;
1435         }
1436
1437         if (irqchip->irq_enable) {
1438                 gc->irq.irq_enable = irqchip->irq_enable;
1439                 irqchip->irq_enable = gpiochip_irq_enable;
1440         } else {
1441                 gc->irq.irq_unmask = irqchip->irq_unmask;
1442                 irqchip->irq_unmask = gpiochip_irq_unmask;
1443         }
1444 }
1445
1446 /**
1447  * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
1448  * @gc: the GPIO chip to add the IRQ chip to
1449  * @lock_key: lockdep class for IRQ lock
1450  * @request_key: lockdep class for IRQ request
1451  */
1452 static int gpiochip_add_irqchip(struct gpio_chip *gc,
1453                                 struct lock_class_key *lock_key,
1454                                 struct lock_class_key *request_key)
1455 {
1456         struct irq_chip *irqchip = gc->irq.chip;
1457         const struct irq_domain_ops *ops = NULL;
1458         struct device_node *np;
1459         unsigned int type;
1460         unsigned int i;
1461
1462         if (!irqchip)
1463                 return 0;
1464
1465         if (gc->irq.parent_handler && gc->can_sleep) {
1466                 chip_err(gc, "you cannot have chained interrupts on a chip that may sleep\n");
1467                 return -EINVAL;
1468         }
1469
1470         np = gc->gpiodev->dev.of_node;
1471         type = gc->irq.default_type;
1472
1473         /*
1474          * Specifying a default trigger is a terrible idea if DT or ACPI is
1475          * used to configure the interrupts, as you may end up with
1476          * conflicting triggers. Tell the user, and reset to NONE.
1477          */
1478         if (WARN(np && type != IRQ_TYPE_NONE,
1479                  "%s: Ignoring %u default trigger\n", np->full_name, type))
1480                 type = IRQ_TYPE_NONE;
1481
1482         if (has_acpi_companion(gc->parent) && type != IRQ_TYPE_NONE) {
1483                 acpi_handle_warn(ACPI_HANDLE(gc->parent),
1484                                  "Ignoring %u default trigger\n", type);
1485                 type = IRQ_TYPE_NONE;
1486         }
1487
1488         gc->to_irq = gpiochip_to_irq;
1489         gc->irq.default_type = type;
1490         gc->irq.lock_key = lock_key;
1491         gc->irq.request_key = request_key;
1492
1493         /* If a parent irqdomain is provided, let's build a hierarchy */
1494         if (gpiochip_hierarchy_is_hierarchical(gc)) {
1495                 int ret = gpiochip_hierarchy_add_domain(gc);
1496                 if (ret)
1497                         return ret;
1498         } else {
1499                 /* Some drivers provide custom irqdomain ops */
1500                 if (gc->irq.domain_ops)
1501                         ops = gc->irq.domain_ops;
1502
1503                 if (!ops)
1504                         ops = &gpiochip_domain_ops;
1505                 gc->irq.domain = irq_domain_add_simple(np,
1506                         gc->ngpio,
1507                         gc->irq.first,
1508                         ops, gc);
1509                 if (!gc->irq.domain)
1510                         return -EINVAL;
1511         }
1512
1513         if (gc->irq.parent_handler) {
1514                 void *data = gc->irq.parent_handler_data ?: gc;
1515
1516                 for (i = 0; i < gc->irq.num_parents; i++) {
1517                         /*
1518                          * The parent IRQ chip is already using the chip_data
1519                          * for this IRQ chip, so our callbacks simply use the
1520                          * handler_data.
1521                          */
1522                         irq_set_chained_handler_and_data(gc->irq.parents[i],
1523                                                          gc->irq.parent_handler,
1524                                                          data);
1525                 }
1526         }
1527
1528         gpiochip_set_irq_hooks(gc);
1529
1530         acpi_gpiochip_request_interrupts(gc);
1531
1532         return 0;
1533 }
1534
1535 /**
1536  * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
1537  * @gc: the gpiochip to remove the irqchip from
1538  *
1539  * This is called only from gpiochip_remove()
1540  */
1541 static void gpiochip_irqchip_remove(struct gpio_chip *gc)
1542 {
1543         struct irq_chip *irqchip = gc->irq.chip;
1544         unsigned int offset;
1545
1546         acpi_gpiochip_free_interrupts(gc);
1547
1548         if (irqchip && gc->irq.parent_handler) {
1549                 struct gpio_irq_chip *irq = &gc->irq;
1550                 unsigned int i;
1551
1552                 for (i = 0; i < irq->num_parents; i++)
1553                         irq_set_chained_handler_and_data(irq->parents[i],
1554                                                          NULL, NULL);
1555         }
1556
1557         /* Remove all IRQ mappings and delete the domain */
1558         if (gc->irq.domain) {
1559                 unsigned int irq;
1560
1561                 for (offset = 0; offset < gc->ngpio; offset++) {
1562                         if (!gpiochip_irqchip_irq_valid(gc, offset))
1563                                 continue;
1564
1565                         irq = irq_find_mapping(gc->irq.domain, offset);
1566                         irq_dispose_mapping(irq);
1567                 }
1568
1569                 irq_domain_remove(gc->irq.domain);
1570         }
1571
1572         if (irqchip) {
1573                 if (irqchip->irq_request_resources == gpiochip_irq_reqres) {
1574                         irqchip->irq_request_resources = NULL;
1575                         irqchip->irq_release_resources = NULL;
1576                 }
1577                 if (irqchip->irq_enable == gpiochip_irq_enable) {
1578                         irqchip->irq_enable = gc->irq.irq_enable;
1579                         irqchip->irq_disable = gc->irq.irq_disable;
1580                 }
1581         }
1582         gc->irq.irq_enable = NULL;
1583         gc->irq.irq_disable = NULL;
1584         gc->irq.chip = NULL;
1585
1586         gpiochip_irqchip_free_valid_mask(gc);
1587 }
1588
1589 /**
1590  * gpiochip_irqchip_add_domain() - adds an irqdomain to a gpiochip
1591  * @gc: the gpiochip to add the irqchip to
1592  * @domain: the irqdomain to add to the gpiochip
1593  *
1594  * This function adds an IRQ domain to the gpiochip.
1595  */
1596 int gpiochip_irqchip_add_domain(struct gpio_chip *gc,
1597                                 struct irq_domain *domain)
1598 {
1599         if (!domain)
1600                 return -EINVAL;
1601
1602         gc->to_irq = gpiochip_to_irq;
1603         gc->irq.domain = domain;
1604
1605         return 0;
1606 }
1607 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_domain);
1608
1609 #else /* CONFIG_GPIOLIB_IRQCHIP */
1610
1611 static inline int gpiochip_add_irqchip(struct gpio_chip *gc,
1612                                        struct lock_class_key *lock_key,
1613                                        struct lock_class_key *request_key)
1614 {
1615         return 0;
1616 }
1617 static void gpiochip_irqchip_remove(struct gpio_chip *gc) {}
1618
1619 static inline int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
1620 {
1621         return 0;
1622 }
1623
1624 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
1625 {
1626         return 0;
1627 }
1628 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc)
1629 { }
1630
1631 #endif /* CONFIG_GPIOLIB_IRQCHIP */
1632
1633 /**
1634  * gpiochip_generic_request() - request the gpio function for a pin
1635  * @gc: the gpiochip owning the GPIO
1636  * @offset: the offset of the GPIO to request for GPIO function
1637  */
1638 int gpiochip_generic_request(struct gpio_chip *gc, unsigned int offset)
1639 {
1640 #ifdef CONFIG_PINCTRL
1641         if (list_empty(&gc->gpiodev->pin_ranges))
1642                 return 0;
1643 #endif
1644
1645         return pinctrl_gpio_request(gc->gpiodev->base + offset);
1646 }
1647 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
1648
1649 /**
1650  * gpiochip_generic_free() - free the gpio function from a pin
1651  * @gc: the gpiochip to request the gpio function for
1652  * @offset: the offset of the GPIO to free from GPIO function
1653  */
1654 void gpiochip_generic_free(struct gpio_chip *gc, unsigned int offset)
1655 {
1656         pinctrl_gpio_free(gc->gpiodev->base + offset);
1657 }
1658 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
1659
1660 /**
1661  * gpiochip_generic_config() - apply configuration for a pin
1662  * @gc: the gpiochip owning the GPIO
1663  * @offset: the offset of the GPIO to apply the configuration
1664  * @config: the configuration to be applied
1665  */
1666 int gpiochip_generic_config(struct gpio_chip *gc, unsigned int offset,
1667                             unsigned long config)
1668 {
1669         return pinctrl_gpio_set_config(gc->gpiodev->base + offset, config);
1670 }
1671 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
1672
1673 #ifdef CONFIG_PINCTRL
1674
1675 /**
1676  * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
1677  * @gc: the gpiochip to add the range for
1678  * @pctldev: the pin controller to map to
1679  * @gpio_offset: the start offset in the current gpio_chip number space
1680  * @pin_group: name of the pin group inside the pin controller
1681  *
1682  * Calling this function directly from a DeviceTree-supported
1683  * pinctrl driver is DEPRECATED. Please see Section 2.1 of
1684  * Documentation/devicetree/bindings/gpio/gpio.txt on how to
1685  * bind pinctrl and gpio drivers via the "gpio-ranges" property.
1686  */
1687 int gpiochip_add_pingroup_range(struct gpio_chip *gc,
1688                         struct pinctrl_dev *pctldev,
1689                         unsigned int gpio_offset, const char *pin_group)
1690 {
1691         struct gpio_pin_range *pin_range;
1692         struct gpio_device *gdev = gc->gpiodev;
1693         int ret;
1694
1695         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1696         if (!pin_range) {
1697                 chip_err(gc, "failed to allocate pin ranges\n");
1698                 return -ENOMEM;
1699         }
1700
1701         /* Use local offset as range ID */
1702         pin_range->range.id = gpio_offset;
1703         pin_range->range.gc = gc;
1704         pin_range->range.name = gc->label;
1705         pin_range->range.base = gdev->base + gpio_offset;
1706         pin_range->pctldev = pctldev;
1707
1708         ret = pinctrl_get_group_pins(pctldev, pin_group,
1709                                         &pin_range->range.pins,
1710                                         &pin_range->range.npins);
1711         if (ret < 0) {
1712                 kfree(pin_range);
1713                 return ret;
1714         }
1715
1716         pinctrl_add_gpio_range(pctldev, &pin_range->range);
1717
1718         chip_dbg(gc, "created GPIO range %d->%d ==> %s PINGRP %s\n",
1719                  gpio_offset, gpio_offset + pin_range->range.npins - 1,
1720                  pinctrl_dev_get_devname(pctldev), pin_group);
1721
1722         list_add_tail(&pin_range->node, &gdev->pin_ranges);
1723
1724         return 0;
1725 }
1726 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
1727
1728 /**
1729  * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
1730  * @gc: the gpiochip to add the range for
1731  * @pinctl_name: the dev_name() of the pin controller to map to
1732  * @gpio_offset: the start offset in the current gpio_chip number space
1733  * @pin_offset: the start offset in the pin controller number space
1734  * @npins: the number of pins from the offset of each pin space (GPIO and
1735  *      pin controller) to accumulate in this range
1736  *
1737  * Returns:
1738  * 0 on success, or a negative error-code on failure.
1739  *
1740  * Calling this function directly from a DeviceTree-supported
1741  * pinctrl driver is DEPRECATED. Please see Section 2.1 of
1742  * Documentation/devicetree/bindings/gpio/gpio.txt on how to
1743  * bind pinctrl and gpio drivers via the "gpio-ranges" property.
1744  */
1745 int gpiochip_add_pin_range(struct gpio_chip *gc, const char *pinctl_name,
1746                            unsigned int gpio_offset, unsigned int pin_offset,
1747                            unsigned int npins)
1748 {
1749         struct gpio_pin_range *pin_range;
1750         struct gpio_device *gdev = gc->gpiodev;
1751         int ret;
1752
1753         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1754         if (!pin_range) {
1755                 chip_err(gc, "failed to allocate pin ranges\n");
1756                 return -ENOMEM;
1757         }
1758
1759         /* Use local offset as range ID */
1760         pin_range->range.id = gpio_offset;
1761         pin_range->range.gc = gc;
1762         pin_range->range.name = gc->label;
1763         pin_range->range.base = gdev->base + gpio_offset;
1764         pin_range->range.pin_base = pin_offset;
1765         pin_range->range.npins = npins;
1766         pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
1767                         &pin_range->range);
1768         if (IS_ERR(pin_range->pctldev)) {
1769                 ret = PTR_ERR(pin_range->pctldev);
1770                 chip_err(gc, "could not create pin range\n");
1771                 kfree(pin_range);
1772                 return ret;
1773         }
1774         chip_dbg(gc, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
1775                  gpio_offset, gpio_offset + npins - 1,
1776                  pinctl_name,
1777                  pin_offset, pin_offset + npins - 1);
1778
1779         list_add_tail(&pin_range->node, &gdev->pin_ranges);
1780
1781         return 0;
1782 }
1783 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
1784
1785 /**
1786  * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
1787  * @gc: the chip to remove all the mappings for
1788  */
1789 void gpiochip_remove_pin_ranges(struct gpio_chip *gc)
1790 {
1791         struct gpio_pin_range *pin_range, *tmp;
1792         struct gpio_device *gdev = gc->gpiodev;
1793
1794         list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
1795                 list_del(&pin_range->node);
1796                 pinctrl_remove_gpio_range(pin_range->pctldev,
1797                                 &pin_range->range);
1798                 kfree(pin_range);
1799         }
1800 }
1801 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
1802
1803 #endif /* CONFIG_PINCTRL */
1804
1805 /* These "optional" allocation calls help prevent drivers from stomping
1806  * on each other, and help provide better diagnostics in debugfs.
1807  * They're called even less than the "set direction" calls.
1808  */
1809 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
1810 {
1811         struct gpio_chip        *gc = desc->gdev->chip;
1812         int                     ret;
1813         unsigned long           flags;
1814         unsigned                offset;
1815
1816         if (label) {
1817                 label = kstrdup_const(label, GFP_KERNEL);
1818                 if (!label)
1819                         return -ENOMEM;
1820         }
1821
1822         spin_lock_irqsave(&gpio_lock, flags);
1823
1824         /* NOTE:  gpio_request() can be called in early boot,
1825          * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
1826          */
1827
1828         if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
1829                 desc_set_label(desc, label ? : "?");
1830                 ret = 0;
1831         } else {
1832                 kfree_const(label);
1833                 ret = -EBUSY;
1834                 goto done;
1835         }
1836
1837         if (gc->request) {
1838                 /* gc->request may sleep */
1839                 spin_unlock_irqrestore(&gpio_lock, flags);
1840                 offset = gpio_chip_hwgpio(desc);
1841                 if (gpiochip_line_is_valid(gc, offset))
1842                         ret = gc->request(gc, offset);
1843                 else
1844                         ret = -EINVAL;
1845                 spin_lock_irqsave(&gpio_lock, flags);
1846
1847                 if (ret < 0) {
1848                         desc_set_label(desc, NULL);
1849                         kfree_const(label);
1850                         clear_bit(FLAG_REQUESTED, &desc->flags);
1851                         goto done;
1852                 }
1853         }
1854         if (gc->get_direction) {
1855                 /* gc->get_direction may sleep */
1856                 spin_unlock_irqrestore(&gpio_lock, flags);
1857                 gpiod_get_direction(desc);
1858                 spin_lock_irqsave(&gpio_lock, flags);
1859         }
1860 done:
1861         spin_unlock_irqrestore(&gpio_lock, flags);
1862         return ret;
1863 }
1864
1865 /*
1866  * This descriptor validation needs to be inserted verbatim into each
1867  * function taking a descriptor, so we need to use a preprocessor
1868  * macro to avoid endless duplication. If the desc is NULL it is an
1869  * optional GPIO and calls should just bail out.
1870  */
1871 static int validate_desc(const struct gpio_desc *desc, const char *func)
1872 {
1873         if (!desc)
1874                 return 0;
1875         if (IS_ERR(desc)) {
1876                 pr_warn("%s: invalid GPIO (errorpointer)\n", func);
1877                 return PTR_ERR(desc);
1878         }
1879         if (!desc->gdev) {
1880                 pr_warn("%s: invalid GPIO (no device)\n", func);
1881                 return -EINVAL;
1882         }
1883         if (!desc->gdev->chip) {
1884                 dev_warn(&desc->gdev->dev,
1885                          "%s: backing chip is gone\n", func);
1886                 return 0;
1887         }
1888         return 1;
1889 }
1890
1891 #define VALIDATE_DESC(desc) do { \
1892         int __valid = validate_desc(desc, __func__); \
1893         if (__valid <= 0) \
1894                 return __valid; \
1895         } while (0)
1896
1897 #define VALIDATE_DESC_VOID(desc) do { \
1898         int __valid = validate_desc(desc, __func__); \
1899         if (__valid <= 0) \
1900                 return; \
1901         } while (0)
1902
1903 int gpiod_request(struct gpio_desc *desc, const char *label)
1904 {
1905         int ret = -EPROBE_DEFER;
1906         struct gpio_device *gdev;
1907
1908         VALIDATE_DESC(desc);
1909         gdev = desc->gdev;
1910
1911         if (try_module_get(gdev->owner)) {
1912                 ret = gpiod_request_commit(desc, label);
1913                 if (ret < 0)
1914                         module_put(gdev->owner);
1915                 else
1916                         get_device(&gdev->dev);
1917         }
1918
1919         if (ret)
1920                 gpiod_dbg(desc, "%s: status %d\n", __func__, ret);
1921
1922         return ret;
1923 }
1924
1925 static bool gpiod_free_commit(struct gpio_desc *desc)
1926 {
1927         bool                    ret = false;
1928         unsigned long           flags;
1929         struct gpio_chip        *gc;
1930
1931         might_sleep();
1932
1933         gpiod_unexport(desc);
1934
1935         spin_lock_irqsave(&gpio_lock, flags);
1936
1937         gc = desc->gdev->chip;
1938         if (gc && test_bit(FLAG_REQUESTED, &desc->flags)) {
1939                 if (gc->free) {
1940                         spin_unlock_irqrestore(&gpio_lock, flags);
1941                         might_sleep_if(gc->can_sleep);
1942                         gc->free(gc, gpio_chip_hwgpio(desc));
1943                         spin_lock_irqsave(&gpio_lock, flags);
1944                 }
1945                 kfree_const(desc->label);
1946                 desc_set_label(desc, NULL);
1947                 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
1948                 clear_bit(FLAG_REQUESTED, &desc->flags);
1949                 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
1950                 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
1951                 clear_bit(FLAG_PULL_UP, &desc->flags);
1952                 clear_bit(FLAG_PULL_DOWN, &desc->flags);
1953                 clear_bit(FLAG_BIAS_DISABLE, &desc->flags);
1954                 clear_bit(FLAG_EDGE_RISING, &desc->flags);
1955                 clear_bit(FLAG_EDGE_FALLING, &desc->flags);
1956                 clear_bit(FLAG_IS_HOGGED, &desc->flags);
1957 #ifdef CONFIG_OF_DYNAMIC
1958                 desc->hog = NULL;
1959 #endif
1960 #ifdef CONFIG_GPIO_CDEV
1961                 WRITE_ONCE(desc->debounce_period_us, 0);
1962 #endif
1963                 ret = true;
1964         }
1965
1966         spin_unlock_irqrestore(&gpio_lock, flags);
1967         blocking_notifier_call_chain(&desc->gdev->notifier,
1968                                      GPIOLINE_CHANGED_RELEASED, desc);
1969
1970         return ret;
1971 }
1972
1973 void gpiod_free(struct gpio_desc *desc)
1974 {
1975         if (desc && desc->gdev && gpiod_free_commit(desc)) {
1976                 module_put(desc->gdev->owner);
1977                 put_device(&desc->gdev->dev);
1978         } else {
1979                 WARN_ON(extra_checks);
1980         }
1981 }
1982
1983 /**
1984  * gpiochip_is_requested - return string iff signal was requested
1985  * @gc: controller managing the signal
1986  * @offset: of signal within controller's 0..(ngpio - 1) range
1987  *
1988  * Returns NULL if the GPIO is not currently requested, else a string.
1989  * The string returned is the label passed to gpio_request(); if none has been
1990  * passed it is a meaningless, non-NULL constant.
1991  *
1992  * This function is for use by GPIO controller drivers.  The label can
1993  * help with diagnostics, and knowing that the signal is used as a GPIO
1994  * can help avoid accidentally multiplexing it to another controller.
1995  */
1996 const char *gpiochip_is_requested(struct gpio_chip *gc, unsigned int offset)
1997 {
1998         struct gpio_desc *desc;
1999
2000         if (offset >= gc->ngpio)
2001                 return NULL;
2002
2003         desc = gpiochip_get_desc(gc, offset);
2004         if (IS_ERR(desc))
2005                 return NULL;
2006
2007         if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
2008                 return NULL;
2009         return desc->label;
2010 }
2011 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
2012
2013 /**
2014  * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2015  * @gc: GPIO chip
2016  * @hwnum: hardware number of the GPIO for which to request the descriptor
2017  * @label: label for the GPIO
2018  * @lflags: lookup flags for this GPIO or 0 if default, this can be used to
2019  * specify things like line inversion semantics with the machine flags
2020  * such as GPIO_OUT_LOW
2021  * @dflags: descriptor request flags for this GPIO or 0 if default, this
2022  * can be used to specify consumer semantics such as open drain
2023  *
2024  * Function allows GPIO chip drivers to request and use their own GPIO
2025  * descriptors via gpiolib API. Difference to gpiod_request() is that this
2026  * function will not increase reference count of the GPIO chip module. This
2027  * allows the GPIO chip module to be unloaded as needed (we assume that the
2028  * GPIO chip driver handles freeing the GPIOs it has requested).
2029  *
2030  * Returns:
2031  * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
2032  * code on failure.
2033  */
2034 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *gc,
2035                                             unsigned int hwnum,
2036                                             const char *label,
2037                                             enum gpio_lookup_flags lflags,
2038                                             enum gpiod_flags dflags)
2039 {
2040         struct gpio_desc *desc = gpiochip_get_desc(gc, hwnum);
2041         int ret;
2042
2043         if (IS_ERR(desc)) {
2044                 chip_err(gc, "failed to get GPIO descriptor\n");
2045                 return desc;
2046         }
2047
2048         ret = gpiod_request_commit(desc, label);
2049         if (ret < 0)
2050                 return ERR_PTR(ret);
2051
2052         ret = gpiod_configure_flags(desc, label, lflags, dflags);
2053         if (ret) {
2054                 chip_err(gc, "setup of own GPIO %s failed\n", label);
2055                 gpiod_free_commit(desc);
2056                 return ERR_PTR(ret);
2057         }
2058
2059         return desc;
2060 }
2061 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
2062
2063 /**
2064  * gpiochip_free_own_desc - Free GPIO requested by the chip driver
2065  * @desc: GPIO descriptor to free
2066  *
2067  * Function frees the given GPIO requested previously with
2068  * gpiochip_request_own_desc().
2069  */
2070 void gpiochip_free_own_desc(struct gpio_desc *desc)
2071 {
2072         if (desc)
2073                 gpiod_free_commit(desc);
2074 }
2075 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
2076
2077 /*
2078  * Drivers MUST set GPIO direction before making get/set calls.  In
2079  * some cases this is done in early boot, before IRQs are enabled.
2080  *
2081  * As a rule these aren't called more than once (except for drivers
2082  * using the open-drain emulation idiom) so these are natural places
2083  * to accumulate extra debugging checks.  Note that we can't (yet)
2084  * rely on gpio_request() having been called beforehand.
2085  */
2086
2087 static int gpio_do_set_config(struct gpio_chip *gc, unsigned int offset,
2088                               unsigned long config)
2089 {
2090         if (!gc->set_config)
2091                 return -ENOTSUPP;
2092
2093         return gc->set_config(gc, offset, config);
2094 }
2095
2096 static int gpio_set_config(struct gpio_desc *desc, enum pin_config_param mode)
2097 {
2098         struct gpio_chip *gc = desc->gdev->chip;
2099         unsigned long config;
2100         unsigned int arg;
2101
2102         switch (mode) {
2103         case PIN_CONFIG_BIAS_PULL_DOWN:
2104         case PIN_CONFIG_BIAS_PULL_UP:
2105                 arg = 1;
2106                 break;
2107
2108         default:
2109                 arg = 0;
2110                 break;
2111         }
2112
2113         config = PIN_CONF_PACKED(mode, arg);
2114         return gpio_do_set_config(gc, gpio_chip_hwgpio(desc), config);
2115 }
2116
2117 static int gpio_set_bias(struct gpio_desc *desc)
2118 {
2119         enum pin_config_param bias;
2120         int ret;
2121
2122         if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
2123                 bias = PIN_CONFIG_BIAS_DISABLE;
2124         else if (test_bit(FLAG_PULL_UP, &desc->flags))
2125                 bias = PIN_CONFIG_BIAS_PULL_UP;
2126         else if (test_bit(FLAG_PULL_DOWN, &desc->flags))
2127                 bias = PIN_CONFIG_BIAS_PULL_DOWN;
2128         else
2129                 return 0;
2130
2131         ret = gpio_set_config(desc, bias);
2132         if (ret != -ENOTSUPP)
2133                 return ret;
2134
2135         return 0;
2136 }
2137
2138 /**
2139  * gpiod_direction_input - set the GPIO direction to input
2140  * @desc:       GPIO to set to input
2141  *
2142  * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2143  * be called safely on it.
2144  *
2145  * Return 0 in case of success, else an error code.
2146  */
2147 int gpiod_direction_input(struct gpio_desc *desc)
2148 {
2149         struct gpio_chip        *gc;
2150         int                     ret = 0;
2151
2152         VALIDATE_DESC(desc);
2153         gc = desc->gdev->chip;
2154
2155         /*
2156          * It is legal to have no .get() and .direction_input() specified if
2157          * the chip is output-only, but you can't specify .direction_input()
2158          * and not support the .get() operation, that doesn't make sense.
2159          */
2160         if (!gc->get && gc->direction_input) {
2161                 gpiod_warn(desc,
2162                            "%s: missing get() but have direction_input()\n",
2163                            __func__);
2164                 return -EIO;
2165         }
2166
2167         /*
2168          * If we have a .direction_input() callback, things are simple,
2169          * just call it. Else we are some input-only chip so try to check the
2170          * direction (if .get_direction() is supported) else we silently
2171          * assume we are in input mode after this.
2172          */
2173         if (gc->direction_input) {
2174                 ret = gc->direction_input(gc, gpio_chip_hwgpio(desc));
2175         } else if (gc->get_direction &&
2176                   (gc->get_direction(gc, gpio_chip_hwgpio(desc)) != 1)) {
2177                 gpiod_warn(desc,
2178                            "%s: missing direction_input() operation and line is output\n",
2179                            __func__);
2180                 return -EIO;
2181         }
2182         if (ret == 0) {
2183                 clear_bit(FLAG_IS_OUT, &desc->flags);
2184                 ret = gpio_set_bias(desc);
2185         }
2186
2187         trace_gpio_direction(desc_to_gpio(desc), 1, ret);
2188
2189         return ret;
2190 }
2191 EXPORT_SYMBOL_GPL(gpiod_direction_input);
2192
2193 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
2194 {
2195         struct gpio_chip *gc = desc->gdev->chip;
2196         int val = !!value;
2197         int ret = 0;
2198
2199         /*
2200          * It's OK not to specify .direction_output() if the gpiochip is
2201          * output-only, but if there is then not even a .set() operation it
2202          * is pretty tricky to drive the output line.
2203          */
2204         if (!gc->set && !gc->direction_output) {
2205                 gpiod_warn(desc,
2206                            "%s: missing set() and direction_output() operations\n",
2207                            __func__);
2208                 return -EIO;
2209         }
2210
2211         if (gc->direction_output) {
2212                 ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
2213         } else {
2214                 /* Check that we are in output mode if we can */
2215                 if (gc->get_direction &&
2216                     gc->get_direction(gc, gpio_chip_hwgpio(desc))) {
2217                         gpiod_warn(desc,
2218                                 "%s: missing direction_output() operation\n",
2219                                 __func__);
2220                         return -EIO;
2221                 }
2222                 /*
2223                  * If we can't actively set the direction, we are some
2224                  * output-only chip, so just drive the output as desired.
2225                  */
2226                 gc->set(gc, gpio_chip_hwgpio(desc), val);
2227         }
2228
2229         if (!ret)
2230                 set_bit(FLAG_IS_OUT, &desc->flags);
2231         trace_gpio_value(desc_to_gpio(desc), 0, val);
2232         trace_gpio_direction(desc_to_gpio(desc), 0, ret);
2233         return ret;
2234 }
2235
2236 /**
2237  * gpiod_direction_output_raw - set the GPIO direction to output
2238  * @desc:       GPIO to set to output
2239  * @value:      initial output value of the GPIO
2240  *
2241  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2242  * be called safely on it. The initial value of the output must be specified
2243  * as raw value on the physical line without regard for the ACTIVE_LOW status.
2244  *
2245  * Return 0 in case of success, else an error code.
2246  */
2247 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2248 {
2249         VALIDATE_DESC(desc);
2250         return gpiod_direction_output_raw_commit(desc, value);
2251 }
2252 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
2253
2254 /**
2255  * gpiod_direction_output - set the GPIO direction to output
2256  * @desc:       GPIO to set to output
2257  * @value:      initial output value of the GPIO
2258  *
2259  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2260  * be called safely on it. The initial value of the output must be specified
2261  * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2262  * account.
2263  *
2264  * Return 0 in case of success, else an error code.
2265  */
2266 int gpiod_direction_output(struct gpio_desc *desc, int value)
2267 {
2268         int ret;
2269
2270         VALIDATE_DESC(desc);
2271         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2272                 value = !value;
2273         else
2274                 value = !!value;
2275
2276         /* GPIOs used for enabled IRQs shall not be set as output */
2277         if (test_bit(FLAG_USED_AS_IRQ, &desc->flags) &&
2278             test_bit(FLAG_IRQ_IS_ENABLED, &desc->flags)) {
2279                 gpiod_err(desc,
2280                           "%s: tried to set a GPIO tied to an IRQ as output\n",
2281                           __func__);
2282                 return -EIO;
2283         }
2284
2285         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
2286                 /* First see if we can enable open drain in hardware */
2287                 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_DRAIN);
2288                 if (!ret)
2289                         goto set_output_value;
2290                 /* Emulate open drain by not actively driving the line high */
2291                 if (value) {
2292                         ret = gpiod_direction_input(desc);
2293                         goto set_output_flag;
2294                 }
2295         }
2296         else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
2297                 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_SOURCE);
2298                 if (!ret)
2299                         goto set_output_value;
2300                 /* Emulate open source by not actively driving the line low */
2301                 if (!value) {
2302                         ret = gpiod_direction_input(desc);
2303                         goto set_output_flag;
2304                 }
2305         } else {
2306                 gpio_set_config(desc, PIN_CONFIG_DRIVE_PUSH_PULL);
2307         }
2308
2309 set_output_value:
2310         ret = gpio_set_bias(desc);
2311         if (ret)
2312                 return ret;
2313         return gpiod_direction_output_raw_commit(desc, value);
2314
2315 set_output_flag:
2316         /*
2317          * When emulating open-source or open-drain functionalities by not
2318          * actively driving the line (setting mode to input) we still need to
2319          * set the IS_OUT flag or otherwise we won't be able to set the line
2320          * value anymore.
2321          */
2322         if (ret == 0)
2323                 set_bit(FLAG_IS_OUT, &desc->flags);
2324         return ret;
2325 }
2326 EXPORT_SYMBOL_GPL(gpiod_direction_output);
2327
2328 /**
2329  * gpiod_set_config - sets @config for a GPIO
2330  * @desc: descriptor of the GPIO for which to set the configuration
2331  * @config: Same packed config format as generic pinconf
2332  *
2333  * Returns:
2334  * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
2335  * configuration.
2336  */
2337 int gpiod_set_config(struct gpio_desc *desc, unsigned long config)
2338 {
2339         struct gpio_chip *gc;
2340
2341         VALIDATE_DESC(desc);
2342         gc = desc->gdev->chip;
2343
2344         return gpio_do_set_config(gc, gpio_chip_hwgpio(desc), config);
2345 }
2346 EXPORT_SYMBOL_GPL(gpiod_set_config);
2347
2348 /**
2349  * gpiod_set_debounce - sets @debounce time for a GPIO
2350  * @desc: descriptor of the GPIO for which to set debounce time
2351  * @debounce: debounce time in microseconds
2352  *
2353  * Returns:
2354  * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
2355  * debounce time.
2356  */
2357 int gpiod_set_debounce(struct gpio_desc *desc, unsigned int debounce)
2358 {
2359         unsigned long config;
2360
2361         config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
2362         return gpiod_set_config(desc, config);
2363 }
2364 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
2365
2366 /**
2367  * gpiod_set_transitory - Lose or retain GPIO state on suspend or reset
2368  * @desc: descriptor of the GPIO for which to configure persistence
2369  * @transitory: True to lose state on suspend or reset, false for persistence
2370  *
2371  * Returns:
2372  * 0 on success, otherwise a negative error code.
2373  */
2374 int gpiod_set_transitory(struct gpio_desc *desc, bool transitory)
2375 {
2376         struct gpio_chip *gc;
2377         unsigned long packed;
2378         int gpio;
2379         int rc;
2380
2381         VALIDATE_DESC(desc);
2382         /*
2383          * Handle FLAG_TRANSITORY first, enabling queries to gpiolib for
2384          * persistence state.
2385          */
2386         assign_bit(FLAG_TRANSITORY, &desc->flags, transitory);
2387
2388         /* If the driver supports it, set the persistence state now */
2389         gc = desc->gdev->chip;
2390         if (!gc->set_config)
2391                 return 0;
2392
2393         packed = pinconf_to_config_packed(PIN_CONFIG_PERSIST_STATE,
2394                                           !transitory);
2395         gpio = gpio_chip_hwgpio(desc);
2396         rc = gpio_do_set_config(gc, gpio, packed);
2397         if (rc == -ENOTSUPP) {
2398                 dev_dbg(&desc->gdev->dev, "Persistence not supported for GPIO %d\n",
2399                                 gpio);
2400                 return 0;
2401         }
2402
2403         return rc;
2404 }
2405 EXPORT_SYMBOL_GPL(gpiod_set_transitory);
2406
2407 /**
2408  * gpiod_is_active_low - test whether a GPIO is active-low or not
2409  * @desc: the gpio descriptor to test
2410  *
2411  * Returns 1 if the GPIO is active-low, 0 otherwise.
2412  */
2413 int gpiod_is_active_low(const struct gpio_desc *desc)
2414 {
2415         VALIDATE_DESC(desc);
2416         return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
2417 }
2418 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
2419
2420 /**
2421  * gpiod_toggle_active_low - toggle whether a GPIO is active-low or not
2422  * @desc: the gpio descriptor to change
2423  */
2424 void gpiod_toggle_active_low(struct gpio_desc *desc)
2425 {
2426         VALIDATE_DESC_VOID(desc);
2427         change_bit(FLAG_ACTIVE_LOW, &desc->flags);
2428 }
2429 EXPORT_SYMBOL_GPL(gpiod_toggle_active_low);
2430
2431 /* I/O calls are only valid after configuration completed; the relevant
2432  * "is this a valid GPIO" error checks should already have been done.
2433  *
2434  * "Get" operations are often inlinable as reading a pin value register,
2435  * and masking the relevant bit in that register.
2436  *
2437  * When "set" operations are inlinable, they involve writing that mask to
2438  * one register to set a low value, or a different register to set it high.
2439  * Otherwise locking is needed, so there may be little value to inlining.
2440  *
2441  *------------------------------------------------------------------------
2442  *
2443  * IMPORTANT!!!  The hot paths -- get/set value -- assume that callers
2444  * have requested the GPIO.  That can include implicit requesting by
2445  * a direction setting call.  Marking a gpio as requested locks its chip
2446  * in memory, guaranteeing that these table lookups need no more locking
2447  * and that gpiochip_remove() will fail.
2448  *
2449  * REVISIT when debugging, consider adding some instrumentation to ensure
2450  * that the GPIO was actually requested.
2451  */
2452
2453 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
2454 {
2455         struct gpio_chip        *gc;
2456         int offset;
2457         int value;
2458
2459         gc = desc->gdev->chip;
2460         offset = gpio_chip_hwgpio(desc);
2461         value = gc->get ? gc->get(gc, offset) : -EIO;
2462         value = value < 0 ? value : !!value;
2463         trace_gpio_value(desc_to_gpio(desc), 1, value);
2464         return value;
2465 }
2466
2467 static int gpio_chip_get_multiple(struct gpio_chip *gc,
2468                                   unsigned long *mask, unsigned long *bits)
2469 {
2470         if (gc->get_multiple) {
2471                 return gc->get_multiple(gc, mask, bits);
2472         } else if (gc->get) {
2473                 int i, value;
2474
2475                 for_each_set_bit(i, mask, gc->ngpio) {
2476                         value = gc->get(gc, i);
2477                         if (value < 0)
2478                                 return value;
2479                         __assign_bit(i, bits, value);
2480                 }
2481                 return 0;
2482         }
2483         return -EIO;
2484 }
2485
2486 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
2487                                   unsigned int array_size,
2488                                   struct gpio_desc **desc_array,
2489                                   struct gpio_array *array_info,
2490                                   unsigned long *value_bitmap)
2491 {
2492         int ret, i = 0;
2493
2494         /*
2495          * Validate array_info against desc_array and its size.
2496          * It should immediately follow desc_array if both
2497          * have been obtained from the same gpiod_get_array() call.
2498          */
2499         if (array_info && array_info->desc == desc_array &&
2500             array_size <= array_info->size &&
2501             (void *)array_info == desc_array + array_info->size) {
2502                 if (!can_sleep)
2503                         WARN_ON(array_info->chip->can_sleep);
2504
2505                 ret = gpio_chip_get_multiple(array_info->chip,
2506                                              array_info->get_mask,
2507                                              value_bitmap);
2508                 if (ret)
2509                         return ret;
2510
2511                 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
2512                         bitmap_xor(value_bitmap, value_bitmap,
2513                                    array_info->invert_mask, array_size);
2514
2515                 i = find_first_zero_bit(array_info->get_mask, array_size);
2516                 if (i == array_size)
2517                         return 0;
2518         } else {
2519                 array_info = NULL;
2520         }
2521
2522         while (i < array_size) {
2523                 struct gpio_chip *gc = desc_array[i]->gdev->chip;
2524                 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
2525                 unsigned long *mask, *bits;
2526                 int first, j, ret;
2527
2528                 if (likely(gc->ngpio <= FASTPATH_NGPIO)) {
2529                         mask = fastpath;
2530                 } else {
2531                         mask = kmalloc_array(2 * BITS_TO_LONGS(gc->ngpio),
2532                                            sizeof(*mask),
2533                                            can_sleep ? GFP_KERNEL : GFP_ATOMIC);
2534                         if (!mask)
2535                                 return -ENOMEM;
2536                 }
2537
2538                 bits = mask + BITS_TO_LONGS(gc->ngpio);
2539                 bitmap_zero(mask, gc->ngpio);
2540
2541                 if (!can_sleep)
2542                         WARN_ON(gc->can_sleep);
2543
2544                 /* collect all inputs belonging to the same chip */
2545                 first = i;
2546                 do {
2547                         const struct gpio_desc *desc = desc_array[i];
2548                         int hwgpio = gpio_chip_hwgpio(desc);
2549
2550                         __set_bit(hwgpio, mask);
2551                         i++;
2552
2553                         if (array_info)
2554                                 i = find_next_zero_bit(array_info->get_mask,
2555                                                        array_size, i);
2556                 } while ((i < array_size) &&
2557                          (desc_array[i]->gdev->chip == gc));
2558
2559                 ret = gpio_chip_get_multiple(gc, mask, bits);
2560                 if (ret) {
2561                         if (mask != fastpath)
2562                                 kfree(mask);
2563                         return ret;
2564                 }
2565
2566                 for (j = first; j < i; ) {
2567                         const struct gpio_desc *desc = desc_array[j];
2568                         int hwgpio = gpio_chip_hwgpio(desc);
2569                         int value = test_bit(hwgpio, bits);
2570
2571                         if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2572                                 value = !value;
2573                         __assign_bit(j, value_bitmap, value);
2574                         trace_gpio_value(desc_to_gpio(desc), 1, value);
2575                         j++;
2576
2577                         if (array_info)
2578                                 j = find_next_zero_bit(array_info->get_mask, i,
2579                                                        j);
2580                 }
2581
2582                 if (mask != fastpath)
2583                         kfree(mask);
2584         }
2585         return 0;
2586 }
2587
2588 /**
2589  * gpiod_get_raw_value() - return a gpio's raw value
2590  * @desc: gpio whose value will be returned
2591  *
2592  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2593  * its ACTIVE_LOW status, or negative errno on failure.
2594  *
2595  * This function can be called from contexts where we cannot sleep, and will
2596  * complain if the GPIO chip functions potentially sleep.
2597  */
2598 int gpiod_get_raw_value(const struct gpio_desc *desc)
2599 {
2600         VALIDATE_DESC(desc);
2601         /* Should be using gpiod_get_raw_value_cansleep() */
2602         WARN_ON(desc->gdev->chip->can_sleep);
2603         return gpiod_get_raw_value_commit(desc);
2604 }
2605 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
2606
2607 /**
2608  * gpiod_get_value() - return a gpio's value
2609  * @desc: gpio whose value will be returned
2610  *
2611  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2612  * account, or negative errno on failure.
2613  *
2614  * This function can be called from contexts where we cannot sleep, and will
2615  * complain if the GPIO chip functions potentially sleep.
2616  */
2617 int gpiod_get_value(const struct gpio_desc *desc)
2618 {
2619         int value;
2620
2621         VALIDATE_DESC(desc);
2622         /* Should be using gpiod_get_value_cansleep() */
2623         WARN_ON(desc->gdev->chip->can_sleep);
2624
2625         value = gpiod_get_raw_value_commit(desc);
2626         if (value < 0)
2627                 return value;
2628
2629         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2630                 value = !value;
2631
2632         return value;
2633 }
2634 EXPORT_SYMBOL_GPL(gpiod_get_value);
2635
2636 /**
2637  * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
2638  * @array_size: number of elements in the descriptor array / value bitmap
2639  * @desc_array: array of GPIO descriptors whose values will be read
2640  * @array_info: information on applicability of fast bitmap processing path
2641  * @value_bitmap: bitmap to store the read values
2642  *
2643  * Read the raw values of the GPIOs, i.e. the values of the physical lines
2644  * without regard for their ACTIVE_LOW status.  Return 0 in case of success,
2645  * else an error code.
2646  *
2647  * This function can be called from contexts where we cannot sleep,
2648  * and it will complain if the GPIO chip functions potentially sleep.
2649  */
2650 int gpiod_get_raw_array_value(unsigned int array_size,
2651                               struct gpio_desc **desc_array,
2652                               struct gpio_array *array_info,
2653                               unsigned long *value_bitmap)
2654 {
2655         if (!desc_array)
2656                 return -EINVAL;
2657         return gpiod_get_array_value_complex(true, false, array_size,
2658                                              desc_array, array_info,
2659                                              value_bitmap);
2660 }
2661 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
2662
2663 /**
2664  * gpiod_get_array_value() - read values from an array of GPIOs
2665  * @array_size: number of elements in the descriptor array / value bitmap
2666  * @desc_array: array of GPIO descriptors whose values will be read
2667  * @array_info: information on applicability of fast bitmap processing path
2668  * @value_bitmap: bitmap to store the read values
2669  *
2670  * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
2671  * into account.  Return 0 in case of success, else an error code.
2672  *
2673  * This function can be called from contexts where we cannot sleep,
2674  * and it will complain if the GPIO chip functions potentially sleep.
2675  */
2676 int gpiod_get_array_value(unsigned int array_size,
2677                           struct gpio_desc **desc_array,
2678                           struct gpio_array *array_info,
2679                           unsigned long *value_bitmap)
2680 {
2681         if (!desc_array)
2682                 return -EINVAL;
2683         return gpiod_get_array_value_complex(false, false, array_size,
2684                                              desc_array, array_info,
2685                                              value_bitmap);
2686 }
2687 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
2688
2689 /*
2690  *  gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
2691  * @desc: gpio descriptor whose state need to be set.
2692  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2693  */
2694 static void gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
2695 {
2696         int ret = 0;
2697         struct gpio_chip *gc = desc->gdev->chip;
2698         int offset = gpio_chip_hwgpio(desc);
2699
2700         if (value) {
2701                 ret = gc->direction_input(gc, offset);
2702         } else {
2703                 ret = gc->direction_output(gc, offset, 0);
2704                 if (!ret)
2705                         set_bit(FLAG_IS_OUT, &desc->flags);
2706         }
2707         trace_gpio_direction(desc_to_gpio(desc), value, ret);
2708         if (ret < 0)
2709                 gpiod_err(desc,
2710                           "%s: Error in set_value for open drain err %d\n",
2711                           __func__, ret);
2712 }
2713
2714 /*
2715  *  _gpio_set_open_source_value() - Set the open source gpio's value.
2716  * @desc: gpio descriptor whose state need to be set.
2717  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2718  */
2719 static void gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
2720 {
2721         int ret = 0;
2722         struct gpio_chip *gc = desc->gdev->chip;
2723         int offset = gpio_chip_hwgpio(desc);
2724
2725         if (value) {
2726                 ret = gc->direction_output(gc, offset, 1);
2727                 if (!ret)
2728                         set_bit(FLAG_IS_OUT, &desc->flags);
2729         } else {
2730                 ret = gc->direction_input(gc, offset);
2731         }
2732         trace_gpio_direction(desc_to_gpio(desc), !value, ret);
2733         if (ret < 0)
2734                 gpiod_err(desc,
2735                           "%s: Error in set_value for open source err %d\n",
2736                           __func__, ret);
2737 }
2738
2739 static void gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
2740 {
2741         struct gpio_chip        *gc;
2742
2743         gc = desc->gdev->chip;
2744         trace_gpio_value(desc_to_gpio(desc), 0, value);
2745         gc->set(gc, gpio_chip_hwgpio(desc), value);
2746 }
2747
2748 /*
2749  * set multiple outputs on the same chip;
2750  * use the chip's set_multiple function if available;
2751  * otherwise set the outputs sequentially;
2752  * @chip: the GPIO chip we operate on
2753  * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
2754  *        defines which outputs are to be changed
2755  * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
2756  *        defines the values the outputs specified by mask are to be set to
2757  */
2758 static void gpio_chip_set_multiple(struct gpio_chip *gc,
2759                                    unsigned long *mask, unsigned long *bits)
2760 {
2761         if (gc->set_multiple) {
2762                 gc->set_multiple(gc, mask, bits);
2763         } else {
2764                 unsigned int i;
2765
2766                 /* set outputs if the corresponding mask bit is set */
2767                 for_each_set_bit(i, mask, gc->ngpio)
2768                         gc->set(gc, i, test_bit(i, bits));
2769         }
2770 }
2771
2772 int gpiod_set_array_value_complex(bool raw, bool can_sleep,
2773                                   unsigned int array_size,
2774                                   struct gpio_desc **desc_array,
2775                                   struct gpio_array *array_info,
2776                                   unsigned long *value_bitmap)
2777 {
2778         int i = 0;
2779
2780         /*
2781          * Validate array_info against desc_array and its size.
2782          * It should immediately follow desc_array if both
2783          * have been obtained from the same gpiod_get_array() call.
2784          */
2785         if (array_info && array_info->desc == desc_array &&
2786             array_size <= array_info->size &&
2787             (void *)array_info == desc_array + array_info->size) {
2788                 if (!can_sleep)
2789                         WARN_ON(array_info->chip->can_sleep);
2790
2791                 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
2792                         bitmap_xor(value_bitmap, value_bitmap,
2793                                    array_info->invert_mask, array_size);
2794
2795                 gpio_chip_set_multiple(array_info->chip, array_info->set_mask,
2796                                        value_bitmap);
2797
2798                 i = find_first_zero_bit(array_info->set_mask, array_size);
2799                 if (i == array_size)
2800                         return 0;
2801         } else {
2802                 array_info = NULL;
2803         }
2804
2805         while (i < array_size) {
2806                 struct gpio_chip *gc = desc_array[i]->gdev->chip;
2807                 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
2808                 unsigned long *mask, *bits;
2809                 int count = 0;
2810
2811                 if (likely(gc->ngpio <= FASTPATH_NGPIO)) {
2812                         mask = fastpath;
2813                 } else {
2814                         mask = kmalloc_array(2 * BITS_TO_LONGS(gc->ngpio),
2815                                            sizeof(*mask),
2816                                            can_sleep ? GFP_KERNEL : GFP_ATOMIC);
2817                         if (!mask)
2818                                 return -ENOMEM;
2819                 }
2820
2821                 bits = mask + BITS_TO_LONGS(gc->ngpio);
2822                 bitmap_zero(mask, gc->ngpio);
2823
2824                 if (!can_sleep)
2825                         WARN_ON(gc->can_sleep);
2826
2827                 do {
2828                         struct gpio_desc *desc = desc_array[i];
2829                         int hwgpio = gpio_chip_hwgpio(desc);
2830                         int value = test_bit(i, value_bitmap);
2831
2832                         /*
2833                          * Pins applicable for fast input but not for
2834                          * fast output processing may have been already
2835                          * inverted inside the fast path, skip them.
2836                          */
2837                         if (!raw && !(array_info &&
2838                             test_bit(i, array_info->invert_mask)) &&
2839                             test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2840                                 value = !value;
2841                         trace_gpio_value(desc_to_gpio(desc), 0, value);
2842                         /*
2843                          * collect all normal outputs belonging to the same chip
2844                          * open drain and open source outputs are set individually
2845                          */
2846                         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
2847                                 gpio_set_open_drain_value_commit(desc, value);
2848                         } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
2849                                 gpio_set_open_source_value_commit(desc, value);
2850                         } else {
2851                                 __set_bit(hwgpio, mask);
2852                                 __assign_bit(hwgpio, bits, value);
2853                                 count++;
2854                         }
2855                         i++;
2856
2857                         if (array_info)
2858                                 i = find_next_zero_bit(array_info->set_mask,
2859                                                        array_size, i);
2860                 } while ((i < array_size) &&
2861                          (desc_array[i]->gdev->chip == gc));
2862                 /* push collected bits to outputs */
2863                 if (count != 0)
2864                         gpio_chip_set_multiple(gc, mask, bits);
2865
2866                 if (mask != fastpath)
2867                         kfree(mask);
2868         }
2869         return 0;
2870 }
2871
2872 /**
2873  * gpiod_set_raw_value() - assign a gpio's raw value
2874  * @desc: gpio whose value will be assigned
2875  * @value: value to assign
2876  *
2877  * Set the raw value of the GPIO, i.e. the value of its physical line without
2878  * regard for its ACTIVE_LOW status.
2879  *
2880  * This function can be called from contexts where we cannot sleep, and will
2881  * complain if the GPIO chip functions potentially sleep.
2882  */
2883 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
2884 {
2885         VALIDATE_DESC_VOID(desc);
2886         /* Should be using gpiod_set_raw_value_cansleep() */
2887         WARN_ON(desc->gdev->chip->can_sleep);
2888         gpiod_set_raw_value_commit(desc, value);
2889 }
2890 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
2891
2892 /**
2893  * gpiod_set_value_nocheck() - set a GPIO line value without checking
2894  * @desc: the descriptor to set the value on
2895  * @value: value to set
2896  *
2897  * This sets the value of a GPIO line backing a descriptor, applying
2898  * different semantic quirks like active low and open drain/source
2899  * handling.
2900  */
2901 static void gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
2902 {
2903         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2904                 value = !value;
2905         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2906                 gpio_set_open_drain_value_commit(desc, value);
2907         else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2908                 gpio_set_open_source_value_commit(desc, value);
2909         else
2910                 gpiod_set_raw_value_commit(desc, value);
2911 }
2912
2913 /**
2914  * gpiod_set_value() - assign a gpio's value
2915  * @desc: gpio whose value will be assigned
2916  * @value: value to assign
2917  *
2918  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
2919  * OPEN_DRAIN and OPEN_SOURCE flags into account.
2920  *
2921  * This function can be called from contexts where we cannot sleep, and will
2922  * complain if the GPIO chip functions potentially sleep.
2923  */
2924 void gpiod_set_value(struct gpio_desc *desc, int value)
2925 {
2926         VALIDATE_DESC_VOID(desc);
2927         /* Should be using gpiod_set_value_cansleep() */
2928         WARN_ON(desc->gdev->chip->can_sleep);
2929         gpiod_set_value_nocheck(desc, value);
2930 }
2931 EXPORT_SYMBOL_GPL(gpiod_set_value);
2932
2933 /**
2934  * gpiod_set_raw_array_value() - assign values to an array of GPIOs
2935  * @array_size: number of elements in the descriptor array / value bitmap
2936  * @desc_array: array of GPIO descriptors whose values will be assigned
2937  * @array_info: information on applicability of fast bitmap processing path
2938  * @value_bitmap: bitmap of values to assign
2939  *
2940  * Set the raw values of the GPIOs, i.e. the values of the physical lines
2941  * without regard for their ACTIVE_LOW status.
2942  *
2943  * This function can be called from contexts where we cannot sleep, and will
2944  * complain if the GPIO chip functions potentially sleep.
2945  */
2946 int gpiod_set_raw_array_value(unsigned int array_size,
2947                               struct gpio_desc **desc_array,
2948                               struct gpio_array *array_info,
2949                               unsigned long *value_bitmap)
2950 {
2951         if (!desc_array)
2952                 return -EINVAL;
2953         return gpiod_set_array_value_complex(true, false, array_size,
2954                                         desc_array, array_info, value_bitmap);
2955 }
2956 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
2957
2958 /**
2959  * gpiod_set_array_value() - assign values to an array of GPIOs
2960  * @array_size: number of elements in the descriptor array / value bitmap
2961  * @desc_array: array of GPIO descriptors whose values will be assigned
2962  * @array_info: information on applicability of fast bitmap processing path
2963  * @value_bitmap: bitmap of values to assign
2964  *
2965  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
2966  * into account.
2967  *
2968  * This function can be called from contexts where we cannot sleep, and will
2969  * complain if the GPIO chip functions potentially sleep.
2970  */
2971 int gpiod_set_array_value(unsigned int array_size,
2972                           struct gpio_desc **desc_array,
2973                           struct gpio_array *array_info,
2974                           unsigned long *value_bitmap)
2975 {
2976         if (!desc_array)
2977                 return -EINVAL;
2978         return gpiod_set_array_value_complex(false, false, array_size,
2979                                              desc_array, array_info,
2980                                              value_bitmap);
2981 }
2982 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
2983
2984 /**
2985  * gpiod_cansleep() - report whether gpio value access may sleep
2986  * @desc: gpio to check
2987  *
2988  */
2989 int gpiod_cansleep(const struct gpio_desc *desc)
2990 {
2991         VALIDATE_DESC(desc);
2992         return desc->gdev->chip->can_sleep;
2993 }
2994 EXPORT_SYMBOL_GPL(gpiod_cansleep);
2995
2996 /**
2997  * gpiod_set_consumer_name() - set the consumer name for the descriptor
2998  * @desc: gpio to set the consumer name on
2999  * @name: the new consumer name
3000  */
3001 int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
3002 {
3003         VALIDATE_DESC(desc);
3004         if (name) {
3005                 name = kstrdup_const(name, GFP_KERNEL);
3006                 if (!name)
3007                         return -ENOMEM;
3008         }
3009
3010         kfree_const(desc->label);
3011         desc_set_label(desc, name);
3012
3013         return 0;
3014 }
3015 EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
3016
3017 /**
3018  * gpiod_to_irq() - return the IRQ corresponding to a GPIO
3019  * @desc: gpio whose IRQ will be returned (already requested)
3020  *
3021  * Return the IRQ corresponding to the passed GPIO, or an error code in case of
3022  * error.
3023  */
3024 int gpiod_to_irq(const struct gpio_desc *desc)
3025 {
3026         struct gpio_chip *gc;
3027         int offset;
3028
3029         /*
3030          * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
3031          * requires this function to not return zero on an invalid descriptor
3032          * but rather a negative error number.
3033          */
3034         if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
3035                 return -EINVAL;
3036
3037         gc = desc->gdev->chip;
3038         offset = gpio_chip_hwgpio(desc);
3039         if (gc->to_irq) {
3040                 int retirq = gc->to_irq(gc, offset);
3041
3042                 /* Zero means NO_IRQ */
3043                 if (!retirq)
3044                         return -ENXIO;
3045
3046                 return retirq;
3047         }
3048         return -ENXIO;
3049 }
3050 EXPORT_SYMBOL_GPL(gpiod_to_irq);
3051
3052 /**
3053  * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
3054  * @gc: the chip the GPIO to lock belongs to
3055  * @offset: the offset of the GPIO to lock as IRQ
3056  *
3057  * This is used directly by GPIO drivers that want to lock down
3058  * a certain GPIO line to be used for IRQs.
3059  */
3060 int gpiochip_lock_as_irq(struct gpio_chip *gc, unsigned int offset)
3061 {
3062         struct gpio_desc *desc;
3063
3064         desc = gpiochip_get_desc(gc, offset);
3065         if (IS_ERR(desc))
3066                 return PTR_ERR(desc);
3067
3068         /*
3069          * If it's fast: flush the direction setting if something changed
3070          * behind our back
3071          */
3072         if (!gc->can_sleep && gc->get_direction) {
3073                 int dir = gpiod_get_direction(desc);
3074
3075                 if (dir < 0) {
3076                         chip_err(gc, "%s: cannot get GPIO direction\n",
3077                                  __func__);
3078                         return dir;
3079                 }
3080         }
3081
3082         /* To be valid for IRQ the line needs to be input or open drain */
3083         if (test_bit(FLAG_IS_OUT, &desc->flags) &&
3084             !test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
3085                 chip_err(gc,
3086                          "%s: tried to flag a GPIO set as output for IRQ\n",
3087                          __func__);
3088                 return -EIO;
3089         }
3090
3091         set_bit(FLAG_USED_AS_IRQ, &desc->flags);
3092         set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3093
3094         /*
3095          * If the consumer has not set up a label (such as when the
3096          * IRQ is referenced from .to_irq()) we set up a label here
3097          * so it is clear this is used as an interrupt.
3098          */
3099         if (!desc->label)
3100                 desc_set_label(desc, "interrupt");
3101
3102         return 0;
3103 }
3104 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
3105
3106 /**
3107  * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
3108  * @gc: the chip the GPIO to lock belongs to
3109  * @offset: the offset of the GPIO to lock as IRQ
3110  *
3111  * This is used directly by GPIO drivers that want to indicate
3112  * that a certain GPIO is no longer used exclusively for IRQ.
3113  */
3114 void gpiochip_unlock_as_irq(struct gpio_chip *gc, unsigned int offset)
3115 {
3116         struct gpio_desc *desc;
3117
3118         desc = gpiochip_get_desc(gc, offset);
3119         if (IS_ERR(desc))
3120                 return;
3121
3122         clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
3123         clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3124
3125         /* If we only had this marking, erase it */
3126         if (desc->label && !strcmp(desc->label, "interrupt"))
3127                 desc_set_label(desc, NULL);
3128 }
3129 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
3130
3131 void gpiochip_disable_irq(struct gpio_chip *gc, unsigned int offset)
3132 {
3133         struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
3134
3135         if (!IS_ERR(desc) &&
3136             !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags)))
3137                 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3138 }
3139 EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
3140
3141 void gpiochip_enable_irq(struct gpio_chip *gc, unsigned int offset)
3142 {
3143         struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
3144
3145         if (!IS_ERR(desc) &&
3146             !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags))) {
3147                 /*
3148                  * We must not be output when using IRQ UNLESS we are
3149                  * open drain.
3150                  */
3151                 WARN_ON(test_bit(FLAG_IS_OUT, &desc->flags) &&
3152                         !test_bit(FLAG_OPEN_DRAIN, &desc->flags));
3153                 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3154         }
3155 }
3156 EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
3157
3158 bool gpiochip_line_is_irq(struct gpio_chip *gc, unsigned int offset)
3159 {
3160         if (offset >= gc->ngpio)
3161                 return false;
3162
3163         return test_bit(FLAG_USED_AS_IRQ, &gc->gpiodev->descs[offset].flags);
3164 }
3165 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
3166
3167 int gpiochip_reqres_irq(struct gpio_chip *gc, unsigned int offset)
3168 {
3169         int ret;
3170
3171         if (!try_module_get(gc->gpiodev->owner))
3172                 return -ENODEV;
3173
3174         ret = gpiochip_lock_as_irq(gc, offset);
3175         if (ret) {
3176                 chip_err(gc, "unable to lock HW IRQ %u for IRQ\n", offset);
3177                 module_put(gc->gpiodev->owner);
3178                 return ret;
3179         }
3180         return 0;
3181 }
3182 EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
3183
3184 void gpiochip_relres_irq(struct gpio_chip *gc, unsigned int offset)
3185 {
3186         gpiochip_unlock_as_irq(gc, offset);
3187         module_put(gc->gpiodev->owner);
3188 }
3189 EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
3190
3191 bool gpiochip_line_is_open_drain(struct gpio_chip *gc, unsigned int offset)
3192 {
3193         if (offset >= gc->ngpio)
3194                 return false;
3195
3196         return test_bit(FLAG_OPEN_DRAIN, &gc->gpiodev->descs[offset].flags);
3197 }
3198 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
3199
3200 bool gpiochip_line_is_open_source(struct gpio_chip *gc, unsigned int offset)
3201 {
3202         if (offset >= gc->ngpio)
3203                 return false;
3204
3205         return test_bit(FLAG_OPEN_SOURCE, &gc->gpiodev->descs[offset].flags);
3206 }
3207 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
3208
3209 bool gpiochip_line_is_persistent(struct gpio_chip *gc, unsigned int offset)
3210 {
3211         if (offset >= gc->ngpio)
3212                 return false;
3213
3214         return !test_bit(FLAG_TRANSITORY, &gc->gpiodev->descs[offset].flags);
3215 }
3216 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
3217
3218 /**
3219  * gpiod_get_raw_value_cansleep() - return a gpio's raw value
3220  * @desc: gpio whose value will be returned
3221  *
3222  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
3223  * its ACTIVE_LOW status, or negative errno on failure.
3224  *
3225  * This function is to be called from contexts that can sleep.
3226  */
3227 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
3228 {
3229         might_sleep_if(extra_checks);
3230         VALIDATE_DESC(desc);
3231         return gpiod_get_raw_value_commit(desc);
3232 }
3233 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
3234
3235 /**
3236  * gpiod_get_value_cansleep() - return a gpio's value
3237  * @desc: gpio whose value will be returned
3238  *
3239  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3240  * account, or negative errno on failure.
3241  *
3242  * This function is to be called from contexts that can sleep.
3243  */
3244 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
3245 {
3246         int value;
3247
3248         might_sleep_if(extra_checks);
3249         VALIDATE_DESC(desc);
3250         value = gpiod_get_raw_value_commit(desc);
3251         if (value < 0)
3252                 return value;
3253
3254         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3255                 value = !value;
3256
3257         return value;
3258 }
3259 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
3260
3261 /**
3262  * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
3263  * @array_size: number of elements in the descriptor array / value bitmap
3264  * @desc_array: array of GPIO descriptors whose values will be read
3265  * @array_info: information on applicability of fast bitmap processing path
3266  * @value_bitmap: bitmap to store the read values
3267  *
3268  * Read the raw values of the GPIOs, i.e. the values of the physical lines
3269  * without regard for their ACTIVE_LOW status.  Return 0 in case of success,
3270  * else an error code.
3271  *
3272  * This function is to be called from contexts that can sleep.
3273  */
3274 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
3275                                        struct gpio_desc **desc_array,
3276                                        struct gpio_array *array_info,
3277                                        unsigned long *value_bitmap)
3278 {
3279         might_sleep_if(extra_checks);
3280         if (!desc_array)
3281                 return -EINVAL;
3282         return gpiod_get_array_value_complex(true, true, array_size,
3283                                              desc_array, array_info,
3284                                              value_bitmap);
3285 }
3286 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
3287
3288 /**
3289  * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
3290  * @array_size: number of elements in the descriptor array / value bitmap
3291  * @desc_array: array of GPIO descriptors whose values will be read
3292  * @array_info: information on applicability of fast bitmap processing path
3293  * @value_bitmap: bitmap to store the read values
3294  *
3295  * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3296  * into account.  Return 0 in case of success, else an error code.
3297  *
3298  * This function is to be called from contexts that can sleep.
3299  */
3300 int gpiod_get_array_value_cansleep(unsigned int array_size,
3301                                    struct gpio_desc **desc_array,
3302                                    struct gpio_array *array_info,
3303                                    unsigned long *value_bitmap)
3304 {
3305         might_sleep_if(extra_checks);
3306         if (!desc_array)
3307                 return -EINVAL;
3308         return gpiod_get_array_value_complex(false, true, array_size,
3309                                              desc_array, array_info,
3310                                              value_bitmap);
3311 }
3312 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
3313
3314 /**
3315  * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
3316  * @desc: gpio whose value will be assigned
3317  * @value: value to assign
3318  *
3319  * Set the raw value of the GPIO, i.e. the value of its physical line without
3320  * regard for its ACTIVE_LOW status.
3321  *
3322  * This function is to be called from contexts that can sleep.
3323  */
3324 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
3325 {
3326         might_sleep_if(extra_checks);
3327         VALIDATE_DESC_VOID(desc);
3328         gpiod_set_raw_value_commit(desc, value);
3329 }
3330 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
3331
3332 /**
3333  * gpiod_set_value_cansleep() - assign a gpio's value
3334  * @desc: gpio whose value will be assigned
3335  * @value: value to assign
3336  *
3337  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3338  * account
3339  *
3340  * This function is to be called from contexts that can sleep.
3341  */
3342 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
3343 {
3344         might_sleep_if(extra_checks);
3345         VALIDATE_DESC_VOID(desc);
3346         gpiod_set_value_nocheck(desc, value);
3347 }
3348 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
3349
3350 /**
3351  * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
3352  * @array_size: number of elements in the descriptor array / value bitmap
3353  * @desc_array: array of GPIO descriptors whose values will be assigned
3354  * @array_info: information on applicability of fast bitmap processing path
3355  * @value_bitmap: bitmap of values to assign
3356  *
3357  * Set the raw values of the GPIOs, i.e. the values of the physical lines
3358  * without regard for their ACTIVE_LOW status.
3359  *
3360  * This function is to be called from contexts that can sleep.
3361  */
3362 int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
3363                                        struct gpio_desc **desc_array,
3364                                        struct gpio_array *array_info,
3365                                        unsigned long *value_bitmap)
3366 {
3367         might_sleep_if(extra_checks);
3368         if (!desc_array)
3369                 return -EINVAL;
3370         return gpiod_set_array_value_complex(true, true, array_size, desc_array,
3371                                       array_info, value_bitmap);
3372 }
3373 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
3374
3375 /**
3376  * gpiod_add_lookup_tables() - register GPIO device consumers
3377  * @tables: list of tables of consumers to register
3378  * @n: number of tables in the list
3379  */
3380 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
3381 {
3382         unsigned int i;
3383
3384         mutex_lock(&gpio_lookup_lock);
3385
3386         for (i = 0; i < n; i++)
3387                 list_add_tail(&tables[i]->list, &gpio_lookup_list);
3388
3389         mutex_unlock(&gpio_lookup_lock);
3390 }
3391
3392 /**
3393  * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
3394  * @array_size: number of elements in the descriptor array / value bitmap
3395  * @desc_array: array of GPIO descriptors whose values will be assigned
3396  * @array_info: information on applicability of fast bitmap processing path
3397  * @value_bitmap: bitmap of values to assign
3398  *
3399  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3400  * into account.
3401  *
3402  * This function is to be called from contexts that can sleep.
3403  */
3404 int gpiod_set_array_value_cansleep(unsigned int array_size,
3405                                    struct gpio_desc **desc_array,
3406                                    struct gpio_array *array_info,
3407                                    unsigned long *value_bitmap)
3408 {
3409         might_sleep_if(extra_checks);
3410         if (!desc_array)
3411                 return -EINVAL;
3412         return gpiod_set_array_value_complex(false, true, array_size,
3413                                              desc_array, array_info,
3414                                              value_bitmap);
3415 }
3416 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
3417
3418 /**
3419  * gpiod_add_lookup_table() - register GPIO device consumers
3420  * @table: table of consumers to register
3421  */
3422 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
3423 {
3424         mutex_lock(&gpio_lookup_lock);
3425
3426         list_add_tail(&table->list, &gpio_lookup_list);
3427
3428         mutex_unlock(&gpio_lookup_lock);
3429 }
3430 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
3431
3432 /**
3433  * gpiod_remove_lookup_table() - unregister GPIO device consumers
3434  * @table: table of consumers to unregister
3435  */
3436 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
3437 {
3438         mutex_lock(&gpio_lookup_lock);
3439
3440         list_del(&table->list);
3441
3442         mutex_unlock(&gpio_lookup_lock);
3443 }
3444 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
3445
3446 /**
3447  * gpiod_add_hogs() - register a set of GPIO hogs from machine code
3448  * @hogs: table of gpio hog entries with a zeroed sentinel at the end
3449  */
3450 void gpiod_add_hogs(struct gpiod_hog *hogs)
3451 {
3452         struct gpio_chip *gc;
3453         struct gpiod_hog *hog;
3454
3455         mutex_lock(&gpio_machine_hogs_mutex);
3456
3457         for (hog = &hogs[0]; hog->chip_label; hog++) {
3458                 list_add_tail(&hog->list, &gpio_machine_hogs);
3459
3460                 /*
3461                  * The chip may have been registered earlier, so check if it
3462                  * exists and, if so, try to hog the line now.
3463                  */
3464                 gc = find_chip_by_name(hog->chip_label);
3465                 if (gc)
3466                         gpiochip_machine_hog(gc, hog);
3467         }
3468
3469         mutex_unlock(&gpio_machine_hogs_mutex);
3470 }
3471 EXPORT_SYMBOL_GPL(gpiod_add_hogs);
3472
3473 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
3474 {
3475         const char *dev_id = dev ? dev_name(dev) : NULL;
3476         struct gpiod_lookup_table *table;
3477
3478         mutex_lock(&gpio_lookup_lock);
3479
3480         list_for_each_entry(table, &gpio_lookup_list, list) {
3481                 if (table->dev_id && dev_id) {
3482                         /*
3483                          * Valid strings on both ends, must be identical to have
3484                          * a match
3485                          */
3486                         if (!strcmp(table->dev_id, dev_id))
3487                                 goto found;
3488                 } else {
3489                         /*
3490                          * One of the pointers is NULL, so both must be to have
3491                          * a match
3492                          */
3493                         if (dev_id == table->dev_id)
3494                                 goto found;
3495                 }
3496         }
3497         table = NULL;
3498
3499 found:
3500         mutex_unlock(&gpio_lookup_lock);
3501         return table;
3502 }
3503
3504 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
3505                                     unsigned int idx, unsigned long *flags)
3506 {
3507         struct gpio_desc *desc = ERR_PTR(-ENOENT);
3508         struct gpiod_lookup_table *table;
3509         struct gpiod_lookup *p;
3510
3511         table = gpiod_find_lookup_table(dev);
3512         if (!table)
3513                 return desc;
3514
3515         for (p = &table->table[0]; p->key; p++) {
3516                 struct gpio_chip *gc;
3517
3518                 /* idx must always match exactly */
3519                 if (p->idx != idx)
3520                         continue;
3521
3522                 /* If the lookup entry has a con_id, require exact match */
3523                 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
3524                         continue;
3525
3526                 if (p->chip_hwnum == U16_MAX) {
3527                         desc = gpio_name_to_desc(p->key);
3528                         if (desc) {
3529                                 *flags = p->flags;
3530                                 return desc;
3531                         }
3532
3533                         dev_warn(dev, "cannot find GPIO line %s, deferring\n",
3534                                  p->key);
3535                         return ERR_PTR(-EPROBE_DEFER);
3536                 }
3537
3538                 gc = find_chip_by_name(p->key);
3539
3540                 if (!gc) {
3541                         /*
3542                          * As the lookup table indicates a chip with
3543                          * p->key should exist, assume it may
3544                          * still appear later and let the interested
3545                          * consumer be probed again or let the Deferred
3546                          * Probe infrastructure handle the error.
3547                          */
3548                         dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
3549                                  p->key);
3550                         return ERR_PTR(-EPROBE_DEFER);
3551                 }
3552
3553                 if (gc->ngpio <= p->chip_hwnum) {
3554                         dev_err(dev,
3555                                 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
3556                                 idx, p->chip_hwnum, gc->ngpio - 1,
3557                                 gc->label);
3558                         return ERR_PTR(-EINVAL);
3559                 }
3560
3561                 desc = gpiochip_get_desc(gc, p->chip_hwnum);
3562                 *flags = p->flags;
3563
3564                 return desc;
3565         }
3566
3567         return desc;
3568 }
3569
3570 static int platform_gpio_count(struct device *dev, const char *con_id)
3571 {
3572         struct gpiod_lookup_table *table;
3573         struct gpiod_lookup *p;
3574         unsigned int count = 0;
3575
3576         table = gpiod_find_lookup_table(dev);
3577         if (!table)
3578                 return -ENOENT;
3579
3580         for (p = &table->table[0]; p->key; p++) {
3581                 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
3582                     (!con_id && !p->con_id))
3583                         count++;
3584         }
3585         if (!count)
3586                 return -ENOENT;
3587
3588         return count;
3589 }
3590
3591 /**
3592  * fwnode_gpiod_get_index - obtain a GPIO from firmware node
3593  * @fwnode:     handle of the firmware node
3594  * @con_id:     function within the GPIO consumer
3595  * @index:      index of the GPIO to obtain for the consumer
3596  * @flags:      GPIO initialization flags
3597  * @label:      label to attach to the requested GPIO
3598  *
3599  * This function can be used for drivers that get their configuration
3600  * from opaque firmware.
3601  *
3602  * The function properly finds the corresponding GPIO using whatever is the
3603  * underlying firmware interface and then makes sure that the GPIO
3604  * descriptor is requested before it is returned to the caller.
3605  *
3606  * Returns:
3607  * On successful request the GPIO pin is configured in accordance with
3608  * provided @flags.
3609  *
3610  * In case of error an ERR_PTR() is returned.
3611  */
3612 struct gpio_desc *fwnode_gpiod_get_index(struct fwnode_handle *fwnode,
3613                                          const char *con_id, int index,
3614                                          enum gpiod_flags flags,
3615                                          const char *label)
3616 {
3617         struct gpio_desc *desc;
3618         char prop_name[32]; /* 32 is max size of property name */
3619         unsigned int i;
3620
3621         for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
3622                 if (con_id)
3623                         snprintf(prop_name, sizeof(prop_name), "%s-%s",
3624                                             con_id, gpio_suffixes[i]);
3625                 else
3626                         snprintf(prop_name, sizeof(prop_name), "%s",
3627                                             gpio_suffixes[i]);
3628
3629                 desc = fwnode_get_named_gpiod(fwnode, prop_name, index, flags,
3630                                               label);
3631                 if (!IS_ERR(desc) || (PTR_ERR(desc) != -ENOENT))
3632                         break;
3633         }
3634
3635         return desc;
3636 }
3637 EXPORT_SYMBOL_GPL(fwnode_gpiod_get_index);
3638
3639 /**
3640  * gpiod_count - return the number of GPIOs associated with a device / function
3641  *              or -ENOENT if no GPIO has been assigned to the requested function
3642  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3643  * @con_id:     function within the GPIO consumer
3644  */
3645 int gpiod_count(struct device *dev, const char *con_id)
3646 {
3647         int count = -ENOENT;
3648
3649         if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
3650                 count = of_gpio_get_count(dev, con_id);
3651         else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
3652                 count = acpi_gpio_count(dev, con_id);
3653
3654         if (count < 0)
3655                 count = platform_gpio_count(dev, con_id);
3656
3657         return count;
3658 }
3659 EXPORT_SYMBOL_GPL(gpiod_count);
3660
3661 /**
3662  * gpiod_get - obtain a GPIO for a given GPIO function
3663  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3664  * @con_id:     function within the GPIO consumer
3665  * @flags:      optional GPIO initialization flags
3666  *
3667  * Return the GPIO descriptor corresponding to the function con_id of device
3668  * dev, -ENOENT if no GPIO has been assigned to the requested function, or
3669  * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
3670  */
3671 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
3672                                          enum gpiod_flags flags)
3673 {
3674         return gpiod_get_index(dev, con_id, 0, flags);
3675 }
3676 EXPORT_SYMBOL_GPL(gpiod_get);
3677
3678 /**
3679  * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
3680  * @dev: GPIO consumer, can be NULL for system-global GPIOs
3681  * @con_id: function within the GPIO consumer
3682  * @flags: optional GPIO initialization flags
3683  *
3684  * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
3685  * the requested function it will return NULL. This is convenient for drivers
3686  * that need to handle optional GPIOs.
3687  */
3688 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
3689                                                   const char *con_id,
3690                                                   enum gpiod_flags flags)
3691 {
3692         return gpiod_get_index_optional(dev, con_id, 0, flags);
3693 }
3694 EXPORT_SYMBOL_GPL(gpiod_get_optional);
3695
3696
3697 /**
3698  * gpiod_configure_flags - helper function to configure a given GPIO
3699  * @desc:       gpio whose value will be assigned
3700  * @con_id:     function within the GPIO consumer
3701  * @lflags:     bitmask of gpio_lookup_flags GPIO_* values - returned from
3702  *              of_find_gpio() or of_get_gpio_hog()
3703  * @dflags:     gpiod_flags - optional GPIO initialization flags
3704  *
3705  * Return 0 on success, -ENOENT if no GPIO has been assigned to the
3706  * requested function and/or index, or another IS_ERR() code if an error
3707  * occurred while trying to acquire the GPIO.
3708  */
3709 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
3710                 unsigned long lflags, enum gpiod_flags dflags)
3711 {
3712         int ret;
3713
3714         if (lflags & GPIO_ACTIVE_LOW)
3715                 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
3716
3717         if (lflags & GPIO_OPEN_DRAIN)
3718                 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3719         else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
3720                 /*
3721                  * This enforces open drain mode from the consumer side.
3722                  * This is necessary for some busses like I2C, but the lookup
3723                  * should *REALLY* have specified them as open drain in the
3724                  * first place, so print a little warning here.
3725                  */
3726                 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3727                 gpiod_warn(desc,
3728                            "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
3729         }
3730
3731         if (lflags & GPIO_OPEN_SOURCE)
3732                 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
3733
3734         if ((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DOWN)) {
3735                 gpiod_err(desc,
3736                           "both pull-up and pull-down enabled, invalid configuration\n");
3737                 return -EINVAL;
3738         }
3739
3740         if (lflags & GPIO_PULL_UP)
3741                 set_bit(FLAG_PULL_UP, &desc->flags);
3742         else if (lflags & GPIO_PULL_DOWN)
3743                 set_bit(FLAG_PULL_DOWN, &desc->flags);
3744
3745         ret = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
3746         if (ret < 0)
3747                 return ret;
3748
3749         /* No particular flag request, return here... */
3750         if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
3751                 gpiod_dbg(desc, "no flags found for %s\n", con_id);
3752                 return 0;
3753         }
3754
3755         /* Process flags */
3756         if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
3757                 ret = gpiod_direction_output(desc,
3758                                 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
3759         else
3760                 ret = gpiod_direction_input(desc);
3761
3762         return ret;
3763 }
3764
3765 /**
3766  * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
3767  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3768  * @con_id:     function within the GPIO consumer
3769  * @idx:        index of the GPIO to obtain in the consumer
3770  * @flags:      optional GPIO initialization flags
3771  *
3772  * This variant of gpiod_get() allows to access GPIOs other than the first
3773  * defined one for functions that define several GPIOs.
3774  *
3775  * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
3776  * requested function and/or index, or another IS_ERR() code if an error
3777  * occurred while trying to acquire the GPIO.
3778  */
3779 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
3780                                                const char *con_id,
3781                                                unsigned int idx,
3782                                                enum gpiod_flags flags)
3783 {
3784         unsigned long lookupflags = GPIO_LOOKUP_FLAGS_DEFAULT;
3785         struct gpio_desc *desc = NULL;
3786         int ret;
3787         /* Maybe we have a device name, maybe not */
3788         const char *devname = dev ? dev_name(dev) : "?";
3789
3790         dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
3791
3792         if (dev) {
3793                 /* Using device tree? */
3794                 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
3795                         dev_dbg(dev, "using device tree for GPIO lookup\n");
3796                         desc = of_find_gpio(dev, con_id, idx, &lookupflags);
3797                 } else if (ACPI_COMPANION(dev)) {
3798                         dev_dbg(dev, "using ACPI for GPIO lookup\n");
3799                         desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
3800                 }
3801         }
3802
3803         /*
3804          * Either we are not using DT or ACPI, or their lookup did not return
3805          * a result. In that case, use platform lookup as a fallback.
3806          */
3807         if (!desc || desc == ERR_PTR(-ENOENT)) {
3808                 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
3809                 desc = gpiod_find(dev, con_id, idx, &lookupflags);
3810         }
3811
3812         if (IS_ERR(desc)) {
3813                 dev_dbg(dev, "No GPIO consumer %s found\n", con_id);
3814                 return desc;
3815         }
3816
3817         /*
3818          * If a connection label was passed use that, else attempt to use
3819          * the device name as label
3820          */
3821         ret = gpiod_request(desc, con_id ? con_id : devname);
3822         if (ret < 0) {
3823                 if (ret == -EBUSY && flags & GPIOD_FLAGS_BIT_NONEXCLUSIVE) {
3824                         /*
3825                          * This happens when there are several consumers for
3826                          * the same GPIO line: we just return here without
3827                          * further initialization. It is a bit if a hack.
3828                          * This is necessary to support fixed regulators.
3829                          *
3830                          * FIXME: Make this more sane and safe.
3831                          */
3832                         dev_info(dev, "nonexclusive access to GPIO for %s\n",
3833                                  con_id ? con_id : devname);
3834                         return desc;
3835                 } else {
3836                         return ERR_PTR(ret);
3837                 }
3838         }
3839
3840         ret = gpiod_configure_flags(desc, con_id, lookupflags, flags);
3841         if (ret < 0) {
3842                 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
3843                 gpiod_put(desc);
3844                 return ERR_PTR(ret);
3845         }
3846
3847         blocking_notifier_call_chain(&desc->gdev->notifier,
3848                                      GPIOLINE_CHANGED_REQUESTED, desc);
3849
3850         return desc;
3851 }
3852 EXPORT_SYMBOL_GPL(gpiod_get_index);
3853
3854 /**
3855  * fwnode_get_named_gpiod - obtain a GPIO from firmware node
3856  * @fwnode:     handle of the firmware node
3857  * @propname:   name of the firmware property representing the GPIO
3858  * @index:      index of the GPIO to obtain for the consumer
3859  * @dflags:     GPIO initialization flags
3860  * @label:      label to attach to the requested GPIO
3861  *
3862  * This function can be used for drivers that get their configuration
3863  * from opaque firmware.
3864  *
3865  * The function properly finds the corresponding GPIO using whatever is the
3866  * underlying firmware interface and then makes sure that the GPIO
3867  * descriptor is requested before it is returned to the caller.
3868  *
3869  * Returns:
3870  * On successful request the GPIO pin is configured in accordance with
3871  * provided @dflags.
3872  *
3873  * In case of error an ERR_PTR() is returned.
3874  */
3875 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
3876                                          const char *propname, int index,
3877                                          enum gpiod_flags dflags,
3878                                          const char *label)
3879 {
3880         unsigned long lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
3881         struct gpio_desc *desc = ERR_PTR(-ENODEV);
3882         int ret;
3883
3884         if (!fwnode)
3885                 return ERR_PTR(-EINVAL);
3886
3887         if (is_of_node(fwnode)) {
3888                 desc = gpiod_get_from_of_node(to_of_node(fwnode),
3889                                               propname, index,
3890                                               dflags,
3891                                               label);
3892                 return desc;
3893         } else if (is_acpi_node(fwnode)) {
3894                 struct acpi_gpio_info info;
3895
3896                 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
3897                 if (IS_ERR(desc))
3898                         return desc;
3899
3900                 acpi_gpio_update_gpiod_flags(&dflags, &info);
3901                 acpi_gpio_update_gpiod_lookup_flags(&lflags, &info);
3902         }
3903
3904         /* Currently only ACPI takes this path */
3905         ret = gpiod_request(desc, label);
3906         if (ret)
3907                 return ERR_PTR(ret);
3908
3909         ret = gpiod_configure_flags(desc, propname, lflags, dflags);
3910         if (ret < 0) {
3911                 gpiod_put(desc);
3912                 return ERR_PTR(ret);
3913         }
3914
3915         blocking_notifier_call_chain(&desc->gdev->notifier,
3916                                      GPIOLINE_CHANGED_REQUESTED, desc);
3917
3918         return desc;
3919 }
3920 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
3921
3922 /**
3923  * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
3924  *                            function
3925  * @dev: GPIO consumer, can be NULL for system-global GPIOs
3926  * @con_id: function within the GPIO consumer
3927  * @index: index of the GPIO to obtain in the consumer
3928  * @flags: optional GPIO initialization flags
3929  *
3930  * This is equivalent to gpiod_get_index(), except that when no GPIO with the
3931  * specified index was assigned to the requested function it will return NULL.
3932  * This is convenient for drivers that need to handle optional GPIOs.
3933  */
3934 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
3935                                                         const char *con_id,
3936                                                         unsigned int index,
3937                                                         enum gpiod_flags flags)
3938 {
3939         struct gpio_desc *desc;
3940
3941         desc = gpiod_get_index(dev, con_id, index, flags);
3942         if (IS_ERR(desc)) {
3943                 if (PTR_ERR(desc) == -ENOENT)
3944                         return NULL;
3945         }
3946
3947         return desc;
3948 }
3949 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
3950
3951 /**
3952  * gpiod_hog - Hog the specified GPIO desc given the provided flags
3953  * @desc:       gpio whose value will be assigned
3954  * @name:       gpio line name
3955  * @lflags:     bitmask of gpio_lookup_flags GPIO_* values - returned from
3956  *              of_find_gpio() or of_get_gpio_hog()
3957  * @dflags:     gpiod_flags - optional GPIO initialization flags
3958  */
3959 int gpiod_hog(struct gpio_desc *desc, const char *name,
3960               unsigned long lflags, enum gpiod_flags dflags)
3961 {
3962         struct gpio_chip *gc;
3963         struct gpio_desc *local_desc;
3964         int hwnum;
3965         int ret;
3966
3967         gc = gpiod_to_chip(desc);
3968         hwnum = gpio_chip_hwgpio(desc);
3969
3970         local_desc = gpiochip_request_own_desc(gc, hwnum, name,
3971                                                lflags, dflags);
3972         if (IS_ERR(local_desc)) {
3973                 ret = PTR_ERR(local_desc);
3974                 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
3975                        name, gc->label, hwnum, ret);
3976                 return ret;
3977         }
3978
3979         /* Mark GPIO as hogged so it can be identified and removed later */
3980         set_bit(FLAG_IS_HOGGED, &desc->flags);
3981
3982         gpiod_info(desc, "hogged as %s%s\n",
3983                 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
3984                 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ?
3985                   (dflags & GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low" : "");
3986
3987         return 0;
3988 }
3989
3990 /**
3991  * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
3992  * @gc: gpio chip to act on
3993  */
3994 static void gpiochip_free_hogs(struct gpio_chip *gc)
3995 {
3996         int id;
3997
3998         for (id = 0; id < gc->ngpio; id++) {
3999                 if (test_bit(FLAG_IS_HOGGED, &gc->gpiodev->descs[id].flags))
4000                         gpiochip_free_own_desc(&gc->gpiodev->descs[id]);
4001         }
4002 }
4003
4004 /**
4005  * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
4006  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
4007  * @con_id:     function within the GPIO consumer
4008  * @flags:      optional GPIO initialization flags
4009  *
4010  * This function acquires all the GPIOs defined under a given function.
4011  *
4012  * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
4013  * no GPIO has been assigned to the requested function, or another IS_ERR()
4014  * code if an error occurred while trying to acquire the GPIOs.
4015  */
4016 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
4017                                                 const char *con_id,
4018                                                 enum gpiod_flags flags)
4019 {
4020         struct gpio_desc *desc;
4021         struct gpio_descs *descs;
4022         struct gpio_array *array_info = NULL;
4023         struct gpio_chip *gc;
4024         int count, bitmap_size;
4025
4026         count = gpiod_count(dev, con_id);
4027         if (count < 0)
4028                 return ERR_PTR(count);
4029
4030         descs = kzalloc(struct_size(descs, desc, count), GFP_KERNEL);
4031         if (!descs)
4032                 return ERR_PTR(-ENOMEM);
4033
4034         for (descs->ndescs = 0; descs->ndescs < count; ) {
4035                 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
4036                 if (IS_ERR(desc)) {
4037                         gpiod_put_array(descs);
4038                         return ERR_CAST(desc);
4039                 }
4040
4041                 descs->desc[descs->ndescs] = desc;
4042
4043                 gc = gpiod_to_chip(desc);
4044                 /*
4045                  * If pin hardware number of array member 0 is also 0, select
4046                  * its chip as a candidate for fast bitmap processing path.
4047                  */
4048                 if (descs->ndescs == 0 && gpio_chip_hwgpio(desc) == 0) {
4049                         struct gpio_descs *array;
4050
4051                         bitmap_size = BITS_TO_LONGS(gc->ngpio > count ?
4052                                                     gc->ngpio : count);
4053
4054                         array = kzalloc(struct_size(descs, desc, count) +
4055                                         struct_size(array_info, invert_mask,
4056                                         3 * bitmap_size), GFP_KERNEL);
4057                         if (!array) {
4058                                 gpiod_put_array(descs);
4059                                 return ERR_PTR(-ENOMEM);
4060                         }
4061
4062                         memcpy(array, descs,
4063                                struct_size(descs, desc, descs->ndescs + 1));
4064                         kfree(descs);
4065
4066                         descs = array;
4067                         array_info = (void *)(descs->desc + count);
4068                         array_info->get_mask = array_info->invert_mask +
4069                                                   bitmap_size;
4070                         array_info->set_mask = array_info->get_mask +
4071                                                   bitmap_size;
4072
4073                         array_info->desc = descs->desc;
4074                         array_info->size = count;
4075                         array_info->chip = gc;
4076                         bitmap_set(array_info->get_mask, descs->ndescs,
4077                                    count - descs->ndescs);
4078                         bitmap_set(array_info->set_mask, descs->ndescs,
4079                                    count - descs->ndescs);
4080                         descs->info = array_info;
4081                 }
4082                 /* Unmark array members which don't belong to the 'fast' chip */
4083                 if (array_info && array_info->chip != gc) {
4084                         __clear_bit(descs->ndescs, array_info->get_mask);
4085                         __clear_bit(descs->ndescs, array_info->set_mask);
4086                 }
4087                 /*
4088                  * Detect array members which belong to the 'fast' chip
4089                  * but their pins are not in hardware order.
4090                  */
4091                 else if (array_info &&
4092                            gpio_chip_hwgpio(desc) != descs->ndescs) {
4093                         /*
4094                          * Don't use fast path if all array members processed so
4095                          * far belong to the same chip as this one but its pin
4096                          * hardware number is different from its array index.
4097                          */
4098                         if (bitmap_full(array_info->get_mask, descs->ndescs)) {
4099                                 array_info = NULL;
4100                         } else {
4101                                 __clear_bit(descs->ndescs,
4102                                             array_info->get_mask);
4103                                 __clear_bit(descs->ndescs,
4104                                             array_info->set_mask);
4105                         }
4106                 } else if (array_info) {
4107                         /* Exclude open drain or open source from fast output */
4108                         if (gpiochip_line_is_open_drain(gc, descs->ndescs) ||
4109                             gpiochip_line_is_open_source(gc, descs->ndescs))
4110                                 __clear_bit(descs->ndescs,
4111                                             array_info->set_mask);
4112                         /* Identify 'fast' pins which require invertion */
4113                         if (gpiod_is_active_low(desc))
4114                                 __set_bit(descs->ndescs,
4115                                           array_info->invert_mask);
4116                 }
4117
4118                 descs->ndescs++;
4119         }
4120         if (array_info)
4121                 dev_dbg(dev,
4122                         "GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
4123                         array_info->chip->label, array_info->size,
4124                         *array_info->get_mask, *array_info->set_mask,
4125                         *array_info->invert_mask);
4126         return descs;
4127 }
4128 EXPORT_SYMBOL_GPL(gpiod_get_array);
4129
4130 /**
4131  * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
4132  *                            function
4133  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
4134  * @con_id:     function within the GPIO consumer
4135  * @flags:      optional GPIO initialization flags
4136  *
4137  * This is equivalent to gpiod_get_array(), except that when no GPIO was
4138  * assigned to the requested function it will return NULL.
4139  */
4140 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
4141                                                         const char *con_id,
4142                                                         enum gpiod_flags flags)
4143 {
4144         struct gpio_descs *descs;
4145
4146         descs = gpiod_get_array(dev, con_id, flags);
4147         if (PTR_ERR(descs) == -ENOENT)
4148                 return NULL;
4149
4150         return descs;
4151 }
4152 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
4153
4154 /**
4155  * gpiod_put - dispose of a GPIO descriptor
4156  * @desc:       GPIO descriptor to dispose of
4157  *
4158  * No descriptor can be used after gpiod_put() has been called on it.
4159  */
4160 void gpiod_put(struct gpio_desc *desc)
4161 {
4162         if (desc)
4163                 gpiod_free(desc);
4164 }
4165 EXPORT_SYMBOL_GPL(gpiod_put);
4166
4167 /**
4168  * gpiod_put_array - dispose of multiple GPIO descriptors
4169  * @descs:      struct gpio_descs containing an array of descriptors
4170  */
4171 void gpiod_put_array(struct gpio_descs *descs)
4172 {
4173         unsigned int i;
4174
4175         for (i = 0; i < descs->ndescs; i++)
4176                 gpiod_put(descs->desc[i]);
4177
4178         kfree(descs);
4179 }
4180 EXPORT_SYMBOL_GPL(gpiod_put_array);
4181
4182 static int __init gpiolib_dev_init(void)
4183 {
4184         int ret;
4185
4186         /* Register GPIO sysfs bus */
4187         ret = bus_register(&gpio_bus_type);
4188         if (ret < 0) {
4189                 pr_err("gpiolib: could not register GPIO bus type\n");
4190                 return ret;
4191         }
4192
4193         ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, GPIOCHIP_NAME);
4194         if (ret < 0) {
4195                 pr_err("gpiolib: failed to allocate char dev region\n");
4196                 bus_unregister(&gpio_bus_type);
4197                 return ret;
4198         }
4199
4200         gpiolib_initialized = true;
4201         gpiochip_setup_devs();
4202
4203 #if IS_ENABLED(CONFIG_OF_DYNAMIC) && IS_ENABLED(CONFIG_OF_GPIO)
4204         WARN_ON(of_reconfig_notifier_register(&gpio_of_notifier));
4205 #endif /* CONFIG_OF_DYNAMIC && CONFIG_OF_GPIO */
4206
4207         return ret;
4208 }
4209 core_initcall(gpiolib_dev_init);
4210
4211 #ifdef CONFIG_DEBUG_FS
4212
4213 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
4214 {
4215         unsigned                i;
4216         struct gpio_chip        *gc = gdev->chip;
4217         unsigned                gpio = gdev->base;
4218         struct gpio_desc        *gdesc = &gdev->descs[0];
4219         bool                    is_out;
4220         bool                    is_irq;
4221         bool                    active_low;
4222
4223         for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
4224                 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
4225                         if (gdesc->name) {
4226                                 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
4227                                            gpio, gdesc->name);
4228                         }
4229                         continue;
4230                 }
4231
4232                 gpiod_get_direction(gdesc);
4233                 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
4234                 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
4235                 active_low = test_bit(FLAG_ACTIVE_LOW, &gdesc->flags);
4236                 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s%s",
4237                         gpio, gdesc->name ? gdesc->name : "", gdesc->label,
4238                         is_out ? "out" : "in ",
4239                         gc->get ? (gc->get(gc, i) ? "hi" : "lo") : "?  ",
4240                         is_irq ? "IRQ " : "",
4241                         active_low ? "ACTIVE LOW" : "");
4242                 seq_printf(s, "\n");
4243         }
4244 }
4245
4246 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
4247 {
4248         unsigned long flags;
4249         struct gpio_device *gdev = NULL;
4250         loff_t index = *pos;
4251
4252         s->private = "";
4253
4254         spin_lock_irqsave(&gpio_lock, flags);
4255         list_for_each_entry(gdev, &gpio_devices, list)
4256                 if (index-- == 0) {
4257                         spin_unlock_irqrestore(&gpio_lock, flags);
4258                         return gdev;
4259                 }
4260         spin_unlock_irqrestore(&gpio_lock, flags);
4261
4262         return NULL;
4263 }
4264
4265 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
4266 {
4267         unsigned long flags;
4268         struct gpio_device *gdev = v;
4269         void *ret = NULL;
4270
4271         spin_lock_irqsave(&gpio_lock, flags);
4272         if (list_is_last(&gdev->list, &gpio_devices))
4273                 ret = NULL;
4274         else
4275                 ret = list_entry(gdev->list.next, struct gpio_device, list);
4276         spin_unlock_irqrestore(&gpio_lock, flags);
4277
4278         s->private = "\n";
4279         ++*pos;
4280
4281         return ret;
4282 }
4283
4284 static void gpiolib_seq_stop(struct seq_file *s, void *v)
4285 {
4286 }
4287
4288 static int gpiolib_seq_show(struct seq_file *s, void *v)
4289 {
4290         struct gpio_device *gdev = v;
4291         struct gpio_chip *gc = gdev->chip;
4292         struct device *parent;
4293
4294         if (!gc) {
4295                 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
4296                            dev_name(&gdev->dev));
4297                 return 0;
4298         }
4299
4300         seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
4301                    dev_name(&gdev->dev),
4302                    gdev->base, gdev->base + gdev->ngpio - 1);
4303         parent = gc->parent;
4304         if (parent)
4305                 seq_printf(s, ", parent: %s/%s",
4306                            parent->bus ? parent->bus->name : "no-bus",
4307                            dev_name(parent));
4308         if (gc->label)
4309                 seq_printf(s, ", %s", gc->label);
4310         if (gc->can_sleep)
4311                 seq_printf(s, ", can sleep");
4312         seq_printf(s, ":\n");
4313
4314         if (gc->dbg_show)
4315                 gc->dbg_show(s, gc);
4316         else
4317                 gpiolib_dbg_show(s, gdev);
4318
4319         return 0;
4320 }
4321
4322 static const struct seq_operations gpiolib_sops = {
4323         .start = gpiolib_seq_start,
4324         .next = gpiolib_seq_next,
4325         .stop = gpiolib_seq_stop,
4326         .show = gpiolib_seq_show,
4327 };
4328 DEFINE_SEQ_ATTRIBUTE(gpiolib);
4329
4330 static int __init gpiolib_debugfs_init(void)
4331 {
4332         /* /sys/kernel/debug/gpio */
4333         debugfs_create_file("gpio", 0444, NULL, NULL, &gpiolib_fops);
4334         return 0;
4335 }
4336 subsys_initcall(gpiolib_debugfs_init);
4337
4338 #endif  /* DEBUG_FS */