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