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