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