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