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