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