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