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