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