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