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