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