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