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