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