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