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