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