gpiolib-cdev.c 28.2 KB
Newer Older
1 2
// SPDX-License-Identifier: GPL-2.0

K
Kent Gibson 已提交
3
#include <linux/anon_inodes.h>
4
#include <linux/bitmap.h>
K
Kent Gibson 已提交
5 6
#include <linux/cdev.h>
#include <linux/compat.h>
7 8
#include <linux/device.h>
#include <linux/err.h>
K
Kent Gibson 已提交
9
#include <linux/file.h>
10 11
#include <linux/gpio.h>
#include <linux/gpio/driver.h>
K
Kent Gibson 已提交
12 13 14
#include <linux/interrupt.h>
#include <linux/irqreturn.h>
#include <linux/kernel.h>
15
#include <linux/kfifo.h>
K
Kent Gibson 已提交
16 17
#include <linux/module.h>
#include <linux/pinctrl/consumer.h>
18
#include <linux/poll.h>
K
Kent Gibson 已提交
19
#include <linux/spinlock.h>
20
#include <linux/timekeeping.h>
K
Kent Gibson 已提交
21
#include <linux/uaccess.h>
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <uapi/linux/gpio.h>

#include "gpiolib.h"
#include "gpiolib-cdev.h"

/* Character device interface to GPIO.
 *
 * The GPIO character device, /dev/gpiochipN, provides userspace an
 * interface to gpiolib GPIOs via ioctl()s.
 */

/*
 * GPIO line handle management
 */

/**
 * struct linehandle_state - contains the state of a userspace handle
 * @gdev: the GPIO device the handle pertains to
 * @label: consumer label used to tag descriptors
 * @descs: the GPIO descriptors held by this handle
42
 * @num_descs: the number of descriptors held in the descs array
43 44 45 46 47
 */
struct linehandle_state {
	struct gpio_device *gdev;
	const char *label;
	struct gpio_desc *descs[GPIOHANDLES_MAX];
48
	u32 num_descs;
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
};

#define GPIOHANDLE_REQUEST_VALID_FLAGS \
	(GPIOHANDLE_REQUEST_INPUT | \
	GPIOHANDLE_REQUEST_OUTPUT | \
	GPIOHANDLE_REQUEST_ACTIVE_LOW | \
	GPIOHANDLE_REQUEST_BIAS_PULL_UP | \
	GPIOHANDLE_REQUEST_BIAS_PULL_DOWN | \
	GPIOHANDLE_REQUEST_BIAS_DISABLE | \
	GPIOHANDLE_REQUEST_OPEN_DRAIN | \
	GPIOHANDLE_REQUEST_OPEN_SOURCE)

static int linehandle_validate_flags(u32 flags)
{
	/* Return an error if an unknown flag is set */
	if (flags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
		return -EINVAL;

	/*
	 * Do not allow both INPUT & OUTPUT flags to be set as they are
	 * contradictory.
	 */
	if ((flags & GPIOHANDLE_REQUEST_INPUT) &&
	    (flags & GPIOHANDLE_REQUEST_OUTPUT))
		return -EINVAL;

	/*
	 * Do not allow OPEN_SOURCE & OPEN_DRAIN flags in a single request. If
	 * the hardware actually supports enabling both at the same time the
	 * electrical result would be disastrous.
	 */
	if ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
	    (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
		return -EINVAL;

	/* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
	if (!(flags & GPIOHANDLE_REQUEST_OUTPUT) &&
	    ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
	     (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
		return -EINVAL;

	/* Bias flags only allowed for input or output mode. */
	if (!((flags & GPIOHANDLE_REQUEST_INPUT) ||
	      (flags & GPIOHANDLE_REQUEST_OUTPUT)) &&
	    ((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) ||
	     (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP) ||
	     (flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)))
		return -EINVAL;

	/* Only one bias flag can be set. */
	if (((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
	     (flags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
101
		       GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
102 103 104 105 106 107 108
	    ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
	     (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
		return -EINVAL;

	return 0;
}

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
static void linehandle_flags_to_desc_flags(u32 lflags, unsigned long *flagsp)
{
	assign_bit(FLAG_ACTIVE_LOW, flagsp,
		   lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW);
	assign_bit(FLAG_OPEN_DRAIN, flagsp,
		   lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN);
	assign_bit(FLAG_OPEN_SOURCE, flagsp,
		   lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE);
	assign_bit(FLAG_PULL_UP, flagsp,
		   lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP);
	assign_bit(FLAG_PULL_DOWN, flagsp,
		   lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN);
	assign_bit(FLAG_BIAS_DISABLE, flagsp,
		   lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE);
}

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
static long linehandle_set_config(struct linehandle_state *lh,
				  void __user *ip)
{
	struct gpiohandle_config gcnf;
	struct gpio_desc *desc;
	int i, ret;
	u32 lflags;

	if (copy_from_user(&gcnf, ip, sizeof(gcnf)))
		return -EFAULT;

	lflags = gcnf.flags;
	ret = linehandle_validate_flags(lflags);
	if (ret)
		return ret;

141
	for (i = 0; i < lh->num_descs; i++) {
142
		desc = lh->descs[i];
143
		linehandle_flags_to_desc_flags(gcnf.flags, &desc->flags);
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

		/*
		 * Lines have to be requested explicitly for input
		 * or output, else the line will be treated "as is".
		 */
		if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
			int val = !!gcnf.default_values[i];

			ret = gpiod_direction_output(desc, val);
			if (ret)
				return ret;
		} else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
			ret = gpiod_direction_input(desc);
			if (ret)
				return ret;
		}

161 162
		blocking_notifier_call_chain(&desc->gdev->notifier,
					     GPIOLINE_CHANGED_CONFIG, desc);
163 164 165 166
	}
	return 0;
}

167
static long linehandle_ioctl(struct file *file, unsigned int cmd,
168 169
			     unsigned long arg)
{
170
	struct linehandle_state *lh = file->private_data;
171 172 173 174 175 176 177 178 179
	void __user *ip = (void __user *)arg;
	struct gpiohandle_data ghd;
	DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
	int i;

	if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
		/* NOTE: It's ok to read values of output lines. */
		int ret = gpiod_get_array_value_complex(false,
							true,
180
							lh->num_descs,
181 182 183 184 185 186 187
							lh->descs,
							NULL,
							vals);
		if (ret)
			return ret;

		memset(&ghd, 0, sizeof(ghd));
188
		for (i = 0; i < lh->num_descs; i++)
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
			ghd.values[i] = test_bit(i, vals);

		if (copy_to_user(ip, &ghd, sizeof(ghd)))
			return -EFAULT;

		return 0;
	} else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
		/*
		 * All line descriptors were created at once with the same
		 * flags so just check if the first one is really output.
		 */
		if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
			return -EPERM;

		if (copy_from_user(&ghd, ip, sizeof(ghd)))
			return -EFAULT;

		/* Clamp all values to [0,1] */
207
		for (i = 0; i < lh->num_descs; i++)
208 209 210 211
			__assign_bit(i, vals, ghd.values[i]);

		/* Reuse the array setting function */
		return gpiod_set_array_value_complex(false,
212
						     true,
213
						     lh->num_descs,
214 215 216
						     lh->descs,
						     NULL,
						     vals);
217 218 219 220 221 222 223
	} else if (cmd == GPIOHANDLE_SET_CONFIG_IOCTL) {
		return linehandle_set_config(lh, ip);
	}
	return -EINVAL;
}

#ifdef CONFIG_COMPAT
224
static long linehandle_ioctl_compat(struct file *file, unsigned int cmd,
225
				    unsigned long arg)
226
{
227
	return linehandle_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
228 229 230
}
#endif

231
static void linehandle_free(struct linehandle_state *lh)
232 233 234
{
	int i;

235
	for (i = 0; i < lh->num_descs; i++)
236 237
		if (lh->descs[i])
			gpiod_free(lh->descs[i]);
238
	kfree(lh->label);
239
	put_device(&lh->gdev->dev);
240
	kfree(lh);
241 242 243 244 245
}

static int linehandle_release(struct inode *inode, struct file *file)
{
	linehandle_free(file->private_data);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
	return 0;
}

static const struct file_operations linehandle_fileops = {
	.release = linehandle_release,
	.owner = THIS_MODULE,
	.llseek = noop_llseek,
	.unlocked_ioctl = linehandle_ioctl,
#ifdef CONFIG_COMPAT
	.compat_ioctl = linehandle_ioctl_compat,
#endif
};

static int linehandle_create(struct gpio_device *gdev, void __user *ip)
{
	struct gpiohandle_request handlereq;
	struct linehandle_state *lh;
	struct file *file;
264
	int fd, i, ret;
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
	u32 lflags;

	if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
		return -EFAULT;
	if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
		return -EINVAL;

	lflags = handlereq.flags;

	ret = linehandle_validate_flags(lflags);
	if (ret)
		return ret;

	lh = kzalloc(sizeof(*lh), GFP_KERNEL);
	if (!lh)
		return -ENOMEM;
	lh->gdev = gdev;
	get_device(&gdev->dev);

	/* Make sure this is terminated */
	handlereq.consumer_label[sizeof(handlereq.consumer_label)-1] = '\0';
	if (strlen(handlereq.consumer_label)) {
		lh->label = kstrdup(handlereq.consumer_label,
				    GFP_KERNEL);
		if (!lh->label) {
			ret = -ENOMEM;
			goto out_free_lh;
		}
	}

295 296
	lh->num_descs = handlereq.lines;

297 298 299 300 301 302 303
	/* Request each GPIO */
	for (i = 0; i < handlereq.lines; i++) {
		u32 offset = handlereq.lineoffsets[i];
		struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);

		if (IS_ERR(desc)) {
			ret = PTR_ERR(desc);
304
			goto out_free_lh;
305 306 307 308
		}

		ret = gpiod_request(desc, lh->label);
		if (ret)
309
			goto out_free_lh;
310
		lh->descs[i] = desc;
311
		linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags);
312 313 314

		ret = gpiod_set_transitory(desc, false);
		if (ret < 0)
315
			goto out_free_lh;
316 317 318 319 320 321 322 323 324 325

		/*
		 * Lines have to be requested explicitly for input
		 * or output, else the line will be treated "as is".
		 */
		if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
			int val = !!handlereq.default_values[i];

			ret = gpiod_direction_output(desc, val);
			if (ret)
326
				goto out_free_lh;
327 328 329
		} else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
			ret = gpiod_direction_input(desc);
			if (ret)
330
				goto out_free_lh;
331 332
		}

333 334
		blocking_notifier_call_chain(&desc->gdev->notifier,
					     GPIOLINE_CHANGED_REQUESTED, desc);
335 336 337 338 339 340 341 342

		dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
			offset);
	}

	fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
	if (fd < 0) {
		ret = fd;
343
		goto out_free_lh;
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
	}

	file = anon_inode_getfile("gpio-linehandle",
				  &linehandle_fileops,
				  lh,
				  O_RDONLY | O_CLOEXEC);
	if (IS_ERR(file)) {
		ret = PTR_ERR(file);
		goto out_put_unused_fd;
	}

	handlereq.fd = fd;
	if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
		/*
		 * fput() will trigger the release() callback, so do not go onto
		 * the regular error cleanup path here.
		 */
		fput(file);
		put_unused_fd(fd);
		return -EFAULT;
	}

	fd_install(fd, file);

	dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
369
		lh->num_descs);
370 371 372 373 374 375

	return 0;

out_put_unused_fd:
	put_unused_fd(fd);
out_free_lh:
376
	linehandle_free(lh);
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
	return ret;
}

/*
 * GPIO line event management
 */

/**
 * struct lineevent_state - contains the state of a userspace event
 * @gdev: the GPIO device the event pertains to
 * @label: consumer label used to tag descriptors
 * @desc: the GPIO descriptor held by this event
 * @eflags: the event flags this line was requested with
 * @irq: the interrupt that trigger in response to events on this GPIO
 * @wait: wait queue that handles blocking reads of events
 * @events: KFIFO for the GPIO events
 * @timestamp: cache for the timestamp storing it between hardirq
 * and IRQ thread, used to bring the timestamp close to the actual
 * event
 */
struct lineevent_state {
	struct gpio_device *gdev;
	const char *label;
	struct gpio_desc *desc;
	u32 eflags;
	int irq;
	wait_queue_head_t wait;
	DECLARE_KFIFO(events, struct gpioevent_data, 16);
	u64 timestamp;
};

#define GPIOEVENT_REQUEST_VALID_FLAGS \
	(GPIOEVENT_REQUEST_RISING_EDGE | \
	GPIOEVENT_REQUEST_FALLING_EDGE)

412
static __poll_t lineevent_poll(struct file *file,
413
			       struct poll_table_struct *wait)
414
{
415
	struct lineevent_state *le = file->private_data;
416 417
	__poll_t events = 0;

418
	poll_wait(file, &le->wait, wait);
419 420 421 422 423 424 425

	if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
		events = EPOLLIN | EPOLLRDNORM;

	return events;
}

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
static ssize_t lineevent_get_size(void)
{
#ifdef __x86_64__
	/* i386 has no padding after 'id' */
	if (in_ia32_syscall()) {
		struct compat_gpioeevent_data {
			compat_u64	timestamp;
			u32		id;
		};

		return sizeof(struct compat_gpioeevent_data);
	}
#endif
	return sizeof(struct gpioevent_data);
}
441

442
static ssize_t lineevent_read(struct file *file,
443 444 445 446
			      char __user *buf,
			      size_t count,
			      loff_t *f_ps)
{
447
	struct lineevent_state *le = file->private_data;
448 449
	struct gpioevent_data ge;
	ssize_t bytes_read = 0;
450
	ssize_t ge_size;
451 452
	int ret;

453 454 455 456 457 458 459 460 461 462 463
	/*
	 * When compatible system call is being used the struct gpioevent_data,
	 * in case of at least ia32, has different size due to the alignment
	 * differences. Because we have first member 64 bits followed by one of
	 * 32 bits there is no gap between them. The only difference is the
	 * padding at the end of the data structure. Hence, we calculate the
	 * actual sizeof() and pass this as an argument to copy_to_user() to
	 * drop unneeded bytes from the output.
	 */
	ge_size = lineevent_get_size();
	if (count < ge_size)
464 465 466 467 468 469 470 471 472 473
		return -EINVAL;

	do {
		spin_lock(&le->wait.lock);
		if (kfifo_is_empty(&le->events)) {
			if (bytes_read) {
				spin_unlock(&le->wait.lock);
				return bytes_read;
			}

474
			if (file->f_flags & O_NONBLOCK) {
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
				spin_unlock(&le->wait.lock);
				return -EAGAIN;
			}

			ret = wait_event_interruptible_locked(le->wait,
					!kfifo_is_empty(&le->events));
			if (ret) {
				spin_unlock(&le->wait.lock);
				return ret;
			}
		}

		ret = kfifo_out(&le->events, &ge, 1);
		spin_unlock(&le->wait.lock);
		if (ret != 1) {
			/*
			 * This should never happen - we were holding the lock
			 * from the moment we learned the fifo is no longer
			 * empty until now.
			 */
			ret = -EIO;
			break;
		}

499
		if (copy_to_user(buf + bytes_read, &ge, ge_size))
500
			return -EFAULT;
501 502
		bytes_read += ge_size;
	} while (count >= bytes_read + ge_size);
503 504 505 506

	return bytes_read;
}

507
static void lineevent_free(struct lineevent_state *le)
508
{
509 510 511 512
	if (le->irq)
		free_irq(le->irq, le);
	if (le->desc)
		gpiod_free(le->desc);
513
	kfree(le->label);
514
	put_device(&le->gdev->dev);
515
	kfree(le);
516 517 518 519 520
}

static int lineevent_release(struct inode *inode, struct file *file)
{
	lineevent_free(file->private_data);
521 522 523
	return 0;
}

524
static long lineevent_ioctl(struct file *file, unsigned int cmd,
525 526
			    unsigned long arg)
{
527
	struct lineevent_state *le = file->private_data;
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
	void __user *ip = (void __user *)arg;
	struct gpiohandle_data ghd;

	/*
	 * We can get the value for an event line but not set it,
	 * because it is input by definition.
	 */
	if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
		int val;

		memset(&ghd, 0, sizeof(ghd));

		val = gpiod_get_value_cansleep(le->desc);
		if (val < 0)
			return val;
		ghd.values[0] = val;

		if (copy_to_user(ip, &ghd, sizeof(ghd)))
			return -EFAULT;

		return 0;
	}
	return -EINVAL;
}

#ifdef CONFIG_COMPAT
554
static long lineevent_ioctl_compat(struct file *file, unsigned int cmd,
555 556
				   unsigned long arg)
{
557
	return lineevent_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
}
#endif

static const struct file_operations lineevent_fileops = {
	.release = lineevent_release,
	.read = lineevent_read,
	.poll = lineevent_poll,
	.owner = THIS_MODULE,
	.llseek = noop_llseek,
	.unlocked_ioctl = lineevent_ioctl,
#ifdef CONFIG_COMPAT
	.compat_ioctl = lineevent_ioctl_compat,
#endif
};

static irqreturn_t lineevent_irq_thread(int irq, void *p)
{
	struct lineevent_state *le = p;
	struct gpioevent_data ge;
	int ret;

	/* Do not leak kernel stack to userspace */
	memset(&ge, 0, sizeof(ge));

	/*
	 * We may be running from a nested threaded interrupt in which case
	 * we didn't get the timestamp from lineevent_irq_handler().
	 */
	if (!le->timestamp)
		ge.timestamp = ktime_get_ns();
	else
		ge.timestamp = le->timestamp;

	if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
	    && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
		int level = gpiod_get_value_cansleep(le->desc);

		if (level)
			/* Emit low-to-high event */
			ge.id = GPIOEVENT_EVENT_RISING_EDGE;
		else
			/* Emit high-to-low event */
			ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
	} else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
		/* Emit low-to-high event */
		ge.id = GPIOEVENT_EVENT_RISING_EDGE;
	} else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
		/* Emit high-to-low event */
		ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
	} else {
		return IRQ_NONE;
	}

	ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
					    1, &le->wait.lock);
	if (ret)
		wake_up_poll(&le->wait, EPOLLIN);
	else
		pr_debug_ratelimited("event FIFO is full - event dropped\n");

	return IRQ_HANDLED;
}

static irqreturn_t lineevent_irq_handler(int irq, void *p)
{
	struct lineevent_state *le = p;

	/*
	 * Just store the timestamp in hardirq context so we get it as
	 * close in time as possible to the actual event.
	 */
	le->timestamp = ktime_get_ns();

	return IRQ_WAKE_THREAD;
}

static int lineevent_create(struct gpio_device *gdev, void __user *ip)
{
	struct gpioevent_request eventreq;
	struct lineevent_state *le;
	struct gpio_desc *desc;
	struct file *file;
	u32 offset;
	u32 lflags;
	u32 eflags;
	int fd;
	int ret;
645
	int irq, irqflags = 0;
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695

	if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
		return -EFAULT;

	offset = eventreq.lineoffset;
	lflags = eventreq.handleflags;
	eflags = eventreq.eventflags;

	desc = gpiochip_get_desc(gdev->chip, offset);
	if (IS_ERR(desc))
		return PTR_ERR(desc);

	/* Return an error if a unknown flag is set */
	if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
	    (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
		return -EINVAL;

	/* This is just wrong: we don't look for events on output lines */
	if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
	    (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
	    (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
		return -EINVAL;

	/* Only one bias flag can be set. */
	if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
	     (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
			GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
	    ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
	     (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
		return -EINVAL;

	le = kzalloc(sizeof(*le), GFP_KERNEL);
	if (!le)
		return -ENOMEM;
	le->gdev = gdev;
	get_device(&gdev->dev);

	/* Make sure this is terminated */
	eventreq.consumer_label[sizeof(eventreq.consumer_label)-1] = '\0';
	if (strlen(eventreq.consumer_label)) {
		le->label = kstrdup(eventreq.consumer_label,
				    GFP_KERNEL);
		if (!le->label) {
			ret = -ENOMEM;
			goto out_free_le;
		}
	}

	ret = gpiod_request(desc, le->label);
	if (ret)
696
		goto out_free_le;
697 698 699
	le->desc = desc;
	le->eflags = eflags;

700
	linehandle_flags_to_desc_flags(lflags, &desc->flags);
701 702 703

	ret = gpiod_direction_input(desc);
	if (ret)
704
		goto out_free_le;
705

706 707
	blocking_notifier_call_chain(&desc->gdev->notifier,
				     GPIOLINE_CHANGED_REQUESTED, desc);
708

709 710
	irq = gpiod_to_irq(desc);
	if (irq <= 0) {
711
		ret = -ENODEV;
712
		goto out_free_le;
713
	}
714
	le->irq = irq;
715 716 717 718 719 720 721 722 723 724 725 726 727 728

	if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
		irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
			IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
	if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
		irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
			IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
	irqflags |= IRQF_ONESHOT;

	INIT_KFIFO(le->events);
	init_waitqueue_head(&le->wait);

	/* Request a thread to read the events */
	ret = request_threaded_irq(le->irq,
729 730 731 732 733
				   lineevent_irq_handler,
				   lineevent_irq_thread,
				   irqflags,
				   le->label,
				   le);
734
	if (ret)
735
		goto out_free_le;
736 737 738 739

	fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
	if (fd < 0) {
		ret = fd;
740
		goto out_free_le;
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
	}

	file = anon_inode_getfile("gpio-event",
				  &lineevent_fileops,
				  le,
				  O_RDONLY | O_CLOEXEC);
	if (IS_ERR(file)) {
		ret = PTR_ERR(file);
		goto out_put_unused_fd;
	}

	eventreq.fd = fd;
	if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
		/*
		 * fput() will trigger the release() callback, so do not go onto
		 * the regular error cleanup path here.
		 */
		fput(file);
		put_unused_fd(fd);
		return -EFAULT;
	}

	fd_install(fd, file);

	return 0;

out_put_unused_fd:
	put_unused_fd(fd);
out_free_le:
770
	lineevent_free(le);
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
	return ret;
}

static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
				  struct gpioline_info *info)
{
	struct gpio_chip *gc = desc->gdev->chip;
	bool ok_for_pinctrl;
	unsigned long flags;

	/*
	 * This function takes a mutex so we must check this before taking
	 * the spinlock.
	 *
	 * FIXME: find a non-racy way to retrieve this information. Maybe a
	 * lock common to both frameworks?
	 */
	ok_for_pinctrl =
		pinctrl_gpio_can_use_line(gc->base + info->line_offset);

	spin_lock_irqsave(&gpio_lock, flags);

	if (desc->name) {
		strncpy(info->name, desc->name, sizeof(info->name));
		info->name[sizeof(info->name) - 1] = '\0';
	} else {
		info->name[0] = '\0';
	}

	if (desc->label) {
		strncpy(info->consumer, desc->label, sizeof(info->consumer));
		info->consumer[sizeof(info->consumer) - 1] = '\0';
	} else {
		info->consumer[0] = '\0';
	}

	/*
	 * Userspace only need to know that the kernel is using this GPIO so
	 * it can't use it.
	 */
	info->flags = 0;
	if (test_bit(FLAG_REQUESTED, &desc->flags) ||
	    test_bit(FLAG_IS_HOGGED, &desc->flags) ||
	    test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
	    test_bit(FLAG_EXPORT, &desc->flags) ||
	    test_bit(FLAG_SYSFS, &desc->flags) ||
	    !ok_for_pinctrl)
		info->flags |= GPIOLINE_FLAG_KERNEL;
	if (test_bit(FLAG_IS_OUT, &desc->flags))
		info->flags |= GPIOLINE_FLAG_IS_OUT;
	if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
		info->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
	if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
		info->flags |= (GPIOLINE_FLAG_OPEN_DRAIN |
				GPIOLINE_FLAG_IS_OUT);
	if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
		info->flags |= (GPIOLINE_FLAG_OPEN_SOURCE |
				GPIOLINE_FLAG_IS_OUT);
	if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
		info->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
	if (test_bit(FLAG_PULL_DOWN, &desc->flags))
		info->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
	if (test_bit(FLAG_PULL_UP, &desc->flags))
		info->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;

	spin_unlock_irqrestore(&gpio_lock, flags);
}

struct gpio_chardev_data {
	struct gpio_device *gdev;
	wait_queue_head_t wait;
	DECLARE_KFIFO(events, struct gpioline_info_changed, 32);
	struct notifier_block lineinfo_changed_nb;
	unsigned long *watched_lines;
};

/*
 * gpio_ioctl() - ioctl handler for the GPIO chardev
 */
850
static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
851
{
K
Kent Gibson 已提交
852 853
	struct gpio_chardev_data *cdev = file->private_data;
	struct gpio_device *gdev = cdev->gdev;
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
	struct gpio_chip *gc = gdev->chip;
	void __user *ip = (void __user *)arg;
	struct gpio_desc *desc;
	__u32 offset;

	/* We fail any subsequent ioctl():s when the chip is gone */
	if (!gc)
		return -ENODEV;

	/* Fill in the struct and pass to userspace */
	if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
		struct gpiochip_info chipinfo;

		memset(&chipinfo, 0, sizeof(chipinfo));

		strncpy(chipinfo.name, dev_name(&gdev->dev),
			sizeof(chipinfo.name));
		chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
		strncpy(chipinfo.label, gdev->label,
			sizeof(chipinfo.label));
		chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
		chipinfo.lines = gdev->ngpio;
		if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
			return -EFAULT;
		return 0;
	} else if (cmd == GPIO_GET_LINEINFO_IOCTL) {
		struct gpioline_info lineinfo;

		if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
			return -EFAULT;

885
		/* this doubles as a range check on line_offset */
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
		desc = gpiochip_get_desc(gc, lineinfo.line_offset);
		if (IS_ERR(desc))
			return PTR_ERR(desc);

		gpio_desc_to_lineinfo(desc, &lineinfo);

		if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
			return -EFAULT;
		return 0;
	} else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
		return linehandle_create(gdev, ip);
	} else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
		return lineevent_create(gdev, ip);
	} else if (cmd == GPIO_GET_LINEINFO_WATCH_IOCTL) {
		struct gpioline_info lineinfo;

		if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
			return -EFAULT;

905
		/* this doubles as a range check on line_offset */
906 907 908 909
		desc = gpiochip_get_desc(gc, lineinfo.line_offset);
		if (IS_ERR(desc))
			return PTR_ERR(desc);

910
		if (test_and_set_bit(lineinfo.line_offset, cdev->watched_lines))
911 912 913 914
			return -EBUSY;

		gpio_desc_to_lineinfo(desc, &lineinfo);

915
		if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
916
			clear_bit(lineinfo.line_offset, cdev->watched_lines);
917
			return -EFAULT;
918
		}
919 920 921 922 923 924

		return 0;
	} else if (cmd == GPIO_GET_LINEINFO_UNWATCH_IOCTL) {
		if (copy_from_user(&offset, ip, sizeof(offset)))
			return -EFAULT;

925 926
		if (offset >= cdev->gdev->ngpio)
			return -EINVAL;
927

928
		if (!test_and_clear_bit(offset, cdev->watched_lines))
929 930 931 932 933 934 935 936
			return -EBUSY;

		return 0;
	}
	return -EINVAL;
}

#ifdef CONFIG_COMPAT
937
static long gpio_ioctl_compat(struct file *file, unsigned int cmd,
938 939
			      unsigned long arg)
{
940
	return gpio_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
941 942 943 944 945 946 947 948 949 950 951 952
}
#endif

static struct gpio_chardev_data *
to_gpio_chardev_data(struct notifier_block *nb)
{
	return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
}

static int lineinfo_changed_notify(struct notifier_block *nb,
				   unsigned long action, void *data)
{
K
Kent Gibson 已提交
953
	struct gpio_chardev_data *cdev = to_gpio_chardev_data(nb);
954 955 956 957
	struct gpioline_info_changed chg;
	struct gpio_desc *desc = data;
	int ret;

K
Kent Gibson 已提交
958
	if (!test_bit(gpio_chip_hwgpio(desc), cdev->watched_lines))
959 960 961 962 963 964 965 966
		return NOTIFY_DONE;

	memset(&chg, 0, sizeof(chg));
	chg.info.line_offset = gpio_chip_hwgpio(desc);
	chg.event_type = action;
	chg.timestamp = ktime_get_ns();
	gpio_desc_to_lineinfo(desc, &chg.info);

K
Kent Gibson 已提交
967
	ret = kfifo_in_spinlocked(&cdev->events, &chg, 1, &cdev->wait.lock);
968
	if (ret)
K
Kent Gibson 已提交
969
		wake_up_poll(&cdev->wait, EPOLLIN);
970 971 972 973 974 975
	else
		pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");

	return NOTIFY_OK;
}

976
static __poll_t lineinfo_watch_poll(struct file *file,
977 978
				    struct poll_table_struct *pollt)
{
K
Kent Gibson 已提交
979
	struct gpio_chardev_data *cdev = file->private_data;
980 981
	__poll_t events = 0;

K
Kent Gibson 已提交
982
	poll_wait(file, &cdev->wait, pollt);
983

K
Kent Gibson 已提交
984 985
	if (!kfifo_is_empty_spinlocked_noirqsave(&cdev->events,
						 &cdev->wait.lock))
986 987 988 989 990
		events = EPOLLIN | EPOLLRDNORM;

	return events;
}

991
static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
992 993
				   size_t count, loff_t *off)
{
K
Kent Gibson 已提交
994
	struct gpio_chardev_data *cdev = file->private_data;
995 996 997 998 999 1000 1001 1002
	struct gpioline_info_changed event;
	ssize_t bytes_read = 0;
	int ret;

	if (count < sizeof(event))
		return -EINVAL;

	do {
K
Kent Gibson 已提交
1003 1004
		spin_lock(&cdev->wait.lock);
		if (kfifo_is_empty(&cdev->events)) {
1005
			if (bytes_read) {
K
Kent Gibson 已提交
1006
				spin_unlock(&cdev->wait.lock);
1007 1008 1009
				return bytes_read;
			}

1010
			if (file->f_flags & O_NONBLOCK) {
K
Kent Gibson 已提交
1011
				spin_unlock(&cdev->wait.lock);
1012 1013 1014
				return -EAGAIN;
			}

K
Kent Gibson 已提交
1015 1016
			ret = wait_event_interruptible_locked(cdev->wait,
					!kfifo_is_empty(&cdev->events));
1017
			if (ret) {
K
Kent Gibson 已提交
1018
				spin_unlock(&cdev->wait.lock);
1019 1020 1021 1022
				return ret;
			}
		}

K
Kent Gibson 已提交
1023 1024
		ret = kfifo_out(&cdev->events, &event, 1);
		spin_unlock(&cdev->wait.lock);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
		if (ret != 1) {
			ret = -EIO;
			break;
			/* We should never get here. See lineevent_read(). */
		}

		if (copy_to_user(buf + bytes_read, &event, sizeof(event)))
			return -EFAULT;
		bytes_read += sizeof(event);
	} while (count >= bytes_read + sizeof(event));

	return bytes_read;
}

/**
 * gpio_chrdev_open() - open the chardev for ioctl operations
 * @inode: inode for this chardev
1042
 * @file: file struct for storing private data
1043 1044
 * Returns 0 on success
 */
1045
static int gpio_chrdev_open(struct inode *inode, struct file *file)
1046 1047
{
	struct gpio_device *gdev = container_of(inode->i_cdev,
1048
						struct gpio_device, chrdev);
K
Kent Gibson 已提交
1049
	struct gpio_chardev_data *cdev;
1050 1051 1052 1053 1054 1055
	int ret = -ENOMEM;

	/* Fail on open if the backing gpiochip is gone */
	if (!gdev->chip)
		return -ENODEV;

K
Kent Gibson 已提交
1056 1057
	cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
	if (!cdev)
1058 1059
		return -ENOMEM;

K
Kent Gibson 已提交
1060 1061 1062
	cdev->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
	if (!cdev->watched_lines)
		goto out_free_cdev;
1063

K
Kent Gibson 已提交
1064 1065 1066
	init_waitqueue_head(&cdev->wait);
	INIT_KFIFO(cdev->events);
	cdev->gdev = gdev;
1067

K
Kent Gibson 已提交
1068
	cdev->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
1069
	ret = blocking_notifier_chain_register(&gdev->notifier,
K
Kent Gibson 已提交
1070
					       &cdev->lineinfo_changed_nb);
1071 1072 1073 1074
	if (ret)
		goto out_free_bitmap;

	get_device(&gdev->dev);
K
Kent Gibson 已提交
1075
	file->private_data = cdev;
1076

1077
	ret = nonseekable_open(inode, file);
1078 1079 1080 1081 1082 1083
	if (ret)
		goto out_unregister_notifier;

	return ret;

out_unregister_notifier:
1084
	blocking_notifier_chain_unregister(&gdev->notifier,
K
Kent Gibson 已提交
1085
					   &cdev->lineinfo_changed_nb);
1086
out_free_bitmap:
K
Kent Gibson 已提交
1087 1088 1089
	bitmap_free(cdev->watched_lines);
out_free_cdev:
	kfree(cdev);
1090 1091 1092 1093 1094 1095
	return ret;
}

/**
 * gpio_chrdev_release() - close chardev after ioctl operations
 * @inode: inode for this chardev
1096
 * @file: file struct for storing private data
1097 1098
 * Returns 0 on success
 */
1099
static int gpio_chrdev_release(struct inode *inode, struct file *file)
1100
{
K
Kent Gibson 已提交
1101 1102
	struct gpio_chardev_data *cdev = file->private_data;
	struct gpio_device *gdev = cdev->gdev;
1103

K
Kent Gibson 已提交
1104
	bitmap_free(cdev->watched_lines);
1105
	blocking_notifier_chain_unregister(&gdev->notifier,
K
Kent Gibson 已提交
1106
					   &cdev->lineinfo_changed_nb);
1107
	put_device(&gdev->dev);
K
Kent Gibson 已提交
1108
	kfree(cdev);
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147

	return 0;
}

static const struct file_operations gpio_fileops = {
	.release = gpio_chrdev_release,
	.open = gpio_chrdev_open,
	.poll = lineinfo_watch_poll,
	.read = lineinfo_watch_read,
	.owner = THIS_MODULE,
	.llseek = no_llseek,
	.unlocked_ioctl = gpio_ioctl,
#ifdef CONFIG_COMPAT
	.compat_ioctl = gpio_ioctl_compat,
#endif
};

int gpiolib_cdev_register(struct gpio_device *gdev, dev_t devt)
{
	int ret;

	cdev_init(&gdev->chrdev, &gpio_fileops);
	gdev->chrdev.owner = THIS_MODULE;
	gdev->dev.devt = MKDEV(MAJOR(devt), gdev->id);

	ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
	if (ret)
		return ret;

	chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
		 MAJOR(devt), gdev->id);

	return 0;
}

void gpiolib_cdev_unregister(struct gpio_device *gdev)
{
	cdev_device_del(&gdev->chrdev, &gdev->dev);
}