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