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