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