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