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