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