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