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