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