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