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