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