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