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