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