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

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

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

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/*
 * Array sizes must ensure 64-bit alignment and not create holes in the
 * struct packing.
 */
static_assert(IS_ALIGNED(GPIO_V2_LINES_MAX, 2));
static_assert(IS_ALIGNED(GPIO_MAX_NAME_SIZE, 8));

/*
 * Check that uAPI structs are 64-bit aligned for 32/64-bit compatibility
 */
static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_attribute), 8));
static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config_attribute), 8));
static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config), 8));
static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_request), 8));
static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info), 8));
static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info_changed), 8));
static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_event), 8));
static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_values), 8));

52 53 54 55 56 57 58 59 60 61
/* 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
 */

62
#ifdef CONFIG_GPIO_CDEV_V1
63 64 65 66 67
/**
 * 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
68
 * @num_descs: the number of descriptors held in the descs array
69 70 71 72 73
 */
struct linehandle_state {
	struct gpio_device *gdev;
	const char *label;
	struct gpio_desc *descs[GPIOHANDLES_MAX];
74
	u32 num_descs;
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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
};

#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 |
127
		       GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
128 129 130 131 132 133 134
	    ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
	     (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
		return -EINVAL;

	return 0;
}

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
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);
}

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
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;

167
	for (i = 0; i < lh->num_descs; i++) {
168
		desc = lh->descs[i];
169
		linehandle_flags_to_desc_flags(gcnf.flags, &desc->flags);
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

		/*
		 * 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;
		}

187
		blocking_notifier_call_chain(&desc->gdev->notifier,
188 189
					     GPIO_V2_LINE_CHANGED_CONFIG,
					     desc);
190 191 192 193
	}
	return 0;
}

194
static long linehandle_ioctl(struct file *file, unsigned int cmd,
195 196
			     unsigned long arg)
{
197
	struct linehandle_state *lh = file->private_data;
198 199 200
	void __user *ip = (void __user *)arg;
	struct gpiohandle_data ghd;
	DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
201 202
	unsigned int i;
	int ret;
203

204 205 206 207 208 209
	switch (cmd) {
	case GPIOHANDLE_GET_LINE_VALUES_IOCTL:
		/* NOTE: It's okay to read values of output lines */
		ret = gpiod_get_array_value_complex(false, true,
						    lh->num_descs, lh->descs,
						    NULL, vals);
210 211 212 213
		if (ret)
			return ret;

		memset(&ghd, 0, sizeof(ghd));
214
		for (i = 0; i < lh->num_descs; i++)
215 216 217 218 219 220
			ghd.values[i] = test_bit(i, vals);

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

		return 0;
221
	case GPIOHANDLE_SET_LINE_VALUES_IOCTL:
222 223 224 225 226 227 228 229 230 231 232
		/*
		 * 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] */
233
		for (i = 0; i < lh->num_descs; i++)
234 235 236 237
			__assign_bit(i, vals, ghd.values[i]);

		/* Reuse the array setting function */
		return gpiod_set_array_value_complex(false,
238
						     true,
239
						     lh->num_descs,
240 241 242
						     lh->descs,
						     NULL,
						     vals);
243
	case GPIOHANDLE_SET_CONFIG_IOCTL:
244
		return linehandle_set_config(lh, ip);
245 246
	default:
		return -EINVAL;
247 248 249 250
	}
}

#ifdef CONFIG_COMPAT
251
static long linehandle_ioctl_compat(struct file *file, unsigned int cmd,
252
				    unsigned long arg)
253
{
254
	return linehandle_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
255 256 257
}
#endif

258
static void linehandle_free(struct linehandle_state *lh)
259 260 261
{
	int i;

262
	for (i = 0; i < lh->num_descs; i++)
263 264
		if (lh->descs[i])
			gpiod_free(lh->descs[i]);
265
	kfree(lh->label);
266
	put_device(&lh->gdev->dev);
267
	kfree(lh);
268 269 270 271 272
}

static int linehandle_release(struct inode *inode, struct file *file)
{
	linehandle_free(file->private_data);
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
	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;
291
	int fd, i, ret;
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
	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);

311 312 313 314 315
	if (handlereq.consumer_label[0] != '\0') {
		/* label is only initialized if consumer_label is set */
		lh->label = kstrndup(handlereq.consumer_label,
				     sizeof(handlereq.consumer_label) - 1,
				     GFP_KERNEL);
316 317 318 319 320 321
		if (!lh->label) {
			ret = -ENOMEM;
			goto out_free_lh;
		}
	}

322 323
	lh->num_descs = handlereq.lines;

324 325 326 327 328 329 330
	/* 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);
331
			goto out_free_lh;
332 333
		}

334
		ret = gpiod_request_user(desc, lh->label);
335
		if (ret)
336
			goto out_free_lh;
337
		lh->descs[i] = desc;
338
		linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags);
339 340 341

		ret = gpiod_set_transitory(desc, false);
		if (ret < 0)
342
			goto out_free_lh;
343 344 345 346 347 348 349 350 351 352

		/*
		 * 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)
353
				goto out_free_lh;
354 355 356
		} else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
			ret = gpiod_direction_input(desc);
			if (ret)
357
				goto out_free_lh;
358 359
		}

360
		blocking_notifier_call_chain(&desc->gdev->notifier,
361
					     GPIO_V2_LINE_CHANGED_REQUESTED, desc);
362 363 364 365 366 367 368 369

		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;
370
		goto out_free_lh;
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
	}

	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",
396
		lh->num_descs);
397 398 399 400 401 402

	return 0;

out_put_unused_fd:
	put_unused_fd(fd);
out_free_lh:
403
	linehandle_free(lh);
404 405
	return ret;
}
406 407 408 409 410
#endif /* CONFIG_GPIO_CDEV_V1 */

/**
 * struct line - contains the state of a requested line
 * @desc: the GPIO descriptor for this line.
411 412 413 414 415 416 417 418 419 420
 * @req: the corresponding line request
 * @irq: the interrupt triggered in response to events on this GPIO
 * @eflags: the edge flags, GPIO_V2_LINE_FLAG_EDGE_RISING and/or
 * GPIO_V2_LINE_FLAG_EDGE_FALLING, indicating the edge detection applied
 * @timestamp_ns: cache for the timestamp storing it between hardirq and
 * IRQ thread, used to bring the timestamp close to the actual event
 * @req_seqno: the seqno for the current edge event in the sequence of
 * events for the corresponding line request. This is drawn from the @req.
 * @line_seqno: the seqno for the current edge event in the sequence of
 * events for this line.
421 422 423
 * @work: the worker that implements software debouncing
 * @sw_debounced: flag indicating if the software debouncer is active
 * @level: the current debounced physical level of the line
424 425 426
 */
struct line {
	struct gpio_desc *desc;
427 428 429 430 431
	/*
	 * -- edge detector specific fields --
	 */
	struct linereq *req;
	unsigned int irq;
432 433 434 435 436 437
	/*
	 * eflags is set by edge_detector_setup(), edge_detector_stop() and
	 * edge_detector_update(), which are themselves mutually exclusive,
	 * and is accessed by edge_irq_thread() and debounce_work_func(),
	 * which can both live with a slightly stale value.
	 */
438 439 440 441 442 443 444 445
	u64 eflags;
	/*
	 * timestamp_ns and req_seqno are accessed only by
	 * edge_irq_handler() and edge_irq_thread(), which are themselves
	 * mutually exclusive, so no additional protection is necessary.
	 */
	u64 timestamp_ns;
	u32 req_seqno;
446 447 448 449 450
	/*
	 * line_seqno is accessed by either edge_irq_thread() or
	 * debounce_work_func(), which are themselves mutually exclusive,
	 * so no additional protection is necessary.
	 */
451
	u32 line_seqno;
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
	/*
	 * -- debouncer specific fields --
	 */
	struct delayed_work work;
	/*
	 * sw_debounce is accessed by linereq_set_config(), which is the
	 * only setter, and linereq_get_values(), which can live with a
	 * slightly stale value.
	 */
	unsigned int sw_debounced;
	/*
	 * level is accessed by debounce_work_func(), which is the only
	 * setter, and linereq_get_values() which can live with a slightly
	 * stale value.
	 */
	unsigned int level;
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
	/*
	 * -- hte specific fields --
	 */
	struct hte_ts_desc hdesc;
	/*
	 * HTE provider sets line level at the time of event. The valid
	 * value is 0 or 1 and negative value for an error.
	 */
	int raw_level;
	/*
	 * when sw_debounce is set on HTE enabled line, this is running
	 * counter of the discarded events.
	 */
	u32 total_discard_seq;
	/*
	 * when sw_debounce is set on HTE enabled line, this variable records
	 * last sequence number before debounce period expires.
	 */
	u32 last_seqno;
487 488 489 490 491 492 493
};

/**
 * struct linereq - contains the state of a userspace line request
 * @gdev: the GPIO device the line request pertains to
 * @label: consumer label used to tag GPIO descriptors
 * @num_lines: the number of lines in the lines array
494 495 496 497 498 499
 * @wait: wait queue that handles blocking reads of events
 * @event_buffer_size: the number of elements allocated in @events
 * @events: KFIFO for the GPIO events
 * @seqno: the sequence number for edge events generated on all lines in
 * this line request.  Note that this is not used when @num_lines is 1, as
 * the line_seqno is then the same and is cheaper to calculate.
500 501
 * @config_mutex: mutex for serializing ioctl() calls to ensure consistency
 * of configuration, particularly multi-step accesses to desc flags.
502 503 504 505 506 507
 * @lines: the lines held by this line request, with @num_lines elements.
 */
struct linereq {
	struct gpio_device *gdev;
	const char *label;
	u32 num_lines;
508 509 510 511
	wait_queue_head_t wait;
	u32 event_buffer_size;
	DECLARE_KFIFO_PTR(events, struct gpio_v2_line_event);
	atomic_t seqno;
512
	struct mutex config_mutex;
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
	struct line lines[];
};

#define GPIO_V2_LINE_BIAS_FLAGS \
	(GPIO_V2_LINE_FLAG_BIAS_PULL_UP | \
	 GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN | \
	 GPIO_V2_LINE_FLAG_BIAS_DISABLED)

#define GPIO_V2_LINE_DIRECTION_FLAGS \
	(GPIO_V2_LINE_FLAG_INPUT | \
	 GPIO_V2_LINE_FLAG_OUTPUT)

#define GPIO_V2_LINE_DRIVE_FLAGS \
	(GPIO_V2_LINE_FLAG_OPEN_DRAIN | \
	 GPIO_V2_LINE_FLAG_OPEN_SOURCE)

529 530 531 532
#define GPIO_V2_LINE_EDGE_FLAGS \
	(GPIO_V2_LINE_FLAG_EDGE_RISING | \
	 GPIO_V2_LINE_FLAG_EDGE_FALLING)

533 534
#define GPIO_V2_LINE_FLAG_EDGE_BOTH GPIO_V2_LINE_EDGE_FLAGS

535 536 537 538
#define GPIO_V2_LINE_VALID_FLAGS \
	(GPIO_V2_LINE_FLAG_ACTIVE_LOW | \
	 GPIO_V2_LINE_DIRECTION_FLAGS | \
	 GPIO_V2_LINE_DRIVE_FLAGS | \
539
	 GPIO_V2_LINE_EDGE_FLAGS | \
540
	 GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME | \
541
	 GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE | \
542 543
	 GPIO_V2_LINE_BIAS_FLAGS)

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
static void linereq_put_event(struct linereq *lr,
			      struct gpio_v2_line_event *le)
{
	bool overflow = false;

	spin_lock(&lr->wait.lock);
	if (kfifo_is_full(&lr->events)) {
		overflow = true;
		kfifo_skip(&lr->events);
	}
	kfifo_in(&lr->events, le, 1);
	spin_unlock(&lr->wait.lock);
	if (!overflow)
		wake_up_poll(&lr->wait, EPOLLIN);
	else
		pr_debug_ratelimited("event FIFO is full - event dropped\n");
}

562 563 564 565
static u64 line_event_timestamp(struct line *line)
{
	if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &line->desc->flags))
		return ktime_get_real_ns();
566 567
	else if (test_bit(FLAG_EVENT_CLOCK_HTE, &line->desc->flags))
		return line->timestamp_ns;
568 569 570 571

	return ktime_get_ns();
}

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 645 646 647 648 649 650 651 652 653 654 655 656 657
static enum hte_return process_hw_ts_thread(void *p)
{
	struct line *line;
	struct linereq *lr;
	struct gpio_v2_line_event le;
	int level;
	u64 eflags;

	if (!p)
		return HTE_CB_HANDLED;

	line = p;
	lr = line->req;

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

	le.timestamp_ns = line->timestamp_ns;
	eflags = READ_ONCE(line->eflags);

	if (eflags == GPIO_V2_LINE_FLAG_EDGE_BOTH) {
		if (line->raw_level >= 0) {
			if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
				level = !line->raw_level;
			else
				level = line->raw_level;
		} else {
			level = gpiod_get_value_cansleep(line->desc);
		}

		if (level)
			le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
		else
			le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
	} else if (eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) {
		/* Emit low-to-high event */
		le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
	} else if (eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) {
		/* Emit high-to-low event */
		le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
	} else {
		return HTE_CB_HANDLED;
	}
	le.line_seqno = line->line_seqno;
	le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
	le.offset = gpio_chip_hwgpio(line->desc);

	linereq_put_event(lr, &le);

	return HTE_CB_HANDLED;
}

static enum hte_return process_hw_ts(struct hte_ts_data *ts, void *p)
{
	struct line *line;
	struct linereq *lr;
	int diff_seqno = 0;

	if (!ts || !p)
		return HTE_CB_HANDLED;

	line = p;
	line->timestamp_ns = ts->tsc;
	line->raw_level = ts->raw_level;
	lr = line->req;

	if (READ_ONCE(line->sw_debounced)) {
		line->total_discard_seq++;
		line->last_seqno = ts->seq;
		mod_delayed_work(system_wq, &line->work,
		  usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
	} else {
		if (unlikely(ts->seq < line->line_seqno))
			return HTE_CB_HANDLED;

		diff_seqno = ts->seq - line->line_seqno;
		line->line_seqno = ts->seq;
		if (lr->num_lines != 1)
			line->req_seqno = atomic_add_return(diff_seqno,
							    &lr->seqno);

		return HTE_RUN_SECOND_CB;
	}

	return HTE_CB_HANDLED;
}

658 659 660 661 662
static irqreturn_t edge_irq_thread(int irq, void *p)
{
	struct line *line = p;
	struct linereq *lr = line->req;
	struct gpio_v2_line_event le;
663
	u64 eflags;
664 665 666 667 668 669 670 671 672 673 674 675

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

	if (line->timestamp_ns) {
		le.timestamp_ns = line->timestamp_ns;
	} else {
		/*
		 * We may be running from a nested threaded interrupt in
		 * which case we didn't get the timestamp from
		 * edge_irq_handler().
		 */
676
		le.timestamp_ns = line_event_timestamp(line);
677 678 679 680 681
		if (lr->num_lines != 1)
			line->req_seqno = atomic_inc_return(&lr->seqno);
	}
	line->timestamp_ns = 0;

682
	eflags = READ_ONCE(line->eflags);
683
	if (eflags == GPIO_V2_LINE_FLAG_EDGE_BOTH) {
684 685 686 687 688 689 690 691
		int level = gpiod_get_value_cansleep(line->desc);

		if (level)
			/* Emit low-to-high event */
			le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
		else
			/* Emit high-to-low event */
			le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
692
	} else if (eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) {
693 694
		/* Emit low-to-high event */
		le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
695
	} else if (eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) {
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
		/* Emit high-to-low event */
		le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
	} else {
		return IRQ_NONE;
	}
	line->line_seqno++;
	le.line_seqno = line->line_seqno;
	le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
	le.offset = gpio_chip_hwgpio(line->desc);

	linereq_put_event(lr, &le);

	return IRQ_HANDLED;
}

static irqreturn_t edge_irq_handler(int irq, void *p)
{
	struct line *line = p;
	struct linereq *lr = line->req;

	/*
	 * Just store the timestamp in hardirq context so we get it as
	 * close in time as possible to the actual event.
	 */
720
	line->timestamp_ns = line_event_timestamp(line);
721 722 723 724 725 726 727

	if (lr->num_lines != 1)
		line->req_seqno = atomic_inc_return(&lr->seqno);

	return IRQ_WAKE_THREAD;
}

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
/*
 * returns the current debounced logical value.
 */
static bool debounced_value(struct line *line)
{
	bool value;

	/*
	 * minor race - debouncer may be stopped here, so edge_detector_stop()
	 * must leave the value unchanged so the following will read the level
	 * from when the debouncer was last running.
	 */
	value = READ_ONCE(line->level);

	if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
		value = !value;

	return value;
}

static irqreturn_t debounce_irq_handler(int irq, void *p)
{
	struct line *line = p;

	mod_delayed_work(system_wq, &line->work,
		usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));

	return IRQ_HANDLED;
}

static void debounce_work_func(struct work_struct *work)
{
	struct gpio_v2_line_event le;
	struct line *line = container_of(work, struct line, work.work);
	struct linereq *lr;
763
	int level, diff_seqno;
764
	u64 eflags;
765

766 767 768 769 770 771 772
	if (test_bit(FLAG_EVENT_CLOCK_HTE, &line->desc->flags)) {
		level = line->raw_level;
		if (level < 0)
			level = gpiod_get_raw_value_cansleep(line->desc);
	} else {
		level = gpiod_get_raw_value_cansleep(line->desc);
	}
773 774 775 776 777 778 779 780 781 782 783
	if (level < 0) {
		pr_debug_ratelimited("debouncer failed to read line value\n");
		return;
	}

	if (READ_ONCE(line->level) == level)
		return;

	WRITE_ONCE(line->level, level);

	/* -- edge detection -- */
784 785
	eflags = READ_ONCE(line->eflags);
	if (!eflags)
786 787 788 789 790 791 792
		return;

	/* switch from physical level to logical - if they differ */
	if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
		level = !level;

	/* ignore edges that are not being monitored */
793 794
	if (((eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) && !level) ||
	    ((eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) && level))
795 796 797 798 799 800
		return;

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

	lr = line->req;
801
	le.timestamp_ns = line_event_timestamp(line);
802
	le.offset = gpio_chip_hwgpio(line->desc);
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
	if (test_bit(FLAG_EVENT_CLOCK_HTE, &line->desc->flags)) {
		/* discard events except the last one */
		line->total_discard_seq -= 1;
		diff_seqno = line->last_seqno - line->total_discard_seq -
				line->line_seqno;
		line->line_seqno = line->last_seqno - line->total_discard_seq;
		le.line_seqno = line->line_seqno;
		le.seqno = (lr->num_lines == 1) ?
			le.line_seqno : atomic_add_return(diff_seqno, &lr->seqno);
	} else {
		line->line_seqno++;
		le.line_seqno = line->line_seqno;
		le.seqno = (lr->num_lines == 1) ?
			le.line_seqno : atomic_inc_return(&lr->seqno);
	}
818 819 820 821 822 823 824 825 826 827 828

	if (level)
		/* Emit low-to-high event */
		le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
	else
		/* Emit high-to-low event */
		le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;

	linereq_put_event(lr, &le);
}

829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
static int hte_edge_setup(struct line *line, u64 eflags)
{
	int ret;
	unsigned long flags = 0;
	struct hte_ts_desc *hdesc = &line->hdesc;

	if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
		flags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
				  HTE_FALLING_EDGE_TS : HTE_RISING_EDGE_TS;
	if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
		flags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
				  HTE_RISING_EDGE_TS : HTE_FALLING_EDGE_TS;

	line->total_discard_seq = 0;

	hte_init_line_attr(hdesc, desc_to_gpio(line->desc), flags,
			   NULL, line->desc);

	ret = hte_ts_get(NULL, hdesc, 0);
	if (ret)
		return ret;

	return hte_request_ts_ns(hdesc, process_hw_ts,
				 process_hw_ts_thread, line);
}

855
static int debounce_setup(struct line *line,
856
			  unsigned int debounce_period_us, bool hte_req)
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
{
	unsigned long irqflags;
	int ret, level, irq;

	/* try hardware */
	ret = gpiod_set_debounce(line->desc, debounce_period_us);
	if (!ret) {
		WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
		return ret;
	}
	if (ret != -ENOTSUPP)
		return ret;

	if (debounce_period_us) {
		/* setup software debounce */
		level = gpiod_get_raw_value_cansleep(line->desc);
		if (level < 0)
			return level;

876 877 878 879
		if (!hte_req) {
			irq = gpiod_to_irq(line->desc);
			if (irq < 0)
				return -ENXIO;
880

881 882 883 884 885 886 887 888 889 890 891 892 893
			irqflags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
			ret = request_irq(irq, debounce_irq_handler, irqflags,
					  line->req->label, line);
			if (ret)
				return ret;
			line->irq = irq;
		} else {
			ret = hte_edge_setup(line,
					     GPIO_V2_LINE_FLAG_EDGE_RISING |
					     GPIO_V2_LINE_FLAG_EDGE_FALLING);
			if (ret)
				return ret;
		}
894

895
		WRITE_ONCE(line->level, level);
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
		WRITE_ONCE(line->sw_debounced, 1);
	}
	return 0;
}

static bool gpio_v2_line_config_debounced(struct gpio_v2_line_config *lc,
					  unsigned int line_idx)
{
	unsigned int i;
	u64 mask = BIT_ULL(line_idx);

	for (i = 0; i < lc->num_attrs; i++) {
		if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
		    (lc->attrs[i].mask & mask))
			return true;
	}
	return false;
}

static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc,
					       unsigned int line_idx)
{
	unsigned int i;
	u64 mask = BIT_ULL(line_idx);

	for (i = 0; i < lc->num_attrs; i++) {
		if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
		    (lc->attrs[i].mask & mask))
			return lc->attrs[i].attr.debounce_period_us;
	}
	return 0;
}

929
static void edge_detector_stop(struct line *line, bool hte_en)
930
{
931
	if (line->irq && !hte_en) {
932 933 934
		free_irq(line->irq, line);
		line->irq = 0;
	}
935

936 937 938
	if (hte_en)
		hte_ts_put(&line->hdesc);

939 940
	cancel_delayed_work_sync(&line->work);
	WRITE_ONCE(line->sw_debounced, 0);
941
	WRITE_ONCE(line->eflags, 0);
942 943
	if (line->desc)
		WRITE_ONCE(line->desc->debounce_period_us, 0);
944
	/* do not change line->level - see comment in debounced_value() */
945 946 947
}

static int edge_detector_setup(struct line *line,
948 949
			       struct gpio_v2_line_config *lc,
			       unsigned int line_idx,
950
			       u64 eflags, bool hte_req)
951
{
952
	u32 debounce_period_us;
953 954 955 956 957 958 959 960 961
	unsigned long irqflags = 0;
	int irq, ret;

	if (eflags && !kfifo_initialized(&line->req->events)) {
		ret = kfifo_alloc(&line->req->events,
				  line->req->event_buffer_size, GFP_KERNEL);
		if (ret)
			return ret;
	}
962
	WRITE_ONCE(line->eflags, eflags);
963 964
	if (gpio_v2_line_config_debounced(lc, line_idx)) {
		debounce_period_us = gpio_v2_line_config_debounce_period(lc, line_idx);
965
		ret = debounce_setup(line, debounce_period_us, hte_req);
966 967 968 969
		if (ret)
			return ret;
		WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
	}
970

971 972
	/* detection disabled or sw debouncer will provide edge detection */
	if (!eflags || READ_ONCE(line->sw_debounced))
973 974
		return 0;

975 976 977
	if (hte_req)
		return hte_edge_setup(line, eflags);

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
	irq = gpiod_to_irq(line->desc);
	if (irq < 0)
		return -ENXIO;

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

	/* Request a thread to read the events */
	ret = request_threaded_irq(irq, edge_irq_handler, edge_irq_thread,
				   irqflags, line->req->label, line);
	if (ret)
		return ret;

	line->irq = irq;
	return 0;
}

1000 1001 1002
static int edge_detector_update(struct line *line,
				struct gpio_v2_line_config *lc,
				unsigned int line_idx,
1003 1004
				u64 flags, bool polarity_change,
				bool prev_hte_flag)
1005
{
1006
	u64 eflags = flags & GPIO_V2_LINE_EDGE_FLAGS;
1007
	unsigned int debounce_period_us =
1008 1009 1010
			gpio_v2_line_config_debounce_period(lc, line_idx);
	bool hte_change = (prev_hte_flag !=
		      ((flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE) != 0));
1011

1012
	if ((READ_ONCE(line->eflags) == eflags) && !polarity_change &&
1013 1014
	    (READ_ONCE(line->desc->debounce_period_us) == debounce_period_us)
	    && !hte_change)
1015 1016 1017 1018
		return 0;

	/* sw debounced and still will be...*/
	if (debounce_period_us && READ_ONCE(line->sw_debounced)) {
1019
		WRITE_ONCE(line->eflags, eflags);
1020
		WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
1021
		return 0;
1022
	}
1023

1024
	/* reconfiguring edge detection or sw debounce being disabled */
1025
	if ((line->irq && !READ_ONCE(line->sw_debounced)) || prev_hte_flag ||
1026
	    (!debounce_period_us && READ_ONCE(line->sw_debounced)))
1027
		edge_detector_stop(line, prev_hte_flag);
1028

1029 1030
	return edge_detector_setup(line, lc, line_idx, eflags,
				   flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE);
1031 1032
}

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
static u64 gpio_v2_line_config_flags(struct gpio_v2_line_config *lc,
				     unsigned int line_idx)
{
	unsigned int i;
	u64 mask = BIT_ULL(line_idx);

	for (i = 0; i < lc->num_attrs; i++) {
		if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_FLAGS) &&
		    (lc->attrs[i].mask & mask))
			return lc->attrs[i].attr.flags;
	}
	return lc->flags;
}

static int gpio_v2_line_config_output_value(struct gpio_v2_line_config *lc,
					    unsigned int line_idx)
{
	unsigned int i;
	u64 mask = BIT_ULL(line_idx);

	for (i = 0; i < lc->num_attrs; i++) {
		if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES) &&
		    (lc->attrs[i].mask & mask))
			return !!(lc->attrs[i].attr.values & mask);
	}
	return 0;
}

static int gpio_v2_line_flags_validate(u64 flags)
{
	/* Return an error if an unknown flag is set */
	if (flags & ~GPIO_V2_LINE_VALID_FLAGS)
		return -EINVAL;
	/*
	 * Do not allow both INPUT and OUTPUT flags to be set as they are
	 * contradictory.
	 */
	if ((flags & GPIO_V2_LINE_FLAG_INPUT) &&
	    (flags & GPIO_V2_LINE_FLAG_OUTPUT))
		return -EINVAL;

1074 1075 1076 1077 1078
	/* Only allow one event clock source */
	if ((flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME) &&
	    (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
		return -EINVAL;

1079 1080 1081 1082 1083
	/* Edge detection requires explicit input. */
	if ((flags & GPIO_V2_LINE_EDGE_FLAGS) &&
	    !(flags & GPIO_V2_LINE_FLAG_INPUT))
		return -EINVAL;

1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
	/*
	 * Do not allow OPEN_SOURCE and 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 & GPIO_V2_LINE_FLAG_OPEN_DRAIN) &&
	    (flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE))
		return -EINVAL;

	/* Drive requires explicit output direction. */
	if ((flags & GPIO_V2_LINE_DRIVE_FLAGS) &&
	    !(flags & GPIO_V2_LINE_FLAG_OUTPUT))
		return -EINVAL;

	/* Bias requires explicit direction. */
	if ((flags & GPIO_V2_LINE_BIAS_FLAGS) &&
	    !(flags & GPIO_V2_LINE_DIRECTION_FLAGS))
		return -EINVAL;

	/* Only one bias flag can be set. */
	if (((flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED) &&
	     (flags & (GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN |
		       GPIO_V2_LINE_FLAG_BIAS_PULL_UP))) ||
	    ((flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN) &&
	     (flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)))
		return -EINVAL;

	return 0;
}

static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc,
					unsigned int num_lines)
{
	unsigned int i;
	u64 flags;
	int ret;

	if (lc->num_attrs > GPIO_V2_LINE_NUM_ATTRS_MAX)
		return -EINVAL;

	if (memchr_inv(lc->padding, 0, sizeof(lc->padding)))
		return -EINVAL;

	for (i = 0; i < num_lines; i++) {
		flags = gpio_v2_line_config_flags(lc, i);
		ret = gpio_v2_line_flags_validate(flags);
		if (ret)
			return ret;
1132 1133 1134 1135 1136

		/* debounce requires explicit input */
		if (gpio_v2_line_config_debounced(lc, i) &&
		    !(flags & GPIO_V2_LINE_FLAG_INPUT))
			return -EINVAL;
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
	}
	return 0;
}

static void gpio_v2_line_config_flags_to_desc_flags(u64 flags,
						    unsigned long *flagsp)
{
	assign_bit(FLAG_ACTIVE_LOW, flagsp,
		   flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW);

	if (flags & GPIO_V2_LINE_FLAG_OUTPUT)
		set_bit(FLAG_IS_OUT, flagsp);
	else if (flags & GPIO_V2_LINE_FLAG_INPUT)
		clear_bit(FLAG_IS_OUT, flagsp);

1152 1153 1154 1155 1156
	assign_bit(FLAG_EDGE_RISING, flagsp,
		   flags & GPIO_V2_LINE_FLAG_EDGE_RISING);
	assign_bit(FLAG_EDGE_FALLING, flagsp,
		   flags & GPIO_V2_LINE_FLAG_EDGE_FALLING);

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
	assign_bit(FLAG_OPEN_DRAIN, flagsp,
		   flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN);
	assign_bit(FLAG_OPEN_SOURCE, flagsp,
		   flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE);

	assign_bit(FLAG_PULL_UP, flagsp,
		   flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP);
	assign_bit(FLAG_PULL_DOWN, flagsp,
		   flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN);
	assign_bit(FLAG_BIAS_DISABLE, flagsp,
		   flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED);
1168 1169 1170

	assign_bit(FLAG_EVENT_CLOCK_REALTIME, flagsp,
		   flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME);
1171 1172
	assign_bit(FLAG_EVENT_CLOCK_HTE, flagsp,
		   flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE);
1173 1174 1175 1176 1177 1178 1179 1180
}

static long linereq_get_values(struct linereq *lr, void __user *ip)
{
	struct gpio_v2_line_values lv;
	DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
	struct gpio_desc **descs;
	unsigned int i, didx, num_get;
1181
	bool val;
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
	int ret;

	/* NOTE: It's ok to read values of output lines. */
	if (copy_from_user(&lv, ip, sizeof(lv)))
		return -EFAULT;

	for (num_get = 0, i = 0; i < lr->num_lines; i++) {
		if (lv.mask & BIT_ULL(i)) {
			num_get++;
			descs = &lr->lines[i].desc;
		}
	}

	if (num_get == 0)
		return -EINVAL;

	if (num_get != 1) {
		descs = kmalloc_array(num_get, sizeof(*descs), GFP_KERNEL);
		if (!descs)
			return -ENOMEM;
		for (didx = 0, i = 0; i < lr->num_lines; i++) {
			if (lv.mask & BIT_ULL(i)) {
				descs[didx] = lr->lines[i].desc;
				didx++;
			}
		}
	}
	ret = gpiod_get_array_value_complex(false, true, num_get,
					    descs, NULL, vals);

	if (num_get != 1)
		kfree(descs);
	if (ret)
		return ret;

	lv.bits = 0;
	for (didx = 0, i = 0; i < lr->num_lines; i++) {
		if (lv.mask & BIT_ULL(i)) {
1220 1221 1222 1223 1224
			if (lr->lines[i].sw_debounced)
				val = debounced_value(&lr->lines[i]);
			else
				val = test_bit(didx, vals);
			if (val)
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
				lv.bits |= BIT_ULL(i);
			didx++;
		}
	}

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

	return 0;
}

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
static long linereq_set_values_unlocked(struct linereq *lr,
					struct gpio_v2_line_values *lv)
{
	DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
	struct gpio_desc **descs;
	unsigned int i, didx, num_set;
	int ret;

	bitmap_zero(vals, GPIO_V2_LINES_MAX);
	for (num_set = 0, i = 0; i < lr->num_lines; i++) {
		if (lv->mask & BIT_ULL(i)) {
			if (!test_bit(FLAG_IS_OUT, &lr->lines[i].desc->flags))
				return -EPERM;
			if (lv->bits & BIT_ULL(i))
				__set_bit(num_set, vals);
			num_set++;
			descs = &lr->lines[i].desc;
		}
	}
	if (num_set == 0)
		return -EINVAL;

	if (num_set != 1) {
		/* build compacted desc array and values */
		descs = kmalloc_array(num_set, sizeof(*descs), GFP_KERNEL);
		if (!descs)
			return -ENOMEM;
		for (didx = 0, i = 0; i < lr->num_lines; i++) {
			if (lv->mask & BIT_ULL(i)) {
				descs[didx] = lr->lines[i].desc;
				didx++;
			}
		}
	}
	ret = gpiod_set_array_value_complex(false, true, num_set,
					    descs, NULL, vals);

	if (num_set != 1)
		kfree(descs);
	return ret;
}

static long linereq_set_values(struct linereq *lr, void __user *ip)
{
	struct gpio_v2_line_values lv;
	int ret;
1282

1283
	if (copy_from_user(&lv, ip, sizeof(lv)))
1284 1285
		return -EFAULT;

1286
	mutex_lock(&lr->config_mutex);
1287

1288 1289 1290 1291 1292 1293 1294
	ret = linereq_set_values_unlocked(lr, &lv);

	mutex_unlock(&lr->config_mutex);

	return ret;
}

1295 1296 1297 1298 1299 1300 1301
static long linereq_set_config_unlocked(struct linereq *lr,
					struct gpio_v2_line_config *lc)
{
	struct gpio_desc *desc;
	unsigned int i;
	u64 flags;
	bool polarity_change;
1302
	bool prev_hte_flag;
1303 1304 1305 1306 1307 1308 1309 1310
	int ret;

	for (i = 0; i < lr->num_lines; i++) {
		desc = lr->lines[i].desc;
		flags = gpio_v2_line_config_flags(lc, i);
		polarity_change =
			(!!test_bit(FLAG_ACTIVE_LOW, &desc->flags) !=
			 ((flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW) != 0));
1311

1312 1313
		prev_hte_flag = !!test_bit(FLAG_EVENT_CLOCK_HTE, &desc->flags);

1314
		gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1315 1316 1317 1318
		/*
		 * Lines have to be requested explicitly for input
		 * or output, else the line will be treated "as is".
		 */
1319 1320
		if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
			int val = gpio_v2_line_config_output_value(lc, i);
1321

1322
			edge_detector_stop(&lr->lines[i], prev_hte_flag);
1323 1324 1325
			ret = gpiod_direction_output(desc, val);
			if (ret)
				return ret;
1326
		} else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1327 1328 1329
			ret = gpiod_direction_input(desc);
			if (ret)
				return ret;
1330

1331
			ret = edge_detector_update(&lr->lines[i], lc, i,
1332
					flags, polarity_change, prev_hte_flag);
1333 1334
			if (ret)
				return ret;
1335 1336
		}

1337
		blocking_notifier_call_chain(&desc->gdev->notifier,
1338 1339
					     GPIO_V2_LINE_CHANGED_CONFIG,
					     desc);
1340 1341 1342 1343
	}
	return 0;
}

1344
static long linereq_set_config(struct linereq *lr, void __user *ip)
1345
{
1346 1347
	struct gpio_v2_line_config lc;
	int ret;
1348

1349 1350
	if (copy_from_user(&lc, ip, sizeof(lc)))
		return -EFAULT;
1351

1352 1353 1354
	ret = gpio_v2_line_config_validate(&lc, lr->num_lines);
	if (ret)
		return ret;
1355

1356
	mutex_lock(&lr->config_mutex);
1357

1358
	ret = linereq_set_config_unlocked(lr, &lc);
1359

1360
	mutex_unlock(&lr->config_mutex);
1361

1362 1363 1364
	return ret;
}

1365 1366 1367 1368 1369 1370
static long linereq_ioctl(struct file *file, unsigned int cmd,
			  unsigned long arg)
{
	struct linereq *lr = file->private_data;
	void __user *ip = (void __user *)arg;

1371 1372
	switch (cmd) {
	case GPIO_V2_LINE_GET_VALUES_IOCTL:
1373
		return linereq_get_values(lr, ip);
1374
	case GPIO_V2_LINE_SET_VALUES_IOCTL:
1375
		return linereq_set_values(lr, ip);
1376
	case GPIO_V2_LINE_SET_CONFIG_IOCTL:
1377
		return linereq_set_config(lr, ip);
1378 1379 1380
	default:
		return -EINVAL;
	}
1381 1382 1383
}

#ifdef CONFIG_COMPAT
1384 1385
static long linereq_ioctl_compat(struct file *file, unsigned int cmd,
				 unsigned long arg)
1386
{
1387
	return linereq_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1388 1389 1390
}
#endif

1391 1392
static __poll_t linereq_poll(struct file *file,
			    struct poll_table_struct *wait)
1393
{
1394 1395
	struct linereq *lr = file->private_data;
	__poll_t events = 0;
1396

1397 1398 1399 1400 1401 1402 1403
	poll_wait(file, &lr->wait, wait);

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

	return events;
1404 1405
}

1406 1407 1408 1409
static ssize_t linereq_read(struct file *file,
			    char __user *buf,
			    size_t count,
			    loff_t *f_ps)
1410
{
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
	struct linereq *lr = file->private_data;
	struct gpio_v2_line_event le;
	ssize_t bytes_read = 0;
	int ret;

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

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

			if (file->f_flags & O_NONBLOCK) {
				spin_unlock(&lr->wait.lock);
				return -EAGAIN;
			}

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

		ret = kfifo_out(&lr->events, &le, 1);
		spin_unlock(&lr->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;
		}

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

	return bytes_read;
}

1460 1461 1462
static void linereq_free(struct linereq *lr)
{
	unsigned int i;
1463
	bool hte;
1464 1465

	for (i = 0; i < lr->num_lines; i++) {
1466 1467 1468
		hte = !!test_bit(FLAG_EVENT_CLOCK_HTE,
				 &lr->lines[i].desc->flags);
		edge_detector_stop(&lr->lines[i], hte);
1469 1470 1471
		if (lr->lines[i].desc)
			gpiod_free(lr->lines[i].desc);
	}
1472
	kfifo_free(&lr->events);
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
	kfree(lr->label);
	put_device(&lr->gdev->dev);
	kfree(lr);
}

static int linereq_release(struct inode *inode, struct file *file)
{
	struct linereq *lr = file->private_data;

	linereq_free(lr);
1483 1484 1485
	return 0;
}

1486 1487
static const struct file_operations line_fileops = {
	.release = linereq_release,
1488 1489
	.read = linereq_read,
	.poll = linereq_poll,
1490 1491
	.owner = THIS_MODULE,
	.llseek = noop_llseek,
1492
	.unlocked_ioctl = linereq_ioctl,
1493
#ifdef CONFIG_COMPAT
1494
	.compat_ioctl = linereq_ioctl_compat,
1495 1496 1497
#endif
};

1498
static int linereq_create(struct gpio_device *gdev, void __user *ip)
1499
{
1500 1501 1502
	struct gpio_v2_line_request ulr;
	struct gpio_v2_line_config *lc;
	struct linereq *lr;
1503
	struct file *file;
1504 1505 1506
	u64 flags;
	unsigned int i;
	int fd, ret;
1507

1508
	if (copy_from_user(&ulr, ip, sizeof(ulr)))
1509
		return -EFAULT;
1510 1511

	if ((ulr.num_lines == 0) || (ulr.num_lines > GPIO_V2_LINES_MAX))
1512 1513
		return -EINVAL;

1514 1515
	if (memchr_inv(ulr.padding, 0, sizeof(ulr.padding)))
		return -EINVAL;
1516

1517 1518
	lc = &ulr.config;
	ret = gpio_v2_line_config_validate(lc, ulr.num_lines);
1519 1520 1521
	if (ret)
		return ret;

1522 1523
	lr = kzalloc(struct_size(lr, lines, ulr.num_lines), GFP_KERNEL);
	if (!lr)
1524
		return -ENOMEM;
1525 1526

	lr->gdev = gdev;
1527 1528
	get_device(&gdev->dev);

1529
	for (i = 0; i < ulr.num_lines; i++) {
1530
		lr->lines[i].req = lr;
1531 1532 1533
		WRITE_ONCE(lr->lines[i].sw_debounced, 0);
		INIT_DELAYED_WORK(&lr->lines[i].work, debounce_work_func);
	}
1534

1535
	if (ulr.consumer[0] != '\0') {
1536
		/* label is only initialized if consumer is set */
1537 1538
		lr->label = kstrndup(ulr.consumer, sizeof(ulr.consumer) - 1,
				     GFP_KERNEL);
1539
		if (!lr->label) {
1540
			ret = -ENOMEM;
1541
			goto out_free_linereq;
1542 1543 1544
		}
	}

1545
	mutex_init(&lr->config_mutex);
1546 1547 1548 1549 1550 1551 1552 1553
	init_waitqueue_head(&lr->wait);
	lr->event_buffer_size = ulr.event_buffer_size;
	if (lr->event_buffer_size == 0)
		lr->event_buffer_size = ulr.num_lines * 16;
	else if (lr->event_buffer_size > GPIO_V2_LINES_MAX * 16)
		lr->event_buffer_size = GPIO_V2_LINES_MAX * 16;

	atomic_set(&lr->seqno, 0);
1554
	lr->num_lines = ulr.num_lines;
1555

1556
	/* Request each GPIO */
1557 1558
	for (i = 0; i < ulr.num_lines; i++) {
		u32 offset = ulr.offsets[i];
1559 1560 1561 1562
		struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);

		if (IS_ERR(desc)) {
			ret = PTR_ERR(desc);
1563
			goto out_free_linereq;
1564 1565
		}

1566
		ret = gpiod_request_user(desc, lr->label);
1567
		if (ret)
1568 1569 1570 1571 1572
			goto out_free_linereq;

		lr->lines[i].desc = desc;
		flags = gpio_v2_line_config_flags(lc, i);
		gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1573 1574 1575

		ret = gpiod_set_transitory(desc, false);
		if (ret < 0)
1576
			goto out_free_linereq;
1577 1578 1579 1580 1581

		/*
		 * Lines have to be requested explicitly for input
		 * or output, else the line will be treated "as is".
		 */
1582 1583
		if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
			int val = gpio_v2_line_config_output_value(lc, i);
1584 1585 1586

			ret = gpiod_direction_output(desc, val);
			if (ret)
1587 1588
				goto out_free_linereq;
		} else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1589 1590
			ret = gpiod_direction_input(desc);
			if (ret)
1591
				goto out_free_linereq;
1592

1593
			ret = edge_detector_setup(&lr->lines[i], lc, i,
1594 1595
				flags & GPIO_V2_LINE_EDGE_FLAGS,
				flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE);
1596 1597
			if (ret)
				goto out_free_linereq;
1598 1599
		}

1600
		blocking_notifier_call_chain(&desc->gdev->notifier,
1601
					     GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1602 1603 1604 1605 1606 1607 1608 1609

		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;
1610
		goto out_free_linereq;
1611 1612
	}

1613
	file = anon_inode_getfile("gpio-line", &line_fileops, lr,
1614 1615 1616 1617 1618 1619
				  O_RDONLY | O_CLOEXEC);
	if (IS_ERR(file)) {
		ret = PTR_ERR(file);
		goto out_put_unused_fd;
	}

1620 1621
	ulr.fd = fd;
	if (copy_to_user(ip, &ulr, sizeof(ulr))) {
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
		/*
		 * 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",
1634
		lr->num_lines);
1635 1636 1637 1638 1639

	return 0;

out_put_unused_fd:
	put_unused_fd(fd);
1640 1641
out_free_linereq:
	linereq_free(lr);
1642 1643 1644
	return ret;
}

1645
#ifdef CONFIG_GPIO_CDEV_V1
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678

/*
 * 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)

1679
static __poll_t lineevent_poll(struct file *file,
1680
			       struct poll_table_struct *wait)
1681
{
1682
	struct lineevent_state *le = file->private_data;
1683 1684
	__poll_t events = 0;

1685
	poll_wait(file, &le->wait, wait);
1686 1687 1688 1689 1690 1691 1692

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

	return events;
}

1693 1694 1695 1696
struct compat_gpioeevent_data {
	compat_u64	timestamp;
	u32		id;
};
1697

1698
static ssize_t lineevent_read(struct file *file,
1699 1700 1701 1702
			      char __user *buf,
			      size_t count,
			      loff_t *f_ps)
{
1703
	struct lineevent_state *le = file->private_data;
1704 1705
	struct gpioevent_data ge;
	ssize_t bytes_read = 0;
1706
	ssize_t ge_size;
1707 1708
	int ret;

1709 1710 1711 1712 1713 1714 1715 1716 1717
	/*
	 * 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.
	 */
1718 1719 1720 1721
	if (compat_need_64bit_alignment_fixup())
		ge_size = sizeof(struct compat_gpioeevent_data);
	else
		ge_size = sizeof(struct gpioevent_data);
1722
	if (count < ge_size)
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
		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;
			}

1733
			if (file->f_flags & O_NONBLOCK) {
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
				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;
		}

1758
		if (copy_to_user(buf + bytes_read, &ge, ge_size))
1759
			return -EFAULT;
1760 1761
		bytes_read += ge_size;
	} while (count >= bytes_read + ge_size);
1762 1763 1764 1765

	return bytes_read;
}

1766
static void lineevent_free(struct lineevent_state *le)
1767
{
1768 1769 1770 1771
	if (le->irq)
		free_irq(le->irq, le);
	if (le->desc)
		gpiod_free(le->desc);
1772
	kfree(le->label);
1773
	put_device(&le->gdev->dev);
1774
	kfree(le);
1775 1776 1777 1778 1779
}

static int lineevent_release(struct inode *inode, struct file *file)
{
	lineevent_free(file->private_data);
1780 1781 1782
	return 0;
}

1783
static long lineevent_ioctl(struct file *file, unsigned int cmd,
1784 1785
			    unsigned long arg)
{
1786
	struct lineevent_state *le = file->private_data;
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
	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
1813
static long lineevent_ioctl_compat(struct file *file, unsigned int cmd,
1814 1815
				   unsigned long arg)
{
1816
	return lineevent_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
}
#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;
1904
	int irq, irqflags = 0;
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941

	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);

1942 1943 1944 1945 1946
	if (eventreq.consumer_label[0] != '\0') {
		/* label is only initialized if consumer_label is set */
		le->label = kstrndup(eventreq.consumer_label,
				     sizeof(eventreq.consumer_label) - 1,
				     GFP_KERNEL);
1947 1948 1949 1950 1951 1952
		if (!le->label) {
			ret = -ENOMEM;
			goto out_free_le;
		}
	}

1953
	ret = gpiod_request_user(desc, le->label);
1954
	if (ret)
1955
		goto out_free_le;
1956 1957 1958
	le->desc = desc;
	le->eflags = eflags;

1959
	linehandle_flags_to_desc_flags(lflags, &desc->flags);
1960 1961 1962

	ret = gpiod_direction_input(desc);
	if (ret)
1963
		goto out_free_le;
1964

1965
	blocking_notifier_call_chain(&desc->gdev->notifier,
1966
				     GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1967

1968 1969
	irq = gpiod_to_irq(desc);
	if (irq <= 0) {
1970
		ret = -ENODEV;
1971
		goto out_free_le;
1972
	}
1973
	le->irq = irq;
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987

	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,
1988 1989 1990 1991 1992
				   lineevent_irq_handler,
				   lineevent_irq_thread,
				   irqflags,
				   le->label,
				   le);
1993
	if (ret)
1994
		goto out_free_le;
1995 1996 1997 1998

	fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
	if (fd < 0) {
		ret = fd;
1999
		goto out_free_le;
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
	}

	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:
2029
	lineevent_free(le);
2030 2031 2032
	return ret;
}

2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
static void gpio_v2_line_info_to_v1(struct gpio_v2_line_info *info_v2,
				    struct gpioline_info *info_v1)
{
	u64 flagsv2 = info_v2->flags;

	memcpy(info_v1->name, info_v2->name, sizeof(info_v1->name));
	memcpy(info_v1->consumer, info_v2->consumer, sizeof(info_v1->consumer));
	info_v1->line_offset = info_v2->offset;
	info_v1->flags = 0;

	if (flagsv2 & GPIO_V2_LINE_FLAG_USED)
		info_v1->flags |= GPIOLINE_FLAG_KERNEL;

	if (flagsv2 & GPIO_V2_LINE_FLAG_OUTPUT)
		info_v1->flags |= GPIOLINE_FLAG_IS_OUT;

	if (flagsv2 & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
		info_v1->flags |= GPIOLINE_FLAG_ACTIVE_LOW;

	if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_DRAIN)
		info_v1->flags |= GPIOLINE_FLAG_OPEN_DRAIN;
	if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_SOURCE)
		info_v1->flags |= GPIOLINE_FLAG_OPEN_SOURCE;

	if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)
		info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
	if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN)
		info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
	if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_DISABLED)
		info_v1->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
}

static void gpio_v2_line_info_changed_to_v1(
		struct gpio_v2_line_info_changed *lic_v2,
		struct gpioline_info_changed *lic_v1)
{
2069
	memset(lic_v1, 0, sizeof(*lic_v1));
2070 2071 2072 2073 2074
	gpio_v2_line_info_to_v1(&lic_v2->info, &lic_v1->info);
	lic_v1->timestamp = lic_v2->timestamp_ns;
	lic_v1->event_type = lic_v2->event_type;
}

2075 2076
#endif /* CONFIG_GPIO_CDEV_V1 */

2077
static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
2078
				  struct gpio_v2_line_info *info)
2079 2080 2081 2082
{
	struct gpio_chip *gc = desc->gdev->chip;
	bool ok_for_pinctrl;
	unsigned long flags;
2083 2084
	u32 debounce_period_us;
	unsigned int num_attrs = 0;
2085

2086
	memset(info, 0, sizeof(*info));
2087
	info->offset = gpio_chip_hwgpio(desc);
2088 2089 2090 2091 2092 2093 2094 2095 2096

	/*
	 * 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 =
2097
		pinctrl_gpio_can_use_line(gc->base + info->offset);
2098 2099 2100

	spin_lock_irqsave(&gpio_lock, flags);

2101 2102
	if (desc->name)
		strscpy(info->name, desc->name, sizeof(info->name));
2103

2104 2105
	if (desc->label)
		strscpy(info->consumer, desc->label, sizeof(info->consumer));
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116

	/*
	 * 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) ||
2117
	    !gpiochip_line_is_valid(gc, info->offset) ||
2118
	    !ok_for_pinctrl)
2119 2120
		info->flags |= GPIO_V2_LINE_FLAG_USED;

2121
	if (test_bit(FLAG_IS_OUT, &desc->flags))
2122 2123 2124 2125
		info->flags |= GPIO_V2_LINE_FLAG_OUTPUT;
	else
		info->flags |= GPIO_V2_LINE_FLAG_INPUT;

2126
	if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2127 2128
		info->flags |= GPIO_V2_LINE_FLAG_ACTIVE_LOW;

2129
	if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2130
		info->flags |= GPIO_V2_LINE_FLAG_OPEN_DRAIN;
2131
	if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2132 2133
		info->flags |= GPIO_V2_LINE_FLAG_OPEN_SOURCE;

2134
	if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
2135
		info->flags |= GPIO_V2_LINE_FLAG_BIAS_DISABLED;
2136
	if (test_bit(FLAG_PULL_DOWN, &desc->flags))
2137
		info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN;
2138
	if (test_bit(FLAG_PULL_UP, &desc->flags))
2139
		info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_UP;
2140

2141 2142 2143 2144 2145
	if (test_bit(FLAG_EDGE_RISING, &desc->flags))
		info->flags |= GPIO_V2_LINE_FLAG_EDGE_RISING;
	if (test_bit(FLAG_EDGE_FALLING, &desc->flags))
		info->flags |= GPIO_V2_LINE_FLAG_EDGE_FALLING;

2146 2147
	if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &desc->flags))
		info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME;
2148 2149
	else if (test_bit(FLAG_EVENT_CLOCK_HTE, &desc->flags))
		info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE;
2150

2151 2152 2153 2154 2155 2156 2157
	debounce_period_us = READ_ONCE(desc->debounce_period_us);
	if (debounce_period_us) {
		info->attrs[num_attrs].id = GPIO_V2_LINE_ATTR_ID_DEBOUNCE;
		info->attrs[num_attrs].debounce_period_us = debounce_period_us;
		num_attrs++;
	}
	info->num_attrs = num_attrs;
2158 2159 2160 2161 2162 2163 2164

	spin_unlock_irqrestore(&gpio_lock, flags);
}

struct gpio_chardev_data {
	struct gpio_device *gdev;
	wait_queue_head_t wait;
2165
	DECLARE_KFIFO(events, struct gpio_v2_line_info_changed, 32);
2166 2167
	struct notifier_block lineinfo_changed_nb;
	unsigned long *watched_lines;
2168 2169 2170
#ifdef CONFIG_GPIO_CDEV_V1
	atomic_t watch_abi_version;
#endif
2171 2172
};

2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
static int chipinfo_get(struct gpio_chardev_data *cdev, void __user *ip)
{
	struct gpio_device *gdev = cdev->gdev;
	struct gpiochip_info chipinfo;

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

	strscpy(chipinfo.name, dev_name(&gdev->dev), sizeof(chipinfo.name));
	strscpy(chipinfo.label, gdev->label, sizeof(chipinfo.label));
	chipinfo.lines = gdev->ngpio;
	if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
		return -EFAULT;
	return 0;
}

2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201
#ifdef CONFIG_GPIO_CDEV_V1
/*
 * returns 0 if the versions match, else the previously selected ABI version
 */
static int lineinfo_ensure_abi_version(struct gpio_chardev_data *cdata,
				       unsigned int version)
{
	int abiv = atomic_cmpxchg(&cdata->watch_abi_version, 0, version);

	if (abiv == version)
		return 0;

	return abiv;
}
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236

static int lineinfo_get_v1(struct gpio_chardev_data *cdev, void __user *ip,
			   bool watch)
{
	struct gpio_desc *desc;
	struct gpioline_info lineinfo;
	struct gpio_v2_line_info lineinfo_v2;

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

	/* this doubles as a range check on line_offset */
	desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.line_offset);
	if (IS_ERR(desc))
		return PTR_ERR(desc);

	if (watch) {
		if (lineinfo_ensure_abi_version(cdev, 1))
			return -EPERM;

		if (test_and_set_bit(lineinfo.line_offset, cdev->watched_lines))
			return -EBUSY;
	}

	gpio_desc_to_lineinfo(desc, &lineinfo_v2);
	gpio_v2_line_info_to_v1(&lineinfo_v2, &lineinfo);

	if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
		if (watch)
			clear_bit(lineinfo.line_offset, cdev->watched_lines);
		return -EFAULT;
	}

	return 0;
}
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273
#endif

static int lineinfo_get(struct gpio_chardev_data *cdev, void __user *ip,
			bool watch)
{
	struct gpio_desc *desc;
	struct gpio_v2_line_info lineinfo;

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

	if (memchr_inv(lineinfo.padding, 0, sizeof(lineinfo.padding)))
		return -EINVAL;

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

	if (watch) {
#ifdef CONFIG_GPIO_CDEV_V1
		if (lineinfo_ensure_abi_version(cdev, 2))
			return -EPERM;
#endif
		if (test_and_set_bit(lineinfo.offset, cdev->watched_lines))
			return -EBUSY;
	}
	gpio_desc_to_lineinfo(desc, &lineinfo);

	if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
		if (watch)
			clear_bit(lineinfo.offset, cdev->watched_lines);
		return -EFAULT;
	}

	return 0;
}

2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
static int lineinfo_unwatch(struct gpio_chardev_data *cdev, void __user *ip)
{
	__u32 offset;

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

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

	if (!test_and_clear_bit(offset, cdev->watched_lines))
		return -EBUSY;

	return 0;
}

2290 2291 2292
/*
 * gpio_ioctl() - ioctl handler for the GPIO chardev
 */
2293
static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2294
{
K
Kent Gibson 已提交
2295 2296
	struct gpio_chardev_data *cdev = file->private_data;
	struct gpio_device *gdev = cdev->gdev;
2297 2298 2299
	void __user *ip = (void __user *)arg;

	/* We fail any subsequent ioctl():s when the chip is gone */
2300
	if (!gdev->chip)
2301 2302 2303
		return -ENODEV;

	/* Fill in the struct and pass to userspace */
2304 2305
	switch (cmd) {
	case GPIO_GET_CHIPINFO_IOCTL:
2306
		return chipinfo_get(cdev, ip);
2307
#ifdef CONFIG_GPIO_CDEV_V1
2308
	case GPIO_GET_LINEHANDLE_IOCTL:
2309
		return linehandle_create(gdev, ip);
2310
	case GPIO_GET_LINEEVENT_IOCTL:
2311
		return lineevent_create(gdev, ip);
2312 2313 2314 2315
	case GPIO_GET_LINEINFO_IOCTL:
		return lineinfo_get_v1(cdev, ip, false);
	case GPIO_GET_LINEINFO_WATCH_IOCTL:
		return lineinfo_get_v1(cdev, ip, true);
2316
#endif /* CONFIG_GPIO_CDEV_V1 */
2317 2318 2319 2320 2321
	case GPIO_V2_GET_LINEINFO_IOCTL:
		return lineinfo_get(cdev, ip, false);
	case GPIO_V2_GET_LINEINFO_WATCH_IOCTL:
		return lineinfo_get(cdev, ip, true);
	case GPIO_V2_GET_LINE_IOCTL:
2322
		return linereq_create(gdev, ip);
2323
	case GPIO_GET_LINEINFO_UNWATCH_IOCTL:
2324
		return lineinfo_unwatch(cdev, ip);
2325 2326
	default:
		return -EINVAL;
2327 2328 2329 2330
	}
}

#ifdef CONFIG_COMPAT
2331
static long gpio_ioctl_compat(struct file *file, unsigned int cmd,
2332 2333
			      unsigned long arg)
{
2334
	return gpio_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
}
#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 已提交
2347
	struct gpio_chardev_data *cdev = to_gpio_chardev_data(nb);
2348
	struct gpio_v2_line_info_changed chg;
2349 2350 2351
	struct gpio_desc *desc = data;
	int ret;

K
Kent Gibson 已提交
2352
	if (!test_bit(gpio_chip_hwgpio(desc), cdev->watched_lines))
2353 2354 2355 2356
		return NOTIFY_DONE;

	memset(&chg, 0, sizeof(chg));
	chg.event_type = action;
2357
	chg.timestamp_ns = ktime_get_ns();
2358 2359
	gpio_desc_to_lineinfo(desc, &chg.info);

K
Kent Gibson 已提交
2360
	ret = kfifo_in_spinlocked(&cdev->events, &chg, 1, &cdev->wait.lock);
2361
	if (ret)
K
Kent Gibson 已提交
2362
		wake_up_poll(&cdev->wait, EPOLLIN);
2363 2364 2365 2366 2367 2368
	else
		pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");

	return NOTIFY_OK;
}

2369
static __poll_t lineinfo_watch_poll(struct file *file,
2370 2371
				    struct poll_table_struct *pollt)
{
K
Kent Gibson 已提交
2372
	struct gpio_chardev_data *cdev = file->private_data;
2373 2374
	__poll_t events = 0;

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

K
Kent Gibson 已提交
2377 2378
	if (!kfifo_is_empty_spinlocked_noirqsave(&cdev->events,
						 &cdev->wait.lock))
2379 2380 2381 2382 2383
		events = EPOLLIN | EPOLLRDNORM;

	return events;
}

2384
static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
2385 2386
				   size_t count, loff_t *off)
{
K
Kent Gibson 已提交
2387
	struct gpio_chardev_data *cdev = file->private_data;
2388
	struct gpio_v2_line_info_changed event;
2389 2390
	ssize_t bytes_read = 0;
	int ret;
2391
	size_t event_size;
2392

2393 2394 2395
#ifndef CONFIG_GPIO_CDEV_V1
	event_size = sizeof(struct gpio_v2_line_info_changed);
	if (count < event_size)
2396
		return -EINVAL;
2397
#endif
2398 2399

	do {
K
Kent Gibson 已提交
2400 2401
		spin_lock(&cdev->wait.lock);
		if (kfifo_is_empty(&cdev->events)) {
2402
			if (bytes_read) {
K
Kent Gibson 已提交
2403
				spin_unlock(&cdev->wait.lock);
2404 2405 2406
				return bytes_read;
			}

2407
			if (file->f_flags & O_NONBLOCK) {
K
Kent Gibson 已提交
2408
				spin_unlock(&cdev->wait.lock);
2409 2410 2411
				return -EAGAIN;
			}

K
Kent Gibson 已提交
2412 2413
			ret = wait_event_interruptible_locked(cdev->wait,
					!kfifo_is_empty(&cdev->events));
2414
			if (ret) {
K
Kent Gibson 已提交
2415
				spin_unlock(&cdev->wait.lock);
2416 2417 2418
				return ret;
			}
		}
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429
#ifdef CONFIG_GPIO_CDEV_V1
		/* must be after kfifo check so watch_abi_version is set */
		if (atomic_read(&cdev->watch_abi_version) == 2)
			event_size = sizeof(struct gpio_v2_line_info_changed);
		else
			event_size = sizeof(struct gpioline_info_changed);
		if (count < event_size) {
			spin_unlock(&cdev->wait.lock);
			return -EINVAL;
		}
#endif
K
Kent Gibson 已提交
2430 2431
		ret = kfifo_out(&cdev->events, &event, 1);
		spin_unlock(&cdev->wait.lock);
2432 2433 2434 2435 2436 2437
		if (ret != 1) {
			ret = -EIO;
			break;
			/* We should never get here. See lineevent_read(). */
		}

2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
#ifdef CONFIG_GPIO_CDEV_V1
		if (event_size == sizeof(struct gpio_v2_line_info_changed)) {
			if (copy_to_user(buf + bytes_read, &event, event_size))
				return -EFAULT;
		} else {
			struct gpioline_info_changed event_v1;

			gpio_v2_line_info_changed_to_v1(&event, &event_v1);
			if (copy_to_user(buf + bytes_read, &event_v1,
					 event_size))
				return -EFAULT;
		}
#else
		if (copy_to_user(buf + bytes_read, &event, event_size))
2452
			return -EFAULT;
2453 2454
#endif
		bytes_read += event_size;
2455 2456 2457 2458 2459 2460 2461 2462
	} while (count >= bytes_read + sizeof(event));

	return bytes_read;
}

/**
 * gpio_chrdev_open() - open the chardev for ioctl operations
 * @inode: inode for this chardev
2463
 * @file: file struct for storing private data
2464 2465
 * Returns 0 on success
 */
2466
static int gpio_chrdev_open(struct inode *inode, struct file *file)
2467 2468
{
	struct gpio_device *gdev = container_of(inode->i_cdev,
2469
						struct gpio_device, chrdev);
K
Kent Gibson 已提交
2470
	struct gpio_chardev_data *cdev;
2471 2472 2473 2474 2475 2476
	int ret = -ENOMEM;

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

K
Kent Gibson 已提交
2477 2478
	cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
	if (!cdev)
2479 2480
		return -ENOMEM;

K
Kent Gibson 已提交
2481 2482 2483
	cdev->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
	if (!cdev->watched_lines)
		goto out_free_cdev;
2484

K
Kent Gibson 已提交
2485 2486 2487
	init_waitqueue_head(&cdev->wait);
	INIT_KFIFO(cdev->events);
	cdev->gdev = gdev;
2488

K
Kent Gibson 已提交
2489
	cdev->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
2490
	ret = blocking_notifier_chain_register(&gdev->notifier,
K
Kent Gibson 已提交
2491
					       &cdev->lineinfo_changed_nb);
2492 2493 2494 2495
	if (ret)
		goto out_free_bitmap;

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

2498
	ret = nonseekable_open(inode, file);
2499 2500 2501 2502 2503 2504
	if (ret)
		goto out_unregister_notifier;

	return ret;

out_unregister_notifier:
2505
	blocking_notifier_chain_unregister(&gdev->notifier,
K
Kent Gibson 已提交
2506
					   &cdev->lineinfo_changed_nb);
2507
out_free_bitmap:
K
Kent Gibson 已提交
2508 2509 2510
	bitmap_free(cdev->watched_lines);
out_free_cdev:
	kfree(cdev);
2511 2512 2513 2514 2515 2516
	return ret;
}

/**
 * gpio_chrdev_release() - close chardev after ioctl operations
 * @inode: inode for this chardev
2517
 * @file: file struct for storing private data
2518 2519
 * Returns 0 on success
 */
2520
static int gpio_chrdev_release(struct inode *inode, struct file *file)
2521
{
K
Kent Gibson 已提交
2522 2523
	struct gpio_chardev_data *cdev = file->private_data;
	struct gpio_device *gdev = cdev->gdev;
2524

K
Kent Gibson 已提交
2525
	bitmap_free(cdev->watched_lines);
2526
	blocking_notifier_chain_unregister(&gdev->notifier,
K
Kent Gibson 已提交
2527
					   &cdev->lineinfo_changed_nb);
2528
	put_device(&gdev->dev);
K
Kent Gibson 已提交
2529
	kfree(cdev);
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568

	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);
}