GNU Linux-libre 4.14.266-gnu1
[releases.git] / drivers / gpio / gpiolib.c
1 #include <linux/bitmap.h>
2 #include <linux/kernel.h>
3 #include <linux/module.h>
4 #include <linux/interrupt.h>
5 #include <linux/irq.h>
6 #include <linux/spinlock.h>
7 #include <linux/list.h>
8 #include <linux/device.h>
9 #include <linux/err.h>
10 #include <linux/debugfs.h>
11 #include <linux/seq_file.h>
12 #include <linux/gpio.h>
13 #include <linux/of_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
33 #define CREATE_TRACE_POINTS
34 #include <trace/events/gpio.h>
35
36 /* Implementation infrastructure for GPIO interfaces.
37  *
38  * The GPIO programming interface allows for inlining speed-critical
39  * get/set operations for common cases, so that access to SOC-integrated
40  * GPIOs can sometimes cost only an instruction or two per bit.
41  */
42
43
44 /* When debugging, extend minimal trust to callers and platform code.
45  * Also emit diagnostic messages that may help initial bringup, when
46  * board setup or driver bugs are most common.
47  *
48  * Otherwise, minimize overhead in what may be bitbanging codepaths.
49  */
50 #ifdef  DEBUG
51 #define extra_checks    1
52 #else
53 #define extra_checks    0
54 #endif
55
56 /* Device and char device-related information */
57 static DEFINE_IDA(gpio_ida);
58 static dev_t gpio_devt;
59 #define GPIO_DEV_MAX 256 /* 256 GPIO chip devices supported */
60 static struct bus_type gpio_bus_type = {
61         .name = "gpio",
62 };
63
64 /* gpio_lock prevents conflicts during gpio_desc[] table updates.
65  * While any GPIO is requested, its gpio_chip is not removable;
66  * each GPIO's "requested" flag serves as a lock and refcount.
67  */
68 DEFINE_SPINLOCK(gpio_lock);
69
70 static DEFINE_MUTEX(gpio_lookup_lock);
71 static LIST_HEAD(gpio_lookup_list);
72 LIST_HEAD(gpio_devices);
73
74 static void gpiochip_free_hogs(struct gpio_chip *chip);
75 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);
76 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip);
77 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip);
78
79 static bool gpiolib_initialized;
80
81 static inline void desc_set_label(struct gpio_desc *d, const char *label)
82 {
83         d->label = label;
84 }
85
86 /**
87  * gpio_to_desc - Convert a GPIO number to its descriptor
88  * @gpio: global GPIO number
89  *
90  * Returns:
91  * The GPIO descriptor associated with the given GPIO, or %NULL if no GPIO
92  * with the given number exists in the system.
93  */
94 struct gpio_desc *gpio_to_desc(unsigned gpio)
95 {
96         struct gpio_device *gdev;
97         unsigned long flags;
98
99         spin_lock_irqsave(&gpio_lock, flags);
100
101         list_for_each_entry(gdev, &gpio_devices, list) {
102                 if (gdev->base <= gpio &&
103                     gdev->base + gdev->ngpio > gpio) {
104                         spin_unlock_irqrestore(&gpio_lock, flags);
105                         return &gdev->descs[gpio - gdev->base];
106                 }
107         }
108
109         spin_unlock_irqrestore(&gpio_lock, flags);
110
111         if (!gpio_is_valid(gpio))
112                 WARN(1, "invalid GPIO %d\n", gpio);
113
114         return NULL;
115 }
116 EXPORT_SYMBOL_GPL(gpio_to_desc);
117
118 /**
119  * gpiochip_get_desc - get the GPIO descriptor corresponding to the given
120  *                     hardware number for this chip
121  * @chip: GPIO chip
122  * @hwnum: hardware number of the GPIO for this chip
123  *
124  * Returns:
125  * A pointer to the GPIO descriptor or %ERR_PTR(-EINVAL) if no GPIO exists
126  * in the given chip for the specified hardware number.
127  */
128 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip,
129                                     u16 hwnum)
130 {
131         struct gpio_device *gdev = chip->gpiodev;
132
133         if (hwnum >= gdev->ngpio)
134                 return ERR_PTR(-EINVAL);
135
136         return &gdev->descs[hwnum];
137 }
138
139 /**
140  * desc_to_gpio - convert a GPIO descriptor to the integer namespace
141  * @desc: GPIO descriptor
142  *
143  * This should disappear in the future but is needed since we still
144  * use GPIO numbers for error messages and sysfs nodes.
145  *
146  * Returns:
147  * The global GPIO number for the GPIO specified by its descriptor.
148  */
149 int desc_to_gpio(const struct gpio_desc *desc)
150 {
151         return desc->gdev->base + (desc - &desc->gdev->descs[0]);
152 }
153 EXPORT_SYMBOL_GPL(desc_to_gpio);
154
155
156 /**
157  * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
158  * @desc:       descriptor to return the chip of
159  */
160 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
161 {
162         if (!desc || !desc->gdev || !desc->gdev->chip)
163                 return NULL;
164         return desc->gdev->chip;
165 }
166 EXPORT_SYMBOL_GPL(gpiod_to_chip);
167
168 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
169 static int gpiochip_find_base(int ngpio)
170 {
171         struct gpio_device *gdev;
172         int base = ARCH_NR_GPIOS - ngpio;
173
174         list_for_each_entry_reverse(gdev, &gpio_devices, list) {
175                 /* found a free space? */
176                 if (gdev->base + gdev->ngpio <= base)
177                         break;
178                 else
179                         /* nope, check the space right before the chip */
180                         base = gdev->base - ngpio;
181         }
182
183         if (gpio_is_valid(base)) {
184                 pr_debug("%s: found new base at %d\n", __func__, base);
185                 return base;
186         } else {
187                 pr_err("%s: cannot find free range\n", __func__);
188                 return -ENOSPC;
189         }
190 }
191
192 /**
193  * gpiod_get_direction - return the current direction of a GPIO
194  * @desc:       GPIO to get the direction of
195  *
196  * Return GPIOF_DIR_IN or GPIOF_DIR_OUT, or an error code in case of error.
197  *
198  * This function may sleep if gpiod_cansleep() is true.
199  */
200 int gpiod_get_direction(struct gpio_desc *desc)
201 {
202         struct gpio_chip        *chip;
203         unsigned                offset;
204         int                     status = -EINVAL;
205
206         chip = gpiod_to_chip(desc);
207         offset = gpio_chip_hwgpio(desc);
208
209         /*
210          * Open drain emulation using input mode may incorrectly report
211          * input here, fix that up.
212          */
213         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) &&
214             test_bit(FLAG_IS_OUT, &desc->flags))
215                 return 0;
216
217         if (!chip->get_direction)
218                 return status;
219
220         status = chip->get_direction(chip, offset);
221         if (status > 0) {
222                 /* GPIOF_DIR_IN, or other positive */
223                 status = 1;
224                 clear_bit(FLAG_IS_OUT, &desc->flags);
225         }
226         if (status == 0) {
227                 /* GPIOF_DIR_OUT */
228                 set_bit(FLAG_IS_OUT, &desc->flags);
229         }
230         return status;
231 }
232 EXPORT_SYMBOL_GPL(gpiod_get_direction);
233
234 /*
235  * Add a new chip to the global chips list, keeping the list of chips sorted
236  * by range(means [base, base + ngpio - 1]) order.
237  *
238  * Return -EBUSY if the new chip overlaps with some other chip's integer
239  * space.
240  */
241 static int gpiodev_add_to_list(struct gpio_device *gdev)
242 {
243         struct gpio_device *prev, *next;
244
245         if (list_empty(&gpio_devices)) {
246                 /* initial entry in list */
247                 list_add_tail(&gdev->list, &gpio_devices);
248                 return 0;
249         }
250
251         next = list_entry(gpio_devices.next, struct gpio_device, list);
252         if (gdev->base + gdev->ngpio <= next->base) {
253                 /* add before first entry */
254                 list_add(&gdev->list, &gpio_devices);
255                 return 0;
256         }
257
258         prev = list_entry(gpio_devices.prev, struct gpio_device, list);
259         if (prev->base + prev->ngpio <= gdev->base) {
260                 /* add behind last entry */
261                 list_add_tail(&gdev->list, &gpio_devices);
262                 return 0;
263         }
264
265         list_for_each_entry_safe(prev, next, &gpio_devices, list) {
266                 /* at the end of the list */
267                 if (&next->list == &gpio_devices)
268                         break;
269
270                 /* add between prev and next */
271                 if (prev->base + prev->ngpio <= gdev->base
272                                 && gdev->base + gdev->ngpio <= next->base) {
273                         list_add(&gdev->list, &prev->list);
274                         return 0;
275                 }
276         }
277
278         dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
279         return -EBUSY;
280 }
281
282 /*
283  * Convert a GPIO name to its descriptor
284  */
285 static struct gpio_desc *gpio_name_to_desc(const char * const name)
286 {
287         struct gpio_device *gdev;
288         unsigned long flags;
289
290         spin_lock_irqsave(&gpio_lock, flags);
291
292         list_for_each_entry(gdev, &gpio_devices, list) {
293                 int i;
294
295                 for (i = 0; i != gdev->ngpio; ++i) {
296                         struct gpio_desc *desc = &gdev->descs[i];
297
298                         if (!desc->name || !name)
299                                 continue;
300
301                         if (!strcmp(desc->name, name)) {
302                                 spin_unlock_irqrestore(&gpio_lock, flags);
303                                 return desc;
304                         }
305                 }
306         }
307
308         spin_unlock_irqrestore(&gpio_lock, flags);
309
310         return NULL;
311 }
312
313 /*
314  * Takes the names from gc->names and checks if they are all unique. If they
315  * are, they are assigned to their gpio descriptors.
316  *
317  * Warning if one of the names is already used for a different GPIO.
318  */
319 static int gpiochip_set_desc_names(struct gpio_chip *gc)
320 {
321         struct gpio_device *gdev = gc->gpiodev;
322         int i;
323
324         if (!gc->names)
325                 return 0;
326
327         /* First check all names if they are unique */
328         for (i = 0; i != gc->ngpio; ++i) {
329                 struct gpio_desc *gpio;
330
331                 gpio = gpio_name_to_desc(gc->names[i]);
332                 if (gpio)
333                         dev_warn(&gdev->dev,
334                                  "Detected name collision for GPIO name '%s'\n",
335                                  gc->names[i]);
336         }
337
338         /* Then add all names to the GPIO descriptors */
339         for (i = 0; i != gc->ngpio; ++i)
340                 gdev->descs[i].name = gc->names[i];
341
342         return 0;
343 }
344
345 /*
346  * GPIO line handle management
347  */
348
349 /**
350  * struct linehandle_state - contains the state of a userspace handle
351  * @gdev: the GPIO device the handle pertains to
352  * @label: consumer label used to tag descriptors
353  * @descs: the GPIO descriptors held by this handle
354  * @numdescs: the number of descriptors held in the descs array
355  */
356 struct linehandle_state {
357         struct gpio_device *gdev;
358         const char *label;
359         struct gpio_desc *descs[GPIOHANDLES_MAX];
360         u32 numdescs;
361 };
362
363 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
364         (GPIOHANDLE_REQUEST_INPUT | \
365         GPIOHANDLE_REQUEST_OUTPUT | \
366         GPIOHANDLE_REQUEST_ACTIVE_LOW | \
367         GPIOHANDLE_REQUEST_OPEN_DRAIN | \
368         GPIOHANDLE_REQUEST_OPEN_SOURCE)
369
370 static long linehandle_ioctl(struct file *filep, unsigned int cmd,
371                              unsigned long arg)
372 {
373         struct linehandle_state *lh = filep->private_data;
374         void __user *ip = (void __user *)arg;
375         struct gpiohandle_data ghd;
376         int i;
377
378         if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
379                 int val;
380
381                 memset(&ghd, 0, sizeof(ghd));
382
383                 /* TODO: check if descriptors are really input */
384                 for (i = 0; i < lh->numdescs; i++) {
385                         val = gpiod_get_value_cansleep(lh->descs[i]);
386                         if (val < 0)
387                                 return val;
388                         ghd.values[i] = val;
389                 }
390
391                 if (copy_to_user(ip, &ghd, sizeof(ghd)))
392                         return -EFAULT;
393
394                 return 0;
395         } else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
396                 int vals[GPIOHANDLES_MAX];
397
398                 /* TODO: check if descriptors are really output */
399                 if (copy_from_user(&ghd, ip, sizeof(ghd)))
400                         return -EFAULT;
401
402                 /* Clamp all values to [0,1] */
403                 for (i = 0; i < lh->numdescs; i++)
404                         vals[i] = !!ghd.values[i];
405
406                 /* Reuse the array setting function */
407                 gpiod_set_array_value_complex(false,
408                                               true,
409                                               lh->numdescs,
410                                               lh->descs,
411                                               vals);
412                 return 0;
413         }
414         return -EINVAL;
415 }
416
417 #ifdef CONFIG_COMPAT
418 static long linehandle_ioctl_compat(struct file *filep, unsigned int cmd,
419                              unsigned long arg)
420 {
421         return linehandle_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
422 }
423 #endif
424
425 static int linehandle_release(struct inode *inode, struct file *filep)
426 {
427         struct linehandle_state *lh = filep->private_data;
428         struct gpio_device *gdev = lh->gdev;
429         int i;
430
431         for (i = 0; i < lh->numdescs; i++)
432                 gpiod_free(lh->descs[i]);
433         kfree(lh->label);
434         kfree(lh);
435         put_device(&gdev->dev);
436         return 0;
437 }
438
439 static const struct file_operations linehandle_fileops = {
440         .release = linehandle_release,
441         .owner = THIS_MODULE,
442         .llseek = noop_llseek,
443         .unlocked_ioctl = linehandle_ioctl,
444 #ifdef CONFIG_COMPAT
445         .compat_ioctl = linehandle_ioctl_compat,
446 #endif
447 };
448
449 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
450 {
451         struct gpiohandle_request handlereq;
452         struct linehandle_state *lh;
453         struct file *file;
454         int fd, i, count = 0, ret;
455         u32 lflags;
456
457         if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
458                 return -EFAULT;
459         if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
460                 return -EINVAL;
461
462         lflags = handlereq.flags;
463
464         /*
465          * Do not allow both INPUT & OUTPUT flags to be set as they are
466          * contradictory.
467          */
468         if ((lflags & GPIOHANDLE_REQUEST_INPUT) &&
469             (lflags & GPIOHANDLE_REQUEST_OUTPUT))
470                 return -EINVAL;
471
472         lh = kzalloc(sizeof(*lh), GFP_KERNEL);
473         if (!lh)
474                 return -ENOMEM;
475         lh->gdev = gdev;
476         get_device(&gdev->dev);
477
478         /* Make sure this is terminated */
479         handlereq.consumer_label[sizeof(handlereq.consumer_label)-1] = '\0';
480         if (strlen(handlereq.consumer_label)) {
481                 lh->label = kstrdup(handlereq.consumer_label,
482                                     GFP_KERNEL);
483                 if (!lh->label) {
484                         ret = -ENOMEM;
485                         goto out_free_lh;
486                 }
487         }
488
489         /* Request each GPIO */
490         for (i = 0; i < handlereq.lines; i++) {
491                 u32 offset = handlereq.lineoffsets[i];
492                 struct gpio_desc *desc;
493
494                 if (offset >= gdev->ngpio) {
495                         ret = -EINVAL;
496                         goto out_free_descs;
497                 }
498
499                 /* Return an error if a unknown flag is set */
500                 if (lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) {
501                         ret = -EINVAL;
502                         goto out_free_descs;
503                 }
504
505                 desc = &gdev->descs[offset];
506                 ret = gpiod_request(desc, lh->label);
507                 if (ret)
508                         goto out_free_descs;
509                 lh->descs[i] = desc;
510                 count = i + 1;
511
512                 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
513                         set_bit(FLAG_ACTIVE_LOW, &desc->flags);
514                 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
515                         set_bit(FLAG_OPEN_DRAIN, &desc->flags);
516                 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
517                         set_bit(FLAG_OPEN_SOURCE, &desc->flags);
518
519                 /*
520                  * Lines have to be requested explicitly for input
521                  * or output, else the line will be treated "as is".
522                  */
523                 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
524                         int val = !!handlereq.default_values[i];
525
526                         ret = gpiod_direction_output(desc, val);
527                         if (ret)
528                                 goto out_free_descs;
529                 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
530                         ret = gpiod_direction_input(desc);
531                         if (ret)
532                                 goto out_free_descs;
533                 }
534                 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
535                         offset);
536         }
537         /* Let i point at the last handle */
538         i--;
539         lh->numdescs = handlereq.lines;
540
541         fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
542         if (fd < 0) {
543                 ret = fd;
544                 goto out_free_descs;
545         }
546
547         file = anon_inode_getfile("gpio-linehandle",
548                                   &linehandle_fileops,
549                                   lh,
550                                   O_RDONLY | O_CLOEXEC);
551         if (IS_ERR(file)) {
552                 ret = PTR_ERR(file);
553                 goto out_put_unused_fd;
554         }
555
556         handlereq.fd = fd;
557         if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
558                 /*
559                  * fput() will trigger the release() callback, so do not go onto
560                  * the regular error cleanup path here.
561                  */
562                 fput(file);
563                 put_unused_fd(fd);
564                 return -EFAULT;
565         }
566
567         fd_install(fd, file);
568
569         dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
570                 lh->numdescs);
571
572         return 0;
573
574 out_put_unused_fd:
575         put_unused_fd(fd);
576 out_free_descs:
577         for (i = 0; i < count; i++)
578                 gpiod_free(lh->descs[i]);
579         kfree(lh->label);
580 out_free_lh:
581         kfree(lh);
582         put_device(&gdev->dev);
583         return ret;
584 }
585
586 /*
587  * GPIO line event management
588  */
589
590 /**
591  * struct lineevent_state - contains the state of a userspace event
592  * @gdev: the GPIO device the event pertains to
593  * @label: consumer label used to tag descriptors
594  * @desc: the GPIO descriptor held by this event
595  * @eflags: the event flags this line was requested with
596  * @irq: the interrupt that trigger in response to events on this GPIO
597  * @wait: wait queue that handles blocking reads of events
598  * @events: KFIFO for the GPIO events
599  * @read_lock: mutex lock to protect reads from colliding with adding
600  * new events to the FIFO
601  */
602 struct lineevent_state {
603         struct gpio_device *gdev;
604         const char *label;
605         struct gpio_desc *desc;
606         u32 eflags;
607         int irq;
608         wait_queue_head_t wait;
609         DECLARE_KFIFO(events, struct gpioevent_data, 16);
610         struct mutex read_lock;
611 };
612
613 #define GPIOEVENT_REQUEST_VALID_FLAGS \
614         (GPIOEVENT_REQUEST_RISING_EDGE | \
615         GPIOEVENT_REQUEST_FALLING_EDGE)
616
617 static unsigned int lineevent_poll(struct file *filep,
618                                    struct poll_table_struct *wait)
619 {
620         struct lineevent_state *le = filep->private_data;
621         unsigned int events = 0;
622
623         poll_wait(filep, &le->wait, wait);
624
625         if (!kfifo_is_empty(&le->events))
626                 events = POLLIN | POLLRDNORM;
627
628         return events;
629 }
630
631
632 static ssize_t lineevent_read(struct file *filep,
633                               char __user *buf,
634                               size_t count,
635                               loff_t *f_ps)
636 {
637         struct lineevent_state *le = filep->private_data;
638         unsigned int copied;
639         int ret;
640
641         if (count < sizeof(struct gpioevent_data))
642                 return -EINVAL;
643
644         do {
645                 if (kfifo_is_empty(&le->events)) {
646                         if (filep->f_flags & O_NONBLOCK)
647                                 return -EAGAIN;
648
649                         ret = wait_event_interruptible(le->wait,
650                                         !kfifo_is_empty(&le->events));
651                         if (ret)
652                                 return ret;
653                 }
654
655                 if (mutex_lock_interruptible(&le->read_lock))
656                         return -ERESTARTSYS;
657                 ret = kfifo_to_user(&le->events, buf, count, &copied);
658                 mutex_unlock(&le->read_lock);
659
660                 if (ret)
661                         return ret;
662
663                 /*
664                  * If we couldn't read anything from the fifo (a different
665                  * thread might have been faster) we either return -EAGAIN if
666                  * the file descriptor is non-blocking, otherwise we go back to
667                  * sleep and wait for more data to arrive.
668                  */
669                 if (copied == 0 && (filep->f_flags & O_NONBLOCK))
670                         return -EAGAIN;
671
672         } while (copied == 0);
673
674         return copied;
675 }
676
677 static int lineevent_release(struct inode *inode, struct file *filep)
678 {
679         struct lineevent_state *le = filep->private_data;
680         struct gpio_device *gdev = le->gdev;
681
682         free_irq(le->irq, le);
683         gpiod_free(le->desc);
684         kfree(le->label);
685         kfree(le);
686         put_device(&gdev->dev);
687         return 0;
688 }
689
690 static long lineevent_ioctl(struct file *filep, unsigned int cmd,
691                             unsigned long arg)
692 {
693         struct lineevent_state *le = filep->private_data;
694         void __user *ip = (void __user *)arg;
695         struct gpiohandle_data ghd;
696
697         /*
698          * We can get the value for an event line but not set it,
699          * because it is input by definition.
700          */
701         if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
702                 int val;
703
704                 memset(&ghd, 0, sizeof(ghd));
705
706                 val = gpiod_get_value_cansleep(le->desc);
707                 if (val < 0)
708                         return val;
709                 ghd.values[0] = val;
710
711                 if (copy_to_user(ip, &ghd, sizeof(ghd)))
712                         return -EFAULT;
713
714                 return 0;
715         }
716         return -EINVAL;
717 }
718
719 #ifdef CONFIG_COMPAT
720 static long lineevent_ioctl_compat(struct file *filep, unsigned int cmd,
721                                    unsigned long arg)
722 {
723         return lineevent_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
724 }
725 #endif
726
727 static const struct file_operations lineevent_fileops = {
728         .release = lineevent_release,
729         .read = lineevent_read,
730         .poll = lineevent_poll,
731         .owner = THIS_MODULE,
732         .llseek = noop_llseek,
733         .unlocked_ioctl = lineevent_ioctl,
734 #ifdef CONFIG_COMPAT
735         .compat_ioctl = lineevent_ioctl_compat,
736 #endif
737 };
738
739 static irqreturn_t lineevent_irq_thread(int irq, void *p)
740 {
741         struct lineevent_state *le = p;
742         struct gpioevent_data ge;
743         int ret, level;
744
745         /* Do not leak kernel stack to userspace */
746         memset(&ge, 0, sizeof(ge));
747
748         ge.timestamp = ktime_get_real_ns();
749         level = gpiod_get_value_cansleep(le->desc);
750
751         if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
752             && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
753                 if (level)
754                         /* Emit low-to-high event */
755                         ge.id = GPIOEVENT_EVENT_RISING_EDGE;
756                 else
757                         /* Emit high-to-low event */
758                         ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
759         } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE && level) {
760                 /* Emit low-to-high event */
761                 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
762         } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE && !level) {
763                 /* Emit high-to-low event */
764                 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
765         } else {
766                 return IRQ_NONE;
767         }
768
769         ret = kfifo_put(&le->events, ge);
770         if (ret != 0)
771                 wake_up_poll(&le->wait, POLLIN);
772
773         return IRQ_HANDLED;
774 }
775
776 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
777 {
778         struct gpioevent_request eventreq;
779         struct lineevent_state *le;
780         struct gpio_desc *desc;
781         struct file *file;
782         u32 offset;
783         u32 lflags;
784         u32 eflags;
785         int fd;
786         int ret;
787         int irqflags = 0;
788
789         if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
790                 return -EFAULT;
791
792         le = kzalloc(sizeof(*le), GFP_KERNEL);
793         if (!le)
794                 return -ENOMEM;
795         le->gdev = gdev;
796         get_device(&gdev->dev);
797
798         /* Make sure this is terminated */
799         eventreq.consumer_label[sizeof(eventreq.consumer_label)-1] = '\0';
800         if (strlen(eventreq.consumer_label)) {
801                 le->label = kstrdup(eventreq.consumer_label,
802                                     GFP_KERNEL);
803                 if (!le->label) {
804                         ret = -ENOMEM;
805                         goto out_free_le;
806                 }
807         }
808
809         offset = eventreq.lineoffset;
810         lflags = eventreq.handleflags;
811         eflags = eventreq.eventflags;
812
813         if (offset >= gdev->ngpio) {
814                 ret = -EINVAL;
815                 goto out_free_label;
816         }
817
818         /* Return an error if a unknown flag is set */
819         if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
820             (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS)) {
821                 ret = -EINVAL;
822                 goto out_free_label;
823         }
824
825         /* This is just wrong: we don't look for events on output lines */
826         if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
827             (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
828             (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)) {
829                 ret = -EINVAL;
830                 goto out_free_label;
831         }
832
833         desc = &gdev->descs[offset];
834         ret = gpiod_request(desc, le->label);
835         if (ret)
836                 goto out_free_label;
837         le->desc = desc;
838         le->eflags = eflags;
839
840         if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
841                 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
842
843         ret = gpiod_direction_input(desc);
844         if (ret)
845                 goto out_free_desc;
846
847         le->irq = gpiod_to_irq(desc);
848         if (le->irq <= 0) {
849                 ret = -ENODEV;
850                 goto out_free_desc;
851         }
852
853         if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
854                 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
855                         IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
856         if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
857                 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
858                         IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
859         irqflags |= IRQF_ONESHOT;
860         irqflags |= IRQF_SHARED;
861
862         INIT_KFIFO(le->events);
863         init_waitqueue_head(&le->wait);
864         mutex_init(&le->read_lock);
865
866         /* Request a thread to read the events */
867         ret = request_threaded_irq(le->irq,
868                         NULL,
869                         lineevent_irq_thread,
870                         irqflags,
871                         le->label,
872                         le);
873         if (ret)
874                 goto out_free_desc;
875
876         fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
877         if (fd < 0) {
878                 ret = fd;
879                 goto out_free_irq;
880         }
881
882         file = anon_inode_getfile("gpio-event",
883                                   &lineevent_fileops,
884                                   le,
885                                   O_RDONLY | O_CLOEXEC);
886         if (IS_ERR(file)) {
887                 ret = PTR_ERR(file);
888                 goto out_put_unused_fd;
889         }
890
891         eventreq.fd = fd;
892         if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
893                 /*
894                  * fput() will trigger the release() callback, so do not go onto
895                  * the regular error cleanup path here.
896                  */
897                 fput(file);
898                 put_unused_fd(fd);
899                 return -EFAULT;
900         }
901
902         fd_install(fd, file);
903
904         return 0;
905
906 out_put_unused_fd:
907         put_unused_fd(fd);
908 out_free_irq:
909         free_irq(le->irq, le);
910 out_free_desc:
911         gpiod_free(le->desc);
912 out_free_label:
913         kfree(le->label);
914 out_free_le:
915         kfree(le);
916         put_device(&gdev->dev);
917         return ret;
918 }
919
920 /*
921  * gpio_ioctl() - ioctl handler for the GPIO chardev
922  */
923 static long gpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
924 {
925         struct gpio_device *gdev = filp->private_data;
926         struct gpio_chip *chip = gdev->chip;
927         void __user *ip = (void __user *)arg;
928
929         /* We fail any subsequent ioctl():s when the chip is gone */
930         if (!chip)
931                 return -ENODEV;
932
933         /* Fill in the struct and pass to userspace */
934         if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
935                 struct gpiochip_info chipinfo;
936
937                 memset(&chipinfo, 0, sizeof(chipinfo));
938
939                 strncpy(chipinfo.name, dev_name(&gdev->dev),
940                         sizeof(chipinfo.name));
941                 chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
942                 strncpy(chipinfo.label, gdev->label,
943                         sizeof(chipinfo.label));
944                 chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
945                 chipinfo.lines = gdev->ngpio;
946                 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
947                         return -EFAULT;
948                 return 0;
949         } else if (cmd == GPIO_GET_LINEINFO_IOCTL) {
950                 struct gpioline_info lineinfo;
951                 struct gpio_desc *desc;
952
953                 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
954                         return -EFAULT;
955                 if (lineinfo.line_offset >= gdev->ngpio)
956                         return -EINVAL;
957
958                 desc = &gdev->descs[lineinfo.line_offset];
959                 if (desc->name) {
960                         strncpy(lineinfo.name, desc->name,
961                                 sizeof(lineinfo.name));
962                         lineinfo.name[sizeof(lineinfo.name)-1] = '\0';
963                 } else {
964                         lineinfo.name[0] = '\0';
965                 }
966                 if (desc->label) {
967                         strncpy(lineinfo.consumer, desc->label,
968                                 sizeof(lineinfo.consumer));
969                         lineinfo.consumer[sizeof(lineinfo.consumer)-1] = '\0';
970                 } else {
971                         lineinfo.consumer[0] = '\0';
972                 }
973
974                 /*
975                  * Userspace only need to know that the kernel is using
976                  * this GPIO so it can't use it.
977                  */
978                 lineinfo.flags = 0;
979                 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
980                     test_bit(FLAG_IS_HOGGED, &desc->flags) ||
981                     test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
982                     test_bit(FLAG_EXPORT, &desc->flags) ||
983                     test_bit(FLAG_SYSFS, &desc->flags))
984                         lineinfo.flags |= GPIOLINE_FLAG_KERNEL;
985                 if (test_bit(FLAG_IS_OUT, &desc->flags))
986                         lineinfo.flags |= GPIOLINE_FLAG_IS_OUT;
987                 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
988                         lineinfo.flags |= GPIOLINE_FLAG_ACTIVE_LOW;
989                 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
990                         lineinfo.flags |= (GPIOLINE_FLAG_OPEN_DRAIN |
991                                            GPIOLINE_FLAG_IS_OUT);
992                 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
993                         lineinfo.flags |= (GPIOLINE_FLAG_OPEN_SOURCE |
994                                            GPIOLINE_FLAG_IS_OUT);
995
996                 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
997                         return -EFAULT;
998                 return 0;
999         } else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
1000                 return linehandle_create(gdev, ip);
1001         } else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
1002                 return lineevent_create(gdev, ip);
1003         }
1004         return -EINVAL;
1005 }
1006
1007 #ifdef CONFIG_COMPAT
1008 static long gpio_ioctl_compat(struct file *filp, unsigned int cmd,
1009                               unsigned long arg)
1010 {
1011         return gpio_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
1012 }
1013 #endif
1014
1015 /**
1016  * gpio_chrdev_open() - open the chardev for ioctl operations
1017  * @inode: inode for this chardev
1018  * @filp: file struct for storing private data
1019  * Returns 0 on success
1020  */
1021 static int gpio_chrdev_open(struct inode *inode, struct file *filp)
1022 {
1023         struct gpio_device *gdev = container_of(inode->i_cdev,
1024                                               struct gpio_device, chrdev);
1025
1026         /* Fail on open if the backing gpiochip is gone */
1027         if (!gdev->chip)
1028                 return -ENODEV;
1029         get_device(&gdev->dev);
1030         filp->private_data = gdev;
1031
1032         return nonseekable_open(inode, filp);
1033 }
1034
1035 /**
1036  * gpio_chrdev_release() - close chardev after ioctl operations
1037  * @inode: inode for this chardev
1038  * @filp: file struct for storing private data
1039  * Returns 0 on success
1040  */
1041 static int gpio_chrdev_release(struct inode *inode, struct file *filp)
1042 {
1043         struct gpio_device *gdev = container_of(inode->i_cdev,
1044                                               struct gpio_device, chrdev);
1045
1046         put_device(&gdev->dev);
1047         return 0;
1048 }
1049
1050
1051 static const struct file_operations gpio_fileops = {
1052         .release = gpio_chrdev_release,
1053         .open = gpio_chrdev_open,
1054         .owner = THIS_MODULE,
1055         .llseek = no_llseek,
1056         .unlocked_ioctl = gpio_ioctl,
1057 #ifdef CONFIG_COMPAT
1058         .compat_ioctl = gpio_ioctl_compat,
1059 #endif
1060 };
1061
1062 static void gpiodevice_release(struct device *dev)
1063 {
1064         struct gpio_device *gdev = dev_get_drvdata(dev);
1065
1066         list_del(&gdev->list);
1067         ida_simple_remove(&gpio_ida, gdev->id);
1068         kfree(gdev->label);
1069         kfree(gdev->descs);
1070         kfree(gdev);
1071 }
1072
1073 static int gpiochip_setup_dev(struct gpio_device *gdev)
1074 {
1075         int status;
1076
1077         cdev_init(&gdev->chrdev, &gpio_fileops);
1078         gdev->chrdev.owner = THIS_MODULE;
1079         gdev->dev.devt = MKDEV(MAJOR(gpio_devt), gdev->id);
1080
1081         status = cdev_device_add(&gdev->chrdev, &gdev->dev);
1082         if (status)
1083                 return status;
1084
1085         chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
1086                  MAJOR(gpio_devt), gdev->id);
1087
1088         status = gpiochip_sysfs_register(gdev);
1089         if (status)
1090                 goto err_remove_device;
1091
1092         /* From this point, the .release() function cleans up gpio_device */
1093         gdev->dev.release = gpiodevice_release;
1094         pr_debug("%s: registered GPIOs %d to %d on device: %s (%s)\n",
1095                  __func__, gdev->base, gdev->base + gdev->ngpio - 1,
1096                  dev_name(&gdev->dev), gdev->chip->label ? : "generic");
1097
1098         return 0;
1099
1100 err_remove_device:
1101         cdev_device_del(&gdev->chrdev, &gdev->dev);
1102         return status;
1103 }
1104
1105 static void gpiochip_setup_devs(void)
1106 {
1107         struct gpio_device *gdev;
1108         int err;
1109
1110         list_for_each_entry(gdev, &gpio_devices, list) {
1111                 err = gpiochip_setup_dev(gdev);
1112                 if (err)
1113                         pr_err("%s: Failed to initialize gpio device (%d)\n",
1114                                dev_name(&gdev->dev), err);
1115         }
1116 }
1117
1118 /**
1119  * gpiochip_add_data() - register a gpio_chip
1120  * @chip: the chip to register, with chip->base initialized
1121  * @data: driver-private data associated with this chip
1122  *
1123  * Context: potentially before irqs will work
1124  *
1125  * When gpiochip_add_data() is called very early during boot, so that GPIOs
1126  * can be freely used, the chip->parent device must be registered before
1127  * the gpio framework's arch_initcall().  Otherwise sysfs initialization
1128  * for GPIOs will fail rudely.
1129  *
1130  * gpiochip_add_data() must only be called after gpiolib initialization,
1131  * ie after core_initcall().
1132  *
1133  * If chip->base is negative, this requests dynamic assignment of
1134  * a range of valid GPIOs.
1135  *
1136  * Returns:
1137  * A negative errno if the chip can't be registered, such as because the
1138  * chip->base is invalid or already associated with a different chip.
1139  * Otherwise it returns zero as a success code.
1140  */
1141 int gpiochip_add_data(struct gpio_chip *chip, void *data)
1142 {
1143         unsigned long   flags;
1144         int             status = 0;
1145         unsigned        i;
1146         int             base = chip->base;
1147         struct gpio_device *gdev;
1148
1149         /*
1150          * First: allocate and populate the internal stat container, and
1151          * set up the struct device.
1152          */
1153         gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1154         if (!gdev)
1155                 return -ENOMEM;
1156         gdev->dev.bus = &gpio_bus_type;
1157         gdev->chip = chip;
1158         chip->gpiodev = gdev;
1159         if (chip->parent) {
1160                 gdev->dev.parent = chip->parent;
1161                 gdev->dev.of_node = chip->parent->of_node;
1162         }
1163
1164 #ifdef CONFIG_OF_GPIO
1165         /* If the gpiochip has an assigned OF node this takes precedence */
1166         if (chip->of_node)
1167                 gdev->dev.of_node = chip->of_node;
1168 #endif
1169
1170         gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
1171         if (gdev->id < 0) {
1172                 status = gdev->id;
1173                 goto err_free_gdev;
1174         }
1175         dev_set_name(&gdev->dev, "gpiochip%d", gdev->id);
1176         device_initialize(&gdev->dev);
1177         dev_set_drvdata(&gdev->dev, gdev);
1178         if (chip->parent && chip->parent->driver)
1179                 gdev->owner = chip->parent->driver->owner;
1180         else if (chip->owner)
1181                 /* TODO: remove chip->owner */
1182                 gdev->owner = chip->owner;
1183         else
1184                 gdev->owner = THIS_MODULE;
1185
1186         gdev->descs = kcalloc(chip->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
1187         if (!gdev->descs) {
1188                 status = -ENOMEM;
1189                 goto err_free_ida;
1190         }
1191
1192         if (chip->ngpio == 0) {
1193                 chip_err(chip, "tried to insert a GPIO chip with zero lines\n");
1194                 status = -EINVAL;
1195                 goto err_free_descs;
1196         }
1197
1198         if (chip->label)
1199                 gdev->label = kstrdup(chip->label, GFP_KERNEL);
1200         else
1201                 gdev->label = kstrdup("unknown", GFP_KERNEL);
1202         if (!gdev->label) {
1203                 status = -ENOMEM;
1204                 goto err_free_descs;
1205         }
1206
1207         gdev->ngpio = chip->ngpio;
1208         gdev->data = data;
1209
1210         spin_lock_irqsave(&gpio_lock, flags);
1211
1212         /*
1213          * TODO: this allocates a Linux GPIO number base in the global
1214          * GPIO numberspace for this chip. In the long run we want to
1215          * get *rid* of this numberspace and use only descriptors, but
1216          * it may be a pipe dream. It will not happen before we get rid
1217          * of the sysfs interface anyways.
1218          */
1219         if (base < 0) {
1220                 base = gpiochip_find_base(chip->ngpio);
1221                 if (base < 0) {
1222                         status = base;
1223                         spin_unlock_irqrestore(&gpio_lock, flags);
1224                         goto err_free_label;
1225                 }
1226                 /*
1227                  * TODO: it should not be necessary to reflect the assigned
1228                  * base outside of the GPIO subsystem. Go over drivers and
1229                  * see if anyone makes use of this, else drop this and assign
1230                  * a poison instead.
1231                  */
1232                 chip->base = base;
1233         }
1234         gdev->base = base;
1235
1236         status = gpiodev_add_to_list(gdev);
1237         if (status) {
1238                 spin_unlock_irqrestore(&gpio_lock, flags);
1239                 goto err_free_label;
1240         }
1241
1242         spin_unlock_irqrestore(&gpio_lock, flags);
1243
1244         for (i = 0; i < chip->ngpio; i++) {
1245                 struct gpio_desc *desc = &gdev->descs[i];
1246
1247                 desc->gdev = gdev;
1248
1249                 /* REVISIT: most hardware initializes GPIOs as inputs (often
1250                  * with pullups enabled) so power usage is minimized. Linux
1251                  * code should set the gpio direction first thing; but until
1252                  * it does, and in case chip->get_direction is not set, we may
1253                  * expose the wrong direction in sysfs.
1254                  */
1255                 desc->flags = !chip->direction_input ? (1 << FLAG_IS_OUT) : 0;
1256         }
1257
1258 #ifdef CONFIG_PINCTRL
1259         INIT_LIST_HEAD(&gdev->pin_ranges);
1260 #endif
1261
1262         status = gpiochip_set_desc_names(chip);
1263         if (status)
1264                 goto err_remove_from_list;
1265
1266         status = gpiochip_irqchip_init_valid_mask(chip);
1267         if (status)
1268                 goto err_remove_from_list;
1269
1270         status = of_gpiochip_add(chip);
1271         if (status)
1272                 goto err_remove_chip;
1273
1274         acpi_gpiochip_add(chip);
1275
1276         /*
1277          * By first adding the chardev, and then adding the device,
1278          * we get a device node entry in sysfs under
1279          * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1280          * coldplug of device nodes and other udev business.
1281          * We can do this only if gpiolib has been initialized.
1282          * Otherwise, defer until later.
1283          */
1284         if (gpiolib_initialized) {
1285                 status = gpiochip_setup_dev(gdev);
1286                 if (status)
1287                         goto err_remove_chip;
1288         }
1289         return 0;
1290
1291 err_remove_chip:
1292         acpi_gpiochip_remove(chip);
1293         gpiochip_free_hogs(chip);
1294         of_gpiochip_remove(chip);
1295         gpiochip_irqchip_free_valid_mask(chip);
1296 err_remove_from_list:
1297         spin_lock_irqsave(&gpio_lock, flags);
1298         list_del(&gdev->list);
1299         spin_unlock_irqrestore(&gpio_lock, flags);
1300 err_free_label:
1301         kfree(gdev->label);
1302 err_free_descs:
1303         kfree(gdev->descs);
1304 err_free_ida:
1305         ida_simple_remove(&gpio_ida, gdev->id);
1306 err_free_gdev:
1307         /* failures here can mean systems won't boot... */
1308         pr_err("%s: GPIOs %d..%d (%s) failed to register\n", __func__,
1309                gdev->base, gdev->base + gdev->ngpio - 1,
1310                chip->label ? : "generic");
1311         kfree(gdev);
1312         return status;
1313 }
1314 EXPORT_SYMBOL_GPL(gpiochip_add_data);
1315
1316 /**
1317  * gpiochip_get_data() - get per-subdriver data for the chip
1318  * @chip: GPIO chip
1319  *
1320  * Returns:
1321  * The per-subdriver data for the chip.
1322  */
1323 void *gpiochip_get_data(struct gpio_chip *chip)
1324 {
1325         return chip->gpiodev->data;
1326 }
1327 EXPORT_SYMBOL_GPL(gpiochip_get_data);
1328
1329 /**
1330  * gpiochip_remove() - unregister a gpio_chip
1331  * @chip: the chip to unregister
1332  *
1333  * A gpio_chip with any GPIOs still requested may not be removed.
1334  */
1335 void gpiochip_remove(struct gpio_chip *chip)
1336 {
1337         struct gpio_device *gdev = chip->gpiodev;
1338         struct gpio_desc *desc;
1339         unsigned long   flags;
1340         unsigned        i;
1341         bool            requested = false;
1342
1343         /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1344         gpiochip_sysfs_unregister(gdev);
1345         gpiochip_free_hogs(chip);
1346         /* Numb the device, cancelling all outstanding operations */
1347         gdev->chip = NULL;
1348         gpiochip_irqchip_remove(chip);
1349         acpi_gpiochip_remove(chip);
1350         gpiochip_remove_pin_ranges(chip);
1351         of_gpiochip_remove(chip);
1352         /*
1353          * We accept no more calls into the driver from this point, so
1354          * NULL the driver data pointer
1355          */
1356         gdev->data = NULL;
1357
1358         spin_lock_irqsave(&gpio_lock, flags);
1359         for (i = 0; i < gdev->ngpio; i++) {
1360                 desc = &gdev->descs[i];
1361                 if (test_bit(FLAG_REQUESTED, &desc->flags))
1362                         requested = true;
1363         }
1364         spin_unlock_irqrestore(&gpio_lock, flags);
1365
1366         if (requested)
1367                 dev_crit(&gdev->dev,
1368                          "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
1369
1370         /*
1371          * The gpiochip side puts its use of the device to rest here:
1372          * if there are no userspace clients, the chardev and device will
1373          * be removed, else it will be dangling until the last user is
1374          * gone.
1375          */
1376         cdev_device_del(&gdev->chrdev, &gdev->dev);
1377         put_device(&gdev->dev);
1378 }
1379 EXPORT_SYMBOL_GPL(gpiochip_remove);
1380
1381 static void devm_gpio_chip_release(struct device *dev, void *res)
1382 {
1383         struct gpio_chip *chip = *(struct gpio_chip **)res;
1384
1385         gpiochip_remove(chip);
1386 }
1387
1388 static int devm_gpio_chip_match(struct device *dev, void *res, void *data)
1389
1390 {
1391         struct gpio_chip **r = res;
1392
1393         if (!r || !*r) {
1394                 WARN_ON(!r || !*r);
1395                 return 0;
1396         }
1397
1398         return *r == data;
1399 }
1400
1401 /**
1402  * devm_gpiochip_add_data() - Resource manager piochip_add_data()
1403  * @dev: the device pointer on which irq_chip belongs to.
1404  * @chip: the chip to register, with chip->base initialized
1405  * @data: driver-private data associated with this chip
1406  *
1407  * Context: potentially before irqs will work
1408  *
1409  * The gpio chip automatically be released when the device is unbound.
1410  *
1411  * Returns:
1412  * A negative errno if the chip can't be registered, such as because the
1413  * chip->base is invalid or already associated with a different chip.
1414  * Otherwise it returns zero as a success code.
1415  */
1416 int devm_gpiochip_add_data(struct device *dev, struct gpio_chip *chip,
1417                            void *data)
1418 {
1419         struct gpio_chip **ptr;
1420         int ret;
1421
1422         ptr = devres_alloc(devm_gpio_chip_release, sizeof(*ptr),
1423                              GFP_KERNEL);
1424         if (!ptr)
1425                 return -ENOMEM;
1426
1427         ret = gpiochip_add_data(chip, data);
1428         if (ret < 0) {
1429                 devres_free(ptr);
1430                 return ret;
1431         }
1432
1433         *ptr = chip;
1434         devres_add(dev, ptr);
1435
1436         return 0;
1437 }
1438 EXPORT_SYMBOL_GPL(devm_gpiochip_add_data);
1439
1440 /**
1441  * devm_gpiochip_remove() - Resource manager of gpiochip_remove()
1442  * @dev: device for which which resource was allocated
1443  * @chip: the chip to remove
1444  *
1445  * A gpio_chip with any GPIOs still requested may not be removed.
1446  */
1447 void devm_gpiochip_remove(struct device *dev, struct gpio_chip *chip)
1448 {
1449         int ret;
1450
1451         ret = devres_release(dev, devm_gpio_chip_release,
1452                              devm_gpio_chip_match, chip);
1453         WARN_ON(ret);
1454 }
1455 EXPORT_SYMBOL_GPL(devm_gpiochip_remove);
1456
1457 /**
1458  * gpiochip_find() - iterator for locating a specific gpio_chip
1459  * @data: data to pass to match function
1460  * @match: Callback function to check gpio_chip
1461  *
1462  * Similar to bus_find_device.  It returns a reference to a gpio_chip as
1463  * determined by a user supplied @match callback.  The callback should return
1464  * 0 if the device doesn't match and non-zero if it does.  If the callback is
1465  * non-zero, this function will return to the caller and not iterate over any
1466  * more gpio_chips.
1467  */
1468 struct gpio_chip *gpiochip_find(void *data,
1469                                 int (*match)(struct gpio_chip *chip,
1470                                              void *data))
1471 {
1472         struct gpio_device *gdev;
1473         struct gpio_chip *chip = NULL;
1474         unsigned long flags;
1475
1476         spin_lock_irqsave(&gpio_lock, flags);
1477         list_for_each_entry(gdev, &gpio_devices, list)
1478                 if (gdev->chip && match(gdev->chip, data)) {
1479                         chip = gdev->chip;
1480                         break;
1481                 }
1482
1483         spin_unlock_irqrestore(&gpio_lock, flags);
1484
1485         return chip;
1486 }
1487 EXPORT_SYMBOL_GPL(gpiochip_find);
1488
1489 static int gpiochip_match_name(struct gpio_chip *chip, void *data)
1490 {
1491         const char *name = data;
1492
1493         return !strcmp(chip->label, name);
1494 }
1495
1496 static struct gpio_chip *find_chip_by_name(const char *name)
1497 {
1498         return gpiochip_find((void *)name, gpiochip_match_name);
1499 }
1500
1501 #ifdef CONFIG_GPIOLIB_IRQCHIP
1502
1503 /*
1504  * The following is irqchip helper code for gpiochips.
1505  */
1506
1507 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
1508 {
1509         if (!gpiochip->irq_need_valid_mask)
1510                 return 0;
1511
1512         gpiochip->irq_valid_mask = kcalloc(BITS_TO_LONGS(gpiochip->ngpio),
1513                                            sizeof(long), GFP_KERNEL);
1514         if (!gpiochip->irq_valid_mask)
1515                 return -ENOMEM;
1516
1517         /* Assume by default all GPIOs are valid */
1518         bitmap_fill(gpiochip->irq_valid_mask, gpiochip->ngpio);
1519
1520         return 0;
1521 }
1522
1523 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1524 {
1525         kfree(gpiochip->irq_valid_mask);
1526         gpiochip->irq_valid_mask = NULL;
1527 }
1528
1529 static bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gpiochip,
1530                                        unsigned int offset)
1531 {
1532         /* No mask means all valid */
1533         if (likely(!gpiochip->irq_valid_mask))
1534                 return true;
1535         return test_bit(offset, gpiochip->irq_valid_mask);
1536 }
1537
1538 /**
1539  * gpiochip_set_cascaded_irqchip() - connects a cascaded irqchip to a gpiochip
1540  * @gpiochip: the gpiochip to set the irqchip chain to
1541  * @irqchip: the irqchip to chain to the gpiochip
1542  * @parent_irq: the irq number corresponding to the parent IRQ for this
1543  * chained irqchip
1544  * @parent_handler: the parent interrupt handler for the accumulated IRQ
1545  * coming out of the gpiochip. If the interrupt is nested rather than
1546  * cascaded, pass NULL in this handler argument
1547  */
1548 static void gpiochip_set_cascaded_irqchip(struct gpio_chip *gpiochip,
1549                                           struct irq_chip *irqchip,
1550                                           unsigned int parent_irq,
1551                                           irq_flow_handler_t parent_handler)
1552 {
1553         unsigned int offset;
1554
1555         if (!gpiochip->irqdomain) {
1556                 chip_err(gpiochip, "called %s before setting up irqchip\n",
1557                          __func__);
1558                 return;
1559         }
1560
1561         if (parent_handler) {
1562                 if (gpiochip->can_sleep) {
1563                         chip_err(gpiochip,
1564                                  "you cannot have chained interrupts on a "
1565                                  "chip that may sleep\n");
1566                         return;
1567                 }
1568                 /*
1569                  * The parent irqchip is already using the chip_data for this
1570                  * irqchip, so our callbacks simply use the handler_data.
1571                  */
1572                 irq_set_chained_handler_and_data(parent_irq, parent_handler,
1573                                                  gpiochip);
1574
1575                 gpiochip->irq_chained_parent = parent_irq;
1576         }
1577
1578         /* Set the parent IRQ for all affected IRQs */
1579         for (offset = 0; offset < gpiochip->ngpio; offset++) {
1580                 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1581                         continue;
1582                 irq_set_parent(irq_find_mapping(gpiochip->irqdomain, offset),
1583                                parent_irq);
1584         }
1585 }
1586
1587 /**
1588  * gpiochip_set_chained_irqchip() - connects a chained irqchip to a gpiochip
1589  * @gpiochip: the gpiochip to set the irqchip chain to
1590  * @irqchip: the irqchip to chain to the gpiochip
1591  * @parent_irq: the irq number corresponding to the parent IRQ for this
1592  * chained irqchip
1593  * @parent_handler: the parent interrupt handler for the accumulated IRQ
1594  * coming out of the gpiochip. If the interrupt is nested rather than
1595  * cascaded, pass NULL in this handler argument
1596  */
1597 void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip,
1598                                   struct irq_chip *irqchip,
1599                                   unsigned int parent_irq,
1600                                   irq_flow_handler_t parent_handler)
1601 {
1602         gpiochip_set_cascaded_irqchip(gpiochip, irqchip, parent_irq,
1603                                       parent_handler);
1604 }
1605 EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip);
1606
1607 /**
1608  * gpiochip_set_nested_irqchip() - connects a nested irqchip to a gpiochip
1609  * @gpiochip: the gpiochip to set the irqchip nested handler to
1610  * @irqchip: the irqchip to nest to the gpiochip
1611  * @parent_irq: the irq number corresponding to the parent IRQ for this
1612  * nested irqchip
1613  */
1614 void gpiochip_set_nested_irqchip(struct gpio_chip *gpiochip,
1615                                  struct irq_chip *irqchip,
1616                                  unsigned int parent_irq)
1617 {
1618         if (!gpiochip->irq_nested) {
1619                 chip_err(gpiochip, "tried to nest a chained gpiochip\n");
1620                 return;
1621         }
1622         gpiochip_set_cascaded_irqchip(gpiochip, irqchip, parent_irq,
1623                                       NULL);
1624 }
1625 EXPORT_SYMBOL_GPL(gpiochip_set_nested_irqchip);
1626
1627 /**
1628  * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
1629  * @d: the irqdomain used by this irqchip
1630  * @irq: the global irq number used by this GPIO irqchip irq
1631  * @hwirq: the local IRQ/GPIO line offset on this gpiochip
1632  *
1633  * This function will set up the mapping for a certain IRQ line on a
1634  * gpiochip by assigning the gpiochip as chip data, and using the irqchip
1635  * stored inside the gpiochip.
1636  */
1637 static int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
1638                             irq_hw_number_t hwirq)
1639 {
1640         struct gpio_chip *chip = d->host_data;
1641
1642         if (!gpiochip_irqchip_irq_valid(chip, hwirq))
1643                 return -ENXIO;
1644
1645         irq_set_chip_data(irq, chip);
1646         /*
1647          * This lock class tells lockdep that GPIO irqs are in a different
1648          * category than their parents, so it won't report false recursion.
1649          */
1650         irq_set_lockdep_class(irq, chip->lock_key);
1651         irq_set_chip_and_handler(irq, chip->irqchip, chip->irq_handler);
1652         /* Chips that use nested thread handlers have them marked */
1653         if (chip->irq_nested)
1654                 irq_set_nested_thread(irq, 1);
1655         irq_set_noprobe(irq);
1656
1657         /*
1658          * No set-up of the hardware will happen if IRQ_TYPE_NONE
1659          * is passed as default type.
1660          */
1661         if (chip->irq_default_type != IRQ_TYPE_NONE)
1662                 irq_set_irq_type(irq, chip->irq_default_type);
1663
1664         return 0;
1665 }
1666
1667 static void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
1668 {
1669         struct gpio_chip *chip = d->host_data;
1670
1671         if (chip->irq_nested)
1672                 irq_set_nested_thread(irq, 0);
1673         irq_set_chip_and_handler(irq, NULL, NULL);
1674         irq_set_chip_data(irq, NULL);
1675 }
1676
1677 static const struct irq_domain_ops gpiochip_domain_ops = {
1678         .map    = gpiochip_irq_map,
1679         .unmap  = gpiochip_irq_unmap,
1680         /* Virtually all GPIO irqchips are twocell:ed */
1681         .xlate  = irq_domain_xlate_twocell,
1682 };
1683
1684 static int gpiochip_irq_reqres(struct irq_data *d)
1685 {
1686         struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1687
1688         if (!try_module_get(chip->gpiodev->owner))
1689                 return -ENODEV;
1690
1691         if (gpiochip_lock_as_irq(chip, d->hwirq)) {
1692                 chip_err(chip,
1693                         "unable to lock HW IRQ %lu for IRQ\n",
1694                         d->hwirq);
1695                 module_put(chip->gpiodev->owner);
1696                 return -EINVAL;
1697         }
1698         return 0;
1699 }
1700
1701 static void gpiochip_irq_relres(struct irq_data *d)
1702 {
1703         struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1704
1705         gpiochip_unlock_as_irq(chip, d->hwirq);
1706         module_put(chip->gpiodev->owner);
1707 }
1708
1709 static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
1710 {
1711         if (!gpiochip_irqchip_irq_valid(chip, offset))
1712                 return -ENXIO;
1713         return irq_create_mapping(chip->irqdomain, offset);
1714 }
1715
1716 /**
1717  * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
1718  * @gpiochip: the gpiochip to remove the irqchip from
1719  *
1720  * This is called only from gpiochip_remove()
1721  */
1722 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
1723 {
1724         unsigned int offset;
1725
1726         acpi_gpiochip_free_interrupts(gpiochip);
1727
1728         if (gpiochip->irq_chained_parent) {
1729                 irq_set_chained_handler(gpiochip->irq_chained_parent, NULL);
1730                 irq_set_handler_data(gpiochip->irq_chained_parent, NULL);
1731         }
1732
1733         /* Remove all IRQ mappings and delete the domain */
1734         if (gpiochip->irqdomain) {
1735                 for (offset = 0; offset < gpiochip->ngpio; offset++) {
1736                         if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1737                                 continue;
1738                         irq_dispose_mapping(
1739                                 irq_find_mapping(gpiochip->irqdomain, offset));
1740                 }
1741                 irq_domain_remove(gpiochip->irqdomain);
1742         }
1743
1744         if (gpiochip->irqchip) {
1745                 gpiochip->irqchip->irq_request_resources = NULL;
1746                 gpiochip->irqchip->irq_release_resources = NULL;
1747                 gpiochip->irqchip = NULL;
1748         }
1749
1750         gpiochip_irqchip_free_valid_mask(gpiochip);
1751 }
1752
1753 /**
1754  * gpiochip_irqchip_add_key() - adds an irqchip to a gpiochip
1755  * @gpiochip: the gpiochip to add the irqchip to
1756  * @irqchip: the irqchip to add to the gpiochip
1757  * @first_irq: if not dynamically assigned, the base (first) IRQ to
1758  * allocate gpiochip irqs from
1759  * @handler: the irq handler to use (often a predefined irq core function)
1760  * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
1761  * to have the core avoid setting up any default type in the hardware.
1762  * @nested: whether this is a nested irqchip calling handle_nested_irq()
1763  * in its IRQ handler
1764  * @lock_key: lockdep class
1765  *
1766  * This function closely associates a certain irqchip with a certain
1767  * gpiochip, providing an irq domain to translate the local IRQs to
1768  * global irqs in the gpiolib core, and making sure that the gpiochip
1769  * is passed as chip data to all related functions. Driver callbacks
1770  * need to use gpiochip_get_data() to get their local state containers back
1771  * from the gpiochip passed as chip data. An irqdomain will be stored
1772  * in the gpiochip that shall be used by the driver to handle IRQ number
1773  * translation. The gpiochip will need to be initialized and registered
1774  * before calling this function.
1775  *
1776  * This function will handle two cell:ed simple IRQs and assumes all
1777  * the pins on the gpiochip can generate a unique IRQ. Everything else
1778  * need to be open coded.
1779  */
1780 int gpiochip_irqchip_add_key(struct gpio_chip *gpiochip,
1781                              struct irq_chip *irqchip,
1782                              unsigned int first_irq,
1783                              irq_flow_handler_t handler,
1784                              unsigned int type,
1785                              bool nested,
1786                              struct lock_class_key *lock_key)
1787 {
1788         struct device_node *of_node;
1789
1790         if (!gpiochip || !irqchip)
1791                 return -EINVAL;
1792
1793         if (!gpiochip->parent) {
1794                 pr_err("missing gpiochip .dev parent pointer\n");
1795                 return -EINVAL;
1796         }
1797         gpiochip->irq_nested = nested;
1798         of_node = gpiochip->parent->of_node;
1799 #ifdef CONFIG_OF_GPIO
1800         /*
1801          * If the gpiochip has an assigned OF node this takes precedence
1802          * FIXME: get rid of this and use gpiochip->parent->of_node
1803          * everywhere
1804          */
1805         if (gpiochip->of_node)
1806                 of_node = gpiochip->of_node;
1807 #endif
1808         /*
1809          * Specifying a default trigger is a terrible idea if DT or ACPI is
1810          * used to configure the interrupts, as you may end-up with
1811          * conflicting triggers. Tell the user, and reset to NONE.
1812          */
1813         if (WARN(of_node && type != IRQ_TYPE_NONE,
1814                  "%pOF: Ignoring %d default trigger\n", of_node, type))
1815                 type = IRQ_TYPE_NONE;
1816         if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
1817                 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
1818                                  "Ignoring %d default trigger\n", type);
1819                 type = IRQ_TYPE_NONE;
1820         }
1821
1822         gpiochip->irqchip = irqchip;
1823         gpiochip->irq_handler = handler;
1824         gpiochip->irq_default_type = type;
1825         gpiochip->to_irq = gpiochip_to_irq;
1826         gpiochip->lock_key = lock_key;
1827         gpiochip->irqdomain = irq_domain_add_simple(of_node,
1828                                         gpiochip->ngpio, first_irq,
1829                                         &gpiochip_domain_ops, gpiochip);
1830         if (!gpiochip->irqdomain) {
1831                 gpiochip->irqchip = NULL;
1832                 return -EINVAL;
1833         }
1834
1835         /*
1836          * It is possible for a driver to override this, but only if the
1837          * alternative functions are both implemented.
1838          */
1839         if (!irqchip->irq_request_resources &&
1840             !irqchip->irq_release_resources) {
1841                 irqchip->irq_request_resources = gpiochip_irq_reqres;
1842                 irqchip->irq_release_resources = gpiochip_irq_relres;
1843         }
1844
1845         acpi_gpiochip_request_interrupts(gpiochip);
1846
1847         return 0;
1848 }
1849 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_key);
1850
1851 #else /* CONFIG_GPIOLIB_IRQCHIP */
1852
1853 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
1854 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
1855 {
1856         return 0;
1857 }
1858 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1859 { }
1860
1861 #endif /* CONFIG_GPIOLIB_IRQCHIP */
1862
1863 /**
1864  * gpiochip_generic_request() - request the gpio function for a pin
1865  * @chip: the gpiochip owning the GPIO
1866  * @offset: the offset of the GPIO to request for GPIO function
1867  */
1868 int gpiochip_generic_request(struct gpio_chip *chip, unsigned offset)
1869 {
1870         return pinctrl_request_gpio(chip->gpiodev->base + offset);
1871 }
1872 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
1873
1874 /**
1875  * gpiochip_generic_free() - free the gpio function from a pin
1876  * @chip: the gpiochip to request the gpio function for
1877  * @offset: the offset of the GPIO to free from GPIO function
1878  */
1879 void gpiochip_generic_free(struct gpio_chip *chip, unsigned offset)
1880 {
1881         pinctrl_free_gpio(chip->gpiodev->base + offset);
1882 }
1883 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
1884
1885 /**
1886  * gpiochip_generic_config() - apply configuration for a pin
1887  * @chip: the gpiochip owning the GPIO
1888  * @offset: the offset of the GPIO to apply the configuration
1889  * @config: the configuration to be applied
1890  */
1891 int gpiochip_generic_config(struct gpio_chip *chip, unsigned offset,
1892                             unsigned long config)
1893 {
1894         return pinctrl_gpio_set_config(chip->gpiodev->base + offset, config);
1895 }
1896 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
1897
1898 #ifdef CONFIG_PINCTRL
1899
1900 /**
1901  * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
1902  * @chip: the gpiochip to add the range for
1903  * @pctldev: the pin controller to map to
1904  * @gpio_offset: the start offset in the current gpio_chip number space
1905  * @pin_group: name of the pin group inside the pin controller
1906  */
1907 int gpiochip_add_pingroup_range(struct gpio_chip *chip,
1908                         struct pinctrl_dev *pctldev,
1909                         unsigned int gpio_offset, const char *pin_group)
1910 {
1911         struct gpio_pin_range *pin_range;
1912         struct gpio_device *gdev = chip->gpiodev;
1913         int ret;
1914
1915         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1916         if (!pin_range) {
1917                 chip_err(chip, "failed to allocate pin ranges\n");
1918                 return -ENOMEM;
1919         }
1920
1921         /* Use local offset as range ID */
1922         pin_range->range.id = gpio_offset;
1923         pin_range->range.gc = chip;
1924         pin_range->range.name = chip->label;
1925         pin_range->range.base = gdev->base + gpio_offset;
1926         pin_range->pctldev = pctldev;
1927
1928         ret = pinctrl_get_group_pins(pctldev, pin_group,
1929                                         &pin_range->range.pins,
1930                                         &pin_range->range.npins);
1931         if (ret < 0) {
1932                 kfree(pin_range);
1933                 return ret;
1934         }
1935
1936         pinctrl_add_gpio_range(pctldev, &pin_range->range);
1937
1938         chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
1939                  gpio_offset, gpio_offset + pin_range->range.npins - 1,
1940                  pinctrl_dev_get_devname(pctldev), pin_group);
1941
1942         list_add_tail(&pin_range->node, &gdev->pin_ranges);
1943
1944         return 0;
1945 }
1946 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
1947
1948 /**
1949  * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
1950  * @chip: the gpiochip to add the range for
1951  * @pinctl_name: the dev_name() of the pin controller to map to
1952  * @gpio_offset: the start offset in the current gpio_chip number space
1953  * @pin_offset: the start offset in the pin controller number space
1954  * @npins: the number of pins from the offset of each pin space (GPIO and
1955  *      pin controller) to accumulate in this range
1956  *
1957  * Returns:
1958  * 0 on success, or a negative error-code on failure.
1959  */
1960 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
1961                            unsigned int gpio_offset, unsigned int pin_offset,
1962                            unsigned int npins)
1963 {
1964         struct gpio_pin_range *pin_range;
1965         struct gpio_device *gdev = chip->gpiodev;
1966         int ret;
1967
1968         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1969         if (!pin_range) {
1970                 chip_err(chip, "failed to allocate pin ranges\n");
1971                 return -ENOMEM;
1972         }
1973
1974         /* Use local offset as range ID */
1975         pin_range->range.id = gpio_offset;
1976         pin_range->range.gc = chip;
1977         pin_range->range.name = chip->label;
1978         pin_range->range.base = gdev->base + gpio_offset;
1979         pin_range->range.pin_base = pin_offset;
1980         pin_range->range.npins = npins;
1981         pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
1982                         &pin_range->range);
1983         if (IS_ERR(pin_range->pctldev)) {
1984                 ret = PTR_ERR(pin_range->pctldev);
1985                 chip_err(chip, "could not create pin range\n");
1986                 kfree(pin_range);
1987                 return ret;
1988         }
1989         chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
1990                  gpio_offset, gpio_offset + npins - 1,
1991                  pinctl_name,
1992                  pin_offset, pin_offset + npins - 1);
1993
1994         list_add_tail(&pin_range->node, &gdev->pin_ranges);
1995
1996         return 0;
1997 }
1998 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
1999
2000 /**
2001  * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2002  * @chip: the chip to remove all the mappings for
2003  */
2004 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
2005 {
2006         struct gpio_pin_range *pin_range, *tmp;
2007         struct gpio_device *gdev = chip->gpiodev;
2008
2009         list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2010                 list_del(&pin_range->node);
2011                 pinctrl_remove_gpio_range(pin_range->pctldev,
2012                                 &pin_range->range);
2013                 kfree(pin_range);
2014         }
2015 }
2016 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2017
2018 #endif /* CONFIG_PINCTRL */
2019
2020 /* These "optional" allocation calls help prevent drivers from stomping
2021  * on each other, and help provide better diagnostics in debugfs.
2022  * They're called even less than the "set direction" calls.
2023  */
2024 static int __gpiod_request(struct gpio_desc *desc, const char *label)
2025 {
2026         struct gpio_chip        *chip = desc->gdev->chip;
2027         int                     status;
2028         unsigned long           flags;
2029
2030         spin_lock_irqsave(&gpio_lock, flags);
2031
2032         /* NOTE:  gpio_request() can be called in early boot,
2033          * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2034          */
2035
2036         if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
2037                 desc_set_label(desc, label ? : "?");
2038                 status = 0;
2039         } else {
2040                 status = -EBUSY;
2041                 goto done;
2042         }
2043
2044         if (chip->request) {
2045                 /* chip->request may sleep */
2046                 spin_unlock_irqrestore(&gpio_lock, flags);
2047                 status = chip->request(chip, gpio_chip_hwgpio(desc));
2048                 spin_lock_irqsave(&gpio_lock, flags);
2049
2050                 if (status < 0) {
2051                         desc_set_label(desc, NULL);
2052                         clear_bit(FLAG_REQUESTED, &desc->flags);
2053                         goto done;
2054                 }
2055         }
2056         if (chip->get_direction) {
2057                 /* chip->get_direction may sleep */
2058                 spin_unlock_irqrestore(&gpio_lock, flags);
2059                 gpiod_get_direction(desc);
2060                 spin_lock_irqsave(&gpio_lock, flags);
2061         }
2062 done:
2063         spin_unlock_irqrestore(&gpio_lock, flags);
2064         return status;
2065 }
2066
2067 /*
2068  * This descriptor validation needs to be inserted verbatim into each
2069  * function taking a descriptor, so we need to use a preprocessor
2070  * macro to avoid endless duplication. If the desc is NULL it is an
2071  * optional GPIO and calls should just bail out.
2072  */
2073 #define VALIDATE_DESC(desc) do { \
2074         if (!desc) \
2075                 return 0; \
2076         if (IS_ERR(desc)) {                                             \
2077                 pr_warn("%s: invalid GPIO (errorpointer)\n", __func__); \
2078                 return PTR_ERR(desc); \
2079         } \
2080         if (!desc->gdev) { \
2081                 pr_warn("%s: invalid GPIO (no device)\n", __func__); \
2082                 return -EINVAL; \
2083         } \
2084         if ( !desc->gdev->chip ) { \
2085                 dev_warn(&desc->gdev->dev, \
2086                          "%s: backing chip is gone\n", __func__); \
2087                 return 0; \
2088         } } while (0)
2089
2090 #define VALIDATE_DESC_VOID(desc) do { \
2091         if (!desc) \
2092                 return; \
2093         if (IS_ERR(desc)) {                                             \
2094                 pr_warn("%s: invalid GPIO (errorpointer)\n", __func__); \
2095                 return; \
2096         } \
2097         if (!desc->gdev) { \
2098                 pr_warn("%s: invalid GPIO (no device)\n", __func__); \
2099                 return; \
2100         } \
2101         if (!desc->gdev->chip) { \
2102                 dev_warn(&desc->gdev->dev, \
2103                          "%s: backing chip is gone\n", __func__); \
2104                 return; \
2105         } } while (0)
2106
2107
2108 int gpiod_request(struct gpio_desc *desc, const char *label)
2109 {
2110         int status = -EPROBE_DEFER;
2111         struct gpio_device *gdev;
2112
2113         VALIDATE_DESC(desc);
2114         gdev = desc->gdev;
2115
2116         if (try_module_get(gdev->owner)) {
2117                 status = __gpiod_request(desc, label);
2118                 if (status < 0)
2119                         module_put(gdev->owner);
2120                 else
2121                         get_device(&gdev->dev);
2122         }
2123
2124         if (status)
2125                 gpiod_dbg(desc, "%s: status %d\n", __func__, status);
2126
2127         return status;
2128 }
2129
2130 static bool __gpiod_free(struct gpio_desc *desc)
2131 {
2132         bool                    ret = false;
2133         unsigned long           flags;
2134         struct gpio_chip        *chip;
2135
2136         might_sleep();
2137
2138         gpiod_unexport(desc);
2139
2140         spin_lock_irqsave(&gpio_lock, flags);
2141
2142         chip = desc->gdev->chip;
2143         if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
2144                 if (chip->free) {
2145                         spin_unlock_irqrestore(&gpio_lock, flags);
2146                         might_sleep_if(chip->can_sleep);
2147                         chip->free(chip, gpio_chip_hwgpio(desc));
2148                         spin_lock_irqsave(&gpio_lock, flags);
2149                 }
2150                 desc_set_label(desc, NULL);
2151                 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
2152                 clear_bit(FLAG_REQUESTED, &desc->flags);
2153                 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
2154                 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
2155                 clear_bit(FLAG_IS_HOGGED, &desc->flags);
2156                 ret = true;
2157         }
2158
2159         spin_unlock_irqrestore(&gpio_lock, flags);
2160         return ret;
2161 }
2162
2163 void gpiod_free(struct gpio_desc *desc)
2164 {
2165         if (desc && desc->gdev && __gpiod_free(desc)) {
2166                 module_put(desc->gdev->owner);
2167                 put_device(&desc->gdev->dev);
2168         } else {
2169                 WARN_ON(extra_checks);
2170         }
2171 }
2172
2173 /**
2174  * gpiochip_is_requested - return string iff signal was requested
2175  * @chip: controller managing the signal
2176  * @offset: of signal within controller's 0..(ngpio - 1) range
2177  *
2178  * Returns NULL if the GPIO is not currently requested, else a string.
2179  * The string returned is the label passed to gpio_request(); if none has been
2180  * passed it is a meaningless, non-NULL constant.
2181  *
2182  * This function is for use by GPIO controller drivers.  The label can
2183  * help with diagnostics, and knowing that the signal is used as a GPIO
2184  * can help avoid accidentally multiplexing it to another controller.
2185  */
2186 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
2187 {
2188         struct gpio_desc *desc;
2189
2190         if (offset >= chip->ngpio)
2191                 return NULL;
2192
2193         desc = &chip->gpiodev->descs[offset];
2194
2195         if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
2196                 return NULL;
2197         return desc->label;
2198 }
2199 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
2200
2201 /**
2202  * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2203  * @chip: GPIO chip
2204  * @hwnum: hardware number of the GPIO for which to request the descriptor
2205  * @label: label for the GPIO
2206  *
2207  * Function allows GPIO chip drivers to request and use their own GPIO
2208  * descriptors via gpiolib API. Difference to gpiod_request() is that this
2209  * function will not increase reference count of the GPIO chip module. This
2210  * allows the GPIO chip module to be unloaded as needed (we assume that the
2211  * GPIO chip driver handles freeing the GPIOs it has requested).
2212  *
2213  * Returns:
2214  * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
2215  * code on failure.
2216  */
2217 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *chip, u16 hwnum,
2218                                             const char *label)
2219 {
2220         struct gpio_desc *desc = gpiochip_get_desc(chip, hwnum);
2221         int err;
2222
2223         if (IS_ERR(desc)) {
2224                 chip_err(chip, "failed to get GPIO descriptor\n");
2225                 return desc;
2226         }
2227
2228         err = __gpiod_request(desc, label);
2229         if (err < 0)
2230                 return ERR_PTR(err);
2231
2232         return desc;
2233 }
2234 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
2235
2236 /**
2237  * gpiochip_free_own_desc - Free GPIO requested by the chip driver
2238  * @desc: GPIO descriptor to free
2239  *
2240  * Function frees the given GPIO requested previously with
2241  * gpiochip_request_own_desc().
2242  */
2243 void gpiochip_free_own_desc(struct gpio_desc *desc)
2244 {
2245         if (desc)
2246                 __gpiod_free(desc);
2247 }
2248 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
2249
2250 /*
2251  * Drivers MUST set GPIO direction before making get/set calls.  In
2252  * some cases this is done in early boot, before IRQs are enabled.
2253  *
2254  * As a rule these aren't called more than once (except for drivers
2255  * using the open-drain emulation idiom) so these are natural places
2256  * to accumulate extra debugging checks.  Note that we can't (yet)
2257  * rely on gpio_request() having been called beforehand.
2258  */
2259
2260 /**
2261  * gpiod_direction_input - set the GPIO direction to input
2262  * @desc:       GPIO to set to input
2263  *
2264  * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2265  * be called safely on it.
2266  *
2267  * Return 0 in case of success, else an error code.
2268  */
2269 int gpiod_direction_input(struct gpio_desc *desc)
2270 {
2271         struct gpio_chip        *chip;
2272         int                     status = -EINVAL;
2273
2274         VALIDATE_DESC(desc);
2275         chip = desc->gdev->chip;
2276
2277         if (!chip->get || !chip->direction_input) {
2278                 gpiod_warn(desc,
2279                         "%s: missing get() or direction_input() operations\n",
2280                         __func__);
2281                 return -EIO;
2282         }
2283
2284         status = chip->direction_input(chip, gpio_chip_hwgpio(desc));
2285         if (status == 0)
2286                 clear_bit(FLAG_IS_OUT, &desc->flags);
2287
2288         trace_gpio_direction(desc_to_gpio(desc), 1, status);
2289
2290         return status;
2291 }
2292 EXPORT_SYMBOL_GPL(gpiod_direction_input);
2293
2294 static int gpio_set_drive_single_ended(struct gpio_chip *gc, unsigned offset,
2295                                        enum pin_config_param mode)
2296 {
2297         unsigned long config = { PIN_CONF_PACKED(mode, 0) };
2298
2299         return gc->set_config ? gc->set_config(gc, offset, config) : -ENOTSUPP;
2300 }
2301
2302 static int _gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2303 {
2304         struct gpio_chip *gc = desc->gdev->chip;
2305         int val = !!value;
2306         int ret;
2307
2308         /* GPIOs used for IRQs shall not be set as output */
2309         if (test_bit(FLAG_USED_AS_IRQ, &desc->flags)) {
2310                 gpiod_err(desc,
2311                           "%s: tried to set a GPIO tied to an IRQ as output\n",
2312                           __func__);
2313                 return -EIO;
2314         }
2315
2316         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
2317                 /* First see if we can enable open drain in hardware */
2318                 ret = gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2319                                                   PIN_CONFIG_DRIVE_OPEN_DRAIN);
2320                 if (!ret)
2321                         goto set_output_value;
2322                 /* Emulate open drain by not actively driving the line high */
2323                 if (val) {
2324                         ret = gpiod_direction_input(desc);
2325                         goto set_output_flag;
2326                 }
2327         }
2328         else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
2329                 ret = gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2330                                                   PIN_CONFIG_DRIVE_OPEN_SOURCE);
2331                 if (!ret)
2332                         goto set_output_value;
2333                 /* Emulate open source by not actively driving the line low */
2334                 if (!val) {
2335                         ret = gpiod_direction_input(desc);
2336                         goto set_output_flag;
2337                 }
2338         } else {
2339                 gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2340                                             PIN_CONFIG_DRIVE_PUSH_PULL);
2341         }
2342
2343 set_output_value:
2344         if (!gc->set || !gc->direction_output) {
2345                 gpiod_warn(desc,
2346                        "%s: missing set() or direction_output() operations\n",
2347                        __func__);
2348                 return -EIO;
2349         }
2350
2351         ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
2352         if (!ret)
2353                 set_bit(FLAG_IS_OUT, &desc->flags);
2354         trace_gpio_value(desc_to_gpio(desc), 0, val);
2355         trace_gpio_direction(desc_to_gpio(desc), 0, ret);
2356         return ret;
2357
2358 set_output_flag:
2359         /*
2360          * When emulating open-source or open-drain functionalities by not
2361          * actively driving the line (setting mode to input) we still need to
2362          * set the IS_OUT flag or otherwise we won't be able to set the line
2363          * value anymore.
2364          */
2365         if (ret == 0)
2366                 set_bit(FLAG_IS_OUT, &desc->flags);
2367         return ret;
2368 }
2369
2370 /**
2371  * gpiod_direction_output_raw - set the GPIO direction to output
2372  * @desc:       GPIO to set to output
2373  * @value:      initial output value of the GPIO
2374  *
2375  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2376  * be called safely on it. The initial value of the output must be specified
2377  * as raw value on the physical line without regard for the ACTIVE_LOW status.
2378  *
2379  * Return 0 in case of success, else an error code.
2380  */
2381 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2382 {
2383         VALIDATE_DESC(desc);
2384         return _gpiod_direction_output_raw(desc, value);
2385 }
2386 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
2387
2388 /**
2389  * gpiod_direction_output - set the GPIO direction to output
2390  * @desc:       GPIO to set to output
2391  * @value:      initial output value of the GPIO
2392  *
2393  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2394  * be called safely on it. The initial value of the output must be specified
2395  * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2396  * account.
2397  *
2398  * Return 0 in case of success, else an error code.
2399  */
2400 int gpiod_direction_output(struct gpio_desc *desc, int value)
2401 {
2402         VALIDATE_DESC(desc);
2403         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2404                 value = !value;
2405         else
2406                 value = !!value;
2407         return _gpiod_direction_output_raw(desc, value);
2408 }
2409 EXPORT_SYMBOL_GPL(gpiod_direction_output);
2410
2411 /**
2412  * gpiod_set_debounce - sets @debounce time for a GPIO
2413  * @desc: descriptor of the GPIO for which to set debounce time
2414  * @debounce: debounce time in microseconds
2415  *
2416  * Returns:
2417  * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
2418  * debounce time.
2419  */
2420 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
2421 {
2422         struct gpio_chip        *chip;
2423         unsigned long           config;
2424
2425         VALIDATE_DESC(desc);
2426         chip = desc->gdev->chip;
2427         if (!chip->set || !chip->set_config) {
2428                 gpiod_dbg(desc,
2429                           "%s: missing set() or set_config() operations\n",
2430                           __func__);
2431                 return -ENOTSUPP;
2432         }
2433
2434         config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
2435         return chip->set_config(chip, gpio_chip_hwgpio(desc), config);
2436 }
2437 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
2438
2439 /**
2440  * gpiod_is_active_low - test whether a GPIO is active-low or not
2441  * @desc: the gpio descriptor to test
2442  *
2443  * Returns 1 if the GPIO is active-low, 0 otherwise.
2444  */
2445 int gpiod_is_active_low(const struct gpio_desc *desc)
2446 {
2447         VALIDATE_DESC(desc);
2448         return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
2449 }
2450 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
2451
2452 /* I/O calls are only valid after configuration completed; the relevant
2453  * "is this a valid GPIO" error checks should already have been done.
2454  *
2455  * "Get" operations are often inlinable as reading a pin value register,
2456  * and masking the relevant bit in that register.
2457  *
2458  * When "set" operations are inlinable, they involve writing that mask to
2459  * one register to set a low value, or a different register to set it high.
2460  * Otherwise locking is needed, so there may be little value to inlining.
2461  *
2462  *------------------------------------------------------------------------
2463  *
2464  * IMPORTANT!!!  The hot paths -- get/set value -- assume that callers
2465  * have requested the GPIO.  That can include implicit requesting by
2466  * a direction setting call.  Marking a gpio as requested locks its chip
2467  * in memory, guaranteeing that these table lookups need no more locking
2468  * and that gpiochip_remove() will fail.
2469  *
2470  * REVISIT when debugging, consider adding some instrumentation to ensure
2471  * that the GPIO was actually requested.
2472  */
2473
2474 static int _gpiod_get_raw_value(const struct gpio_desc *desc)
2475 {
2476         struct gpio_chip        *chip;
2477         int offset;
2478         int value;
2479
2480         chip = desc->gdev->chip;
2481         offset = gpio_chip_hwgpio(desc);
2482         value = chip->get ? chip->get(chip, offset) : -EIO;
2483         value = value < 0 ? value : !!value;
2484         trace_gpio_value(desc_to_gpio(desc), 1, value);
2485         return value;
2486 }
2487
2488 /**
2489  * gpiod_get_raw_value() - return a gpio's raw value
2490  * @desc: gpio whose value will be returned
2491  *
2492  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2493  * its ACTIVE_LOW status, or negative errno on failure.
2494  *
2495  * This function should be called from contexts where we cannot sleep, and will
2496  * complain if the GPIO chip functions potentially sleep.
2497  */
2498 int gpiod_get_raw_value(const struct gpio_desc *desc)
2499 {
2500         VALIDATE_DESC(desc);
2501         /* Should be using gpiod_get_raw_value_cansleep() */
2502         WARN_ON(desc->gdev->chip->can_sleep);
2503         return _gpiod_get_raw_value(desc);
2504 }
2505 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
2506
2507 /**
2508  * gpiod_get_value() - return a gpio's value
2509  * @desc: gpio whose value will be returned
2510  *
2511  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2512  * account, or negative errno on failure.
2513  *
2514  * This function should be called from contexts where we cannot sleep, and will
2515  * complain if the GPIO chip functions potentially sleep.
2516  */
2517 int gpiod_get_value(const struct gpio_desc *desc)
2518 {
2519         int value;
2520
2521         VALIDATE_DESC(desc);
2522         /* Should be using gpiod_get_value_cansleep() */
2523         WARN_ON(desc->gdev->chip->can_sleep);
2524
2525         value = _gpiod_get_raw_value(desc);
2526         if (value < 0)
2527                 return value;
2528
2529         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2530                 value = !value;
2531
2532         return value;
2533 }
2534 EXPORT_SYMBOL_GPL(gpiod_get_value);
2535
2536 /*
2537  *  _gpio_set_open_drain_value() - Set the open drain gpio's value.
2538  * @desc: gpio descriptor whose state need to be set.
2539  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2540  */
2541 static void _gpio_set_open_drain_value(struct gpio_desc *desc, bool value)
2542 {
2543         int err = 0;
2544         struct gpio_chip *chip = desc->gdev->chip;
2545         int offset = gpio_chip_hwgpio(desc);
2546
2547         if (value) {
2548                 err = chip->direction_input(chip, offset);
2549         } else {
2550                 err = chip->direction_output(chip, offset, 0);
2551                 if (!err)
2552                         set_bit(FLAG_IS_OUT, &desc->flags);
2553         }
2554         trace_gpio_direction(desc_to_gpio(desc), value, err);
2555         if (err < 0)
2556                 gpiod_err(desc,
2557                           "%s: Error in set_value for open drain err %d\n",
2558                           __func__, err);
2559 }
2560
2561 /*
2562  *  _gpio_set_open_source_value() - Set the open source gpio's value.
2563  * @desc: gpio descriptor whose state need to be set.
2564  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2565  */
2566 static void _gpio_set_open_source_value(struct gpio_desc *desc, bool value)
2567 {
2568         int err = 0;
2569         struct gpio_chip *chip = desc->gdev->chip;
2570         int offset = gpio_chip_hwgpio(desc);
2571
2572         if (value) {
2573                 err = chip->direction_output(chip, offset, 1);
2574                 if (!err)
2575                         set_bit(FLAG_IS_OUT, &desc->flags);
2576         } else {
2577                 err = chip->direction_input(chip, offset);
2578         }
2579         trace_gpio_direction(desc_to_gpio(desc), !value, err);
2580         if (err < 0)
2581                 gpiod_err(desc,
2582                           "%s: Error in set_value for open source err %d\n",
2583                           __func__, err);
2584 }
2585
2586 static void _gpiod_set_raw_value(struct gpio_desc *desc, bool value)
2587 {
2588         struct gpio_chip        *chip;
2589
2590         chip = desc->gdev->chip;
2591         trace_gpio_value(desc_to_gpio(desc), 0, value);
2592         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2593                 _gpio_set_open_drain_value(desc, value);
2594         else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2595                 _gpio_set_open_source_value(desc, value);
2596         else
2597                 chip->set(chip, gpio_chip_hwgpio(desc), value);
2598 }
2599
2600 /*
2601  * set multiple outputs on the same chip;
2602  * use the chip's set_multiple function if available;
2603  * otherwise set the outputs sequentially;
2604  * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
2605  *        defines which outputs are to be changed
2606  * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
2607  *        defines the values the outputs specified by mask are to be set to
2608  */
2609 static void gpio_chip_set_multiple(struct gpio_chip *chip,
2610                                    unsigned long *mask, unsigned long *bits)
2611 {
2612         if (chip->set_multiple) {
2613                 chip->set_multiple(chip, mask, bits);
2614         } else {
2615                 unsigned int i;
2616
2617                 /* set outputs if the corresponding mask bit is set */
2618                 for_each_set_bit(i, mask, chip->ngpio)
2619                         chip->set(chip, i, test_bit(i, bits));
2620         }
2621 }
2622
2623 void gpiod_set_array_value_complex(bool raw, bool can_sleep,
2624                                    unsigned int array_size,
2625                                    struct gpio_desc **desc_array,
2626                                    int *value_array)
2627 {
2628         int i = 0;
2629
2630         while (i < array_size) {
2631                 struct gpio_chip *chip = desc_array[i]->gdev->chip;
2632                 unsigned long mask[BITS_TO_LONGS(chip->ngpio)];
2633                 unsigned long bits[BITS_TO_LONGS(chip->ngpio)];
2634                 int count = 0;
2635
2636                 if (!can_sleep)
2637                         WARN_ON(chip->can_sleep);
2638
2639                 memset(mask, 0, sizeof(mask));
2640                 do {
2641                         struct gpio_desc *desc = desc_array[i];
2642                         int hwgpio = gpio_chip_hwgpio(desc);
2643                         int value = value_array[i];
2644
2645                         if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2646                                 value = !value;
2647                         trace_gpio_value(desc_to_gpio(desc), 0, value);
2648                         /*
2649                          * collect all normal outputs belonging to the same chip
2650                          * open drain and open source outputs are set individually
2651                          */
2652                         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
2653                                 _gpio_set_open_drain_value(desc, value);
2654                         } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
2655                                 _gpio_set_open_source_value(desc, value);
2656                         } else {
2657                                 __set_bit(hwgpio, mask);
2658                                 if (value)
2659                                         __set_bit(hwgpio, bits);
2660                                 else
2661                                         __clear_bit(hwgpio, bits);
2662                                 count++;
2663                         }
2664                         i++;
2665                 } while ((i < array_size) &&
2666                          (desc_array[i]->gdev->chip == chip));
2667                 /* push collected bits to outputs */
2668                 if (count != 0)
2669                         gpio_chip_set_multiple(chip, mask, bits);
2670         }
2671 }
2672
2673 /**
2674  * gpiod_set_raw_value() - assign a gpio's raw value
2675  * @desc: gpio whose value will be assigned
2676  * @value: value to assign
2677  *
2678  * Set the raw value of the GPIO, i.e. the value of its physical line without
2679  * regard for its ACTIVE_LOW status.
2680  *
2681  * This function should be called from contexts where we cannot sleep, and will
2682  * complain if the GPIO chip functions potentially sleep.
2683  */
2684 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
2685 {
2686         VALIDATE_DESC_VOID(desc);
2687         /* Should be using gpiod_set_raw_value_cansleep() */
2688         WARN_ON(desc->gdev->chip->can_sleep);
2689         _gpiod_set_raw_value(desc, value);
2690 }
2691 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
2692
2693 /**
2694  * gpiod_set_value() - assign a gpio's value
2695  * @desc: gpio whose value will be assigned
2696  * @value: value to assign
2697  *
2698  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2699  * account
2700  *
2701  * This function should be called from contexts where we cannot sleep, and will
2702  * complain if the GPIO chip functions potentially sleep.
2703  */
2704 void gpiod_set_value(struct gpio_desc *desc, int value)
2705 {
2706         VALIDATE_DESC_VOID(desc);
2707         /* Should be using gpiod_set_value_cansleep() */
2708         WARN_ON(desc->gdev->chip->can_sleep);
2709         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2710                 value = !value;
2711         _gpiod_set_raw_value(desc, value);
2712 }
2713 EXPORT_SYMBOL_GPL(gpiod_set_value);
2714
2715 /**
2716  * gpiod_set_raw_array_value() - assign values to an array of GPIOs
2717  * @array_size: number of elements in the descriptor / value arrays
2718  * @desc_array: array of GPIO descriptors whose values will be assigned
2719  * @value_array: array of values to assign
2720  *
2721  * Set the raw values of the GPIOs, i.e. the values of the physical lines
2722  * without regard for their ACTIVE_LOW status.
2723  *
2724  * This function should be called from contexts where we cannot sleep, and will
2725  * complain if the GPIO chip functions potentially sleep.
2726  */
2727 void gpiod_set_raw_array_value(unsigned int array_size,
2728                          struct gpio_desc **desc_array, int *value_array)
2729 {
2730         if (!desc_array)
2731                 return;
2732         gpiod_set_array_value_complex(true, false, array_size, desc_array,
2733                                       value_array);
2734 }
2735 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
2736
2737 /**
2738  * gpiod_set_array_value() - assign values to an array of GPIOs
2739  * @array_size: number of elements in the descriptor / value arrays
2740  * @desc_array: array of GPIO descriptors whose values will be assigned
2741  * @value_array: array of values to assign
2742  *
2743  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
2744  * into account.
2745  *
2746  * This function should be called from contexts where we cannot sleep, and will
2747  * complain if the GPIO chip functions potentially sleep.
2748  */
2749 void gpiod_set_array_value(unsigned int array_size,
2750                            struct gpio_desc **desc_array, int *value_array)
2751 {
2752         if (!desc_array)
2753                 return;
2754         gpiod_set_array_value_complex(false, false, array_size, desc_array,
2755                                       value_array);
2756 }
2757 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
2758
2759 /**
2760  * gpiod_cansleep() - report whether gpio value access may sleep
2761  * @desc: gpio to check
2762  *
2763  */
2764 int gpiod_cansleep(const struct gpio_desc *desc)
2765 {
2766         VALIDATE_DESC(desc);
2767         return desc->gdev->chip->can_sleep;
2768 }
2769 EXPORT_SYMBOL_GPL(gpiod_cansleep);
2770
2771 /**
2772  * gpiod_to_irq() - return the IRQ corresponding to a GPIO
2773  * @desc: gpio whose IRQ will be returned (already requested)
2774  *
2775  * Return the IRQ corresponding to the passed GPIO, or an error code in case of
2776  * error.
2777  */
2778 int gpiod_to_irq(const struct gpio_desc *desc)
2779 {
2780         struct gpio_chip *chip;
2781         int offset;
2782
2783         /*
2784          * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
2785          * requires this function to not return zero on an invalid descriptor
2786          * but rather a negative error number.
2787          */
2788         if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
2789                 return -EINVAL;
2790
2791         chip = desc->gdev->chip;
2792         offset = gpio_chip_hwgpio(desc);
2793         if (chip->to_irq) {
2794                 int retirq = chip->to_irq(chip, offset);
2795
2796                 /* Zero means NO_IRQ */
2797                 if (!retirq)
2798                         return -ENXIO;
2799
2800                 return retirq;
2801         }
2802         return -ENXIO;
2803 }
2804 EXPORT_SYMBOL_GPL(gpiod_to_irq);
2805
2806 /**
2807  * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
2808  * @chip: the chip the GPIO to lock belongs to
2809  * @offset: the offset of the GPIO to lock as IRQ
2810  *
2811  * This is used directly by GPIO drivers that want to lock down
2812  * a certain GPIO line to be used for IRQs.
2813  */
2814 int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
2815 {
2816         struct gpio_desc *desc;
2817
2818         desc = gpiochip_get_desc(chip, offset);
2819         if (IS_ERR(desc))
2820                 return PTR_ERR(desc);
2821
2822         /*
2823          * If it's fast: flush the direction setting if something changed
2824          * behind our back
2825          */
2826         if (!chip->can_sleep && chip->get_direction) {
2827                 int dir = chip->get_direction(chip, offset);
2828
2829                 if (dir)
2830                         clear_bit(FLAG_IS_OUT, &desc->flags);
2831                 else
2832                         set_bit(FLAG_IS_OUT, &desc->flags);
2833         }
2834
2835         if (test_bit(FLAG_IS_OUT, &desc->flags)) {
2836                 chip_err(chip,
2837                           "%s: tried to flag a GPIO set as output for IRQ\n",
2838                           __func__);
2839                 return -EIO;
2840         }
2841
2842         set_bit(FLAG_USED_AS_IRQ, &desc->flags);
2843
2844         /*
2845          * If the consumer has not set up a label (such as when the
2846          * IRQ is referenced from .to_irq()) we set up a label here
2847          * so it is clear this is used as an interrupt.
2848          */
2849         if (!desc->label)
2850                 desc_set_label(desc, "interrupt");
2851
2852         return 0;
2853 }
2854 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
2855
2856 /**
2857  * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
2858  * @chip: the chip the GPIO to lock belongs to
2859  * @offset: the offset of the GPIO to lock as IRQ
2860  *
2861  * This is used directly by GPIO drivers that want to indicate
2862  * that a certain GPIO is no longer used exclusively for IRQ.
2863  */
2864 void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
2865 {
2866         struct gpio_desc *desc;
2867
2868         desc = gpiochip_get_desc(chip, offset);
2869         if (IS_ERR(desc))
2870                 return;
2871
2872         clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
2873
2874         /* If we only had this marking, erase it */
2875         if (desc->label && !strcmp(desc->label, "interrupt"))
2876                 desc_set_label(desc, NULL);
2877 }
2878 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
2879
2880 bool gpiochip_line_is_irq(struct gpio_chip *chip, unsigned int offset)
2881 {
2882         if (offset >= chip->ngpio)
2883                 return false;
2884
2885         return test_bit(FLAG_USED_AS_IRQ, &chip->gpiodev->descs[offset].flags);
2886 }
2887 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
2888
2889 bool gpiochip_line_is_open_drain(struct gpio_chip *chip, unsigned int offset)
2890 {
2891         if (offset >= chip->ngpio)
2892                 return false;
2893
2894         return test_bit(FLAG_OPEN_DRAIN, &chip->gpiodev->descs[offset].flags);
2895 }
2896 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
2897
2898 bool gpiochip_line_is_open_source(struct gpio_chip *chip, unsigned int offset)
2899 {
2900         if (offset >= chip->ngpio)
2901                 return false;
2902
2903         return test_bit(FLAG_OPEN_SOURCE, &chip->gpiodev->descs[offset].flags);
2904 }
2905 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
2906
2907 bool gpiochip_line_is_persistent(struct gpio_chip *chip, unsigned int offset)
2908 {
2909         if (offset >= chip->ngpio)
2910                 return false;
2911
2912         return !test_bit(FLAG_SLEEP_MAY_LOOSE_VALUE,
2913                          &chip->gpiodev->descs[offset].flags);
2914 }
2915 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
2916
2917 /**
2918  * gpiod_get_raw_value_cansleep() - return a gpio's raw value
2919  * @desc: gpio whose value will be returned
2920  *
2921  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2922  * its ACTIVE_LOW status, or negative errno on failure.
2923  *
2924  * This function is to be called from contexts that can sleep.
2925  */
2926 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
2927 {
2928         might_sleep_if(extra_checks);
2929         VALIDATE_DESC(desc);
2930         return _gpiod_get_raw_value(desc);
2931 }
2932 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
2933
2934 /**
2935  * gpiod_get_value_cansleep() - return a gpio's value
2936  * @desc: gpio whose value will be returned
2937  *
2938  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2939  * account, or negative errno on failure.
2940  *
2941  * This function is to be called from contexts that can sleep.
2942  */
2943 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
2944 {
2945         int value;
2946
2947         might_sleep_if(extra_checks);
2948         VALIDATE_DESC(desc);
2949         value = _gpiod_get_raw_value(desc);
2950         if (value < 0)
2951                 return value;
2952
2953         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2954                 value = !value;
2955
2956         return value;
2957 }
2958 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
2959
2960 /**
2961  * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
2962  * @desc: gpio whose value will be assigned
2963  * @value: value to assign
2964  *
2965  * Set the raw value of the GPIO, i.e. the value of its physical line without
2966  * regard for its ACTIVE_LOW status.
2967  *
2968  * This function is to be called from contexts that can sleep.
2969  */
2970 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
2971 {
2972         might_sleep_if(extra_checks);
2973         VALIDATE_DESC_VOID(desc);
2974         _gpiod_set_raw_value(desc, value);
2975 }
2976 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
2977
2978 /**
2979  * gpiod_set_value_cansleep() - assign a gpio's value
2980  * @desc: gpio whose value will be assigned
2981  * @value: value to assign
2982  *
2983  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2984  * account
2985  *
2986  * This function is to be called from contexts that can sleep.
2987  */
2988 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
2989 {
2990         might_sleep_if(extra_checks);
2991         VALIDATE_DESC_VOID(desc);
2992         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2993                 value = !value;
2994         _gpiod_set_raw_value(desc, value);
2995 }
2996 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
2997
2998 /**
2999  * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
3000  * @array_size: number of elements in the descriptor / value arrays
3001  * @desc_array: array of GPIO descriptors whose values will be assigned
3002  * @value_array: array of values to assign
3003  *
3004  * Set the raw values of the GPIOs, i.e. the values of the physical lines
3005  * without regard for their ACTIVE_LOW status.
3006  *
3007  * This function is to be called from contexts that can sleep.
3008  */
3009 void gpiod_set_raw_array_value_cansleep(unsigned int array_size,
3010                                         struct gpio_desc **desc_array,
3011                                         int *value_array)
3012 {
3013         might_sleep_if(extra_checks);
3014         if (!desc_array)
3015                 return;
3016         gpiod_set_array_value_complex(true, true, array_size, desc_array,
3017                                       value_array);
3018 }
3019 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
3020
3021 /**
3022  * gpiod_add_lookup_tables() - register GPIO device consumers
3023  * @tables: list of tables of consumers to register
3024  * @n: number of tables in the list
3025  */
3026 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
3027 {
3028         unsigned int i;
3029
3030         mutex_lock(&gpio_lookup_lock);
3031
3032         for (i = 0; i < n; i++)
3033                 list_add_tail(&tables[i]->list, &gpio_lookup_list);
3034
3035         mutex_unlock(&gpio_lookup_lock);
3036 }
3037
3038 /**
3039  * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
3040  * @array_size: number of elements in the descriptor / value arrays
3041  * @desc_array: array of GPIO descriptors whose values will be assigned
3042  * @value_array: array of values to assign
3043  *
3044  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3045  * into account.
3046  *
3047  * This function is to be called from contexts that can sleep.
3048  */
3049 void gpiod_set_array_value_cansleep(unsigned int array_size,
3050                                     struct gpio_desc **desc_array,
3051                                     int *value_array)
3052 {
3053         might_sleep_if(extra_checks);
3054         if (!desc_array)
3055                 return;
3056         gpiod_set_array_value_complex(false, true, array_size, desc_array,
3057                                       value_array);
3058 }
3059 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
3060
3061 /**
3062  * gpiod_add_lookup_table() - register GPIO device consumers
3063  * @table: table of consumers to register
3064  */
3065 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
3066 {
3067         mutex_lock(&gpio_lookup_lock);
3068
3069         list_add_tail(&table->list, &gpio_lookup_list);
3070
3071         mutex_unlock(&gpio_lookup_lock);
3072 }
3073 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
3074
3075 /**
3076  * gpiod_remove_lookup_table() - unregister GPIO device consumers
3077  * @table: table of consumers to unregister
3078  */
3079 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
3080 {
3081         mutex_lock(&gpio_lookup_lock);
3082
3083         list_del(&table->list);
3084
3085         mutex_unlock(&gpio_lookup_lock);
3086 }
3087 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
3088
3089 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
3090 {
3091         const char *dev_id = dev ? dev_name(dev) : NULL;
3092         struct gpiod_lookup_table *table;
3093
3094         mutex_lock(&gpio_lookup_lock);
3095
3096         list_for_each_entry(table, &gpio_lookup_list, list) {
3097                 if (table->dev_id && dev_id) {
3098                         /*
3099                          * Valid strings on both ends, must be identical to have
3100                          * a match
3101                          */
3102                         if (!strcmp(table->dev_id, dev_id))
3103                                 goto found;
3104                 } else {
3105                         /*
3106                          * One of the pointers is NULL, so both must be to have
3107                          * a match
3108                          */
3109                         if (dev_id == table->dev_id)
3110                                 goto found;
3111                 }
3112         }
3113         table = NULL;
3114
3115 found:
3116         mutex_unlock(&gpio_lookup_lock);
3117         return table;
3118 }
3119
3120 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
3121                                     unsigned int idx,
3122                                     enum gpio_lookup_flags *flags)
3123 {
3124         struct gpio_desc *desc = ERR_PTR(-ENOENT);
3125         struct gpiod_lookup_table *table;
3126         struct gpiod_lookup *p;
3127
3128         table = gpiod_find_lookup_table(dev);
3129         if (!table)
3130                 return desc;
3131
3132         for (p = &table->table[0]; p->chip_label; p++) {
3133                 struct gpio_chip *chip;
3134
3135                 /* idx must always match exactly */
3136                 if (p->idx != idx)
3137                         continue;
3138
3139                 /* If the lookup entry has a con_id, require exact match */
3140                 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
3141                         continue;
3142
3143                 chip = find_chip_by_name(p->chip_label);
3144
3145                 if (!chip) {
3146                         dev_err(dev, "cannot find GPIO chip %s\n",
3147                                 p->chip_label);
3148                         return ERR_PTR(-ENODEV);
3149                 }
3150
3151                 if (chip->ngpio <= p->chip_hwnum) {
3152                         dev_err(dev,
3153                                 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
3154                                 idx, p->chip_hwnum, chip->ngpio - 1,
3155                                 chip->label);
3156                         return ERR_PTR(-EINVAL);
3157                 }
3158
3159                 desc = gpiochip_get_desc(chip, p->chip_hwnum);
3160                 *flags = p->flags;
3161
3162                 return desc;
3163         }
3164
3165         return desc;
3166 }
3167
3168 static int dt_gpio_count(struct device *dev, const char *con_id)
3169 {
3170         int ret;
3171         char propname[32];
3172         unsigned int i;
3173
3174         for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
3175                 if (con_id)
3176                         snprintf(propname, sizeof(propname), "%s-%s",
3177                                  con_id, gpio_suffixes[i]);
3178                 else
3179                         snprintf(propname, sizeof(propname), "%s",
3180                                  gpio_suffixes[i]);
3181
3182                 ret = of_gpio_named_count(dev->of_node, propname);
3183                 if (ret > 0)
3184                         break;
3185         }
3186         return ret ? ret : -ENOENT;
3187 }
3188
3189 static int platform_gpio_count(struct device *dev, const char *con_id)
3190 {
3191         struct gpiod_lookup_table *table;
3192         struct gpiod_lookup *p;
3193         unsigned int count = 0;
3194
3195         table = gpiod_find_lookup_table(dev);
3196         if (!table)
3197                 return -ENOENT;
3198
3199         for (p = &table->table[0]; p->chip_label; p++) {
3200                 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
3201                     (!con_id && !p->con_id))
3202                         count++;
3203         }
3204         if (!count)
3205                 return -ENOENT;
3206
3207         return count;
3208 }
3209
3210 /**
3211  * gpiod_count - return the number of GPIOs associated with a device / function
3212  *              or -ENOENT if no GPIO has been assigned to the requested function
3213  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3214  * @con_id:     function within the GPIO consumer
3215  */
3216 int gpiod_count(struct device *dev, const char *con_id)
3217 {
3218         int count = -ENOENT;
3219
3220         if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
3221                 count = dt_gpio_count(dev, con_id);
3222         else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
3223                 count = acpi_gpio_count(dev, con_id);
3224
3225         if (count < 0)
3226                 count = platform_gpio_count(dev, con_id);
3227
3228         return count;
3229 }
3230 EXPORT_SYMBOL_GPL(gpiod_count);
3231
3232 /**
3233  * gpiod_get - obtain a GPIO for a given GPIO function
3234  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3235  * @con_id:     function within the GPIO consumer
3236  * @flags:      optional GPIO initialization flags
3237  *
3238  * Return the GPIO descriptor corresponding to the function con_id of device
3239  * dev, -ENOENT if no GPIO has been assigned to the requested function, or
3240  * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
3241  */
3242 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
3243                                          enum gpiod_flags flags)
3244 {
3245         return gpiod_get_index(dev, con_id, 0, flags);
3246 }
3247 EXPORT_SYMBOL_GPL(gpiod_get);
3248
3249 /**
3250  * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
3251  * @dev: GPIO consumer, can be NULL for system-global GPIOs
3252  * @con_id: function within the GPIO consumer
3253  * @flags: optional GPIO initialization flags
3254  *
3255  * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
3256  * the requested function it will return NULL. This is convenient for drivers
3257  * that need to handle optional GPIOs.
3258  */
3259 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
3260                                                   const char *con_id,
3261                                                   enum gpiod_flags flags)
3262 {
3263         return gpiod_get_index_optional(dev, con_id, 0, flags);
3264 }
3265 EXPORT_SYMBOL_GPL(gpiod_get_optional);
3266
3267
3268 /**
3269  * gpiod_configure_flags - helper function to configure a given GPIO
3270  * @desc:       gpio whose value will be assigned
3271  * @con_id:     function within the GPIO consumer
3272  * @lflags:     gpio_lookup_flags - returned from of_find_gpio() or
3273  *              of_get_gpio_hog()
3274  * @dflags:     gpiod_flags - optional GPIO initialization flags
3275  *
3276  * Return 0 on success, -ENOENT if no GPIO has been assigned to the
3277  * requested function and/or index, or another IS_ERR() code if an error
3278  * occurred while trying to acquire the GPIO.
3279  */
3280 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
3281                 unsigned long lflags, enum gpiod_flags dflags)
3282 {
3283         int status;
3284
3285         if (lflags & GPIO_ACTIVE_LOW)
3286                 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
3287         if (lflags & GPIO_OPEN_DRAIN)
3288                 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3289         if (lflags & GPIO_OPEN_SOURCE)
3290                 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
3291         if (lflags & GPIO_SLEEP_MAY_LOOSE_VALUE)
3292                 set_bit(FLAG_SLEEP_MAY_LOOSE_VALUE, &desc->flags);
3293
3294         /* No particular flag request, return here... */
3295         if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
3296                 pr_debug("no flags found for %s\n", con_id);
3297                 return 0;
3298         }
3299
3300         /* Process flags */
3301         if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
3302                 status = gpiod_direction_output(desc,
3303                                 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
3304         else
3305                 status = gpiod_direction_input(desc);
3306
3307         return status;
3308 }
3309
3310 /**
3311  * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
3312  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3313  * @con_id:     function within the GPIO consumer
3314  * @idx:        index of the GPIO to obtain in the consumer
3315  * @flags:      optional GPIO initialization flags
3316  *
3317  * This variant of gpiod_get() allows to access GPIOs other than the first
3318  * defined one for functions that define several GPIOs.
3319  *
3320  * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
3321  * requested function and/or index, or another IS_ERR() code if an error
3322  * occurred while trying to acquire the GPIO.
3323  */
3324 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
3325                                                const char *con_id,
3326                                                unsigned int idx,
3327                                                enum gpiod_flags flags)
3328 {
3329         struct gpio_desc *desc = NULL;
3330         int status;
3331         enum gpio_lookup_flags lookupflags = 0;
3332         /* Maybe we have a device name, maybe not */
3333         const char *devname = dev ? dev_name(dev) : "?";
3334
3335         dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
3336
3337         if (dev) {
3338                 /* Using device tree? */
3339                 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
3340                         dev_dbg(dev, "using device tree for GPIO lookup\n");
3341                         desc = of_find_gpio(dev, con_id, idx, &lookupflags);
3342                 } else if (ACPI_COMPANION(dev)) {
3343                         dev_dbg(dev, "using ACPI for GPIO lookup\n");
3344                         desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
3345                 }
3346         }
3347
3348         /*
3349          * Either we are not using DT or ACPI, or their lookup did not return
3350          * a result. In that case, use platform lookup as a fallback.
3351          */
3352         if (!desc || desc == ERR_PTR(-ENOENT)) {
3353                 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
3354                 desc = gpiod_find(dev, con_id, idx, &lookupflags);
3355         }
3356
3357         if (IS_ERR(desc)) {
3358                 dev_dbg(dev, "lookup for GPIO %s failed\n", con_id);
3359                 return desc;
3360         }
3361
3362         /*
3363          * If a connection label was passed use that, else attempt to use
3364          * the device name as label
3365          */
3366         status = gpiod_request(desc, con_id ? con_id : devname);
3367         if (status < 0)
3368                 return ERR_PTR(status);
3369
3370         status = gpiod_configure_flags(desc, con_id, lookupflags, flags);
3371         if (status < 0) {
3372                 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
3373                 gpiod_put(desc);
3374                 return ERR_PTR(status);
3375         }
3376
3377         return desc;
3378 }
3379 EXPORT_SYMBOL_GPL(gpiod_get_index);
3380
3381 /**
3382  * fwnode_get_named_gpiod - obtain a GPIO from firmware node
3383  * @fwnode:     handle of the firmware node
3384  * @propname:   name of the firmware property representing the GPIO
3385  * @index:      index of the GPIO to obtain in the consumer
3386  * @dflags:     GPIO initialization flags
3387  * @label:      label to attach to the requested GPIO
3388  *
3389  * This function can be used for drivers that get their configuration
3390  * from firmware.
3391  *
3392  * Function properly finds the corresponding GPIO using whatever is the
3393  * underlying firmware interface and then makes sure that the GPIO
3394  * descriptor is requested before it is returned to the caller.
3395  *
3396  * Returns:
3397  * On successful request the GPIO pin is configured in accordance with
3398  * provided @dflags.
3399  *
3400  * In case of error an ERR_PTR() is returned.
3401  */
3402 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
3403                                          const char *propname, int index,
3404                                          enum gpiod_flags dflags,
3405                                          const char *label)
3406 {
3407         struct gpio_desc *desc = ERR_PTR(-ENODEV);
3408         unsigned long lflags = 0;
3409         bool active_low = false;
3410         bool single_ended = false;
3411         bool open_drain = false;
3412         int ret;
3413
3414         if (!fwnode)
3415                 return ERR_PTR(-EINVAL);
3416
3417         if (is_of_node(fwnode)) {
3418                 enum of_gpio_flags flags;
3419
3420                 desc = of_get_named_gpiod_flags(to_of_node(fwnode), propname,
3421                                                 index, &flags);
3422                 if (!IS_ERR(desc)) {
3423                         active_low = flags & OF_GPIO_ACTIVE_LOW;
3424                         single_ended = flags & OF_GPIO_SINGLE_ENDED;
3425                         open_drain = flags & OF_GPIO_OPEN_DRAIN;
3426                 }
3427         } else if (is_acpi_node(fwnode)) {
3428                 struct acpi_gpio_info info;
3429
3430                 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
3431                 if (!IS_ERR(desc)) {
3432                         active_low = info.polarity == GPIO_ACTIVE_LOW;
3433                         ret = acpi_gpio_update_gpiod_flags(&dflags, info.flags);
3434                         if (ret)
3435                                 pr_debug("Override GPIO initialization flags\n");
3436                 }
3437         }
3438
3439         if (IS_ERR(desc))
3440                 return desc;
3441
3442         ret = gpiod_request(desc, label);
3443         if (ret)
3444                 return ERR_PTR(ret);
3445
3446         if (active_low)
3447                 lflags |= GPIO_ACTIVE_LOW;
3448
3449         if (single_ended) {
3450                 if (open_drain)
3451                         lflags |= GPIO_OPEN_DRAIN;
3452                 else
3453                         lflags |= GPIO_OPEN_SOURCE;
3454         }
3455
3456         ret = gpiod_configure_flags(desc, propname, lflags, dflags);
3457         if (ret < 0) {
3458                 gpiod_put(desc);
3459                 return ERR_PTR(ret);
3460         }
3461
3462         return desc;
3463 }
3464 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
3465
3466 /**
3467  * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
3468  *                            function
3469  * @dev: GPIO consumer, can be NULL for system-global GPIOs
3470  * @con_id: function within the GPIO consumer
3471  * @index: index of the GPIO to obtain in the consumer
3472  * @flags: optional GPIO initialization flags
3473  *
3474  * This is equivalent to gpiod_get_index(), except that when no GPIO with the
3475  * specified index was assigned to the requested function it will return NULL.
3476  * This is convenient for drivers that need to handle optional GPIOs.
3477  */
3478 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
3479                                                         const char *con_id,
3480                                                         unsigned int index,
3481                                                         enum gpiod_flags flags)
3482 {
3483         struct gpio_desc *desc;
3484
3485         desc = gpiod_get_index(dev, con_id, index, flags);
3486         if (IS_ERR(desc)) {
3487                 if (PTR_ERR(desc) == -ENOENT)
3488                         return NULL;
3489         }
3490
3491         return desc;
3492 }
3493 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
3494
3495 /**
3496  * gpiod_hog - Hog the specified GPIO desc given the provided flags
3497  * @desc:       gpio whose value will be assigned
3498  * @name:       gpio line name
3499  * @lflags:     gpio_lookup_flags - returned from of_find_gpio() or
3500  *              of_get_gpio_hog()
3501  * @dflags:     gpiod_flags - optional GPIO initialization flags
3502  */
3503 int gpiod_hog(struct gpio_desc *desc, const char *name,
3504               unsigned long lflags, enum gpiod_flags dflags)
3505 {
3506         struct gpio_chip *chip;
3507         struct gpio_desc *local_desc;
3508         int hwnum;
3509         int status;
3510
3511         chip = gpiod_to_chip(desc);
3512         hwnum = gpio_chip_hwgpio(desc);
3513
3514         local_desc = gpiochip_request_own_desc(chip, hwnum, name);
3515         if (IS_ERR(local_desc)) {
3516                 status = PTR_ERR(local_desc);
3517                 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
3518                        name, chip->label, hwnum, status);
3519                 return status;
3520         }
3521
3522         status = gpiod_configure_flags(desc, name, lflags, dflags);
3523         if (status < 0) {
3524                 pr_err("setup of hog GPIO %s (chip %s, offset %d) failed, %d\n",
3525                        name, chip->label, hwnum, status);
3526                 gpiochip_free_own_desc(desc);
3527                 return status;
3528         }
3529
3530         /* Mark GPIO as hogged so it can be identified and removed later */
3531         set_bit(FLAG_IS_HOGGED, &desc->flags);
3532
3533         pr_info("GPIO line %d (%s) hogged as %s%s\n",
3534                 desc_to_gpio(desc), name,
3535                 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
3536                 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ?
3537                   (dflags&GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low":"");
3538
3539         return 0;
3540 }
3541
3542 /**
3543  * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
3544  * @chip:       gpio chip to act on
3545  *
3546  * This is only used by of_gpiochip_remove to free hogged gpios
3547  */
3548 static void gpiochip_free_hogs(struct gpio_chip *chip)
3549 {
3550         int id;
3551
3552         for (id = 0; id < chip->ngpio; id++) {
3553                 if (test_bit(FLAG_IS_HOGGED, &chip->gpiodev->descs[id].flags))
3554                         gpiochip_free_own_desc(&chip->gpiodev->descs[id]);
3555         }
3556 }
3557
3558 /**
3559  * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
3560  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3561  * @con_id:     function within the GPIO consumer
3562  * @flags:      optional GPIO initialization flags
3563  *
3564  * This function acquires all the GPIOs defined under a given function.
3565  *
3566  * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
3567  * no GPIO has been assigned to the requested function, or another IS_ERR()
3568  * code if an error occurred while trying to acquire the GPIOs.
3569  */
3570 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
3571                                                 const char *con_id,
3572                                                 enum gpiod_flags flags)
3573 {
3574         struct gpio_desc *desc;
3575         struct gpio_descs *descs;
3576         int count;
3577
3578         count = gpiod_count(dev, con_id);
3579         if (count < 0)
3580                 return ERR_PTR(count);
3581
3582         descs = kzalloc(sizeof(*descs) + sizeof(descs->desc[0]) * count,
3583                         GFP_KERNEL);
3584         if (!descs)
3585                 return ERR_PTR(-ENOMEM);
3586
3587         for (descs->ndescs = 0; descs->ndescs < count; ) {
3588                 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
3589                 if (IS_ERR(desc)) {
3590                         gpiod_put_array(descs);
3591                         return ERR_CAST(desc);
3592                 }
3593                 descs->desc[descs->ndescs] = desc;
3594                 descs->ndescs++;
3595         }
3596         return descs;
3597 }
3598 EXPORT_SYMBOL_GPL(gpiod_get_array);
3599
3600 /**
3601  * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
3602  *                            function
3603  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3604  * @con_id:     function within the GPIO consumer
3605  * @flags:      optional GPIO initialization flags
3606  *
3607  * This is equivalent to gpiod_get_array(), except that when no GPIO was
3608  * assigned to the requested function it will return NULL.
3609  */
3610 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
3611                                                         const char *con_id,
3612                                                         enum gpiod_flags flags)
3613 {
3614         struct gpio_descs *descs;
3615
3616         descs = gpiod_get_array(dev, con_id, flags);
3617         if (IS_ERR(descs) && (PTR_ERR(descs) == -ENOENT))
3618                 return NULL;
3619
3620         return descs;
3621 }
3622 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
3623
3624 /**
3625  * gpiod_put - dispose of a GPIO descriptor
3626  * @desc:       GPIO descriptor to dispose of
3627  *
3628  * No descriptor can be used after gpiod_put() has been called on it.
3629  */
3630 void gpiod_put(struct gpio_desc *desc)
3631 {
3632         gpiod_free(desc);
3633 }
3634 EXPORT_SYMBOL_GPL(gpiod_put);
3635
3636 /**
3637  * gpiod_put_array - dispose of multiple GPIO descriptors
3638  * @descs:      struct gpio_descs containing an array of descriptors
3639  */
3640 void gpiod_put_array(struct gpio_descs *descs)
3641 {
3642         unsigned int i;
3643
3644         for (i = 0; i < descs->ndescs; i++)
3645                 gpiod_put(descs->desc[i]);
3646
3647         kfree(descs);
3648 }
3649 EXPORT_SYMBOL_GPL(gpiod_put_array);
3650
3651 static int __init gpiolib_dev_init(void)
3652 {
3653         int ret;
3654
3655         /* Register GPIO sysfs bus */
3656         ret  = bus_register(&gpio_bus_type);
3657         if (ret < 0) {
3658                 pr_err("gpiolib: could not register GPIO bus type\n");
3659                 return ret;
3660         }
3661
3662         ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, "gpiochip");
3663         if (ret < 0) {
3664                 pr_err("gpiolib: failed to allocate char dev region\n");
3665                 bus_unregister(&gpio_bus_type);
3666         } else {
3667                 gpiolib_initialized = true;
3668                 gpiochip_setup_devs();
3669         }
3670         return ret;
3671 }
3672 core_initcall(gpiolib_dev_init);
3673
3674 #ifdef CONFIG_DEBUG_FS
3675
3676 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
3677 {
3678         unsigned                i;
3679         struct gpio_chip        *chip = gdev->chip;
3680         unsigned                gpio = gdev->base;
3681         struct gpio_desc        *gdesc = &gdev->descs[0];
3682         int                     is_out;
3683         int                     is_irq;
3684
3685         for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
3686                 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
3687                         if (gdesc->name) {
3688                                 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
3689                                            gpio, gdesc->name);
3690                         }
3691                         continue;
3692                 }
3693
3694                 gpiod_get_direction(gdesc);
3695                 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
3696                 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
3697                 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s",
3698                         gpio, gdesc->name ? gdesc->name : "", gdesc->label,
3699                         is_out ? "out" : "in ",
3700                         chip->get
3701                                 ? (chip->get(chip, i) ? "hi" : "lo")
3702                                 : "?  ",
3703                         is_irq ? "IRQ" : "   ");
3704                 seq_printf(s, "\n");
3705         }
3706 }
3707
3708 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
3709 {
3710         unsigned long flags;
3711         struct gpio_device *gdev = NULL;
3712         loff_t index = *pos;
3713
3714         s->private = "";
3715
3716         spin_lock_irqsave(&gpio_lock, flags);
3717         list_for_each_entry(gdev, &gpio_devices, list)
3718                 if (index-- == 0) {
3719                         spin_unlock_irqrestore(&gpio_lock, flags);
3720                         return gdev;
3721                 }
3722         spin_unlock_irqrestore(&gpio_lock, flags);
3723
3724         return NULL;
3725 }
3726
3727 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
3728 {
3729         unsigned long flags;
3730         struct gpio_device *gdev = v;
3731         void *ret = NULL;
3732
3733         spin_lock_irqsave(&gpio_lock, flags);
3734         if (list_is_last(&gdev->list, &gpio_devices))
3735                 ret = NULL;
3736         else
3737                 ret = list_entry(gdev->list.next, struct gpio_device, list);
3738         spin_unlock_irqrestore(&gpio_lock, flags);
3739
3740         s->private = "\n";
3741         ++*pos;
3742
3743         return ret;
3744 }
3745
3746 static void gpiolib_seq_stop(struct seq_file *s, void *v)
3747 {
3748 }
3749
3750 static int gpiolib_seq_show(struct seq_file *s, void *v)
3751 {
3752         struct gpio_device *gdev = v;
3753         struct gpio_chip *chip = gdev->chip;
3754         struct device *parent;
3755
3756         if (!chip) {
3757                 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
3758                            dev_name(&gdev->dev));
3759                 return 0;
3760         }
3761
3762         seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
3763                    dev_name(&gdev->dev),
3764                    gdev->base, gdev->base + gdev->ngpio - 1);
3765         parent = chip->parent;
3766         if (parent)
3767                 seq_printf(s, ", parent: %s/%s",
3768                            parent->bus ? parent->bus->name : "no-bus",
3769                            dev_name(parent));
3770         if (chip->label)
3771                 seq_printf(s, ", %s", chip->label);
3772         if (chip->can_sleep)
3773                 seq_printf(s, ", can sleep");
3774         seq_printf(s, ":\n");
3775
3776         if (chip->dbg_show)
3777                 chip->dbg_show(s, chip);
3778         else
3779                 gpiolib_dbg_show(s, gdev);
3780
3781         return 0;
3782 }
3783
3784 static const struct seq_operations gpiolib_seq_ops = {
3785         .start = gpiolib_seq_start,
3786         .next = gpiolib_seq_next,
3787         .stop = gpiolib_seq_stop,
3788         .show = gpiolib_seq_show,
3789 };
3790
3791 static int gpiolib_open(struct inode *inode, struct file *file)
3792 {
3793         return seq_open(file, &gpiolib_seq_ops);
3794 }
3795
3796 static const struct file_operations gpiolib_operations = {
3797         .owner          = THIS_MODULE,
3798         .open           = gpiolib_open,
3799         .read           = seq_read,
3800         .llseek         = seq_lseek,
3801         .release        = seq_release,
3802 };
3803
3804 static int __init gpiolib_debugfs_init(void)
3805 {
3806         /* /sys/kernel/debug/gpio */
3807         (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
3808                                 NULL, NULL, &gpiolib_operations);
3809         return 0;
3810 }
3811 subsys_initcall(gpiolib_debugfs_init);
3812
3813 #endif  /* DEBUG_FS */