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