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

Kent Gibson's avatar
Kent Gibson committed
3
#include <linux/anon_inodes.h>
4
#include <linux/atomic.h>
5
#include <linux/bitmap.h>
6
#include <linux/build_bug.h>
Kent Gibson's avatar
Kent Gibson committed
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>
Kent Gibson's avatar
Kent Gibson committed
12
#include <linux/file.h>
13
14
#include <linux/gpio.h>
#include <linux/gpio/driver.h>
Kent Gibson's avatar
Kent Gibson committed
15
16
17
#include <linux/interrupt.h>
#include <linux/irqreturn.h>
#include <linux/kernel.h>
18
#include <linux/kfifo.h>
Kent Gibson's avatar
Kent Gibson committed
19
#include <linux/module.h>
20
#include <linux/mutex.h>
Kent Gibson's avatar
Kent Gibson committed
21
#include <linux/pinctrl/consumer.h>
22
#include <linux/poll.h>
Kent Gibson's avatar
Kent Gibson committed
23
#include <linux/spinlock.h>
24
#include <linux/timekeeping.h>
Kent Gibson's avatar
Kent Gibson committed
25
#include <linux/uaccess.h>
26
#include <linux/workqueue.h>
27
#include <uapi/linux/gpio.h>
28
#include <evl/devices/gpio.h>
29
30
31
32

#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
	u32 lflags;
	struct linehandle_oob_state oob_state;
77
78
79
80
81
82
83
84
85
86
};

#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 | \
87
88
89
90
91
92
93
	GPIOHANDLE_REQUEST_OPEN_SOURCE | \
	(IS_ENABLED(CONFIG_GPIOLIB_OOB) ? GPIOHANDLE_REQUEST_OOB : 0))

static inline bool oob_handling_requested(u32 lflags)
{
	return IS_ENABLED(CONFIG_GPIOLIB_OOB) && lflags & GPIOHANDLE_REQUEST_OOB;
}
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
127
128
129
130
131
132
133
134

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 |
135
		       GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
136
137
138
139
140
141
142
	    ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
	     (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
		return -EINVAL;

	return 0;
}

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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);
}

159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
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;

175
	for (i = 0; i < lh->num_descs; i++) {
176
		desc = lh->descs[i];
177
		linehandle_flags_to_desc_flags(gcnf.flags, &desc->flags);
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

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

195
		blocking_notifier_call_chain(&desc->gdev->notifier,
196
197
					     GPIO_V2_LINE_CHANGED_CONFIG,
					     desc);
198
199
200
201
	}
	return 0;
}

202
static long linehandle_ioctl(struct file *file, unsigned int cmd,
203
204
			     unsigned long arg)
{
205
	struct linehandle_state *lh = file->private_data;
206
207
208
209
210
211
212
213
214
	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,
215
							lh->num_descs,
216
217
218
219
220
221
222
							lh->descs,
							NULL,
							vals);
		if (ret)
			return ret;

		memset(&ghd, 0, sizeof(ghd));
223
		for (i = 0; i < lh->num_descs; i++)
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
			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] */
242
		for (i = 0; i < lh->num_descs; i++)
243
244
245
246
			__assign_bit(i, vals, ghd.values[i]);

		/* Reuse the array setting function */
		return gpiod_set_array_value_complex(false,
247
						     true,
248
						     lh->num_descs,
249
250
251
						     lh->descs,
						     NULL,
						     vals);
252
253
254
255
256
257
258
	} else if (cmd == GPIOHANDLE_SET_CONFIG_IOCTL) {
		return linehandle_set_config(lh, ip);
	}
	return -EINVAL;
}

#ifdef CONFIG_COMPAT
259
static long linehandle_ioctl_compat(struct file *file, unsigned int cmd,
260
				    unsigned long arg)
261
{
262
	return linehandle_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
263
264
265
}
#endif

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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#ifdef CONFIG_GPIOLIB_OOB

static long linehandle_oob_ioctl(struct file *file, unsigned int cmd,
				unsigned long arg)
{
	struct linehandle_state *lh = file->private_data;
	DECLARE_BITMAP(valmap, GPIOHANDLES_MAX);
	struct gpio_chip *gc = lh->gdev->chip;
	void __user *ip = (void __user *)arg;
	struct gpiohandle_data ghd;
	int i, ret;

	if (!oob_handling_requested(lh->lflags))
		return -EPERM;

	if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
		ret = gpiod_get_array_value_oob(gc, valmap,
					lh->num_descs, lh->descs);
		if (ret)
			return ret;

		memset(&ghd, 0, sizeof(ghd));
		for (i = 0; i < lh->num_descs; i++)
			ghd.values[i] = test_bit(i, valmap);

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

		return 0;
	} else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
		if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
			return -EPERM;

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

		for (i = 0; i < lh->num_descs; i++)
			__assign_bit(i, valmap, ghd.values[i]);

		return gpiod_set_array_value_oob(gc, valmap,
					lh->num_descs, lh->descs);
	}

	return -EINVAL;
}

#endif	/* CONFIG_GPIOLIB_OOB */

314
static void linehandle_free(struct linehandle_state *lh)
315
316
317
{
	int i;

318
	for (i = 0; i < lh->num_descs; i++)
319
320
		if (lh->descs[i])
			gpiod_free(lh->descs[i]);
321
	kfree(lh->label);
322
	put_device(&lh->gdev->dev);
323
	kfree(lh);
324
325
326
327
}

static int linehandle_release(struct inode *inode, struct file *file)
{
328
329
330
331
332
333
 	struct linehandle_state *lh = file->private_data;

	if (oob_handling_requested(lh->lflags))
		evl_release_file(&lh->oob_state.efile);

	linehandle_free(lh);
334
335
336
337
338
339
340
341
	return 0;
}

static const struct file_operations linehandle_fileops = {
	.release = linehandle_release,
	.owner = THIS_MODULE,
	.llseek = noop_llseek,
	.unlocked_ioctl = linehandle_ioctl,
342
343
344
#ifdef CONFIG_GPIOLIB_OOB
	.oob_ioctl = linehandle_oob_ioctl,
#endif
345
346
347
#ifdef CONFIG_COMPAT
	.compat_ioctl = linehandle_ioctl_compat,
#endif
348
349
350
#ifdef CONFIG_GPIOLIB_OOB
	.compat_oob_ioctl = compat_ptr_oob_ioctl,
#endif
351
352
353
354
355
356
357
};

static int linehandle_create(struct gpio_device *gdev, void __user *ip)
{
	struct gpiohandle_request handlereq;
	struct linehandle_state *lh;
	struct file *file;
358
	int fd, i, ret;
359
360
361
362
363
364
365
366
367
	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;

368
369
370
371
372
373
374
375
376
377
378
379
	if (oob_handling_requested(lflags)) {
		if (gdev->chip->ngpio > CONFIG_GPIOLIB_FASTPATH_LIMIT) {
			chip_warn(gdev->chip,
				"too many lines for out-of-band handling"
				" (%u > %u fastpath)\n",
				gdev->chip->ngpio, CONFIG_GPIOLIB_FASTPATH_LIMIT);
			return -EOPNOTSUPP;
		}
		if (gdev->chip->can_sleep)
			return -EOPNOTSUPP;
	}

380
381
382
383
384
385
386
387
	ret = linehandle_validate_flags(lflags);
	if (ret)
		return ret;

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

391
392
393
394
395
	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);
396
397
398
399
400
401
		if (!lh->label) {
			ret = -ENOMEM;
			goto out_free_lh;
		}
	}

402
403
	lh->num_descs = handlereq.lines;

404
405
406
407
408
409
410
	/* 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);
411
			goto out_free_lh;
412
413
414
415
		}

		ret = gpiod_request(desc, lh->label);
		if (ret)
416
			goto out_free_lh;
417
		lh->descs[i] = desc;
418
		linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags);
419
420
421

		ret = gpiod_set_transitory(desc, false);
		if (ret < 0)
422
			goto out_free_lh;
423
424
425
426
427
428
429
430
431
432

		/*
		 * 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)
433
				goto out_free_lh;
434
435
436
		} else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
			ret = gpiod_direction_input(desc);
			if (ret)
437
				goto out_free_lh;
438
439
		}

440
		blocking_notifier_call_chain(&desc->gdev->notifier,
441
					     GPIO_V2_LINE_CHANGED_REQUESTED, desc);
442
443
444
445
446
447
448
449

		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;
450
		goto out_free_lh;
451
452
453
454
455
456
457
458
459
460
461
	}

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

462
463
464
465
466
467
468
469
	if (oob_handling_requested(lflags)) {
		ret = evl_open_file(&lh->oob_state.efile, file);
		if (ret) {
			fput(file);
			goto out_put_unused_fd;
		}
	}

470
471
472
473
474
475
476
477
478
479
480
481
482
483
	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",
484
		lh->num_descs);
485
486
487
488
489
490

	return 0;

out_put_unused_fd:
	put_unused_fd(fd);
out_free_lh:
491
	linehandle_free(lh);
492
493
	return ret;
}
494
495
496
497
498
#endif /* CONFIG_GPIO_CDEV_V1 */

/**
 * struct line - contains the state of a requested line
 * @desc: the GPIO descriptor for this line.
499
500
501
502
503
504
505
506
507
508
 * @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.
509
510
511
 * @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
512
513
514
 */
struct line {
	struct gpio_desc *desc;
515
516
517
518
519
	/*
	 * -- edge detector specific fields --
	 */
	struct linereq *req;
	unsigned int irq;
520
521
522
523
524
525
	/*
	 * 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.
	 */
526
527
528
529
530
531
532
533
	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;
534
535
536
537
538
	/*
	 * line_seqno is accessed by either edge_irq_thread() or
	 * debounce_work_func(), which are themselves mutually exclusive,
	 * so no additional protection is necessary.
	 */
539
	u32 line_seqno;
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
	/*
	 * -- 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;
556
557
558
559
560
561
562
};

/**
 * 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
563
564
565
566
567
568
 * @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.
569
570
 * @config_mutex: mutex for serializing ioctl() calls to ensure consistency
 * of configuration, particularly multi-step accesses to desc flags.
571
572
573
574
575
576
 * @lines: the lines held by this line request, with @num_lines elements.
 */
struct linereq {
	struct gpio_device *gdev;
	const char *label;
	u32 num_lines;
577
578
579
580
	wait_queue_head_t wait;
	u32 event_buffer_size;
	DECLARE_KFIFO_PTR(events, struct gpio_v2_line_event);
	atomic_t seqno;
581
	struct mutex config_mutex;
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
	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)

598
599
600
601
#define GPIO_V2_LINE_EDGE_FLAGS \
	(GPIO_V2_LINE_FLAG_EDGE_RISING | \
	 GPIO_V2_LINE_FLAG_EDGE_FALLING)

602
603
#define GPIO_V2_LINE_FLAG_EDGE_BOTH GPIO_V2_LINE_EDGE_FLAGS

604
605
606
607
#define GPIO_V2_LINE_VALID_FLAGS \
	(GPIO_V2_LINE_FLAG_ACTIVE_LOW | \
	 GPIO_V2_LINE_DIRECTION_FLAGS | \
	 GPIO_V2_LINE_DRIVE_FLAGS | \
608
	 GPIO_V2_LINE_EDGE_FLAGS | \
609
	 GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME | \
610
611
	 GPIO_V2_LINE_BIAS_FLAGS)

612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
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");
}

630
631
632
633
634
635
636
637
static u64 line_event_timestamp(struct line *line)
{
	if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &line->desc->flags))
		return ktime_get_real_ns();

	return ktime_get_ns();
}

638
639
640
641
642
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;
643
	u64 eflags;
644
645
646
647
648
649
650
651
652
653
654
655

	/* 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().
		 */
656
		le.timestamp_ns = line_event_timestamp(line);
657
658
659
660
661
		if (lr->num_lines != 1)
			line->req_seqno = atomic_inc_return(&lr->seqno);
	}
	line->timestamp_ns = 0;

662
	eflags = READ_ONCE(line->eflags);
663
	if (eflags == GPIO_V2_LINE_FLAG_EDGE_BOTH) {
664
665
666
667
668
669
670
671
		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;
672
	} else if (eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) {
673
674
		/* Emit low-to-high event */
		le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
675
	} else if (eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) {
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
		/* 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.
	 */
700
	line->timestamp_ns = line_event_timestamp(line);
701
702
703
704
705
706
707

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

	return IRQ_WAKE_THREAD;
}

708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
/*
 * 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;
	int level;
744
	u64 eflags;
745
746
747
748
749
750
751
752
753
754
755
756
757

	level = gpiod_get_raw_value_cansleep(line->desc);
	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 -- */
758
759
	eflags = READ_ONCE(line->eflags);
	if (!eflags)
760
761
762
763
764
765
766
		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 */
767
768
	if (((eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) && !level) ||
	    ((eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) && level))
769
770
771
772
773
774
		return;

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

	lr = line->req;
775
	le.timestamp_ns = line_event_timestamp(line);
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
850
851
852
853
854
855
856
857
	le.offset = gpio_chip_hwgpio(line->desc);
	line->line_seqno++;
	le.line_seqno = line->line_seqno;
	le.seqno = (lr->num_lines == 1) ?
		le.line_seqno : atomic_inc_return(&lr->seqno);

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

static int debounce_setup(struct line *line,
			  unsigned int debounce_period_us)
{
	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;

		irq = gpiod_to_irq(line->desc);
		if (irq < 0)
			return -ENXIO;

		WRITE_ONCE(line->level, level);
		irqflags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
		ret = request_irq(irq, debounce_irq_handler, irqflags,
				  line->req->label, line);
		if (ret)
			return ret;

		WRITE_ONCE(line->sw_debounced, 1);
		line->irq = irq;
	}
	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;
}

858
859
860
861
862
863
static void edge_detector_stop(struct line *line)
{
	if (line->irq) {
		free_irq(line->irq, line);
		line->irq = 0;
	}
864

865
866
	cancel_delayed_work_sync(&line->work);
	WRITE_ONCE(line->sw_debounced, 0);
867
	WRITE_ONCE(line->eflags, 0);
868
869
	if (line->desc)
		WRITE_ONCE(line->desc->debounce_period_us, 0);
870
	/* do not change line->level - see comment in debounced_value() */
871
872
873
}

static int edge_detector_setup(struct line *line,
874
875
			       struct gpio_v2_line_config *lc,
			       unsigned int line_idx,
876
877
			       u64 eflags)
{
878
	u32 debounce_period_us;
879
880
881
882
883
884
885
886
887
	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;
	}
888
	WRITE_ONCE(line->eflags, eflags);
889
890
891
892
893
894
895
	if (gpio_v2_line_config_debounced(lc, line_idx)) {
		debounce_period_us = gpio_v2_line_config_debounce_period(lc, line_idx);
		ret = debounce_setup(line, debounce_period_us);
		if (ret)
			return ret;
		WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
	}
896

897
898
	/* detection disabled or sw debouncer will provide edge detection */
	if (!eflags || READ_ONCE(line->sw_debounced))
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
		return 0;

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

923
924
925
926
static int edge_detector_update(struct line *line,
				struct gpio_v2_line_config *lc,
				unsigned int line_idx,
				u64 eflags, bool polarity_change)
927
{
928
929
930
	unsigned int debounce_period_us =
		gpio_v2_line_config_debounce_period(lc, line_idx);

931
	if ((READ_ONCE(line->eflags) == eflags) && !polarity_change &&
932
933
934
935
936
	    (READ_ONCE(line->desc->debounce_period_us) == debounce_period_us))
		return 0;

	/* sw debounced and still will be...*/
	if (debounce_period_us && READ_ONCE(line->sw_debounced)) {
937
		WRITE_ONCE(line->eflags, eflags);
938
		WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
939
		return 0;
940
	}
941

942
943
944
945
	/* reconfiguring edge detection or sw debounce being disabled */
	if ((line->irq && !READ_ONCE(line->sw_debounced)) ||
	    (!debounce_period_us && READ_ONCE(line->sw_debounced)))
		edge_detector_stop(line);
946

947
	return edge_detector_setup(line, lc, line_idx, eflags);
948
949
}

950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
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;

992
993
994
995
996
	/* Edge detection requires explicit input. */
	if ((flags & GPIO_V2_LINE_EDGE_FLAGS) &&
	    !(flags & GPIO_V2_LINE_FLAG_INPUT))
		return -EINVAL;

997
998
999
1000
	/*
	 * 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.
For faster browsing, not all history is shown. View entire blame