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