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