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