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