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