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