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