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