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