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