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