Merge tag 'v4.9.209' of git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux...
[platform/kernel/linux-amlogic.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
1237                  * (often with pullups enabled) so power usage is
1238                  * minimized. Linux code should set the gpio direction
1239                  * first thing; but until it does, and in case
1240                  * chip->get_direction is not set, we may expose the
1241                  * wrong direction in sysfs.
1242                  */
1243
1244                 if (chip->get_direction) {
1245                         /*
1246                          * If we have .get_direction, set up the initial
1247                          * direction flag from the hardware.
1248                          */
1249                         int dir = chip->get_direction(chip, i);
1250
1251                         if (!dir)
1252                                 set_bit(FLAG_IS_OUT, &desc->flags);
1253                 } else if (!chip->direction_input) {
1254                         /*
1255                          * If the chip lacks the .direction_input callback
1256                          * we logically assume all lines are outputs.
1257                          */
1258                         set_bit(FLAG_IS_OUT, &desc->flags);
1259                 }
1260         }
1261
1262 #ifdef CONFIG_PINCTRL
1263         INIT_LIST_HEAD(&gdev->pin_ranges);
1264 #endif
1265
1266         status = gpiochip_set_desc_names(chip);
1267         if (status)
1268                 goto err_remove_from_list;
1269
1270         status = gpiochip_irqchip_init_valid_mask(chip);
1271         if (status)
1272                 goto err_remove_from_list;
1273
1274         status = of_gpiochip_add(chip);
1275         if (status)
1276                 goto err_remove_chip;
1277
1278         acpi_gpiochip_add(chip);
1279
1280         /*
1281          * By first adding the chardev, and then adding the device,
1282          * we get a device node entry in sysfs under
1283          * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1284          * coldplug of device nodes and other udev business.
1285          * We can do this only if gpiolib has been initialized.
1286          * Otherwise, defer until later.
1287          */
1288         if (gpiolib_initialized) {
1289                 status = gpiochip_setup_dev(gdev);
1290                 if (status)
1291                         goto err_remove_chip;
1292         }
1293         return 0;
1294
1295 err_remove_chip:
1296         acpi_gpiochip_remove(chip);
1297         gpiochip_free_hogs(chip);
1298         of_gpiochip_remove(chip);
1299         gpiochip_irqchip_free_valid_mask(chip);
1300 err_remove_from_list:
1301         spin_lock_irqsave(&gpio_lock, flags);
1302         list_del(&gdev->list);
1303         spin_unlock_irqrestore(&gpio_lock, flags);
1304 err_free_label:
1305         kfree(gdev->label);
1306 err_free_descs:
1307         kfree(gdev->descs);
1308 err_free_ida:
1309         ida_simple_remove(&gpio_ida, gdev->id);
1310 err_free_gdev:
1311         /* failures here can mean systems won't boot... */
1312         pr_err("%s: GPIOs %d..%d (%s) failed to register\n", __func__,
1313                gdev->base, gdev->base + gdev->ngpio - 1,
1314                chip->label ? : "generic");
1315         kfree(gdev);
1316         return status;
1317 }
1318 EXPORT_SYMBOL_GPL(gpiochip_add_data);
1319
1320 /**
1321  * gpiochip_get_data() - get per-subdriver data for the chip
1322  */
1323 void *gpiochip_get_data(struct gpio_chip *chip)
1324 {
1325         return chip->gpiodev->data;
1326 }
1327 EXPORT_SYMBOL_GPL(gpiochip_get_data);
1328
1329 /**
1330  * gpiochip_remove() - unregister a gpio_chip
1331  * @chip: the chip to unregister
1332  *
1333  * A gpio_chip with any GPIOs still requested may not be removed.
1334  */
1335 void gpiochip_remove(struct gpio_chip *chip)
1336 {
1337         struct gpio_device *gdev = chip->gpiodev;
1338         struct gpio_desc *desc;
1339         unsigned long   flags;
1340         unsigned        i;
1341         bool            requested = false;
1342
1343         /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1344         gpiochip_sysfs_unregister(gdev);
1345         gpiochip_free_hogs(chip);
1346         /* Numb the device, cancelling all outstanding operations */
1347         gdev->chip = NULL;
1348         gpiochip_irqchip_remove(chip);
1349         acpi_gpiochip_remove(chip);
1350         gpiochip_remove_pin_ranges(chip);
1351         of_gpiochip_remove(chip);
1352         /*
1353          * We accept no more calls into the driver from this point, so
1354          * NULL the driver data pointer
1355          */
1356         gdev->data = NULL;
1357
1358         spin_lock_irqsave(&gpio_lock, flags);
1359         for (i = 0; i < gdev->ngpio; i++) {
1360                 desc = &gdev->descs[i];
1361                 if (test_bit(FLAG_REQUESTED, &desc->flags))
1362                         requested = true;
1363         }
1364         spin_unlock_irqrestore(&gpio_lock, flags);
1365
1366         if (requested)
1367                 dev_crit(&gdev->dev,
1368                          "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
1369
1370         /*
1371          * The gpiochip side puts its use of the device to rest here:
1372          * if there are no userspace clients, the chardev and device will
1373          * be removed, else it will be dangling until the last user is
1374          * gone.
1375          */
1376         cdev_del(&gdev->chrdev);
1377         device_del(&gdev->dev);
1378         put_device(&gdev->dev);
1379 }
1380 EXPORT_SYMBOL_GPL(gpiochip_remove);
1381
1382 static void devm_gpio_chip_release(struct device *dev, void *res)
1383 {
1384         struct gpio_chip *chip = *(struct gpio_chip **)res;
1385
1386         gpiochip_remove(chip);
1387 }
1388
1389 static int devm_gpio_chip_match(struct device *dev, void *res, void *data)
1390
1391 {
1392         struct gpio_chip **r = res;
1393
1394         if (!r || !*r) {
1395                 WARN_ON(!r || !*r);
1396                 return 0;
1397         }
1398
1399         return *r == data;
1400 }
1401
1402 /**
1403  * devm_gpiochip_add_data() - Resource manager piochip_add_data()
1404  * @dev: the device pointer on which irq_chip belongs to.
1405  * @chip: the chip to register, with chip->base initialized
1406  * Context: potentially before irqs will work
1407  *
1408  * Returns a negative errno if the chip can't be registered, such as
1409  * because the chip->base is invalid or already associated with a
1410  * different chip.  Otherwise it returns zero as a success code.
1411  *
1412  * The gpio chip automatically be released when the device is unbound.
1413  */
1414 int devm_gpiochip_add_data(struct device *dev, struct gpio_chip *chip,
1415                            void *data)
1416 {
1417         struct gpio_chip **ptr;
1418         int ret;
1419
1420         ptr = devres_alloc(devm_gpio_chip_release, sizeof(*ptr),
1421                              GFP_KERNEL);
1422         if (!ptr)
1423                 return -ENOMEM;
1424
1425         ret = gpiochip_add_data(chip, data);
1426         if (ret < 0) {
1427                 devres_free(ptr);
1428                 return ret;
1429         }
1430
1431         *ptr = chip;
1432         devres_add(dev, ptr);
1433
1434         return 0;
1435 }
1436 EXPORT_SYMBOL_GPL(devm_gpiochip_add_data);
1437
1438 /**
1439  * devm_gpiochip_remove() - Resource manager of gpiochip_remove()
1440  * @dev: device for which which resource was allocated
1441  * @chip: the chip to remove
1442  *
1443  * A gpio_chip with any GPIOs still requested may not be removed.
1444  */
1445 void devm_gpiochip_remove(struct device *dev, struct gpio_chip *chip)
1446 {
1447         int ret;
1448
1449         ret = devres_release(dev, devm_gpio_chip_release,
1450                              devm_gpio_chip_match, chip);
1451         if (!ret)
1452                 WARN_ON(ret);
1453 }
1454 EXPORT_SYMBOL_GPL(devm_gpiochip_remove);
1455
1456 /**
1457  * gpiochip_find() - iterator for locating a specific gpio_chip
1458  * @data: data to pass to match function
1459  * @callback: Callback function to check gpio_chip
1460  *
1461  * Similar to bus_find_device.  It returns a reference to a gpio_chip as
1462  * determined by a user supplied @match callback.  The callback should return
1463  * 0 if the device doesn't match and non-zero if it does.  If the callback is
1464  * non-zero, this function will return to the caller and not iterate over any
1465  * more gpio_chips.
1466  */
1467 struct gpio_chip *gpiochip_find(void *data,
1468                                 int (*match)(struct gpio_chip *chip,
1469                                              void *data))
1470 {
1471         struct gpio_device *gdev;
1472         struct gpio_chip *chip = NULL;
1473         unsigned long flags;
1474
1475         spin_lock_irqsave(&gpio_lock, flags);
1476         list_for_each_entry(gdev, &gpio_devices, list)
1477                 if (gdev->chip && match(gdev->chip, data)) {
1478                         chip = gdev->chip;
1479                         break;
1480                 }
1481
1482         spin_unlock_irqrestore(&gpio_lock, flags);
1483
1484         return chip;
1485 }
1486 EXPORT_SYMBOL_GPL(gpiochip_find);
1487
1488 static int gpiochip_match_name(struct gpio_chip *chip, void *data)
1489 {
1490         const char *name = data;
1491
1492         return !strcmp(chip->label, name);
1493 }
1494
1495 static struct gpio_chip *find_chip_by_name(const char *name)
1496 {
1497         return gpiochip_find((void *)name, gpiochip_match_name);
1498 }
1499
1500 #ifdef CONFIG_GPIOLIB_IRQCHIP
1501
1502 /*
1503  * The following is irqchip helper code for gpiochips.
1504  */
1505
1506 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
1507 {
1508         int i;
1509
1510         if (!gpiochip->irq_need_valid_mask)
1511                 return 0;
1512
1513         gpiochip->irq_valid_mask = kcalloc(BITS_TO_LONGS(gpiochip->ngpio),
1514                                            sizeof(long), GFP_KERNEL);
1515         if (!gpiochip->irq_valid_mask)
1516                 return -ENOMEM;
1517
1518         /* Assume by default all GPIOs are valid */
1519         for (i = 0; i < gpiochip->ngpio; i++)
1520                 set_bit(i, gpiochip->irq_valid_mask);
1521
1522         return 0;
1523 }
1524
1525 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1526 {
1527         kfree(gpiochip->irq_valid_mask);
1528         gpiochip->irq_valid_mask = NULL;
1529 }
1530
1531 static bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gpiochip,
1532                                        unsigned int offset)
1533 {
1534         /* No mask means all valid */
1535         if (likely(!gpiochip->irq_valid_mask))
1536                 return true;
1537         return test_bit(offset, gpiochip->irq_valid_mask);
1538 }
1539
1540 /**
1541  * gpiochip_set_chained_irqchip() - sets a chained irqchip to a gpiochip
1542  * @gpiochip: the gpiochip to set the irqchip chain to
1543  * @irqchip: the irqchip to chain to the gpiochip
1544  * @parent_irq: the irq number corresponding to the parent IRQ for this
1545  * chained irqchip
1546  * @parent_handler: the parent interrupt handler for the accumulated IRQ
1547  * coming out of the gpiochip. If the interrupt is nested rather than
1548  * cascaded, pass NULL in this handler argument
1549  */
1550 void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip,
1551                                   struct irq_chip *irqchip,
1552                                   int parent_irq,
1553                                   irq_flow_handler_t parent_handler)
1554 {
1555         unsigned int offset;
1556
1557         if (!gpiochip->irqdomain) {
1558                 chip_err(gpiochip, "called %s before setting up irqchip\n",
1559                          __func__);
1560                 return;
1561         }
1562
1563         if (parent_handler) {
1564                 if (gpiochip->can_sleep) {
1565                         chip_err(gpiochip,
1566                                  "you cannot have chained interrupts on a "
1567                                  "chip that may sleep\n");
1568                         return;
1569                 }
1570                 /*
1571                  * The parent irqchip is already using the chip_data for this
1572                  * irqchip, so our callbacks simply use the handler_data.
1573                  */
1574                 irq_set_chained_handler_and_data(parent_irq, parent_handler,
1575                                                  gpiochip);
1576
1577                 gpiochip->irq_parent = parent_irq;
1578         }
1579
1580         /* Set the parent IRQ for all affected IRQs */
1581         for (offset = 0; offset < gpiochip->ngpio; offset++) {
1582                 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1583                         continue;
1584                 irq_set_parent(irq_find_mapping(gpiochip->irqdomain, offset),
1585                                parent_irq);
1586         }
1587 }
1588 EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip);
1589
1590 /**
1591  * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
1592  * @d: the irqdomain used by this irqchip
1593  * @irq: the global irq number used by this GPIO irqchip irq
1594  * @hwirq: the local IRQ/GPIO line offset on this gpiochip
1595  *
1596  * This function will set up the mapping for a certain IRQ line on a
1597  * gpiochip by assigning the gpiochip as chip data, and using the irqchip
1598  * stored inside the gpiochip.
1599  */
1600 static int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
1601                             irq_hw_number_t hwirq)
1602 {
1603         struct gpio_chip *chip = d->host_data;
1604
1605         irq_set_chip_data(irq, chip);
1606         /*
1607          * This lock class tells lockdep that GPIO irqs are in a different
1608          * category than their parents, so it won't report false recursion.
1609          */
1610         irq_set_lockdep_class(irq, chip->lock_key);
1611         irq_set_chip_and_handler(irq, chip->irqchip, chip->irq_handler);
1612         /* Chips that can sleep need nested thread handlers */
1613         if (chip->can_sleep && !chip->irq_not_threaded)
1614                 irq_set_nested_thread(irq, 1);
1615         irq_set_noprobe(irq);
1616
1617         /*
1618          * No set-up of the hardware will happen if IRQ_TYPE_NONE
1619          * is passed as default type.
1620          */
1621         if (chip->irq_default_type != IRQ_TYPE_NONE)
1622                 irq_set_irq_type(irq, chip->irq_default_type);
1623
1624         return 0;
1625 }
1626
1627 static void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
1628 {
1629         struct gpio_chip *chip = d->host_data;
1630
1631         if (chip->can_sleep)
1632                 irq_set_nested_thread(irq, 0);
1633         irq_set_chip_and_handler(irq, NULL, NULL);
1634         irq_set_chip_data(irq, NULL);
1635 }
1636
1637 static const struct irq_domain_ops gpiochip_domain_ops = {
1638         .map    = gpiochip_irq_map,
1639         .unmap  = gpiochip_irq_unmap,
1640         /* Virtually all GPIO irqchips are twocell:ed */
1641         .xlate  = irq_domain_xlate_twocell,
1642 };
1643
1644 static int gpiochip_irq_reqres(struct irq_data *d)
1645 {
1646         struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1647
1648         if (!try_module_get(chip->gpiodev->owner))
1649                 return -ENODEV;
1650
1651         if (gpiochip_lock_as_irq(chip, d->hwirq)) {
1652                 chip_err(chip,
1653                         "unable to lock HW IRQ %lu for IRQ\n",
1654                         d->hwirq);
1655                 module_put(chip->gpiodev->owner);
1656                 return -EINVAL;
1657         }
1658         return 0;
1659 }
1660
1661 static void gpiochip_irq_relres(struct irq_data *d)
1662 {
1663         struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1664
1665         gpiochip_unlock_as_irq(chip, d->hwirq);
1666         module_put(chip->gpiodev->owner);
1667 }
1668
1669 static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
1670 {
1671         return irq_find_mapping(chip->irqdomain, offset);
1672 }
1673
1674 /**
1675  * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
1676  * @gpiochip: the gpiochip to remove the irqchip from
1677  *
1678  * This is called only from gpiochip_remove()
1679  */
1680 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
1681 {
1682         unsigned int offset;
1683
1684         acpi_gpiochip_free_interrupts(gpiochip);
1685
1686         if (gpiochip->irq_parent) {
1687                 irq_set_chained_handler(gpiochip->irq_parent, NULL);
1688                 irq_set_handler_data(gpiochip->irq_parent, NULL);
1689         }
1690
1691         /* Remove all IRQ mappings and delete the domain */
1692         if (gpiochip->irqdomain) {
1693                 for (offset = 0; offset < gpiochip->ngpio; offset++) {
1694                         if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1695                                 continue;
1696                         irq_dispose_mapping(
1697                                 irq_find_mapping(gpiochip->irqdomain, offset));
1698                 }
1699                 irq_domain_remove(gpiochip->irqdomain);
1700         }
1701
1702         if (gpiochip->irqchip) {
1703                 gpiochip->irqchip->irq_request_resources = NULL;
1704                 gpiochip->irqchip->irq_release_resources = NULL;
1705                 gpiochip->irqchip = NULL;
1706         }
1707
1708         gpiochip_irqchip_free_valid_mask(gpiochip);
1709 }
1710
1711 /**
1712  * gpiochip_irqchip_add() - adds an irqchip to a gpiochip
1713  * @gpiochip: the gpiochip to add the irqchip to
1714  * @irqchip: the irqchip to add to the gpiochip
1715  * @first_irq: if not dynamically assigned, the base (first) IRQ to
1716  * allocate gpiochip irqs from
1717  * @handler: the irq handler to use (often a predefined irq core function)
1718  * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
1719  * to have the core avoid setting up any default type in the hardware.
1720  * @lock_key: lockdep class
1721  *
1722  * This function closely associates a certain irqchip with a certain
1723  * gpiochip, providing an irq domain to translate the local IRQs to
1724  * global irqs in the gpiolib core, and making sure that the gpiochip
1725  * is passed as chip data to all related functions. Driver callbacks
1726  * need to use gpiochip_get_data() to get their local state containers back
1727  * from the gpiochip passed as chip data. An irqdomain will be stored
1728  * in the gpiochip that shall be used by the driver to handle IRQ number
1729  * translation. The gpiochip will need to be initialized and registered
1730  * before calling this function.
1731  *
1732  * This function will handle two cell:ed simple IRQs and assumes all
1733  * the pins on the gpiochip can generate a unique IRQ. Everything else
1734  * need to be open coded.
1735  */
1736 int _gpiochip_irqchip_add(struct gpio_chip *gpiochip,
1737                           struct irq_chip *irqchip,
1738                           unsigned int first_irq,
1739                           irq_flow_handler_t handler,
1740                           unsigned int type,
1741                           struct lock_class_key *lock_key)
1742 {
1743         struct device_node *of_node;
1744         bool irq_base_set = false;
1745         unsigned int offset;
1746         unsigned irq_base = 0;
1747
1748         if (!gpiochip || !irqchip)
1749                 return -EINVAL;
1750
1751         if (!gpiochip->parent) {
1752                 pr_err("missing gpiochip .dev parent pointer\n");
1753                 return -EINVAL;
1754         }
1755         of_node = gpiochip->parent->of_node;
1756 #ifdef CONFIG_OF_GPIO
1757         /*
1758          * If the gpiochip has an assigned OF node this takes precedence
1759          * FIXME: get rid of this and use gpiochip->parent->of_node
1760          * everywhere
1761          */
1762         if (gpiochip->of_node)
1763                 of_node = gpiochip->of_node;
1764 #endif
1765         /*
1766          * Specifying a default trigger is a terrible idea if DT or ACPI is
1767          * used to configure the interrupts, as you may end-up with
1768          * conflicting triggers. Tell the user, and reset to NONE.
1769          */
1770         if (WARN(of_node && type != IRQ_TYPE_NONE,
1771                  "%s: Ignoring %d default trigger\n", of_node->full_name, type))
1772                 type = IRQ_TYPE_NONE;
1773         if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
1774                 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
1775                                  "Ignoring %d default trigger\n", type);
1776                 type = IRQ_TYPE_NONE;
1777         }
1778
1779         gpiochip->irqchip = irqchip;
1780         gpiochip->irq_handler = handler;
1781         gpiochip->irq_default_type = type;
1782         gpiochip->to_irq = gpiochip_to_irq;
1783         gpiochip->lock_key = lock_key;
1784         gpiochip->irqdomain = irq_domain_add_simple(of_node,
1785                                         gpiochip->ngpio, first_irq,
1786                                         &gpiochip_domain_ops, gpiochip);
1787         if (!gpiochip->irqdomain) {
1788                 gpiochip->irqchip = NULL;
1789                 return -EINVAL;
1790         }
1791
1792         /*
1793          * It is possible for a driver to override this, but only if the
1794          * alternative functions are both implemented.
1795          */
1796         if (!irqchip->irq_request_resources &&
1797             !irqchip->irq_release_resources) {
1798                 irqchip->irq_request_resources = gpiochip_irq_reqres;
1799                 irqchip->irq_release_resources = gpiochip_irq_relres;
1800         }
1801
1802         /*
1803          * Prepare the mapping since the irqchip shall be orthogonal to
1804          * any gpiochip calls. If the first_irq was zero, this is
1805          * necessary to allocate descriptors for all IRQs.
1806          */
1807         for (offset = 0; offset < gpiochip->ngpio; offset++) {
1808                 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1809                         continue;
1810                 irq_base = irq_create_mapping(gpiochip->irqdomain, offset);
1811                 if (!irq_base_set) {
1812                         /*
1813                          * Store the base into the gpiochip to be used when
1814                          * unmapping the irqs.
1815                          */
1816                         gpiochip->irq_base = irq_base;
1817                         irq_base_set = true;
1818                 }
1819         }
1820
1821         acpi_gpiochip_request_interrupts(gpiochip);
1822
1823         return 0;
1824 }
1825 EXPORT_SYMBOL_GPL(_gpiochip_irqchip_add);
1826
1827 #else /* CONFIG_GPIOLIB_IRQCHIP */
1828
1829 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
1830 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
1831 {
1832         return 0;
1833 }
1834 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1835 { }
1836
1837 #endif /* CONFIG_GPIOLIB_IRQCHIP */
1838
1839 /**
1840  * gpiochip_generic_request() - request the gpio function for a pin
1841  * @chip: the gpiochip owning the GPIO
1842  * @offset: the offset of the GPIO to request for GPIO function
1843  */
1844 int gpiochip_generic_request(struct gpio_chip *chip, unsigned offset)
1845 {
1846         return pinctrl_request_gpio(chip->gpiodev->base + offset);
1847 }
1848 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
1849
1850 /**
1851  * gpiochip_generic_free() - free the gpio function from a pin
1852  * @chip: the gpiochip to request the gpio function for
1853  * @offset: the offset of the GPIO to free from GPIO function
1854  */
1855 void gpiochip_generic_free(struct gpio_chip *chip, unsigned offset)
1856 {
1857         pinctrl_free_gpio(chip->gpiodev->base + offset);
1858 }
1859 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
1860
1861 #ifdef CONFIG_PINCTRL
1862
1863 /**
1864  * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
1865  * @chip: the gpiochip to add the range for
1866  * @pctldev: the pin controller to map to
1867  * @gpio_offset: the start offset in the current gpio_chip number space
1868  * @pin_group: name of the pin group inside the pin controller
1869  */
1870 int gpiochip_add_pingroup_range(struct gpio_chip *chip,
1871                         struct pinctrl_dev *pctldev,
1872                         unsigned int gpio_offset, const char *pin_group)
1873 {
1874         struct gpio_pin_range *pin_range;
1875         struct gpio_device *gdev = chip->gpiodev;
1876         int ret;
1877
1878         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1879         if (!pin_range) {
1880                 chip_err(chip, "failed to allocate pin ranges\n");
1881                 return -ENOMEM;
1882         }
1883
1884         /* Use local offset as range ID */
1885         pin_range->range.id = gpio_offset;
1886         pin_range->range.gc = chip;
1887         pin_range->range.name = chip->label;
1888         pin_range->range.base = gdev->base + gpio_offset;
1889         pin_range->pctldev = pctldev;
1890
1891         ret = pinctrl_get_group_pins(pctldev, pin_group,
1892                                         &pin_range->range.pins,
1893                                         &pin_range->range.npins);
1894         if (ret < 0) {
1895                 kfree(pin_range);
1896                 return ret;
1897         }
1898
1899         pinctrl_add_gpio_range(pctldev, &pin_range->range);
1900
1901         chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
1902                  gpio_offset, gpio_offset + pin_range->range.npins - 1,
1903                  pinctrl_dev_get_devname(pctldev), pin_group);
1904
1905         list_add_tail(&pin_range->node, &gdev->pin_ranges);
1906
1907         return 0;
1908 }
1909 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
1910
1911 /**
1912  * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
1913  * @chip: the gpiochip to add the range for
1914  * @pinctrl_name: the dev_name() of the pin controller to map to
1915  * @gpio_offset: the start offset in the current gpio_chip number space
1916  * @pin_offset: the start offset in the pin controller number space
1917  * @npins: the number of pins from the offset of each pin space (GPIO and
1918  *      pin controller) to accumulate in this range
1919  */
1920 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
1921                            unsigned int gpio_offset, unsigned int pin_offset,
1922                            unsigned int npins)
1923 {
1924         struct gpio_pin_range *pin_range;
1925         struct gpio_device *gdev = chip->gpiodev;
1926         int ret;
1927
1928         pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1929         if (!pin_range) {
1930                 chip_err(chip, "failed to allocate pin ranges\n");
1931                 return -ENOMEM;
1932         }
1933
1934         /* Use local offset as range ID */
1935         pin_range->range.id = gpio_offset;
1936         pin_range->range.gc = chip;
1937         pin_range->range.name = chip->label;
1938         pin_range->range.base = gdev->base + gpio_offset;
1939         pin_range->range.pin_base = pin_offset;
1940         pin_range->range.npins = npins;
1941         pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
1942                         &pin_range->range);
1943         if (IS_ERR(pin_range->pctldev)) {
1944                 ret = PTR_ERR(pin_range->pctldev);
1945                 chip_err(chip, "could not create pin range\n");
1946                 kfree(pin_range);
1947                 return ret;
1948         }
1949         chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
1950                  gpio_offset, gpio_offset + npins - 1,
1951                  pinctl_name,
1952                  pin_offset, pin_offset + npins - 1);
1953
1954         list_add_tail(&pin_range->node, &gdev->pin_ranges);
1955
1956         return 0;
1957 }
1958 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
1959
1960 /**
1961  * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
1962  * @chip: the chip to remove all the mappings for
1963  */
1964 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
1965 {
1966         struct gpio_pin_range *pin_range, *tmp;
1967         struct gpio_device *gdev = chip->gpiodev;
1968
1969         list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
1970                 list_del(&pin_range->node);
1971                 pinctrl_remove_gpio_range(pin_range->pctldev,
1972                                 &pin_range->range);
1973                 kfree(pin_range);
1974         }
1975 }
1976 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
1977
1978 #endif /* CONFIG_PINCTRL */
1979
1980 /* These "optional" allocation calls help prevent drivers from stomping
1981  * on each other, and help provide better diagnostics in debugfs.
1982  * They're called even less than the "set direction" calls.
1983  */
1984 static int __gpiod_request(struct gpio_desc *desc, const char *label)
1985 {
1986         struct gpio_chip        *chip = desc->gdev->chip;
1987         int                     status;
1988         unsigned long           flags;
1989
1990         spin_lock_irqsave(&gpio_lock, flags);
1991
1992         /* NOTE:  gpio_request() can be called in early boot,
1993          * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
1994          */
1995
1996         if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
1997                 desc_set_label(desc, label ? : "?");
1998                 status = 0;
1999         } else {
2000                 status = -EBUSY;
2001                 goto done;
2002         }
2003
2004         if (chip->request) {
2005                 /* chip->request may sleep */
2006                 spin_unlock_irqrestore(&gpio_lock, flags);
2007                 status = chip->request(chip, gpio_chip_hwgpio(desc));
2008                 spin_lock_irqsave(&gpio_lock, flags);
2009
2010                 if (status < 0) {
2011                         desc_set_label(desc, NULL);
2012                         clear_bit(FLAG_REQUESTED, &desc->flags);
2013                         goto done;
2014                 }
2015         }
2016         if (chip->get_direction) {
2017                 /* chip->get_direction may sleep */
2018                 spin_unlock_irqrestore(&gpio_lock, flags);
2019                 gpiod_get_direction(desc);
2020                 spin_lock_irqsave(&gpio_lock, flags);
2021         }
2022 done:
2023         spin_unlock_irqrestore(&gpio_lock, flags);
2024         return status;
2025 }
2026
2027 /*
2028  * This descriptor validation needs to be inserted verbatim into each
2029  * function taking a descriptor, so we need to use a preprocessor
2030  * macro to avoid endless duplication. If the desc is NULL it is an
2031  * optional GPIO and calls should just bail out.
2032  */
2033 #define VALIDATE_DESC(desc) do { \
2034         if (!desc) \
2035                 return 0; \
2036         if (IS_ERR(desc)) {                                             \
2037                 pr_warn("%s: invalid GPIO (errorpointer)\n", __func__); \
2038                 return PTR_ERR(desc); \
2039         } \
2040         if (!desc->gdev) { \
2041                 pr_warn("%s: invalid GPIO (no device)\n", __func__); \
2042                 return -EINVAL; \
2043         } \
2044         if ( !desc->gdev->chip ) { \
2045                 dev_warn(&desc->gdev->dev, \
2046                          "%s: backing chip is gone\n", __func__); \
2047                 return 0; \
2048         } } while (0)
2049
2050 #define VALIDATE_DESC_VOID(desc) do { \
2051         if (!desc) \
2052                 return; \
2053         if (IS_ERR(desc)) {                                             \
2054                 pr_warn("%s: invalid GPIO (errorpointer)\n", __func__); \
2055                 return; \
2056         } \
2057         if (!desc->gdev) { \
2058                 pr_warn("%s: invalid GPIO (no device)\n", __func__); \
2059                 return; \
2060         } \
2061         if (!desc->gdev->chip) { \
2062                 dev_warn(&desc->gdev->dev, \
2063                          "%s: backing chip is gone\n", __func__); \
2064                 return; \
2065         } } while (0)
2066
2067
2068 int gpiod_request(struct gpio_desc *desc, const char *label)
2069 {
2070         int status = -EPROBE_DEFER;
2071         struct gpio_device *gdev;
2072
2073         VALIDATE_DESC(desc);
2074         gdev = desc->gdev;
2075
2076         if (try_module_get(gdev->owner)) {
2077                 status = __gpiod_request(desc, label);
2078                 if (status < 0)
2079                         module_put(gdev->owner);
2080                 else
2081                         get_device(&gdev->dev);
2082         }
2083
2084         if (status)
2085                 gpiod_dbg(desc, "%s: status %d\n", __func__, status);
2086
2087         return status;
2088 }
2089
2090 static bool __gpiod_free(struct gpio_desc *desc)
2091 {
2092         bool                    ret = false;
2093         unsigned long           flags;
2094         struct gpio_chip        *chip;
2095
2096         might_sleep();
2097
2098         gpiod_unexport(desc);
2099
2100         spin_lock_irqsave(&gpio_lock, flags);
2101
2102         chip = desc->gdev->chip;
2103         if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
2104                 if (chip->free) {
2105                         spin_unlock_irqrestore(&gpio_lock, flags);
2106                         might_sleep_if(chip->can_sleep);
2107                         chip->free(chip, gpio_chip_hwgpio(desc));
2108                         spin_lock_irqsave(&gpio_lock, flags);
2109                 }
2110                 desc_set_label(desc, NULL);
2111                 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
2112                 clear_bit(FLAG_REQUESTED, &desc->flags);
2113                 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
2114                 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
2115                 clear_bit(FLAG_IS_HOGGED, &desc->flags);
2116                 ret = true;
2117         }
2118
2119         spin_unlock_irqrestore(&gpio_lock, flags);
2120         return ret;
2121 }
2122
2123 void gpiod_free(struct gpio_desc *desc)
2124 {
2125         if (desc && desc->gdev && __gpiod_free(desc)) {
2126                 module_put(desc->gdev->owner);
2127                 put_device(&desc->gdev->dev);
2128         } else {
2129                 WARN_ON(extra_checks);
2130         }
2131 }
2132
2133 /**
2134  * gpiochip_is_requested - return string iff signal was requested
2135  * @chip: controller managing the signal
2136  * @offset: of signal within controller's 0..(ngpio - 1) range
2137  *
2138  * Returns NULL if the GPIO is not currently requested, else a string.
2139  * The string returned is the label passed to gpio_request(); if none has been
2140  * passed it is a meaningless, non-NULL constant.
2141  *
2142  * This function is for use by GPIO controller drivers.  The label can
2143  * help with diagnostics, and knowing that the signal is used as a GPIO
2144  * can help avoid accidentally multiplexing it to another controller.
2145  */
2146 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
2147 {
2148         struct gpio_desc *desc;
2149
2150         if (offset >= chip->ngpio)
2151                 return NULL;
2152
2153         desc = &chip->gpiodev->descs[offset];
2154
2155         if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
2156                 return NULL;
2157         return desc->label;
2158 }
2159 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
2160
2161 /**
2162  * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2163  * @desc: GPIO descriptor to request
2164  * @label: label for the GPIO
2165  *
2166  * Function allows GPIO chip drivers to request and use their own GPIO
2167  * descriptors via gpiolib API. Difference to gpiod_request() is that this
2168  * function will not increase reference count of the GPIO chip module. This
2169  * allows the GPIO chip module to be unloaded as needed (we assume that the
2170  * GPIO chip driver handles freeing the GPIOs it has requested).
2171  */
2172 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *chip, u16 hwnum,
2173                                             const char *label)
2174 {
2175         struct gpio_desc *desc = gpiochip_get_desc(chip, hwnum);
2176         int err;
2177
2178         if (IS_ERR(desc)) {
2179                 chip_err(chip, "failed to get GPIO descriptor\n");
2180                 return desc;
2181         }
2182
2183         err = __gpiod_request(desc, label);
2184         if (err < 0)
2185                 return ERR_PTR(err);
2186
2187         return desc;
2188 }
2189 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
2190
2191 /**
2192  * gpiochip_free_own_desc - Free GPIO requested by the chip driver
2193  * @desc: GPIO descriptor to free
2194  *
2195  * Function frees the given GPIO requested previously with
2196  * gpiochip_request_own_desc().
2197  */
2198 void gpiochip_free_own_desc(struct gpio_desc *desc)
2199 {
2200         if (desc)
2201                 __gpiod_free(desc);
2202 }
2203 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
2204
2205 /*
2206  * Drivers MUST set GPIO direction before making get/set calls.  In
2207  * some cases this is done in early boot, before IRQs are enabled.
2208  *
2209  * As a rule these aren't called more than once (except for drivers
2210  * using the open-drain emulation idiom) so these are natural places
2211  * to accumulate extra debugging checks.  Note that we can't (yet)
2212  * rely on gpio_request() having been called beforehand.
2213  */
2214
2215 /**
2216  * gpiod_direction_input - set the GPIO direction to input
2217  * @desc:       GPIO to set to input
2218  *
2219  * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2220  * be called safely on it.
2221  *
2222  * Return 0 in case of success, else an error code.
2223  */
2224 int gpiod_direction_input(struct gpio_desc *desc)
2225 {
2226         struct gpio_chip        *chip;
2227         int                     status = -EINVAL;
2228
2229         VALIDATE_DESC(desc);
2230         chip = desc->gdev->chip;
2231
2232         if (!chip->get || !chip->direction_input) {
2233                 gpiod_warn(desc,
2234                         "%s: missing get() or direction_input() operations\n",
2235                         __func__);
2236                 return -EIO;
2237         }
2238
2239         status = chip->direction_input(chip, gpio_chip_hwgpio(desc));
2240         if (status == 0)
2241                 clear_bit(FLAG_IS_OUT, &desc->flags);
2242
2243         trace_gpio_direction(desc_to_gpio(desc), 1, status);
2244
2245         return status;
2246 }
2247 EXPORT_SYMBOL_GPL(gpiod_direction_input);
2248
2249 static int _gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2250 {
2251         struct gpio_chip *gc = desc->gdev->chip;
2252         int ret;
2253
2254         /* GPIOs used for IRQs shall not be set as output */
2255         if (test_bit(FLAG_USED_AS_IRQ, &desc->flags)) {
2256                 gpiod_err(desc,
2257                           "%s: tried to set a GPIO tied to an IRQ as output\n",
2258                           __func__);
2259                 return -EIO;
2260         }
2261
2262         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
2263                 /* First see if we can enable open drain in hardware */
2264                 if (gc->set_single_ended) {
2265                         ret = gc->set_single_ended(gc, gpio_chip_hwgpio(desc),
2266                                                    LINE_MODE_OPEN_DRAIN);
2267                         if (!ret)
2268                                 goto set_output_value;
2269                 }
2270                 /* Emulate open drain by not actively driving the line high */
2271                 if (value)
2272                         return gpiod_direction_input(desc);
2273         }
2274         else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
2275                 if (gc->set_single_ended) {
2276                         ret = gc->set_single_ended(gc, gpio_chip_hwgpio(desc),
2277                                                    LINE_MODE_OPEN_SOURCE);
2278                         if (!ret)
2279                                 goto set_output_value;
2280                 }
2281                 /* Emulate open source by not actively driving the line low */
2282                 if (!value)
2283                         return gpiod_direction_input(desc);
2284         } else {
2285                 /* Make sure to disable open drain/source hardware, if any */
2286                 if (gc->set_single_ended)
2287                         gc->set_single_ended(gc,
2288                                              gpio_chip_hwgpio(desc),
2289                                              LINE_MODE_PUSH_PULL);
2290         }
2291
2292 set_output_value:
2293         if (!gc->set || !gc->direction_output) {
2294                 gpiod_warn(desc,
2295                        "%s: missing set() or direction_output() operations\n",
2296                        __func__);
2297                 return -EIO;
2298         }
2299
2300         ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), value);
2301         if (!ret)
2302                 set_bit(FLAG_IS_OUT, &desc->flags);
2303         trace_gpio_value(desc_to_gpio(desc), 0, value);
2304         trace_gpio_direction(desc_to_gpio(desc), 0, ret);
2305         return ret;
2306 }
2307
2308 /**
2309  * gpiod_direction_output_raw - set the GPIO direction to output
2310  * @desc:       GPIO to set to output
2311  * @value:      initial output value of the GPIO
2312  *
2313  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2314  * be called safely on it. The initial value of the output must be specified
2315  * as raw value on the physical line without regard for the ACTIVE_LOW status.
2316  *
2317  * Return 0 in case of success, else an error code.
2318  */
2319 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2320 {
2321         VALIDATE_DESC(desc);
2322         return _gpiod_direction_output_raw(desc, value);
2323 }
2324 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
2325
2326 /**
2327  * gpiod_direction_output - set the GPIO direction to output
2328  * @desc:       GPIO to set to output
2329  * @value:      initial output value of the GPIO
2330  *
2331  * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2332  * be called safely on it. The initial value of the output must be specified
2333  * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2334  * account.
2335  *
2336  * Return 0 in case of success, else an error code.
2337  */
2338 int gpiod_direction_output(struct gpio_desc *desc, int value)
2339 {
2340         VALIDATE_DESC(desc);
2341         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2342                 value = !value;
2343         return _gpiod_direction_output_raw(desc, value);
2344 }
2345 EXPORT_SYMBOL_GPL(gpiod_direction_output);
2346
2347 /**
2348  * gpiod_set_debounce - sets @debounce time for a @gpio
2349  * @gpio: the gpio to set debounce time
2350  * @debounce: debounce time is microseconds
2351  *
2352  * returns -ENOTSUPP if the controller does not support setting
2353  * debounce.
2354  */
2355 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
2356 {
2357         struct gpio_chip        *chip;
2358
2359         VALIDATE_DESC(desc);
2360         chip = desc->gdev->chip;
2361         if (!chip->set || !chip->set_debounce) {
2362                 gpiod_dbg(desc,
2363                           "%s: missing set() or set_debounce() operations\n",
2364                           __func__);
2365                 return -ENOTSUPP;
2366         }
2367
2368         return chip->set_debounce(chip, gpio_chip_hwgpio(desc), debounce);
2369 }
2370 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
2371
2372 /**
2373  * gpiod_is_active_low - test whether a GPIO is active-low or not
2374  * @desc: the gpio descriptor to test
2375  *
2376  * Returns 1 if the GPIO is active-low, 0 otherwise.
2377  */
2378 int gpiod_is_active_low(const struct gpio_desc *desc)
2379 {
2380         VALIDATE_DESC(desc);
2381         return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
2382 }
2383 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
2384
2385 /* I/O calls are only valid after configuration completed; the relevant
2386  * "is this a valid GPIO" error checks should already have been done.
2387  *
2388  * "Get" operations are often inlinable as reading a pin value register,
2389  * and masking the relevant bit in that register.
2390  *
2391  * When "set" operations are inlinable, they involve writing that mask to
2392  * one register to set a low value, or a different register to set it high.
2393  * Otherwise locking is needed, so there may be little value to inlining.
2394  *
2395  *------------------------------------------------------------------------
2396  *
2397  * IMPORTANT!!!  The hot paths -- get/set value -- assume that callers
2398  * have requested the GPIO.  That can include implicit requesting by
2399  * a direction setting call.  Marking a gpio as requested locks its chip
2400  * in memory, guaranteeing that these table lookups need no more locking
2401  * and that gpiochip_remove() will fail.
2402  *
2403  * REVISIT when debugging, consider adding some instrumentation to ensure
2404  * that the GPIO was actually requested.
2405  */
2406
2407 static int _gpiod_get_raw_value(const struct gpio_desc *desc)
2408 {
2409         struct gpio_chip        *chip;
2410         int offset;
2411         int value;
2412
2413         chip = desc->gdev->chip;
2414         offset = gpio_chip_hwgpio(desc);
2415         value = chip->get ? chip->get(chip, offset) : -EIO;
2416         value = value < 0 ? value : !!value;
2417         trace_gpio_value(desc_to_gpio(desc), 1, value);
2418         return value;
2419 }
2420
2421 /**
2422  * gpiod_get_raw_value() - return a gpio's raw value
2423  * @desc: gpio whose value will be returned
2424  *
2425  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2426  * its ACTIVE_LOW status, or negative errno on failure.
2427  *
2428  * This function should be called from contexts where we cannot sleep, and will
2429  * complain if the GPIO chip functions potentially sleep.
2430  */
2431 int gpiod_get_raw_value(const struct gpio_desc *desc)
2432 {
2433         VALIDATE_DESC(desc);
2434         /* Should be using gpiod_get_raw_value_cansleep() */
2435         WARN_ON(desc->gdev->chip->can_sleep);
2436         return _gpiod_get_raw_value(desc);
2437 }
2438 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
2439
2440 /**
2441  * gpiod_get_value() - return a gpio's value
2442  * @desc: gpio whose value will be returned
2443  *
2444  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2445  * account, or negative errno on failure.
2446  *
2447  * This function should be called from contexts where we cannot sleep, and will
2448  * complain if the GPIO chip functions potentially sleep.
2449  */
2450 int gpiod_get_value(const struct gpio_desc *desc)
2451 {
2452         int value;
2453
2454         VALIDATE_DESC(desc);
2455         /* Should be using gpiod_get_value_cansleep() */
2456         WARN_ON(desc->gdev->chip->can_sleep);
2457
2458         value = _gpiod_get_raw_value(desc);
2459         if (value < 0)
2460                 return value;
2461
2462         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2463                 value = !value;
2464
2465         return value;
2466 }
2467 EXPORT_SYMBOL_GPL(gpiod_get_value);
2468
2469 /*
2470  *  _gpio_set_open_drain_value() - Set the open drain gpio's value.
2471  * @desc: gpio descriptor whose state need to be set.
2472  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2473  */
2474 static void _gpio_set_open_drain_value(struct gpio_desc *desc, bool value)
2475 {
2476         int err = 0;
2477         struct gpio_chip *chip = desc->gdev->chip;
2478         int offset = gpio_chip_hwgpio(desc);
2479
2480         if (value) {
2481                 err = chip->direction_input(chip, offset);
2482                 if (!err)
2483                         clear_bit(FLAG_IS_OUT, &desc->flags);
2484         } else {
2485                 err = chip->direction_output(chip, offset, 0);
2486                 if (!err)
2487                         set_bit(FLAG_IS_OUT, &desc->flags);
2488         }
2489         trace_gpio_direction(desc_to_gpio(desc), value, err);
2490         if (err < 0)
2491                 gpiod_err(desc,
2492                           "%s: Error in set_value for open drain err %d\n",
2493                           __func__, err);
2494 }
2495
2496 /*
2497  *  _gpio_set_open_source_value() - Set the open source gpio's value.
2498  * @desc: gpio descriptor whose state need to be set.
2499  * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2500  */
2501 static void _gpio_set_open_source_value(struct gpio_desc *desc, bool value)
2502 {
2503         int err = 0;
2504         struct gpio_chip *chip = desc->gdev->chip;
2505         int offset = gpio_chip_hwgpio(desc);
2506
2507         if (value) {
2508                 err = chip->direction_output(chip, offset, 1);
2509                 if (!err)
2510                         set_bit(FLAG_IS_OUT, &desc->flags);
2511         } else {
2512                 err = chip->direction_input(chip, offset);
2513                 if (!err)
2514                         clear_bit(FLAG_IS_OUT, &desc->flags);
2515         }
2516         trace_gpio_direction(desc_to_gpio(desc), !value, err);
2517         if (err < 0)
2518                 gpiod_err(desc,
2519                           "%s: Error in set_value for open source err %d\n",
2520                           __func__, err);
2521 }
2522
2523 static void _gpiod_set_raw_value(struct gpio_desc *desc, bool value)
2524 {
2525         struct gpio_chip        *chip;
2526
2527         chip = desc->gdev->chip;
2528         trace_gpio_value(desc_to_gpio(desc), 0, value);
2529         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2530                 _gpio_set_open_drain_value(desc, value);
2531         else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2532                 _gpio_set_open_source_value(desc, value);
2533         else
2534                 chip->set(chip, gpio_chip_hwgpio(desc), value);
2535 }
2536
2537 #ifdef CONFIG_AMLOGIC_PINCTRL
2538 static int _gpiod_set_pull(struct gpio_desc *desc, int value)
2539 {
2540         struct gpio_chip *chip;
2541         int status = -EINVAL;
2542
2543         chip = desc->gdev->chip;
2544         if (!chip || !chip->set_pull) {
2545                 gpiod_warn(desc,
2546                         "%s: missing set_pull() operations\n",
2547                         __func__);
2548                 return -EIO;
2549         }
2550         if (test_bit(FLAG_REQUESTED, &desc->flags))
2551                 status = chip->set_pull(chip, gpio_chip_hwgpio(desc), value);
2552
2553         return status;
2554 }
2555 #endif
2556
2557 /*
2558  * set multiple outputs on the same chip;
2559  * use the chip's set_multiple function if available;
2560  * otherwise set the outputs sequentially;
2561  * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
2562  *        defines which outputs are to be changed
2563  * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
2564  *        defines the values the outputs specified by mask are to be set to
2565  */
2566 static void gpio_chip_set_multiple(struct gpio_chip *chip,
2567                                    unsigned long *mask, unsigned long *bits)
2568 {
2569         if (chip->set_multiple) {
2570                 chip->set_multiple(chip, mask, bits);
2571         } else {
2572                 int i;
2573                 for (i = 0; i < chip->ngpio; i++) {
2574                         if (mask[BIT_WORD(i)] == 0) {
2575                                 /* no more set bits in this mask word;
2576                                  * skip ahead to the next word */
2577                                 i = (BIT_WORD(i) + 1) * BITS_PER_LONG - 1;
2578                                 continue;
2579                         }
2580                         /* set outputs if the corresponding mask bit is set */
2581                         if (__test_and_clear_bit(i, mask))
2582                                 chip->set(chip, i, test_bit(i, bits));
2583                 }
2584         }
2585 }
2586
2587 void gpiod_set_array_value_complex(bool raw, bool can_sleep,
2588                                    unsigned int array_size,
2589                                    struct gpio_desc **desc_array,
2590                                    int *value_array)
2591 {
2592         int i = 0;
2593
2594         while (i < array_size) {
2595                 struct gpio_chip *chip = desc_array[i]->gdev->chip;
2596                 unsigned long mask[BITS_TO_LONGS(chip->ngpio)];
2597                 unsigned long bits[BITS_TO_LONGS(chip->ngpio)];
2598                 int count = 0;
2599
2600                 if (!can_sleep)
2601                         WARN_ON(chip->can_sleep);
2602
2603                 memset(mask, 0, sizeof(mask));
2604                 do {
2605                         struct gpio_desc *desc = desc_array[i];
2606                         int hwgpio = gpio_chip_hwgpio(desc);
2607                         int value = value_array[i];
2608
2609                         if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2610                                 value = !value;
2611                         trace_gpio_value(desc_to_gpio(desc), 0, value);
2612                         /*
2613                          * collect all normal outputs belonging to the same chip
2614                          * open drain and open source outputs are set individually
2615                          */
2616                         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
2617                                 _gpio_set_open_drain_value(desc, value);
2618                         } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
2619                                 _gpio_set_open_source_value(desc, value);
2620                         } else {
2621                                 __set_bit(hwgpio, mask);
2622                                 if (value)
2623                                         __set_bit(hwgpio, bits);
2624                                 else
2625                                         __clear_bit(hwgpio, bits);
2626                                 count++;
2627                         }
2628                         i++;
2629                 } while ((i < array_size) &&
2630                          (desc_array[i]->gdev->chip == chip));
2631                 /* push collected bits to outputs */
2632                 if (count != 0)
2633                         gpio_chip_set_multiple(chip, mask, bits);
2634         }
2635 }
2636
2637 /**
2638  * gpiod_set_raw_value() - assign a gpio's raw value
2639  * @desc: gpio whose value will be assigned
2640  * @value: value to assign
2641  *
2642  * Set the raw value of the GPIO, i.e. the value of its physical line without
2643  * regard for its ACTIVE_LOW status.
2644  *
2645  * This function should be called from contexts where we cannot sleep, and will
2646  * complain if the GPIO chip functions potentially sleep.
2647  */
2648 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
2649 {
2650         VALIDATE_DESC_VOID(desc);
2651         /* Should be using gpiod_set_raw_value_cansleep() */
2652         WARN_ON(desc->gdev->chip->can_sleep);
2653         _gpiod_set_raw_value(desc, value);
2654 }
2655 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
2656
2657 /**
2658  * gpiod_set_value() - assign a gpio's value
2659  * @desc: gpio whose value will be assigned
2660  * @value: value to assign
2661  *
2662  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2663  * account
2664  *
2665  * This function should be called from contexts where we cannot sleep, and will
2666  * complain if the GPIO chip functions potentially sleep.
2667  */
2668 void gpiod_set_value(struct gpio_desc *desc, int value)
2669 {
2670         VALIDATE_DESC_VOID(desc);
2671         /* Should be using gpiod_set_value_cansleep() */
2672         WARN_ON(desc->gdev->chip->can_sleep);
2673         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2674                 value = !value;
2675         _gpiod_set_raw_value(desc, value);
2676 }
2677 EXPORT_SYMBOL_GPL(gpiod_set_value);
2678
2679 /**
2680  * gpiod_set_pull() - enable pull-down/up for the gpio, or disable.
2681  * @desc: gpio whose value will be set
2682  * @value: value to set
2683  *
2684  * This function should be called from contexts where we cannot sleep, and will
2685  * complain if the GPIO chip functions potentially sleep.
2686  */
2687 #ifdef CONFIG_AMLOGIC_PINCTRL
2688 int gpiod_set_pull(struct gpio_desc *desc, int value)
2689 {
2690         VALIDATE_DESC(desc);
2691         /* Should be using gpiod_set_pull_cansleep() */
2692         WARN_ON(desc->gdev->chip->can_sleep);
2693         return _gpiod_set_pull(desc, value);
2694 }
2695 EXPORT_SYMBOL_GPL(gpiod_set_pull);
2696 #endif
2697
2698 /**
2699  * gpiod_set_raw_array_value() - assign values to an array of GPIOs
2700  * @array_size: number of elements in the descriptor / value arrays
2701  * @desc_array: array of GPIO descriptors whose values will be assigned
2702  * @value_array: array of values to assign
2703  *
2704  * Set the raw values of the GPIOs, i.e. the values of the physical lines
2705  * without regard for their ACTIVE_LOW status.
2706  *
2707  * This function should be called from contexts where we cannot sleep, and will
2708  * complain if the GPIO chip functions potentially sleep.
2709  */
2710 void gpiod_set_raw_array_value(unsigned int array_size,
2711                          struct gpio_desc **desc_array, int *value_array)
2712 {
2713         if (!desc_array)
2714                 return;
2715         gpiod_set_array_value_complex(true, false, array_size, desc_array,
2716                                       value_array);
2717 }
2718 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
2719
2720 /**
2721  * gpiod_set_array_value() - assign values to an array of GPIOs
2722  * @array_size: number of elements in the descriptor / value arrays
2723  * @desc_array: array of GPIO descriptors whose values will be assigned
2724  * @value_array: array of values to assign
2725  *
2726  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
2727  * into account.
2728  *
2729  * This function should be called from contexts where we cannot sleep, and will
2730  * complain if the GPIO chip functions potentially sleep.
2731  */
2732 void gpiod_set_array_value(unsigned int array_size,
2733                            struct gpio_desc **desc_array, int *value_array)
2734 {
2735         if (!desc_array)
2736                 return;
2737         gpiod_set_array_value_complex(false, false, array_size, desc_array,
2738                                       value_array);
2739 }
2740 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
2741
2742 /**
2743  * gpiod_cansleep() - report whether gpio value access may sleep
2744  * @desc: gpio to check
2745  *
2746  */
2747 int gpiod_cansleep(const struct gpio_desc *desc)
2748 {
2749         VALIDATE_DESC(desc);
2750         return desc->gdev->chip->can_sleep;
2751 }
2752 EXPORT_SYMBOL_GPL(gpiod_cansleep);
2753
2754 /**
2755  * gpiod_to_irq() - return the IRQ corresponding to a GPIO
2756  * @desc: gpio whose IRQ will be returned (already requested)
2757  *
2758  * Return the IRQ corresponding to the passed GPIO, or an error code in case of
2759  * error.
2760  */
2761 int gpiod_to_irq(const struct gpio_desc *desc)
2762 {
2763         struct gpio_chip *chip;
2764         int offset;
2765
2766         /*
2767          * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
2768          * requires this function to not return zero on an invalid descriptor
2769          * but rather a negative error number.
2770          */
2771         if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
2772                 return -EINVAL;
2773
2774         chip = desc->gdev->chip;
2775         offset = gpio_chip_hwgpio(desc);
2776         if (chip->to_irq) {
2777                 int retirq = chip->to_irq(chip, offset);
2778
2779                 /* Zero means NO_IRQ */
2780                 if (!retirq)
2781                         return -ENXIO;
2782
2783                 return retirq;
2784         }
2785         return -ENXIO;
2786 }
2787 EXPORT_SYMBOL_GPL(gpiod_to_irq);
2788
2789 /**
2790  * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
2791  * @chip: the chip the GPIO to lock belongs to
2792  * @offset: the offset of the GPIO to lock as IRQ
2793  *
2794  * This is used directly by GPIO drivers that want to lock down
2795  * a certain GPIO line to be used for IRQs.
2796  */
2797 int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
2798 {
2799         struct gpio_desc *desc;
2800
2801         desc = gpiochip_get_desc(chip, offset);
2802         if (IS_ERR(desc))
2803                 return PTR_ERR(desc);
2804
2805         /*
2806          * If it's fast: flush the direction setting if something changed
2807          * behind our back
2808          */
2809         if (!chip->can_sleep && chip->get_direction) {
2810                 int dir = chip->get_direction(chip, offset);
2811
2812                 if (dir)
2813                         clear_bit(FLAG_IS_OUT, &desc->flags);
2814                 else
2815                         set_bit(FLAG_IS_OUT, &desc->flags);
2816         }
2817
2818         if (test_bit(FLAG_IS_OUT, &desc->flags)) {
2819                 chip_err(chip,
2820                           "%s: tried to flag a GPIO set as output for IRQ\n",
2821                           __func__);
2822                 return -EIO;
2823         }
2824
2825         set_bit(FLAG_USED_AS_IRQ, &desc->flags);
2826         return 0;
2827 }
2828 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
2829
2830 /**
2831  * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
2832  * @chip: the chip the GPIO to lock belongs to
2833  * @offset: the offset of the GPIO to lock as IRQ
2834  *
2835  * This is used directly by GPIO drivers that want to indicate
2836  * that a certain GPIO is no longer used exclusively for IRQ.
2837  */
2838 void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
2839 {
2840         if (offset >= chip->ngpio)
2841                 return;
2842
2843         clear_bit(FLAG_USED_AS_IRQ, &chip->gpiodev->descs[offset].flags);
2844 }
2845 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
2846
2847 bool gpiochip_line_is_irq(struct gpio_chip *chip, unsigned int offset)
2848 {
2849         if (offset >= chip->ngpio)
2850                 return false;
2851
2852         return test_bit(FLAG_USED_AS_IRQ, &chip->gpiodev->descs[offset].flags);
2853 }
2854 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
2855
2856 bool gpiochip_line_is_open_drain(struct gpio_chip *chip, unsigned int offset)
2857 {
2858         if (offset >= chip->ngpio)
2859                 return false;
2860
2861         return test_bit(FLAG_OPEN_DRAIN, &chip->gpiodev->descs[offset].flags);
2862 }
2863 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
2864
2865 bool gpiochip_line_is_open_source(struct gpio_chip *chip, unsigned int offset)
2866 {
2867         if (offset >= chip->ngpio)
2868                 return false;
2869
2870         return test_bit(FLAG_OPEN_SOURCE, &chip->gpiodev->descs[offset].flags);
2871 }
2872 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
2873
2874 /**
2875  * gpiod_get_raw_value_cansleep() - return a gpio's raw value
2876  * @desc: gpio whose value will be returned
2877  *
2878  * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2879  * its ACTIVE_LOW status, or negative errno on failure.
2880  *
2881  * This function is to be called from contexts that can sleep.
2882  */
2883 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
2884 {
2885         might_sleep_if(extra_checks);
2886         VALIDATE_DESC(desc);
2887         return _gpiod_get_raw_value(desc);
2888 }
2889 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
2890
2891 /**
2892  * gpiod_get_value_cansleep() - return a gpio's value
2893  * @desc: gpio whose value will be returned
2894  *
2895  * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2896  * account, or negative errno on failure.
2897  *
2898  * This function is to be called from contexts that can sleep.
2899  */
2900 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
2901 {
2902         int value;
2903
2904         might_sleep_if(extra_checks);
2905         VALIDATE_DESC(desc);
2906         value = _gpiod_get_raw_value(desc);
2907         if (value < 0)
2908                 return value;
2909
2910         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2911                 value = !value;
2912
2913         return value;
2914 }
2915 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
2916
2917 /**
2918  * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
2919  * @desc: gpio whose value will be assigned
2920  * @value: value to assign
2921  *
2922  * Set the raw value of the GPIO, i.e. the value of its physical line without
2923  * regard for its ACTIVE_LOW status.
2924  *
2925  * This function is to be called from contexts that can sleep.
2926  */
2927 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
2928 {
2929         might_sleep_if(extra_checks);
2930         VALIDATE_DESC_VOID(desc);
2931         _gpiod_set_raw_value(desc, value);
2932 }
2933 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
2934
2935 /**
2936  * gpiod_set_value_cansleep() - assign a gpio's value
2937  * @desc: gpio whose value will be assigned
2938  * @value: value to assign
2939  *
2940  * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2941  * account
2942  *
2943  * This function is to be called from contexts that can sleep.
2944  */
2945 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
2946 {
2947         might_sleep_if(extra_checks);
2948         VALIDATE_DESC_VOID(desc);
2949         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2950                 value = !value;
2951         _gpiod_set_raw_value(desc, value);
2952 }
2953 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
2954
2955 /**
2956  * gpiod_set_pull_cansleep() - enable pull-down/up for the gpio, or disable.
2957  * @desc: gpio whose value will be set
2958  * @value: value to set
2959  *
2960  * This function is to be called from contexts that can sleep.
2961  */
2962 #ifdef CONFIG_AMLOGIC_PINCTRL
2963 int gpiod_set_pull_cansleep(struct gpio_desc *desc, int value)
2964 {
2965         might_sleep_if(extra_checks);
2966         VALIDATE_DESC(desc);
2967         return _gpiod_set_pull(desc, value);
2968 }
2969 EXPORT_SYMBOL_GPL(gpiod_set_pull_cansleep);
2970 #endif
2971
2972 /**
2973  * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
2974  * @array_size: number of elements in the descriptor / value arrays
2975  * @desc_array: array of GPIO descriptors whose values will be assigned
2976  * @value_array: array of values to assign
2977  *
2978  * Set the raw values of the GPIOs, i.e. the values of the physical lines
2979  * without regard for their ACTIVE_LOW status.
2980  *
2981  * This function is to be called from contexts that can sleep.
2982  */
2983 void gpiod_set_raw_array_value_cansleep(unsigned int array_size,
2984                                         struct gpio_desc **desc_array,
2985                                         int *value_array)
2986 {
2987         might_sleep_if(extra_checks);
2988         if (!desc_array)
2989                 return;
2990         gpiod_set_array_value_complex(true, true, array_size, desc_array,
2991                                       value_array);
2992 }
2993 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
2994
2995 /**
2996  * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
2997  * @array_size: number of elements in the descriptor / value arrays
2998  * @desc_array: array of GPIO descriptors whose values will be assigned
2999  * @value_array: array of values to assign
3000  *
3001  * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3002  * into account.
3003  *
3004  * This function is to be called from contexts that can sleep.
3005  */
3006 void gpiod_set_array_value_cansleep(unsigned int array_size,
3007                                     struct gpio_desc **desc_array,
3008                                     int *value_array)
3009 {
3010         might_sleep_if(extra_checks);
3011         if (!desc_array)
3012                 return;
3013         gpiod_set_array_value_complex(false, true, array_size, desc_array,
3014                                       value_array);
3015 }
3016 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
3017
3018 /**
3019  * gpiod_add_lookup_table() - register GPIO device consumers
3020  * @table: table of consumers to register
3021  */
3022 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
3023 {
3024         mutex_lock(&gpio_lookup_lock);
3025
3026         list_add_tail(&table->list, &gpio_lookup_list);
3027
3028         mutex_unlock(&gpio_lookup_lock);
3029 }
3030
3031 /**
3032  * gpiod_remove_lookup_table() - unregister GPIO device consumers
3033  * @table: table of consumers to unregister
3034  */
3035 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
3036 {
3037         mutex_lock(&gpio_lookup_lock);
3038
3039         list_del(&table->list);
3040
3041         mutex_unlock(&gpio_lookup_lock);
3042 }
3043
3044 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
3045 {
3046         const char *dev_id = dev ? dev_name(dev) : NULL;
3047         struct gpiod_lookup_table *table;
3048
3049         mutex_lock(&gpio_lookup_lock);
3050
3051         list_for_each_entry(table, &gpio_lookup_list, list) {
3052                 if (table->dev_id && dev_id) {
3053                         /*
3054                          * Valid strings on both ends, must be identical to have
3055                          * a match
3056                          */
3057                         if (!strcmp(table->dev_id, dev_id))
3058                                 goto found;
3059                 } else {
3060                         /*
3061                          * One of the pointers is NULL, so both must be to have
3062                          * a match
3063                          */
3064                         if (dev_id == table->dev_id)
3065                                 goto found;
3066                 }
3067         }
3068         table = NULL;
3069
3070 found:
3071         mutex_unlock(&gpio_lookup_lock);
3072         return table;
3073 }
3074
3075 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
3076                                     unsigned int idx,
3077                                     enum gpio_lookup_flags *flags)
3078 {
3079         struct gpio_desc *desc = ERR_PTR(-ENOENT);
3080         struct gpiod_lookup_table *table;
3081         struct gpiod_lookup *p;
3082
3083         table = gpiod_find_lookup_table(dev);
3084         if (!table)
3085                 return desc;
3086
3087         for (p = &table->table[0]; p->chip_label; p++) {
3088                 struct gpio_chip *chip;
3089
3090                 /* idx must always match exactly */
3091                 if (p->idx != idx)
3092                         continue;
3093
3094                 /* If the lookup entry has a con_id, require exact match */
3095                 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
3096                         continue;
3097
3098                 chip = find_chip_by_name(p->chip_label);
3099
3100                 if (!chip) {
3101                         dev_err(dev, "cannot find GPIO chip %s\n",
3102                                 p->chip_label);
3103                         return ERR_PTR(-ENODEV);
3104                 }
3105
3106                 if (chip->ngpio <= p->chip_hwnum) {
3107                         dev_err(dev,
3108                                 "requested GPIO %d is out of range [0..%d] for chip %s\n",
3109                                 idx, chip->ngpio, chip->label);
3110                         return ERR_PTR(-EINVAL);
3111                 }
3112
3113                 desc = gpiochip_get_desc(chip, p->chip_hwnum);
3114                 *flags = p->flags;
3115
3116                 return desc;
3117         }
3118
3119         return desc;
3120 }
3121
3122 static int dt_gpio_count(struct device *dev, const char *con_id)
3123 {
3124         int ret;
3125         char propname[32];
3126         unsigned int i;
3127
3128         for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
3129                 if (con_id)
3130                         snprintf(propname, sizeof(propname), "%s-%s",
3131                                  con_id, gpio_suffixes[i]);
3132                 else
3133                         snprintf(propname, sizeof(propname), "%s",
3134                                  gpio_suffixes[i]);
3135
3136                 ret = of_gpio_named_count(dev->of_node, propname);
3137                 if (ret >= 0)
3138                         break;
3139         }
3140         return ret;
3141 }
3142
3143 static int platform_gpio_count(struct device *dev, const char *con_id)
3144 {
3145         struct gpiod_lookup_table *table;
3146         struct gpiod_lookup *p;
3147         unsigned int count = 0;
3148
3149         table = gpiod_find_lookup_table(dev);
3150         if (!table)
3151                 return -ENOENT;
3152
3153         for (p = &table->table[0]; p->chip_label; p++) {
3154                 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
3155                     (!con_id && !p->con_id))
3156                         count++;
3157         }
3158         if (!count)
3159                 return -ENOENT;
3160
3161         return count;
3162 }
3163
3164 /**
3165  * gpiod_count - return the number of GPIOs associated with a device / function
3166  *              or -ENOENT if no GPIO has been assigned to the requested function
3167  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3168  * @con_id:     function within the GPIO consumer
3169  */
3170 int gpiod_count(struct device *dev, const char *con_id)
3171 {
3172         int count = -ENOENT;
3173
3174         if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
3175                 count = dt_gpio_count(dev, con_id);
3176         else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
3177                 count = acpi_gpio_count(dev, con_id);
3178
3179         if (count < 0)
3180                 count = platform_gpio_count(dev, con_id);
3181
3182         return count;
3183 }
3184 EXPORT_SYMBOL_GPL(gpiod_count);
3185
3186 /**
3187  * gpiod_get - obtain a GPIO for a given GPIO function
3188  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3189  * @con_id:     function within the GPIO consumer
3190  * @flags:      optional GPIO initialization flags
3191  *
3192  * Return the GPIO descriptor corresponding to the function con_id of device
3193  * dev, -ENOENT if no GPIO has been assigned to the requested function, or
3194  * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
3195  */
3196 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
3197                                          enum gpiod_flags flags)
3198 {
3199         return gpiod_get_index(dev, con_id, 0, flags);
3200 }
3201 EXPORT_SYMBOL_GPL(gpiod_get);
3202
3203 /**
3204  * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
3205  * @dev: GPIO consumer, can be NULL for system-global GPIOs
3206  * @con_id: function within the GPIO consumer
3207  * @flags: optional GPIO initialization flags
3208  *
3209  * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
3210  * the requested function it will return NULL. This is convenient for drivers
3211  * that need to handle optional GPIOs.
3212  */
3213 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
3214                                                   const char *con_id,
3215                                                   enum gpiod_flags flags)
3216 {
3217         return gpiod_get_index_optional(dev, con_id, 0, flags);
3218 }
3219 EXPORT_SYMBOL_GPL(gpiod_get_optional);
3220
3221
3222 /**
3223  * gpiod_configure_flags - helper function to configure a given GPIO
3224  * @desc:       gpio whose value will be assigned
3225  * @con_id:     function within the GPIO consumer
3226  * @lflags:     gpio_lookup_flags - returned from of_find_gpio() or
3227  *              of_get_gpio_hog()
3228  * @dflags:     gpiod_flags - optional GPIO initialization flags
3229  *
3230  * Return 0 on success, -ENOENT if no GPIO has been assigned to the
3231  * requested function and/or index, or another IS_ERR() code if an error
3232  * occurred while trying to acquire the GPIO.
3233  */
3234 static int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
3235                 unsigned long lflags, enum gpiod_flags dflags)
3236 {
3237         int status;
3238
3239         if (lflags & GPIO_ACTIVE_LOW)
3240                 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
3241         if (lflags & GPIO_OPEN_DRAIN)
3242                 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3243         if (lflags & GPIO_OPEN_SOURCE)
3244                 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
3245
3246         /* No particular flag request, return here... */
3247         if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
3248                 pr_debug("no flags found for %s\n", con_id);
3249                 return 0;
3250         }
3251
3252         /* Process flags */
3253         if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
3254                 status = gpiod_direction_output(desc,
3255                                               dflags & GPIOD_FLAGS_BIT_DIR_VAL);
3256         else
3257                 status = gpiod_direction_input(desc);
3258
3259         return status;
3260 }
3261
3262 /**
3263  * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
3264  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3265  * @con_id:     function within the GPIO consumer
3266  * @idx:        index of the GPIO to obtain in the consumer
3267  * @flags:      optional GPIO initialization flags
3268  *
3269  * This variant of gpiod_get() allows to access GPIOs other than the first
3270  * defined one for functions that define several GPIOs.
3271  *
3272  * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
3273  * requested function and/or index, or another IS_ERR() code if an error
3274  * occurred while trying to acquire the GPIO.
3275  */
3276 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
3277                                                const char *con_id,
3278                                                unsigned int idx,
3279                                                enum gpiod_flags flags)
3280 {
3281         struct gpio_desc *desc = NULL;
3282         int status;
3283         enum gpio_lookup_flags lookupflags = 0;
3284         /* Maybe we have a device name, maybe not */
3285         const char *devname = dev ? dev_name(dev) : "?";
3286
3287         dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
3288
3289         if (dev) {
3290                 /* Using device tree? */
3291                 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
3292                         dev_dbg(dev, "using device tree for GPIO lookup\n");
3293                         desc = of_find_gpio(dev, con_id, idx, &lookupflags);
3294                 } else if (ACPI_COMPANION(dev)) {
3295                         dev_dbg(dev, "using ACPI for GPIO lookup\n");
3296                         desc = acpi_find_gpio(dev, con_id, idx, flags, &lookupflags);
3297                 }
3298         }
3299
3300         /*
3301          * Either we are not using DT or ACPI, or their lookup did not return
3302          * a result. In that case, use platform lookup as a fallback.
3303          */
3304         if (!desc || desc == ERR_PTR(-ENOENT)) {
3305                 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
3306                 desc = gpiod_find(dev, con_id, idx, &lookupflags);
3307         }
3308
3309         if (IS_ERR(desc)) {
3310                 dev_dbg(dev, "lookup for GPIO %s failed\n", con_id);
3311                 return desc;
3312         }
3313
3314         /*
3315          * If a connection label was passed use that, else attempt to use
3316          * the device name as label
3317          */
3318         status = gpiod_request(desc, con_id ? con_id : devname);
3319         if (status < 0)
3320                 return ERR_PTR(status);
3321
3322         status = gpiod_configure_flags(desc, con_id, lookupflags, flags);
3323         if (status < 0) {
3324                 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
3325                 gpiod_put(desc);
3326                 return ERR_PTR(status);
3327         }
3328
3329         return desc;
3330 }
3331 EXPORT_SYMBOL_GPL(gpiod_get_index);
3332
3333 /**
3334  * fwnode_get_named_gpiod - obtain a GPIO from firmware node
3335  * @fwnode:     handle of the firmware node
3336  * @propname:   name of the firmware property representing the GPIO
3337  *
3338  * This function can be used for drivers that get their configuration
3339  * from firmware.
3340  *
3341  * Function properly finds the corresponding GPIO using whatever is the
3342  * underlying firmware interface and then makes sure that the GPIO
3343  * descriptor is requested before it is returned to the caller.
3344  *
3345  * In case of error an ERR_PTR() is returned.
3346  */
3347 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
3348                                          const char *propname)
3349 {
3350         struct gpio_desc *desc = ERR_PTR(-ENODEV);
3351         bool active_low = false;
3352         bool single_ended = false;
3353 #ifdef CONFIG_AMLOGIC_MODIFY
3354         bool open_drain = false;
3355 #endif
3356         int ret;
3357
3358         if (!fwnode)
3359                 return ERR_PTR(-EINVAL);
3360
3361         if (is_of_node(fwnode)) {
3362                 enum of_gpio_flags flags;
3363
3364                 desc = of_get_named_gpiod_flags(to_of_node(fwnode), propname, 0,
3365                                                 &flags);
3366                 if (!IS_ERR(desc)) {
3367                         active_low = flags & OF_GPIO_ACTIVE_LOW;
3368                         single_ended = flags & OF_GPIO_SINGLE_ENDED;
3369 #ifdef CONFIG_AMLOGIC_MODIFY
3370                         open_drain = flags & OF_GPIO_OPEN_DRAIN;
3371 #endif
3372                 }
3373         } else if (is_acpi_node(fwnode)) {
3374                 struct acpi_gpio_info info;
3375
3376                 desc = acpi_node_get_gpiod(fwnode, propname, 0, &info);
3377                 if (!IS_ERR(desc))
3378                         active_low = info.polarity == GPIO_ACTIVE_LOW;
3379         }
3380
3381         if (IS_ERR(desc))
3382                 return desc;
3383
3384         ret = gpiod_request(desc, NULL);
3385         if (ret)
3386                 return ERR_PTR(ret);
3387
3388         if (active_low)
3389                 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
3390
3391         if (single_ended) {
3392 #ifdef CONFIG_AMLOGIC_MODIFY
3393                 if (open_drain)
3394 #else
3395                 if (active_low)
3396 #endif
3397                         set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3398                 else
3399                         set_bit(FLAG_OPEN_SOURCE, &desc->flags);
3400         }
3401
3402         return desc;
3403 }
3404 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
3405
3406 /**
3407  * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
3408  *                            function
3409  * @dev: GPIO consumer, can be NULL for system-global GPIOs
3410  * @con_id: function within the GPIO consumer
3411  * @index: index of the GPIO to obtain in the consumer
3412  * @flags: optional GPIO initialization flags
3413  *
3414  * This is equivalent to gpiod_get_index(), except that when no GPIO with the
3415  * specified index was assigned to the requested function it will return NULL.
3416  * This is convenient for drivers that need to handle optional GPIOs.
3417  */
3418 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
3419                                                         const char *con_id,
3420                                                         unsigned int index,
3421                                                         enum gpiod_flags flags)
3422 {
3423         struct gpio_desc *desc;
3424
3425         desc = gpiod_get_index(dev, con_id, index, flags);
3426         if (IS_ERR(desc)) {
3427                 if (PTR_ERR(desc) == -ENOENT)
3428                         return NULL;
3429         }
3430
3431         return desc;
3432 }
3433 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
3434
3435 /**
3436  * gpiod_hog - Hog the specified GPIO desc given the provided flags
3437  * @desc:       gpio whose value will be assigned
3438  * @name:       gpio line name
3439  * @lflags:     gpio_lookup_flags - returned from of_find_gpio() or
3440  *              of_get_gpio_hog()
3441  * @dflags:     gpiod_flags - optional GPIO initialization flags
3442  */
3443 int gpiod_hog(struct gpio_desc *desc, const char *name,
3444               unsigned long lflags, enum gpiod_flags dflags)
3445 {
3446         struct gpio_chip *chip;
3447         struct gpio_desc *local_desc;
3448         int hwnum;
3449         int status;
3450
3451         chip = gpiod_to_chip(desc);
3452         hwnum = gpio_chip_hwgpio(desc);
3453
3454         local_desc = gpiochip_request_own_desc(chip, hwnum, name);
3455         if (IS_ERR(local_desc)) {
3456                 status = PTR_ERR(local_desc);
3457                 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
3458                        name, chip->label, hwnum, status);
3459                 return status;
3460         }
3461
3462         status = gpiod_configure_flags(desc, name, lflags, dflags);
3463         if (status < 0) {
3464                 pr_err("setup of hog GPIO %s (chip %s, offset %d) failed, %d\n",
3465                        name, chip->label, hwnum, status);
3466                 gpiochip_free_own_desc(desc);
3467                 return status;
3468         }
3469
3470         /* Mark GPIO as hogged so it can be identified and removed later */
3471         set_bit(FLAG_IS_HOGGED, &desc->flags);
3472
3473         pr_info("GPIO line %d (%s) hogged as %s%s\n",
3474                 desc_to_gpio(desc), name,
3475                 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
3476                 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ?
3477                   (dflags&GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low":"");
3478
3479         return 0;
3480 }
3481
3482 /**
3483  * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
3484  * @chip:       gpio chip to act on
3485  *
3486  * This is only used by of_gpiochip_remove to free hogged gpios
3487  */
3488 static void gpiochip_free_hogs(struct gpio_chip *chip)
3489 {
3490         int id;
3491
3492         for (id = 0; id < chip->ngpio; id++) {
3493                 if (test_bit(FLAG_IS_HOGGED, &chip->gpiodev->descs[id].flags))
3494                         gpiochip_free_own_desc(&chip->gpiodev->descs[id]);
3495         }
3496 }
3497
3498 /**
3499  * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
3500  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3501  * @con_id:     function within the GPIO consumer
3502  * @flags:      optional GPIO initialization flags
3503  *
3504  * This function acquires all the GPIOs defined under a given function.
3505  *
3506  * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
3507  * no GPIO has been assigned to the requested function, or another IS_ERR()
3508  * code if an error occurred while trying to acquire the GPIOs.
3509  */
3510 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
3511                                                 const char *con_id,
3512                                                 enum gpiod_flags flags)
3513 {
3514         struct gpio_desc *desc;
3515         struct gpio_descs *descs;
3516         int count;
3517
3518         count = gpiod_count(dev, con_id);
3519         if (count < 0)
3520                 return ERR_PTR(count);
3521
3522         descs = kzalloc(sizeof(*descs) + sizeof(descs->desc[0]) * count,
3523                         GFP_KERNEL);
3524         if (!descs)
3525                 return ERR_PTR(-ENOMEM);
3526
3527         for (descs->ndescs = 0; descs->ndescs < count; ) {
3528                 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
3529                 if (IS_ERR(desc)) {
3530                         gpiod_put_array(descs);
3531                         return ERR_CAST(desc);
3532                 }
3533                 descs->desc[descs->ndescs] = desc;
3534                 descs->ndescs++;
3535         }
3536         return descs;
3537 }
3538 EXPORT_SYMBOL_GPL(gpiod_get_array);
3539
3540 /**
3541  * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
3542  *                            function
3543  * @dev:        GPIO consumer, can be NULL for system-global GPIOs
3544  * @con_id:     function within the GPIO consumer
3545  * @flags:      optional GPIO initialization flags
3546  *
3547  * This is equivalent to gpiod_get_array(), except that when no GPIO was
3548  * assigned to the requested function it will return NULL.
3549  */
3550 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
3551                                                         const char *con_id,
3552                                                         enum gpiod_flags flags)
3553 {
3554         struct gpio_descs *descs;
3555
3556         descs = gpiod_get_array(dev, con_id, flags);
3557         if (IS_ERR(descs) && (PTR_ERR(descs) == -ENOENT))
3558                 return NULL;
3559
3560         return descs;
3561 }
3562 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
3563
3564 /**
3565  * gpiod_put - dispose of a GPIO descriptor
3566  * @desc:       GPIO descriptor to dispose of
3567  *
3568  * No descriptor can be used after gpiod_put() has been called on it.
3569  */
3570 void gpiod_put(struct gpio_desc *desc)
3571 {
3572         gpiod_free(desc);
3573 }
3574 EXPORT_SYMBOL_GPL(gpiod_put);
3575
3576 /**
3577  * gpiod_put_array - dispose of multiple GPIO descriptors
3578  * @descs:      struct gpio_descs containing an array of descriptors
3579  */
3580 void gpiod_put_array(struct gpio_descs *descs)
3581 {
3582         unsigned int i;
3583
3584         for (i = 0; i < descs->ndescs; i++)
3585                 gpiod_put(descs->desc[i]);
3586
3587         kfree(descs);
3588 }
3589 EXPORT_SYMBOL_GPL(gpiod_put_array);
3590
3591 static int __init gpiolib_dev_init(void)
3592 {
3593         int ret;
3594
3595         /* Register GPIO sysfs bus */
3596         ret  = bus_register(&gpio_bus_type);
3597         if (ret < 0) {
3598                 pr_err("gpiolib: could not register GPIO bus type\n");
3599                 return ret;
3600         }
3601
3602         ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, "gpiochip");
3603         if (ret < 0) {
3604                 pr_err("gpiolib: failed to allocate char dev region\n");
3605                 bus_unregister(&gpio_bus_type);
3606         } else {
3607                 gpiolib_initialized = true;
3608                 gpiochip_setup_devs();
3609         }
3610         return ret;
3611 }
3612 core_initcall(gpiolib_dev_init);
3613
3614 #ifdef CONFIG_DEBUG_FS
3615
3616 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
3617 {
3618         unsigned                i;
3619         struct gpio_chip        *chip = gdev->chip;
3620         unsigned                gpio = gdev->base;
3621         struct gpio_desc        *gdesc = &gdev->descs[0];
3622         int                     is_out;
3623         int                     is_irq;
3624
3625         for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
3626                 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
3627                         if (gdesc->name) {
3628                                 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
3629                                            gpio, gdesc->name);
3630                         }
3631                         continue;
3632                 }
3633
3634                 gpiod_get_direction(gdesc);
3635                 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
3636                 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
3637                 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s",
3638                         gpio, gdesc->name ? gdesc->name : "", gdesc->label,
3639                         is_out ? "out" : "in ",
3640                         chip->get
3641                                 ? (chip->get(chip, i) ? "hi" : "lo")
3642                                 : "?  ",
3643                         is_irq ? "IRQ" : "   ");
3644                 seq_printf(s, "\n");
3645         }
3646 }
3647
3648 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
3649 {
3650         unsigned long flags;
3651         struct gpio_device *gdev = NULL;
3652         loff_t index = *pos;
3653
3654         s->private = "";
3655
3656         spin_lock_irqsave(&gpio_lock, flags);
3657         list_for_each_entry(gdev, &gpio_devices, list)
3658                 if (index-- == 0) {
3659                         spin_unlock_irqrestore(&gpio_lock, flags);
3660                         return gdev;
3661                 }
3662         spin_unlock_irqrestore(&gpio_lock, flags);
3663
3664         return NULL;
3665 }
3666
3667 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
3668 {
3669         unsigned long flags;
3670         struct gpio_device *gdev = v;
3671         void *ret = NULL;
3672
3673         spin_lock_irqsave(&gpio_lock, flags);
3674         if (list_is_last(&gdev->list, &gpio_devices))
3675                 ret = NULL;
3676         else
3677                 ret = list_entry(gdev->list.next, struct gpio_device, list);
3678         spin_unlock_irqrestore(&gpio_lock, flags);
3679
3680         s->private = "\n";
3681         ++*pos;
3682
3683         return ret;
3684 }
3685
3686 static void gpiolib_seq_stop(struct seq_file *s, void *v)
3687 {
3688 }
3689
3690 static int gpiolib_seq_show(struct seq_file *s, void *v)
3691 {
3692         struct gpio_device *gdev = v;
3693         struct gpio_chip *chip = gdev->chip;
3694         struct device *parent;
3695
3696         if (!chip) {
3697                 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
3698                            dev_name(&gdev->dev));
3699                 return 0;
3700         }
3701
3702         seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
3703                    dev_name(&gdev->dev),
3704                    gdev->base, gdev->base + gdev->ngpio - 1);
3705         parent = chip->parent;
3706         if (parent)
3707                 seq_printf(s, ", parent: %s/%s",
3708                            parent->bus ? parent->bus->name : "no-bus",
3709                            dev_name(parent));
3710         if (chip->label)
3711                 seq_printf(s, ", %s", chip->label);
3712         if (chip->can_sleep)
3713                 seq_printf(s, ", can sleep");
3714         seq_printf(s, ":\n");
3715
3716         if (chip->dbg_show)
3717                 chip->dbg_show(s, chip);
3718         else
3719                 gpiolib_dbg_show(s, gdev);
3720
3721         return 0;
3722 }
3723
3724 static const struct seq_operations gpiolib_seq_ops = {
3725         .start = gpiolib_seq_start,
3726         .next = gpiolib_seq_next,
3727         .stop = gpiolib_seq_stop,
3728         .show = gpiolib_seq_show,
3729 };
3730
3731 static int gpiolib_open(struct inode *inode, struct file *file)
3732 {
3733         return seq_open(file, &gpiolib_seq_ops);
3734 }
3735
3736 static const struct file_operations gpiolib_operations = {
3737         .owner          = THIS_MODULE,
3738         .open           = gpiolib_open,
3739         .read           = seq_read,
3740         .llseek         = seq_lseek,
3741         .release        = seq_release,
3742 };
3743
3744 static int __init gpiolib_debugfs_init(void)
3745 {
3746         /* /sys/kernel/debug/gpio */
3747         (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
3748                                 NULL, NULL, &gpiolib_operations);
3749         return 0;
3750 }
3751 subsys_initcall(gpiolib_debugfs_init);
3752
3753 #endif  /* DEBUG_FS */