• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <linux/anon_inodes.h>
4 #include <linux/atomic.h>
5 #include <linux/bitmap.h>
6 #include <linux/build_bug.h>
7 #include <linux/cdev.h>
8 #include <linux/compat.h>
9 #include <linux/compiler.h>
10 #include <linux/device.h>
11 #include <linux/err.h>
12 #include <linux/file.h>
13 #include <linux/gpio.h>
14 #include <linux/gpio/driver.h>
15 #include <linux/interrupt.h>
16 #include <linux/irqreturn.h>
17 #include <linux/kernel.h>
18 #include <linux/kfifo.h>
19 #include <linux/module.h>
20 #include <linux/mutex.h>
21 #include <linux/pinctrl/consumer.h>
22 #include <linux/poll.h>
23 #include <linux/spinlock.h>
24 #include <linux/timekeeping.h>
25 #include <linux/uaccess.h>
26 #include <linux/workqueue.h>
27 #include <uapi/linux/gpio.h>
28 
29 #include "gpiolib.h"
30 #include "gpiolib-cdev.h"
31 
32 /*
33  * Array sizes must ensure 64-bit alignment and not create holes in the
34  * struct packing.
35  */
36 static_assert(IS_ALIGNED(GPIO_V2_LINES_MAX, 2));
37 static_assert(IS_ALIGNED(GPIO_MAX_NAME_SIZE, 8));
38 
39 /*
40  * Check that uAPI structs are 64-bit aligned for 32/64-bit compatibility
41  */
42 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_attribute), 8));
43 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config_attribute), 8));
44 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config), 8));
45 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_request), 8));
46 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info), 8));
47 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info_changed), 8));
48 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_event), 8));
49 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_values), 8));
50 
51 /* Character device interface to GPIO.
52  *
53  * The GPIO character device, /dev/gpiochipN, provides userspace an
54  * interface to gpiolib GPIOs via ioctl()s.
55  */
56 
57 /*
58  * GPIO line handle management
59  */
60 
61 #ifdef CONFIG_GPIO_CDEV_V1
62 /**
63  * struct linehandle_state - contains the state of a userspace handle
64  * @gdev: the GPIO device the handle pertains to
65  * @label: consumer label used to tag descriptors
66  * @descs: the GPIO descriptors held by this handle
67  * @num_descs: the number of descriptors held in the descs array
68  */
69 struct linehandle_state {
70 	struct gpio_device *gdev;
71 	const char *label;
72 	struct gpio_desc *descs[GPIOHANDLES_MAX];
73 	u32 num_descs;
74 };
75 
76 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
77 	(GPIOHANDLE_REQUEST_INPUT | \
78 	GPIOHANDLE_REQUEST_OUTPUT | \
79 	GPIOHANDLE_REQUEST_ACTIVE_LOW | \
80 	GPIOHANDLE_REQUEST_BIAS_PULL_UP | \
81 	GPIOHANDLE_REQUEST_BIAS_PULL_DOWN | \
82 	GPIOHANDLE_REQUEST_BIAS_DISABLE | \
83 	GPIOHANDLE_REQUEST_OPEN_DRAIN | \
84 	GPIOHANDLE_REQUEST_OPEN_SOURCE)
85 
linehandle_validate_flags(u32 flags)86 static int linehandle_validate_flags(u32 flags)
87 {
88 	/* Return an error if an unknown flag is set */
89 	if (flags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
90 		return -EINVAL;
91 
92 	/*
93 	 * Do not allow both INPUT & OUTPUT flags to be set as they are
94 	 * contradictory.
95 	 */
96 	if ((flags & GPIOHANDLE_REQUEST_INPUT) &&
97 	    (flags & GPIOHANDLE_REQUEST_OUTPUT))
98 		return -EINVAL;
99 
100 	/*
101 	 * Do not allow OPEN_SOURCE & OPEN_DRAIN flags in a single request. If
102 	 * the hardware actually supports enabling both at the same time the
103 	 * electrical result would be disastrous.
104 	 */
105 	if ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
106 	    (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
107 		return -EINVAL;
108 
109 	/* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
110 	if (!(flags & GPIOHANDLE_REQUEST_OUTPUT) &&
111 	    ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
112 	     (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
113 		return -EINVAL;
114 
115 	/* Bias flags only allowed for input or output mode. */
116 	if (!((flags & GPIOHANDLE_REQUEST_INPUT) ||
117 	      (flags & GPIOHANDLE_REQUEST_OUTPUT)) &&
118 	    ((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) ||
119 	     (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP) ||
120 	     (flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)))
121 		return -EINVAL;
122 
123 	/* Only one bias flag can be set. */
124 	if (((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
125 	     (flags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
126 		       GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
127 	    ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
128 	     (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
129 		return -EINVAL;
130 
131 	return 0;
132 }
133 
linehandle_flags_to_desc_flags(u32 lflags,unsigned long * flagsp)134 static void linehandle_flags_to_desc_flags(u32 lflags, unsigned long *flagsp)
135 {
136 	assign_bit(FLAG_ACTIVE_LOW, flagsp,
137 		   lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW);
138 	assign_bit(FLAG_OPEN_DRAIN, flagsp,
139 		   lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN);
140 	assign_bit(FLAG_OPEN_SOURCE, flagsp,
141 		   lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE);
142 	assign_bit(FLAG_PULL_UP, flagsp,
143 		   lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP);
144 	assign_bit(FLAG_PULL_DOWN, flagsp,
145 		   lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN);
146 	assign_bit(FLAG_BIAS_DISABLE, flagsp,
147 		   lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE);
148 }
149 
linehandle_set_config(struct linehandle_state * lh,void __user * ip)150 static long linehandle_set_config(struct linehandle_state *lh,
151 				  void __user *ip)
152 {
153 	struct gpiohandle_config gcnf;
154 	struct gpio_desc *desc;
155 	int i, ret;
156 	u32 lflags;
157 
158 	if (copy_from_user(&gcnf, ip, sizeof(gcnf)))
159 		return -EFAULT;
160 
161 	lflags = gcnf.flags;
162 	ret = linehandle_validate_flags(lflags);
163 	if (ret)
164 		return ret;
165 
166 	for (i = 0; i < lh->num_descs; i++) {
167 		desc = lh->descs[i];
168 		linehandle_flags_to_desc_flags(gcnf.flags, &desc->flags);
169 
170 		/*
171 		 * Lines have to be requested explicitly for input
172 		 * or output, else the line will be treated "as is".
173 		 */
174 		if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
175 			int val = !!gcnf.default_values[i];
176 
177 			ret = gpiod_direction_output(desc, val);
178 			if (ret)
179 				return ret;
180 		} else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
181 			ret = gpiod_direction_input(desc);
182 			if (ret)
183 				return ret;
184 		}
185 
186 		blocking_notifier_call_chain(&desc->gdev->notifier,
187 					     GPIO_V2_LINE_CHANGED_CONFIG,
188 					     desc);
189 	}
190 	return 0;
191 }
192 
linehandle_ioctl(struct file * file,unsigned int cmd,unsigned long arg)193 static long linehandle_ioctl(struct file *file, unsigned int cmd,
194 			     unsigned long arg)
195 {
196 	struct linehandle_state *lh = file->private_data;
197 	void __user *ip = (void __user *)arg;
198 	struct gpiohandle_data ghd;
199 	DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
200 	unsigned int i;
201 	int ret;
202 
203 	if (!lh->gdev->chip)
204 		return -ENODEV;
205 
206 	switch (cmd) {
207 	case GPIOHANDLE_GET_LINE_VALUES_IOCTL:
208 		/* NOTE: It's okay to read values of output lines */
209 		ret = gpiod_get_array_value_complex(false, true,
210 						    lh->num_descs, lh->descs,
211 						    NULL, vals);
212 		if (ret)
213 			return ret;
214 
215 		memset(&ghd, 0, sizeof(ghd));
216 		for (i = 0; i < lh->num_descs; i++)
217 			ghd.values[i] = test_bit(i, vals);
218 
219 		if (copy_to_user(ip, &ghd, sizeof(ghd)))
220 			return -EFAULT;
221 
222 		return 0;
223 	case GPIOHANDLE_SET_LINE_VALUES_IOCTL:
224 		/*
225 		 * All line descriptors were created at once with the same
226 		 * flags so just check if the first one is really output.
227 		 */
228 		if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
229 			return -EPERM;
230 
231 		if (copy_from_user(&ghd, ip, sizeof(ghd)))
232 			return -EFAULT;
233 
234 		/* Clamp all values to [0,1] */
235 		for (i = 0; i < lh->num_descs; i++)
236 			__assign_bit(i, vals, ghd.values[i]);
237 
238 		/* Reuse the array setting function */
239 		return gpiod_set_array_value_complex(false,
240 						     true,
241 						     lh->num_descs,
242 						     lh->descs,
243 						     NULL,
244 						     vals);
245 	case GPIOHANDLE_SET_CONFIG_IOCTL:
246 		return linehandle_set_config(lh, ip);
247 	default:
248 		return -EINVAL;
249 	}
250 }
251 
252 #ifdef CONFIG_COMPAT
linehandle_ioctl_compat(struct file * file,unsigned int cmd,unsigned long arg)253 static long linehandle_ioctl_compat(struct file *file, unsigned int cmd,
254 				    unsigned long arg)
255 {
256 	return linehandle_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
257 }
258 #endif
259 
linehandle_free(struct linehandle_state * lh)260 static void linehandle_free(struct linehandle_state *lh)
261 {
262 	int i;
263 
264 	for (i = 0; i < lh->num_descs; i++)
265 		if (lh->descs[i])
266 			gpiod_free(lh->descs[i]);
267 	kfree(lh->label);
268 	put_device(&lh->gdev->dev);
269 	kfree(lh);
270 }
271 
linehandle_release(struct inode * inode,struct file * file)272 static int linehandle_release(struct inode *inode, struct file *file)
273 {
274 	linehandle_free(file->private_data);
275 	return 0;
276 }
277 
278 static const struct file_operations linehandle_fileops = {
279 	.release = linehandle_release,
280 	.owner = THIS_MODULE,
281 	.llseek = noop_llseek,
282 	.unlocked_ioctl = linehandle_ioctl,
283 #ifdef CONFIG_COMPAT
284 	.compat_ioctl = linehandle_ioctl_compat,
285 #endif
286 };
287 
linehandle_create(struct gpio_device * gdev,void __user * ip)288 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
289 {
290 	struct gpiohandle_request handlereq;
291 	struct linehandle_state *lh;
292 	struct file *file;
293 	int fd, i, ret;
294 	u32 lflags;
295 
296 	if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
297 		return -EFAULT;
298 	if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
299 		return -EINVAL;
300 
301 	lflags = handlereq.flags;
302 
303 	ret = linehandle_validate_flags(lflags);
304 	if (ret)
305 		return ret;
306 
307 	lh = kzalloc(sizeof(*lh), GFP_KERNEL);
308 	if (!lh)
309 		return -ENOMEM;
310 	lh->gdev = gdev;
311 	get_device(&gdev->dev);
312 
313 	if (handlereq.consumer_label[0] != '\0') {
314 		/* label is only initialized if consumer_label is set */
315 		lh->label = kstrndup(handlereq.consumer_label,
316 				     sizeof(handlereq.consumer_label) - 1,
317 				     GFP_KERNEL);
318 		if (!lh->label) {
319 			ret = -ENOMEM;
320 			goto out_free_lh;
321 		}
322 	}
323 
324 	lh->num_descs = handlereq.lines;
325 
326 	/* Request each GPIO */
327 	for (i = 0; i < handlereq.lines; i++) {
328 		u32 offset = handlereq.lineoffsets[i];
329 		struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
330 
331 		if (IS_ERR(desc)) {
332 			ret = PTR_ERR(desc);
333 			goto out_free_lh;
334 		}
335 
336 		ret = gpiod_request_user(desc, lh->label);
337 		if (ret)
338 			goto out_free_lh;
339 		lh->descs[i] = desc;
340 		linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags);
341 
342 		ret = gpiod_set_transitory(desc, false);
343 		if (ret < 0)
344 			goto out_free_lh;
345 
346 		/*
347 		 * Lines have to be requested explicitly for input
348 		 * or output, else the line will be treated "as is".
349 		 */
350 		if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
351 			int val = !!handlereq.default_values[i];
352 
353 			ret = gpiod_direction_output(desc, val);
354 			if (ret)
355 				goto out_free_lh;
356 		} else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
357 			ret = gpiod_direction_input(desc);
358 			if (ret)
359 				goto out_free_lh;
360 		}
361 
362 		blocking_notifier_call_chain(&desc->gdev->notifier,
363 					     GPIO_V2_LINE_CHANGED_REQUESTED, desc);
364 
365 		dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
366 			offset);
367 	}
368 
369 	fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
370 	if (fd < 0) {
371 		ret = fd;
372 		goto out_free_lh;
373 	}
374 
375 	file = anon_inode_getfile("gpio-linehandle",
376 				  &linehandle_fileops,
377 				  lh,
378 				  O_RDONLY | O_CLOEXEC);
379 	if (IS_ERR(file)) {
380 		ret = PTR_ERR(file);
381 		goto out_put_unused_fd;
382 	}
383 
384 	handlereq.fd = fd;
385 	if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
386 		/*
387 		 * fput() will trigger the release() callback, so do not go onto
388 		 * the regular error cleanup path here.
389 		 */
390 		fput(file);
391 		put_unused_fd(fd);
392 		return -EFAULT;
393 	}
394 
395 	fd_install(fd, file);
396 
397 	dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
398 		lh->num_descs);
399 
400 	return 0;
401 
402 out_put_unused_fd:
403 	put_unused_fd(fd);
404 out_free_lh:
405 	linehandle_free(lh);
406 	return ret;
407 }
408 #endif /* CONFIG_GPIO_CDEV_V1 */
409 
410 /**
411  * struct line - contains the state of a requested line
412  * @desc: the GPIO descriptor for this line.
413  * @req: the corresponding line request
414  * @irq: the interrupt triggered in response to events on this GPIO
415  * @eflags: the edge flags, GPIO_V2_LINE_FLAG_EDGE_RISING and/or
416  * GPIO_V2_LINE_FLAG_EDGE_FALLING, indicating the edge detection applied
417  * @timestamp_ns: cache for the timestamp storing it between hardirq and
418  * IRQ thread, used to bring the timestamp close to the actual event
419  * @req_seqno: the seqno for the current edge event in the sequence of
420  * events for the corresponding line request. This is drawn from the @req.
421  * @line_seqno: the seqno for the current edge event in the sequence of
422  * events for this line.
423  * @work: the worker that implements software debouncing
424  * @sw_debounced: flag indicating if the software debouncer is active
425  * @level: the current debounced physical level of the line
426  */
427 struct line {
428 	struct gpio_desc *desc;
429 	/*
430 	 * -- edge detector specific fields --
431 	 */
432 	struct linereq *req;
433 	unsigned int irq;
434 	/*
435 	 * eflags is set by edge_detector_setup(), edge_detector_stop() and
436 	 * edge_detector_update(), which are themselves mutually exclusive,
437 	 * and is accessed by edge_irq_thread() and debounce_work_func(),
438 	 * which can both live with a slightly stale value.
439 	 */
440 	u64 eflags;
441 	/*
442 	 * timestamp_ns and req_seqno are accessed only by
443 	 * edge_irq_handler() and edge_irq_thread(), which are themselves
444 	 * mutually exclusive, so no additional protection is necessary.
445 	 */
446 	u64 timestamp_ns;
447 	u32 req_seqno;
448 	/*
449 	 * line_seqno is accessed by either edge_irq_thread() or
450 	 * debounce_work_func(), which are themselves mutually exclusive,
451 	 * so no additional protection is necessary.
452 	 */
453 	u32 line_seqno;
454 	/*
455 	 * -- debouncer specific fields --
456 	 */
457 	struct delayed_work work;
458 	/*
459 	 * sw_debounce is accessed by linereq_set_config(), which is the
460 	 * only setter, and linereq_get_values(), which can live with a
461 	 * slightly stale value.
462 	 */
463 	unsigned int sw_debounced;
464 	/*
465 	 * level is accessed by debounce_work_func(), which is the only
466 	 * setter, and linereq_get_values() which can live with a slightly
467 	 * stale value.
468 	 */
469 	unsigned int level;
470 };
471 
472 /**
473  * struct linereq - contains the state of a userspace line request
474  * @gdev: the GPIO device the line request pertains to
475  * @label: consumer label used to tag GPIO descriptors
476  * @num_lines: the number of lines in the lines array
477  * @wait: wait queue that handles blocking reads of events
478  * @event_buffer_size: the number of elements allocated in @events
479  * @events: KFIFO for the GPIO events
480  * @seqno: the sequence number for edge events generated on all lines in
481  * this line request.  Note that this is not used when @num_lines is 1, as
482  * the line_seqno is then the same and is cheaper to calculate.
483  * @config_mutex: mutex for serializing ioctl() calls to ensure consistency
484  * of configuration, particularly multi-step accesses to desc flags.
485  * @lines: the lines held by this line request, with @num_lines elements.
486  */
487 struct linereq {
488 	struct gpio_device *gdev;
489 	const char *label;
490 	u32 num_lines;
491 	wait_queue_head_t wait;
492 	u32 event_buffer_size;
493 	DECLARE_KFIFO_PTR(events, struct gpio_v2_line_event);
494 	atomic_t seqno;
495 	struct mutex config_mutex;
496 	struct line lines[];
497 };
498 
499 #define GPIO_V2_LINE_BIAS_FLAGS \
500 	(GPIO_V2_LINE_FLAG_BIAS_PULL_UP | \
501 	 GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN | \
502 	 GPIO_V2_LINE_FLAG_BIAS_DISABLED)
503 
504 #define GPIO_V2_LINE_DIRECTION_FLAGS \
505 	(GPIO_V2_LINE_FLAG_INPUT | \
506 	 GPIO_V2_LINE_FLAG_OUTPUT)
507 
508 #define GPIO_V2_LINE_DRIVE_FLAGS \
509 	(GPIO_V2_LINE_FLAG_OPEN_DRAIN | \
510 	 GPIO_V2_LINE_FLAG_OPEN_SOURCE)
511 
512 #define GPIO_V2_LINE_EDGE_FLAGS \
513 	(GPIO_V2_LINE_FLAG_EDGE_RISING | \
514 	 GPIO_V2_LINE_FLAG_EDGE_FALLING)
515 
516 #define GPIO_V2_LINE_FLAG_EDGE_BOTH GPIO_V2_LINE_EDGE_FLAGS
517 
518 #define GPIO_V2_LINE_VALID_FLAGS \
519 	(GPIO_V2_LINE_FLAG_ACTIVE_LOW | \
520 	 GPIO_V2_LINE_DIRECTION_FLAGS | \
521 	 GPIO_V2_LINE_DRIVE_FLAGS | \
522 	 GPIO_V2_LINE_EDGE_FLAGS | \
523 	 GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME | \
524 	 GPIO_V2_LINE_BIAS_FLAGS)
525 
linereq_put_event(struct linereq * lr,struct gpio_v2_line_event * le)526 static void linereq_put_event(struct linereq *lr,
527 			      struct gpio_v2_line_event *le)
528 {
529 	bool overflow = false;
530 
531 	spin_lock(&lr->wait.lock);
532 	if (kfifo_is_full(&lr->events)) {
533 		overflow = true;
534 		kfifo_skip(&lr->events);
535 	}
536 	kfifo_in(&lr->events, le, 1);
537 	spin_unlock(&lr->wait.lock);
538 	if (!overflow)
539 		wake_up_poll(&lr->wait, EPOLLIN);
540 	else
541 		pr_debug_ratelimited("event FIFO is full - event dropped\n");
542 }
543 
line_event_timestamp(struct line * line)544 static u64 line_event_timestamp(struct line *line)
545 {
546 	if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &line->desc->flags))
547 		return ktime_get_real_ns();
548 
549 	return ktime_get_ns();
550 }
551 
edge_irq_thread(int irq,void * p)552 static irqreturn_t edge_irq_thread(int irq, void *p)
553 {
554 	struct line *line = p;
555 	struct linereq *lr = line->req;
556 	struct gpio_v2_line_event le;
557 	u64 eflags;
558 
559 	/* Do not leak kernel stack to userspace */
560 	memset(&le, 0, sizeof(le));
561 
562 	if (line->timestamp_ns) {
563 		le.timestamp_ns = line->timestamp_ns;
564 	} else {
565 		/*
566 		 * We may be running from a nested threaded interrupt in
567 		 * which case we didn't get the timestamp from
568 		 * edge_irq_handler().
569 		 */
570 		le.timestamp_ns = line_event_timestamp(line);
571 		if (lr->num_lines != 1)
572 			line->req_seqno = atomic_inc_return(&lr->seqno);
573 	}
574 	line->timestamp_ns = 0;
575 
576 	eflags = READ_ONCE(line->eflags);
577 	if (eflags == GPIO_V2_LINE_FLAG_EDGE_BOTH) {
578 		int level = gpiod_get_value_cansleep(line->desc);
579 
580 		if (level)
581 			/* Emit low-to-high event */
582 			le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
583 		else
584 			/* Emit high-to-low event */
585 			le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
586 	} else if (eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) {
587 		/* Emit low-to-high event */
588 		le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
589 	} else if (eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) {
590 		/* Emit high-to-low event */
591 		le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
592 	} else {
593 		return IRQ_NONE;
594 	}
595 	line->line_seqno++;
596 	le.line_seqno = line->line_seqno;
597 	le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
598 	le.offset = gpio_chip_hwgpio(line->desc);
599 
600 	linereq_put_event(lr, &le);
601 
602 	return IRQ_HANDLED;
603 }
604 
edge_irq_handler(int irq,void * p)605 static irqreturn_t edge_irq_handler(int irq, void *p)
606 {
607 	struct line *line = p;
608 	struct linereq *lr = line->req;
609 
610 	/*
611 	 * Just store the timestamp in hardirq context so we get it as
612 	 * close in time as possible to the actual event.
613 	 */
614 	line->timestamp_ns = line_event_timestamp(line);
615 
616 	if (lr->num_lines != 1)
617 		line->req_seqno = atomic_inc_return(&lr->seqno);
618 
619 	return IRQ_WAKE_THREAD;
620 }
621 
622 /*
623  * returns the current debounced logical value.
624  */
debounced_value(struct line * line)625 static bool debounced_value(struct line *line)
626 {
627 	bool value;
628 
629 	/*
630 	 * minor race - debouncer may be stopped here, so edge_detector_stop()
631 	 * must leave the value unchanged so the following will read the level
632 	 * from when the debouncer was last running.
633 	 */
634 	value = READ_ONCE(line->level);
635 
636 	if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
637 		value = !value;
638 
639 	return value;
640 }
641 
debounce_irq_handler(int irq,void * p)642 static irqreturn_t debounce_irq_handler(int irq, void *p)
643 {
644 	struct line *line = p;
645 
646 	mod_delayed_work(system_wq, &line->work,
647 		usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
648 
649 	return IRQ_HANDLED;
650 }
651 
debounce_work_func(struct work_struct * work)652 static void debounce_work_func(struct work_struct *work)
653 {
654 	struct gpio_v2_line_event le;
655 	struct line *line = container_of(work, struct line, work.work);
656 	struct linereq *lr;
657 	int level;
658 	u64 eflags;
659 
660 	level = gpiod_get_raw_value_cansleep(line->desc);
661 	if (level < 0) {
662 		pr_debug_ratelimited("debouncer failed to read line value\n");
663 		return;
664 	}
665 
666 	if (READ_ONCE(line->level) == level)
667 		return;
668 
669 	WRITE_ONCE(line->level, level);
670 
671 	/* -- edge detection -- */
672 	eflags = READ_ONCE(line->eflags);
673 	if (!eflags)
674 		return;
675 
676 	/* switch from physical level to logical - if they differ */
677 	if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
678 		level = !level;
679 
680 	/* ignore edges that are not being monitored */
681 	if (((eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) && !level) ||
682 	    ((eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) && level))
683 		return;
684 
685 	/* Do not leak kernel stack to userspace */
686 	memset(&le, 0, sizeof(le));
687 
688 	lr = line->req;
689 	le.timestamp_ns = line_event_timestamp(line);
690 	le.offset = gpio_chip_hwgpio(line->desc);
691 	line->line_seqno++;
692 	le.line_seqno = line->line_seqno;
693 	le.seqno = (lr->num_lines == 1) ?
694 		le.line_seqno : atomic_inc_return(&lr->seqno);
695 
696 	if (level)
697 		/* Emit low-to-high event */
698 		le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
699 	else
700 		/* Emit high-to-low event */
701 		le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
702 
703 	linereq_put_event(lr, &le);
704 }
705 
debounce_setup(struct line * line,unsigned int debounce_period_us)706 static int debounce_setup(struct line *line,
707 			  unsigned int debounce_period_us)
708 {
709 	unsigned long irqflags;
710 	int ret, level, irq;
711 
712 	/* try hardware */
713 	ret = gpiod_set_debounce(line->desc, debounce_period_us);
714 	if (!ret) {
715 		WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
716 		return ret;
717 	}
718 	if (ret != -ENOTSUPP)
719 		return ret;
720 
721 	if (debounce_period_us) {
722 		/* setup software debounce */
723 		level = gpiod_get_raw_value_cansleep(line->desc);
724 		if (level < 0)
725 			return level;
726 
727 		irq = gpiod_to_irq(line->desc);
728 		if (irq < 0)
729 			return -ENXIO;
730 
731 		WRITE_ONCE(line->level, level);
732 		irqflags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
733 		ret = request_irq(irq, debounce_irq_handler, irqflags,
734 				  line->req->label, line);
735 		if (ret)
736 			return ret;
737 
738 		WRITE_ONCE(line->sw_debounced, 1);
739 		line->irq = irq;
740 	}
741 	return 0;
742 }
743 
gpio_v2_line_config_debounced(struct gpio_v2_line_config * lc,unsigned int line_idx)744 static bool gpio_v2_line_config_debounced(struct gpio_v2_line_config *lc,
745 					  unsigned int line_idx)
746 {
747 	unsigned int i;
748 	u64 mask = BIT_ULL(line_idx);
749 
750 	for (i = 0; i < lc->num_attrs; i++) {
751 		if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
752 		    (lc->attrs[i].mask & mask))
753 			return true;
754 	}
755 	return false;
756 }
757 
gpio_v2_line_config_debounce_period(struct gpio_v2_line_config * lc,unsigned int line_idx)758 static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc,
759 					       unsigned int line_idx)
760 {
761 	unsigned int i;
762 	u64 mask = BIT_ULL(line_idx);
763 
764 	for (i = 0; i < lc->num_attrs; i++) {
765 		if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
766 		    (lc->attrs[i].mask & mask))
767 			return lc->attrs[i].attr.debounce_period_us;
768 	}
769 	return 0;
770 }
771 
edge_detector_stop(struct line * line)772 static void edge_detector_stop(struct line *line)
773 {
774 	if (line->irq) {
775 		free_irq(line->irq, line);
776 		line->irq = 0;
777 	}
778 
779 	cancel_delayed_work_sync(&line->work);
780 	WRITE_ONCE(line->sw_debounced, 0);
781 	WRITE_ONCE(line->eflags, 0);
782 	if (line->desc)
783 		WRITE_ONCE(line->desc->debounce_period_us, 0);
784 	/* do not change line->level - see comment in debounced_value() */
785 }
786 
edge_detector_setup(struct line * line,struct gpio_v2_line_config * lc,unsigned int line_idx,u64 eflags)787 static int edge_detector_setup(struct line *line,
788 			       struct gpio_v2_line_config *lc,
789 			       unsigned int line_idx,
790 			       u64 eflags)
791 {
792 	u32 debounce_period_us;
793 	unsigned long irqflags = 0;
794 	int irq, ret;
795 
796 	if (eflags && !kfifo_initialized(&line->req->events)) {
797 		ret = kfifo_alloc(&line->req->events,
798 				  line->req->event_buffer_size, GFP_KERNEL);
799 		if (ret)
800 			return ret;
801 	}
802 	WRITE_ONCE(line->eflags, eflags);
803 	if (gpio_v2_line_config_debounced(lc, line_idx)) {
804 		debounce_period_us = gpio_v2_line_config_debounce_period(lc, line_idx);
805 		ret = debounce_setup(line, debounce_period_us);
806 		if (ret)
807 			return ret;
808 		WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
809 	}
810 
811 	/* detection disabled or sw debouncer will provide edge detection */
812 	if (!eflags || READ_ONCE(line->sw_debounced))
813 		return 0;
814 
815 	irq = gpiod_to_irq(line->desc);
816 	if (irq < 0)
817 		return -ENXIO;
818 
819 	if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
820 		irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
821 			IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
822 	if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
823 		irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
824 			IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
825 	irqflags |= IRQF_ONESHOT;
826 
827 	/* Request a thread to read the events */
828 	ret = request_threaded_irq(irq, edge_irq_handler, edge_irq_thread,
829 				   irqflags, line->req->label, line);
830 	if (ret)
831 		return ret;
832 
833 	line->irq = irq;
834 	return 0;
835 }
836 
edge_detector_update(struct line * line,struct gpio_v2_line_config * lc,unsigned int line_idx,u64 eflags,bool polarity_change)837 static int edge_detector_update(struct line *line,
838 				struct gpio_v2_line_config *lc,
839 				unsigned int line_idx,
840 				u64 eflags, bool polarity_change)
841 {
842 	unsigned int debounce_period_us =
843 		gpio_v2_line_config_debounce_period(lc, line_idx);
844 
845 	if ((READ_ONCE(line->eflags) == eflags) && !polarity_change &&
846 	    (READ_ONCE(line->desc->debounce_period_us) == debounce_period_us))
847 		return 0;
848 
849 	/* sw debounced and still will be...*/
850 	if (debounce_period_us && READ_ONCE(line->sw_debounced)) {
851 		WRITE_ONCE(line->eflags, eflags);
852 		WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
853 		return 0;
854 	}
855 
856 	/* reconfiguring edge detection or sw debounce being disabled */
857 	if ((line->irq && !READ_ONCE(line->sw_debounced)) ||
858 	    (!debounce_period_us && READ_ONCE(line->sw_debounced)))
859 		edge_detector_stop(line);
860 
861 	return edge_detector_setup(line, lc, line_idx, eflags);
862 }
863 
gpio_v2_line_config_flags(struct gpio_v2_line_config * lc,unsigned int line_idx)864 static u64 gpio_v2_line_config_flags(struct gpio_v2_line_config *lc,
865 				     unsigned int line_idx)
866 {
867 	unsigned int i;
868 	u64 mask = BIT_ULL(line_idx);
869 
870 	for (i = 0; i < lc->num_attrs; i++) {
871 		if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_FLAGS) &&
872 		    (lc->attrs[i].mask & mask))
873 			return lc->attrs[i].attr.flags;
874 	}
875 	return lc->flags;
876 }
877 
gpio_v2_line_config_output_value(struct gpio_v2_line_config * lc,unsigned int line_idx)878 static int gpio_v2_line_config_output_value(struct gpio_v2_line_config *lc,
879 					    unsigned int line_idx)
880 {
881 	unsigned int i;
882 	u64 mask = BIT_ULL(line_idx);
883 
884 	for (i = 0; i < lc->num_attrs; i++) {
885 		if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES) &&
886 		    (lc->attrs[i].mask & mask))
887 			return !!(lc->attrs[i].attr.values & mask);
888 	}
889 	return 0;
890 }
891 
gpio_v2_line_flags_validate(u64 flags)892 static int gpio_v2_line_flags_validate(u64 flags)
893 {
894 	/* Return an error if an unknown flag is set */
895 	if (flags & ~GPIO_V2_LINE_VALID_FLAGS)
896 		return -EINVAL;
897 
898 	/*
899 	 * Do not allow both INPUT and OUTPUT flags to be set as they are
900 	 * contradictory.
901 	 */
902 	if ((flags & GPIO_V2_LINE_FLAG_INPUT) &&
903 	    (flags & GPIO_V2_LINE_FLAG_OUTPUT))
904 		return -EINVAL;
905 
906 	/* Edge detection requires explicit input. */
907 	if ((flags & GPIO_V2_LINE_EDGE_FLAGS) &&
908 	    !(flags & GPIO_V2_LINE_FLAG_INPUT))
909 		return -EINVAL;
910 
911 	/*
912 	 * Do not allow OPEN_SOURCE and OPEN_DRAIN flags in a single
913 	 * request. If the hardware actually supports enabling both at the
914 	 * same time the electrical result would be disastrous.
915 	 */
916 	if ((flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN) &&
917 	    (flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE))
918 		return -EINVAL;
919 
920 	/* Drive requires explicit output direction. */
921 	if ((flags & GPIO_V2_LINE_DRIVE_FLAGS) &&
922 	    !(flags & GPIO_V2_LINE_FLAG_OUTPUT))
923 		return -EINVAL;
924 
925 	/* Bias requires explicit direction. */
926 	if ((flags & GPIO_V2_LINE_BIAS_FLAGS) &&
927 	    !(flags & GPIO_V2_LINE_DIRECTION_FLAGS))
928 		return -EINVAL;
929 
930 	/* Only one bias flag can be set. */
931 	if (((flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED) &&
932 	     (flags & (GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN |
933 		       GPIO_V2_LINE_FLAG_BIAS_PULL_UP))) ||
934 	    ((flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN) &&
935 	     (flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)))
936 		return -EINVAL;
937 
938 	return 0;
939 }
940 
gpio_v2_line_config_validate(struct gpio_v2_line_config * lc,unsigned int num_lines)941 static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc,
942 					unsigned int num_lines)
943 {
944 	unsigned int i;
945 	u64 flags;
946 	int ret;
947 
948 	if (lc->num_attrs > GPIO_V2_LINE_NUM_ATTRS_MAX)
949 		return -EINVAL;
950 
951 	if (memchr_inv(lc->padding, 0, sizeof(lc->padding)))
952 		return -EINVAL;
953 
954 	for (i = 0; i < num_lines; i++) {
955 		flags = gpio_v2_line_config_flags(lc, i);
956 		ret = gpio_v2_line_flags_validate(flags);
957 		if (ret)
958 			return ret;
959 
960 		/* debounce requires explicit input */
961 		if (gpio_v2_line_config_debounced(lc, i) &&
962 		    !(flags & GPIO_V2_LINE_FLAG_INPUT))
963 			return -EINVAL;
964 	}
965 	return 0;
966 }
967 
gpio_v2_line_config_flags_to_desc_flags(u64 flags,unsigned long * flagsp)968 static void gpio_v2_line_config_flags_to_desc_flags(u64 flags,
969 						    unsigned long *flagsp)
970 {
971 	assign_bit(FLAG_ACTIVE_LOW, flagsp,
972 		   flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW);
973 
974 	if (flags & GPIO_V2_LINE_FLAG_OUTPUT)
975 		set_bit(FLAG_IS_OUT, flagsp);
976 	else if (flags & GPIO_V2_LINE_FLAG_INPUT)
977 		clear_bit(FLAG_IS_OUT, flagsp);
978 
979 	assign_bit(FLAG_EDGE_RISING, flagsp,
980 		   flags & GPIO_V2_LINE_FLAG_EDGE_RISING);
981 	assign_bit(FLAG_EDGE_FALLING, flagsp,
982 		   flags & GPIO_V2_LINE_FLAG_EDGE_FALLING);
983 
984 	assign_bit(FLAG_OPEN_DRAIN, flagsp,
985 		   flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN);
986 	assign_bit(FLAG_OPEN_SOURCE, flagsp,
987 		   flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE);
988 
989 	assign_bit(FLAG_PULL_UP, flagsp,
990 		   flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP);
991 	assign_bit(FLAG_PULL_DOWN, flagsp,
992 		   flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN);
993 	assign_bit(FLAG_BIAS_DISABLE, flagsp,
994 		   flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED);
995 
996 	assign_bit(FLAG_EVENT_CLOCK_REALTIME, flagsp,
997 		   flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME);
998 }
999 
linereq_get_values(struct linereq * lr,void __user * ip)1000 static long linereq_get_values(struct linereq *lr, void __user *ip)
1001 {
1002 	struct gpio_v2_line_values lv;
1003 	DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1004 	struct gpio_desc **descs;
1005 	unsigned int i, didx, num_get;
1006 	bool val;
1007 	int ret;
1008 
1009 	/* NOTE: It's ok to read values of output lines. */
1010 	if (copy_from_user(&lv, ip, sizeof(lv)))
1011 		return -EFAULT;
1012 
1013 	for (num_get = 0, i = 0; i < lr->num_lines; i++) {
1014 		if (lv.mask & BIT_ULL(i)) {
1015 			num_get++;
1016 			descs = &lr->lines[i].desc;
1017 		}
1018 	}
1019 
1020 	if (num_get == 0)
1021 		return -EINVAL;
1022 
1023 	if (num_get != 1) {
1024 		descs = kmalloc_array(num_get, sizeof(*descs), GFP_KERNEL);
1025 		if (!descs)
1026 			return -ENOMEM;
1027 		for (didx = 0, i = 0; i < lr->num_lines; i++) {
1028 			if (lv.mask & BIT_ULL(i)) {
1029 				descs[didx] = lr->lines[i].desc;
1030 				didx++;
1031 			}
1032 		}
1033 	}
1034 	ret = gpiod_get_array_value_complex(false, true, num_get,
1035 					    descs, NULL, vals);
1036 
1037 	if (num_get != 1)
1038 		kfree(descs);
1039 	if (ret)
1040 		return ret;
1041 
1042 	lv.bits = 0;
1043 	for (didx = 0, i = 0; i < lr->num_lines; i++) {
1044 		if (lv.mask & BIT_ULL(i)) {
1045 			if (lr->lines[i].sw_debounced)
1046 				val = debounced_value(&lr->lines[i]);
1047 			else
1048 				val = test_bit(didx, vals);
1049 			if (val)
1050 				lv.bits |= BIT_ULL(i);
1051 			didx++;
1052 		}
1053 	}
1054 
1055 	if (copy_to_user(ip, &lv, sizeof(lv)))
1056 		return -EFAULT;
1057 
1058 	return 0;
1059 }
1060 
linereq_set_values_unlocked(struct linereq * lr,struct gpio_v2_line_values * lv)1061 static long linereq_set_values_unlocked(struct linereq *lr,
1062 					struct gpio_v2_line_values *lv)
1063 {
1064 	DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1065 	struct gpio_desc **descs;
1066 	unsigned int i, didx, num_set;
1067 	int ret;
1068 
1069 	bitmap_zero(vals, GPIO_V2_LINES_MAX);
1070 	for (num_set = 0, i = 0; i < lr->num_lines; i++) {
1071 		if (lv->mask & BIT_ULL(i)) {
1072 			if (!test_bit(FLAG_IS_OUT, &lr->lines[i].desc->flags))
1073 				return -EPERM;
1074 			if (lv->bits & BIT_ULL(i))
1075 				__set_bit(num_set, vals);
1076 			num_set++;
1077 			descs = &lr->lines[i].desc;
1078 		}
1079 	}
1080 	if (num_set == 0)
1081 		return -EINVAL;
1082 
1083 	if (num_set != 1) {
1084 		/* build compacted desc array and values */
1085 		descs = kmalloc_array(num_set, sizeof(*descs), GFP_KERNEL);
1086 		if (!descs)
1087 			return -ENOMEM;
1088 		for (didx = 0, i = 0; i < lr->num_lines; i++) {
1089 			if (lv->mask & BIT_ULL(i)) {
1090 				descs[didx] = lr->lines[i].desc;
1091 				didx++;
1092 			}
1093 		}
1094 	}
1095 	ret = gpiod_set_array_value_complex(false, true, num_set,
1096 					    descs, NULL, vals);
1097 
1098 	if (num_set != 1)
1099 		kfree(descs);
1100 	return ret;
1101 }
1102 
linereq_set_values(struct linereq * lr,void __user * ip)1103 static long linereq_set_values(struct linereq *lr, void __user *ip)
1104 {
1105 	struct gpio_v2_line_values lv;
1106 	int ret;
1107 
1108 	if (copy_from_user(&lv, ip, sizeof(lv)))
1109 		return -EFAULT;
1110 
1111 	mutex_lock(&lr->config_mutex);
1112 
1113 	ret = linereq_set_values_unlocked(lr, &lv);
1114 
1115 	mutex_unlock(&lr->config_mutex);
1116 
1117 	return ret;
1118 }
1119 
linereq_set_config_unlocked(struct linereq * lr,struct gpio_v2_line_config * lc)1120 static long linereq_set_config_unlocked(struct linereq *lr,
1121 					struct gpio_v2_line_config *lc)
1122 {
1123 	struct gpio_desc *desc;
1124 	unsigned int i;
1125 	u64 flags;
1126 	bool polarity_change;
1127 	int ret;
1128 
1129 	for (i = 0; i < lr->num_lines; i++) {
1130 		desc = lr->lines[i].desc;
1131 		flags = gpio_v2_line_config_flags(lc, i);
1132 		polarity_change =
1133 			(!!test_bit(FLAG_ACTIVE_LOW, &desc->flags) !=
1134 			 ((flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW) != 0));
1135 
1136 		gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1137 		/*
1138 		 * Lines have to be requested explicitly for input
1139 		 * or output, else the line will be treated "as is".
1140 		 */
1141 		if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1142 			int val = gpio_v2_line_config_output_value(lc, i);
1143 
1144 			edge_detector_stop(&lr->lines[i]);
1145 			ret = gpiod_direction_output(desc, val);
1146 			if (ret)
1147 				return ret;
1148 		} else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1149 			ret = gpiod_direction_input(desc);
1150 			if (ret)
1151 				return ret;
1152 
1153 			ret = edge_detector_update(&lr->lines[i], lc, i,
1154 					flags & GPIO_V2_LINE_EDGE_FLAGS,
1155 					polarity_change);
1156 			if (ret)
1157 				return ret;
1158 		}
1159 
1160 		blocking_notifier_call_chain(&desc->gdev->notifier,
1161 					     GPIO_V2_LINE_CHANGED_CONFIG,
1162 					     desc);
1163 	}
1164 	return 0;
1165 }
1166 
linereq_set_config(struct linereq * lr,void __user * ip)1167 static long linereq_set_config(struct linereq *lr, void __user *ip)
1168 {
1169 	struct gpio_v2_line_config lc;
1170 	int ret;
1171 
1172 	if (copy_from_user(&lc, ip, sizeof(lc)))
1173 		return -EFAULT;
1174 
1175 	ret = gpio_v2_line_config_validate(&lc, lr->num_lines);
1176 	if (ret)
1177 		return ret;
1178 
1179 	mutex_lock(&lr->config_mutex);
1180 
1181 	ret = linereq_set_config_unlocked(lr, &lc);
1182 
1183 	mutex_unlock(&lr->config_mutex);
1184 
1185 	return ret;
1186 }
1187 
linereq_ioctl(struct file * file,unsigned int cmd,unsigned long arg)1188 static long linereq_ioctl(struct file *file, unsigned int cmd,
1189 			  unsigned long arg)
1190 {
1191 	struct linereq *lr = file->private_data;
1192 	void __user *ip = (void __user *)arg;
1193 
1194 	if (!lr->gdev->chip)
1195 		return -ENODEV;
1196 
1197 	switch (cmd) {
1198 	case GPIO_V2_LINE_GET_VALUES_IOCTL:
1199 		return linereq_get_values(lr, ip);
1200 	case GPIO_V2_LINE_SET_VALUES_IOCTL:
1201 		return linereq_set_values(lr, ip);
1202 	case GPIO_V2_LINE_SET_CONFIG_IOCTL:
1203 		return linereq_set_config(lr, ip);
1204 	default:
1205 		return -EINVAL;
1206 	}
1207 }
1208 
1209 #ifdef CONFIG_COMPAT
linereq_ioctl_compat(struct file * file,unsigned int cmd,unsigned long arg)1210 static long linereq_ioctl_compat(struct file *file, unsigned int cmd,
1211 				 unsigned long arg)
1212 {
1213 	return linereq_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1214 }
1215 #endif
1216 
linereq_poll(struct file * file,struct poll_table_struct * wait)1217 static __poll_t linereq_poll(struct file *file,
1218 			    struct poll_table_struct *wait)
1219 {
1220 	struct linereq *lr = file->private_data;
1221 	__poll_t events = 0;
1222 
1223 	if (!lr->gdev->chip)
1224 		return EPOLLHUP | EPOLLERR;
1225 
1226 	poll_wait(file, &lr->wait, wait);
1227 
1228 	if (!kfifo_is_empty_spinlocked_noirqsave(&lr->events,
1229 						 &lr->wait.lock))
1230 		events = EPOLLIN | EPOLLRDNORM;
1231 
1232 	return events;
1233 }
1234 
linereq_read(struct file * file,char __user * buf,size_t count,loff_t * f_ps)1235 static ssize_t linereq_read(struct file *file,
1236 			    char __user *buf,
1237 			    size_t count,
1238 			    loff_t *f_ps)
1239 {
1240 	struct linereq *lr = file->private_data;
1241 	struct gpio_v2_line_event le;
1242 	ssize_t bytes_read = 0;
1243 	int ret;
1244 
1245 	if (!lr->gdev->chip)
1246 		return -ENODEV;
1247 
1248 	if (count < sizeof(le))
1249 		return -EINVAL;
1250 
1251 	do {
1252 		spin_lock(&lr->wait.lock);
1253 		if (kfifo_is_empty(&lr->events)) {
1254 			if (bytes_read) {
1255 				spin_unlock(&lr->wait.lock);
1256 				return bytes_read;
1257 			}
1258 
1259 			if (file->f_flags & O_NONBLOCK) {
1260 				spin_unlock(&lr->wait.lock);
1261 				return -EAGAIN;
1262 			}
1263 
1264 			ret = wait_event_interruptible_locked(lr->wait,
1265 					!kfifo_is_empty(&lr->events));
1266 			if (ret) {
1267 				spin_unlock(&lr->wait.lock);
1268 				return ret;
1269 			}
1270 		}
1271 
1272 		ret = kfifo_out(&lr->events, &le, 1);
1273 		spin_unlock(&lr->wait.lock);
1274 		if (ret != 1) {
1275 			/*
1276 			 * This should never happen - we were holding the
1277 			 * lock from the moment we learned the fifo is no
1278 			 * longer empty until now.
1279 			 */
1280 			ret = -EIO;
1281 			break;
1282 		}
1283 
1284 		if (copy_to_user(buf + bytes_read, &le, sizeof(le)))
1285 			return -EFAULT;
1286 		bytes_read += sizeof(le);
1287 	} while (count >= bytes_read + sizeof(le));
1288 
1289 	return bytes_read;
1290 }
1291 
linereq_free(struct linereq * lr)1292 static void linereq_free(struct linereq *lr)
1293 {
1294 	unsigned int i;
1295 
1296 	for (i = 0; i < lr->num_lines; i++) {
1297 		edge_detector_stop(&lr->lines[i]);
1298 		if (lr->lines[i].desc)
1299 			gpiod_free(lr->lines[i].desc);
1300 	}
1301 	kfifo_free(&lr->events);
1302 	kfree(lr->label);
1303 	put_device(&lr->gdev->dev);
1304 	kfree(lr);
1305 }
1306 
linereq_release(struct inode * inode,struct file * file)1307 static int linereq_release(struct inode *inode, struct file *file)
1308 {
1309 	struct linereq *lr = file->private_data;
1310 
1311 	linereq_free(lr);
1312 	return 0;
1313 }
1314 
1315 static const struct file_operations line_fileops = {
1316 	.release = linereq_release,
1317 	.read = linereq_read,
1318 	.poll = linereq_poll,
1319 	.owner = THIS_MODULE,
1320 	.llseek = noop_llseek,
1321 	.unlocked_ioctl = linereq_ioctl,
1322 #ifdef CONFIG_COMPAT
1323 	.compat_ioctl = linereq_ioctl_compat,
1324 #endif
1325 };
1326 
linereq_create(struct gpio_device * gdev,void __user * ip)1327 static int linereq_create(struct gpio_device *gdev, void __user *ip)
1328 {
1329 	struct gpio_v2_line_request ulr;
1330 	struct gpio_v2_line_config *lc;
1331 	struct linereq *lr;
1332 	struct file *file;
1333 	u64 flags;
1334 	unsigned int i;
1335 	int fd, ret;
1336 
1337 	if (copy_from_user(&ulr, ip, sizeof(ulr)))
1338 		return -EFAULT;
1339 
1340 	if ((ulr.num_lines == 0) || (ulr.num_lines > GPIO_V2_LINES_MAX))
1341 		return -EINVAL;
1342 
1343 	if (memchr_inv(ulr.padding, 0, sizeof(ulr.padding)))
1344 		return -EINVAL;
1345 
1346 	lc = &ulr.config;
1347 	ret = gpio_v2_line_config_validate(lc, ulr.num_lines);
1348 	if (ret)
1349 		return ret;
1350 
1351 	lr = kzalloc(struct_size(lr, lines, ulr.num_lines), GFP_KERNEL);
1352 	if (!lr)
1353 		return -ENOMEM;
1354 
1355 	lr->gdev = gdev;
1356 	get_device(&gdev->dev);
1357 
1358 	for (i = 0; i < ulr.num_lines; i++) {
1359 		lr->lines[i].req = lr;
1360 		WRITE_ONCE(lr->lines[i].sw_debounced, 0);
1361 		INIT_DELAYED_WORK(&lr->lines[i].work, debounce_work_func);
1362 	}
1363 
1364 	if (ulr.consumer[0] != '\0') {
1365 		/* label is only initialized if consumer is set */
1366 		lr->label = kstrndup(ulr.consumer, sizeof(ulr.consumer) - 1,
1367 				     GFP_KERNEL);
1368 		if (!lr->label) {
1369 			ret = -ENOMEM;
1370 			goto out_free_linereq;
1371 		}
1372 	}
1373 
1374 	mutex_init(&lr->config_mutex);
1375 	init_waitqueue_head(&lr->wait);
1376 	lr->event_buffer_size = ulr.event_buffer_size;
1377 	if (lr->event_buffer_size == 0)
1378 		lr->event_buffer_size = ulr.num_lines * 16;
1379 	else if (lr->event_buffer_size > GPIO_V2_LINES_MAX * 16)
1380 		lr->event_buffer_size = GPIO_V2_LINES_MAX * 16;
1381 
1382 	atomic_set(&lr->seqno, 0);
1383 	lr->num_lines = ulr.num_lines;
1384 
1385 	/* Request each GPIO */
1386 	for (i = 0; i < ulr.num_lines; i++) {
1387 		u32 offset = ulr.offsets[i];
1388 		struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
1389 
1390 		if (IS_ERR(desc)) {
1391 			ret = PTR_ERR(desc);
1392 			goto out_free_linereq;
1393 		}
1394 
1395 		ret = gpiod_request_user(desc, lr->label);
1396 		if (ret)
1397 			goto out_free_linereq;
1398 
1399 		lr->lines[i].desc = desc;
1400 		flags = gpio_v2_line_config_flags(lc, i);
1401 		gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1402 
1403 		ret = gpiod_set_transitory(desc, false);
1404 		if (ret < 0)
1405 			goto out_free_linereq;
1406 
1407 		/*
1408 		 * Lines have to be requested explicitly for input
1409 		 * or output, else the line will be treated "as is".
1410 		 */
1411 		if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1412 			int val = gpio_v2_line_config_output_value(lc, i);
1413 
1414 			ret = gpiod_direction_output(desc, val);
1415 			if (ret)
1416 				goto out_free_linereq;
1417 		} else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1418 			ret = gpiod_direction_input(desc);
1419 			if (ret)
1420 				goto out_free_linereq;
1421 
1422 			ret = edge_detector_setup(&lr->lines[i], lc, i,
1423 					flags & GPIO_V2_LINE_EDGE_FLAGS);
1424 			if (ret)
1425 				goto out_free_linereq;
1426 		}
1427 
1428 		blocking_notifier_call_chain(&desc->gdev->notifier,
1429 					     GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1430 
1431 		dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
1432 			offset);
1433 	}
1434 
1435 	fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1436 	if (fd < 0) {
1437 		ret = fd;
1438 		goto out_free_linereq;
1439 	}
1440 
1441 	file = anon_inode_getfile("gpio-line", &line_fileops, lr,
1442 				  O_RDONLY | O_CLOEXEC);
1443 	if (IS_ERR(file)) {
1444 		ret = PTR_ERR(file);
1445 		goto out_put_unused_fd;
1446 	}
1447 
1448 	ulr.fd = fd;
1449 	if (copy_to_user(ip, &ulr, sizeof(ulr))) {
1450 		/*
1451 		 * fput() will trigger the release() callback, so do not go onto
1452 		 * the regular error cleanup path here.
1453 		 */
1454 		fput(file);
1455 		put_unused_fd(fd);
1456 		return -EFAULT;
1457 	}
1458 
1459 	fd_install(fd, file);
1460 
1461 	dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
1462 		lr->num_lines);
1463 
1464 	return 0;
1465 
1466 out_put_unused_fd:
1467 	put_unused_fd(fd);
1468 out_free_linereq:
1469 	linereq_free(lr);
1470 	return ret;
1471 }
1472 
1473 #ifdef CONFIG_GPIO_CDEV_V1
1474 
1475 /*
1476  * GPIO line event management
1477  */
1478 
1479 /**
1480  * struct lineevent_state - contains the state of a userspace event
1481  * @gdev: the GPIO device the event pertains to
1482  * @label: consumer label used to tag descriptors
1483  * @desc: the GPIO descriptor held by this event
1484  * @eflags: the event flags this line was requested with
1485  * @irq: the interrupt that trigger in response to events on this GPIO
1486  * @wait: wait queue that handles blocking reads of events
1487  * @events: KFIFO for the GPIO events
1488  * @timestamp: cache for the timestamp storing it between hardirq
1489  * and IRQ thread, used to bring the timestamp close to the actual
1490  * event
1491  */
1492 struct lineevent_state {
1493 	struct gpio_device *gdev;
1494 	const char *label;
1495 	struct gpio_desc *desc;
1496 	u32 eflags;
1497 	int irq;
1498 	wait_queue_head_t wait;
1499 	DECLARE_KFIFO(events, struct gpioevent_data, 16);
1500 	u64 timestamp;
1501 };
1502 
1503 #define GPIOEVENT_REQUEST_VALID_FLAGS \
1504 	(GPIOEVENT_REQUEST_RISING_EDGE | \
1505 	GPIOEVENT_REQUEST_FALLING_EDGE)
1506 
lineevent_poll(struct file * file,struct poll_table_struct * wait)1507 static __poll_t lineevent_poll(struct file *file,
1508 			       struct poll_table_struct *wait)
1509 {
1510 	struct lineevent_state *le = file->private_data;
1511 	__poll_t events = 0;
1512 
1513 	if (!le->gdev->chip)
1514 		return EPOLLHUP | EPOLLERR;
1515 
1516 	poll_wait(file, &le->wait, wait);
1517 
1518 	if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
1519 		events = EPOLLIN | EPOLLRDNORM;
1520 
1521 	return events;
1522 }
1523 
1524 struct compat_gpioeevent_data {
1525 	compat_u64	timestamp;
1526 	u32		id;
1527 };
1528 
lineevent_read(struct file * file,char __user * buf,size_t count,loff_t * f_ps)1529 static ssize_t lineevent_read(struct file *file,
1530 			      char __user *buf,
1531 			      size_t count,
1532 			      loff_t *f_ps)
1533 {
1534 	struct lineevent_state *le = file->private_data;
1535 	struct gpioevent_data ge;
1536 	ssize_t bytes_read = 0;
1537 	ssize_t ge_size;
1538 	int ret;
1539 
1540 	if (!le->gdev->chip)
1541 		return -ENODEV;
1542 
1543 	/*
1544 	 * When compatible system call is being used the struct gpioevent_data,
1545 	 * in case of at least ia32, has different size due to the alignment
1546 	 * differences. Because we have first member 64 bits followed by one of
1547 	 * 32 bits there is no gap between them. The only difference is the
1548 	 * padding at the end of the data structure. Hence, we calculate the
1549 	 * actual sizeof() and pass this as an argument to copy_to_user() to
1550 	 * drop unneeded bytes from the output.
1551 	 */
1552 	if (compat_need_64bit_alignment_fixup())
1553 		ge_size = sizeof(struct compat_gpioeevent_data);
1554 	else
1555 		ge_size = sizeof(struct gpioevent_data);
1556 	if (count < ge_size)
1557 		return -EINVAL;
1558 
1559 	do {
1560 		spin_lock(&le->wait.lock);
1561 		if (kfifo_is_empty(&le->events)) {
1562 			if (bytes_read) {
1563 				spin_unlock(&le->wait.lock);
1564 				return bytes_read;
1565 			}
1566 
1567 			if (file->f_flags & O_NONBLOCK) {
1568 				spin_unlock(&le->wait.lock);
1569 				return -EAGAIN;
1570 			}
1571 
1572 			ret = wait_event_interruptible_locked(le->wait,
1573 					!kfifo_is_empty(&le->events));
1574 			if (ret) {
1575 				spin_unlock(&le->wait.lock);
1576 				return ret;
1577 			}
1578 		}
1579 
1580 		ret = kfifo_out(&le->events, &ge, 1);
1581 		spin_unlock(&le->wait.lock);
1582 		if (ret != 1) {
1583 			/*
1584 			 * This should never happen - we were holding the lock
1585 			 * from the moment we learned the fifo is no longer
1586 			 * empty until now.
1587 			 */
1588 			ret = -EIO;
1589 			break;
1590 		}
1591 
1592 		if (copy_to_user(buf + bytes_read, &ge, ge_size))
1593 			return -EFAULT;
1594 		bytes_read += ge_size;
1595 	} while (count >= bytes_read + ge_size);
1596 
1597 	return bytes_read;
1598 }
1599 
lineevent_free(struct lineevent_state * le)1600 static void lineevent_free(struct lineevent_state *le)
1601 {
1602 	if (le->irq)
1603 		free_irq(le->irq, le);
1604 	if (le->desc)
1605 		gpiod_free(le->desc);
1606 	kfree(le->label);
1607 	put_device(&le->gdev->dev);
1608 	kfree(le);
1609 }
1610 
lineevent_release(struct inode * inode,struct file * file)1611 static int lineevent_release(struct inode *inode, struct file *file)
1612 {
1613 	lineevent_free(file->private_data);
1614 	return 0;
1615 }
1616 
lineevent_ioctl(struct file * file,unsigned int cmd,unsigned long arg)1617 static long lineevent_ioctl(struct file *file, unsigned int cmd,
1618 			    unsigned long arg)
1619 {
1620 	struct lineevent_state *le = file->private_data;
1621 	void __user *ip = (void __user *)arg;
1622 	struct gpiohandle_data ghd;
1623 
1624 	if (!le->gdev->chip)
1625 		return -ENODEV;
1626 
1627 	/*
1628 	 * We can get the value for an event line but not set it,
1629 	 * because it is input by definition.
1630 	 */
1631 	if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
1632 		int val;
1633 
1634 		memset(&ghd, 0, sizeof(ghd));
1635 
1636 		val = gpiod_get_value_cansleep(le->desc);
1637 		if (val < 0)
1638 			return val;
1639 		ghd.values[0] = val;
1640 
1641 		if (copy_to_user(ip, &ghd, sizeof(ghd)))
1642 			return -EFAULT;
1643 
1644 		return 0;
1645 	}
1646 	return -EINVAL;
1647 }
1648 
1649 #ifdef CONFIG_COMPAT
lineevent_ioctl_compat(struct file * file,unsigned int cmd,unsigned long arg)1650 static long lineevent_ioctl_compat(struct file *file, unsigned int cmd,
1651 				   unsigned long arg)
1652 {
1653 	return lineevent_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1654 }
1655 #endif
1656 
1657 static const struct file_operations lineevent_fileops = {
1658 	.release = lineevent_release,
1659 	.read = lineevent_read,
1660 	.poll = lineevent_poll,
1661 	.owner = THIS_MODULE,
1662 	.llseek = noop_llseek,
1663 	.unlocked_ioctl = lineevent_ioctl,
1664 #ifdef CONFIG_COMPAT
1665 	.compat_ioctl = lineevent_ioctl_compat,
1666 #endif
1667 };
1668 
lineevent_irq_thread(int irq,void * p)1669 static irqreturn_t lineevent_irq_thread(int irq, void *p)
1670 {
1671 	struct lineevent_state *le = p;
1672 	struct gpioevent_data ge;
1673 	int ret;
1674 
1675 	/* Do not leak kernel stack to userspace */
1676 	memset(&ge, 0, sizeof(ge));
1677 
1678 	/*
1679 	 * We may be running from a nested threaded interrupt in which case
1680 	 * we didn't get the timestamp from lineevent_irq_handler().
1681 	 */
1682 	if (!le->timestamp)
1683 		ge.timestamp = ktime_get_ns();
1684 	else
1685 		ge.timestamp = le->timestamp;
1686 
1687 	if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
1688 	    && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
1689 		int level = gpiod_get_value_cansleep(le->desc);
1690 
1691 		if (level)
1692 			/* Emit low-to-high event */
1693 			ge.id = GPIOEVENT_EVENT_RISING_EDGE;
1694 		else
1695 			/* Emit high-to-low event */
1696 			ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
1697 	} else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
1698 		/* Emit low-to-high event */
1699 		ge.id = GPIOEVENT_EVENT_RISING_EDGE;
1700 	} else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
1701 		/* Emit high-to-low event */
1702 		ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
1703 	} else {
1704 		return IRQ_NONE;
1705 	}
1706 
1707 	ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
1708 					    1, &le->wait.lock);
1709 	if (ret)
1710 		wake_up_poll(&le->wait, EPOLLIN);
1711 	else
1712 		pr_debug_ratelimited("event FIFO is full - event dropped\n");
1713 
1714 	return IRQ_HANDLED;
1715 }
1716 
lineevent_irq_handler(int irq,void * p)1717 static irqreturn_t lineevent_irq_handler(int irq, void *p)
1718 {
1719 	struct lineevent_state *le = p;
1720 
1721 	/*
1722 	 * Just store the timestamp in hardirq context so we get it as
1723 	 * close in time as possible to the actual event.
1724 	 */
1725 	le->timestamp = ktime_get_ns();
1726 
1727 	return IRQ_WAKE_THREAD;
1728 }
1729 
lineevent_create(struct gpio_device * gdev,void __user * ip)1730 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
1731 {
1732 	struct gpioevent_request eventreq;
1733 	struct lineevent_state *le;
1734 	struct gpio_desc *desc;
1735 	struct file *file;
1736 	u32 offset;
1737 	u32 lflags;
1738 	u32 eflags;
1739 	int fd;
1740 	int ret;
1741 	int irq, irqflags = 0;
1742 
1743 	if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
1744 		return -EFAULT;
1745 
1746 	offset = eventreq.lineoffset;
1747 	lflags = eventreq.handleflags;
1748 	eflags = eventreq.eventflags;
1749 
1750 	desc = gpiochip_get_desc(gdev->chip, offset);
1751 	if (IS_ERR(desc))
1752 		return PTR_ERR(desc);
1753 
1754 	/* Return an error if a unknown flag is set */
1755 	if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
1756 	    (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
1757 		return -EINVAL;
1758 
1759 	/* This is just wrong: we don't look for events on output lines */
1760 	if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
1761 	    (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
1762 	    (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
1763 		return -EINVAL;
1764 
1765 	/* Only one bias flag can be set. */
1766 	if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
1767 	     (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
1768 			GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
1769 	    ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
1770 	     (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
1771 		return -EINVAL;
1772 
1773 	le = kzalloc(sizeof(*le), GFP_KERNEL);
1774 	if (!le)
1775 		return -ENOMEM;
1776 	le->gdev = gdev;
1777 	get_device(&gdev->dev);
1778 
1779 	if (eventreq.consumer_label[0] != '\0') {
1780 		/* label is only initialized if consumer_label is set */
1781 		le->label = kstrndup(eventreq.consumer_label,
1782 				     sizeof(eventreq.consumer_label) - 1,
1783 				     GFP_KERNEL);
1784 		if (!le->label) {
1785 			ret = -ENOMEM;
1786 			goto out_free_le;
1787 		}
1788 	}
1789 
1790 	ret = gpiod_request_user(desc, le->label);
1791 	if (ret)
1792 		goto out_free_le;
1793 	le->desc = desc;
1794 	le->eflags = eflags;
1795 
1796 	linehandle_flags_to_desc_flags(lflags, &desc->flags);
1797 
1798 	ret = gpiod_direction_input(desc);
1799 	if (ret)
1800 		goto out_free_le;
1801 
1802 	blocking_notifier_call_chain(&desc->gdev->notifier,
1803 				     GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1804 
1805 	irq = gpiod_to_irq(desc);
1806 	if (irq <= 0) {
1807 		ret = -ENODEV;
1808 		goto out_free_le;
1809 	}
1810 
1811 	if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
1812 		irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1813 			IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1814 	if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
1815 		irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1816 			IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1817 	irqflags |= IRQF_ONESHOT;
1818 
1819 	INIT_KFIFO(le->events);
1820 	init_waitqueue_head(&le->wait);
1821 
1822 	/* Request a thread to read the events */
1823 	ret = request_threaded_irq(irq,
1824 				   lineevent_irq_handler,
1825 				   lineevent_irq_thread,
1826 				   irqflags,
1827 				   le->label,
1828 				   le);
1829 	if (ret)
1830 		goto out_free_le;
1831 
1832 	le->irq = irq;
1833 
1834 	fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1835 	if (fd < 0) {
1836 		ret = fd;
1837 		goto out_free_le;
1838 	}
1839 
1840 	file = anon_inode_getfile("gpio-event",
1841 				  &lineevent_fileops,
1842 				  le,
1843 				  O_RDONLY | O_CLOEXEC);
1844 	if (IS_ERR(file)) {
1845 		ret = PTR_ERR(file);
1846 		goto out_put_unused_fd;
1847 	}
1848 
1849 	eventreq.fd = fd;
1850 	if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
1851 		/*
1852 		 * fput() will trigger the release() callback, so do not go onto
1853 		 * the regular error cleanup path here.
1854 		 */
1855 		fput(file);
1856 		put_unused_fd(fd);
1857 		return -EFAULT;
1858 	}
1859 
1860 	fd_install(fd, file);
1861 
1862 	return 0;
1863 
1864 out_put_unused_fd:
1865 	put_unused_fd(fd);
1866 out_free_le:
1867 	lineevent_free(le);
1868 	return ret;
1869 }
1870 
gpio_v2_line_info_to_v1(struct gpio_v2_line_info * info_v2,struct gpioline_info * info_v1)1871 static void gpio_v2_line_info_to_v1(struct gpio_v2_line_info *info_v2,
1872 				    struct gpioline_info *info_v1)
1873 {
1874 	u64 flagsv2 = info_v2->flags;
1875 
1876 	memcpy(info_v1->name, info_v2->name, sizeof(info_v1->name));
1877 	memcpy(info_v1->consumer, info_v2->consumer, sizeof(info_v1->consumer));
1878 	info_v1->line_offset = info_v2->offset;
1879 	info_v1->flags = 0;
1880 
1881 	if (flagsv2 & GPIO_V2_LINE_FLAG_USED)
1882 		info_v1->flags |= GPIOLINE_FLAG_KERNEL;
1883 
1884 	if (flagsv2 & GPIO_V2_LINE_FLAG_OUTPUT)
1885 		info_v1->flags |= GPIOLINE_FLAG_IS_OUT;
1886 
1887 	if (flagsv2 & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
1888 		info_v1->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
1889 
1890 	if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_DRAIN)
1891 		info_v1->flags |= GPIOLINE_FLAG_OPEN_DRAIN;
1892 	if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_SOURCE)
1893 		info_v1->flags |= GPIOLINE_FLAG_OPEN_SOURCE;
1894 
1895 	if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)
1896 		info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
1897 	if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN)
1898 		info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
1899 	if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_DISABLED)
1900 		info_v1->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
1901 }
1902 
gpio_v2_line_info_changed_to_v1(struct gpio_v2_line_info_changed * lic_v2,struct gpioline_info_changed * lic_v1)1903 static void gpio_v2_line_info_changed_to_v1(
1904 		struct gpio_v2_line_info_changed *lic_v2,
1905 		struct gpioline_info_changed *lic_v1)
1906 {
1907 	memset(lic_v1, 0, sizeof(*lic_v1));
1908 	gpio_v2_line_info_to_v1(&lic_v2->info, &lic_v1->info);
1909 	lic_v1->timestamp = lic_v2->timestamp_ns;
1910 	lic_v1->event_type = lic_v2->event_type;
1911 }
1912 
1913 #endif /* CONFIG_GPIO_CDEV_V1 */
1914 
gpio_desc_to_lineinfo(struct gpio_desc * desc,struct gpio_v2_line_info * info)1915 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
1916 				  struct gpio_v2_line_info *info)
1917 {
1918 	struct gpio_chip *gc = desc->gdev->chip;
1919 	bool ok_for_pinctrl;
1920 	unsigned long flags;
1921 	u32 debounce_period_us;
1922 	unsigned int num_attrs = 0;
1923 
1924 	memset(info, 0, sizeof(*info));
1925 	info->offset = gpio_chip_hwgpio(desc);
1926 
1927 	/*
1928 	 * This function takes a mutex so we must check this before taking
1929 	 * the spinlock.
1930 	 *
1931 	 * FIXME: find a non-racy way to retrieve this information. Maybe a
1932 	 * lock common to both frameworks?
1933 	 */
1934 	ok_for_pinctrl =
1935 		pinctrl_gpio_can_use_line(gc->base + info->offset);
1936 
1937 	spin_lock_irqsave(&gpio_lock, flags);
1938 
1939 	if (desc->name)
1940 		strscpy(info->name, desc->name, sizeof(info->name));
1941 
1942 	if (desc->label)
1943 		strscpy(info->consumer, desc->label, sizeof(info->consumer));
1944 
1945 	/*
1946 	 * Userspace only need to know that the kernel is using this GPIO so
1947 	 * it can't use it.
1948 	 */
1949 	info->flags = 0;
1950 	if (test_bit(FLAG_REQUESTED, &desc->flags) ||
1951 	    test_bit(FLAG_IS_HOGGED, &desc->flags) ||
1952 	    test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
1953 	    test_bit(FLAG_EXPORT, &desc->flags) ||
1954 	    test_bit(FLAG_SYSFS, &desc->flags) ||
1955 	    !gpiochip_line_is_valid(gc, info->offset) ||
1956 	    !ok_for_pinctrl)
1957 		info->flags |= GPIO_V2_LINE_FLAG_USED;
1958 
1959 	if (test_bit(FLAG_IS_OUT, &desc->flags))
1960 		info->flags |= GPIO_V2_LINE_FLAG_OUTPUT;
1961 	else
1962 		info->flags |= GPIO_V2_LINE_FLAG_INPUT;
1963 
1964 	if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1965 		info->flags |= GPIO_V2_LINE_FLAG_ACTIVE_LOW;
1966 
1967 	if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
1968 		info->flags |= GPIO_V2_LINE_FLAG_OPEN_DRAIN;
1969 	if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
1970 		info->flags |= GPIO_V2_LINE_FLAG_OPEN_SOURCE;
1971 
1972 	if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
1973 		info->flags |= GPIO_V2_LINE_FLAG_BIAS_DISABLED;
1974 	if (test_bit(FLAG_PULL_DOWN, &desc->flags))
1975 		info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN;
1976 	if (test_bit(FLAG_PULL_UP, &desc->flags))
1977 		info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_UP;
1978 
1979 	if (test_bit(FLAG_EDGE_RISING, &desc->flags))
1980 		info->flags |= GPIO_V2_LINE_FLAG_EDGE_RISING;
1981 	if (test_bit(FLAG_EDGE_FALLING, &desc->flags))
1982 		info->flags |= GPIO_V2_LINE_FLAG_EDGE_FALLING;
1983 
1984 	if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &desc->flags))
1985 		info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME;
1986 
1987 	debounce_period_us = READ_ONCE(desc->debounce_period_us);
1988 	if (debounce_period_us) {
1989 		info->attrs[num_attrs].id = GPIO_V2_LINE_ATTR_ID_DEBOUNCE;
1990 		info->attrs[num_attrs].debounce_period_us = debounce_period_us;
1991 		num_attrs++;
1992 	}
1993 	info->num_attrs = num_attrs;
1994 
1995 	spin_unlock_irqrestore(&gpio_lock, flags);
1996 }
1997 
1998 struct gpio_chardev_data {
1999 	struct gpio_device *gdev;
2000 	wait_queue_head_t wait;
2001 	DECLARE_KFIFO(events, struct gpio_v2_line_info_changed, 32);
2002 	struct notifier_block lineinfo_changed_nb;
2003 	unsigned long *watched_lines;
2004 #ifdef CONFIG_GPIO_CDEV_V1
2005 	atomic_t watch_abi_version;
2006 #endif
2007 };
2008 
chipinfo_get(struct gpio_chardev_data * cdev,void __user * ip)2009 static int chipinfo_get(struct gpio_chardev_data *cdev, void __user *ip)
2010 {
2011 	struct gpio_device *gdev = cdev->gdev;
2012 	struct gpiochip_info chipinfo;
2013 
2014 	memset(&chipinfo, 0, sizeof(chipinfo));
2015 
2016 	strscpy(chipinfo.name, dev_name(&gdev->dev), sizeof(chipinfo.name));
2017 	strscpy(chipinfo.label, gdev->label, sizeof(chipinfo.label));
2018 	chipinfo.lines = gdev->ngpio;
2019 	if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
2020 		return -EFAULT;
2021 	return 0;
2022 }
2023 
2024 #ifdef CONFIG_GPIO_CDEV_V1
2025 /*
2026  * returns 0 if the versions match, else the previously selected ABI version
2027  */
lineinfo_ensure_abi_version(struct gpio_chardev_data * cdata,unsigned int version)2028 static int lineinfo_ensure_abi_version(struct gpio_chardev_data *cdata,
2029 				       unsigned int version)
2030 {
2031 	int abiv = atomic_cmpxchg(&cdata->watch_abi_version, 0, version);
2032 
2033 	if (abiv == version)
2034 		return 0;
2035 
2036 	return abiv;
2037 }
2038 
lineinfo_get_v1(struct gpio_chardev_data * cdev,void __user * ip,bool watch)2039 static int lineinfo_get_v1(struct gpio_chardev_data *cdev, void __user *ip,
2040 			   bool watch)
2041 {
2042 	struct gpio_desc *desc;
2043 	struct gpioline_info lineinfo;
2044 	struct gpio_v2_line_info lineinfo_v2;
2045 
2046 	if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2047 		return -EFAULT;
2048 
2049 	/* this doubles as a range check on line_offset */
2050 	desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.line_offset);
2051 	if (IS_ERR(desc))
2052 		return PTR_ERR(desc);
2053 
2054 	if (watch) {
2055 		if (lineinfo_ensure_abi_version(cdev, 1))
2056 			return -EPERM;
2057 
2058 		if (test_and_set_bit(lineinfo.line_offset, cdev->watched_lines))
2059 			return -EBUSY;
2060 	}
2061 
2062 	gpio_desc_to_lineinfo(desc, &lineinfo_v2);
2063 	gpio_v2_line_info_to_v1(&lineinfo_v2, &lineinfo);
2064 
2065 	if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2066 		if (watch)
2067 			clear_bit(lineinfo.line_offset, cdev->watched_lines);
2068 		return -EFAULT;
2069 	}
2070 
2071 	return 0;
2072 }
2073 #endif
2074 
lineinfo_get(struct gpio_chardev_data * cdev,void __user * ip,bool watch)2075 static int lineinfo_get(struct gpio_chardev_data *cdev, void __user *ip,
2076 			bool watch)
2077 {
2078 	struct gpio_desc *desc;
2079 	struct gpio_v2_line_info lineinfo;
2080 
2081 	if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2082 		return -EFAULT;
2083 
2084 	if (memchr_inv(lineinfo.padding, 0, sizeof(lineinfo.padding)))
2085 		return -EINVAL;
2086 
2087 	desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.offset);
2088 	if (IS_ERR(desc))
2089 		return PTR_ERR(desc);
2090 
2091 	if (watch) {
2092 #ifdef CONFIG_GPIO_CDEV_V1
2093 		if (lineinfo_ensure_abi_version(cdev, 2))
2094 			return -EPERM;
2095 #endif
2096 		if (test_and_set_bit(lineinfo.offset, cdev->watched_lines))
2097 			return -EBUSY;
2098 	}
2099 	gpio_desc_to_lineinfo(desc, &lineinfo);
2100 
2101 	if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2102 		if (watch)
2103 			clear_bit(lineinfo.offset, cdev->watched_lines);
2104 		return -EFAULT;
2105 	}
2106 
2107 	return 0;
2108 }
2109 
lineinfo_unwatch(struct gpio_chardev_data * cdev,void __user * ip)2110 static int lineinfo_unwatch(struct gpio_chardev_data *cdev, void __user *ip)
2111 {
2112 	__u32 offset;
2113 
2114 	if (copy_from_user(&offset, ip, sizeof(offset)))
2115 		return -EFAULT;
2116 
2117 	if (offset >= cdev->gdev->ngpio)
2118 		return -EINVAL;
2119 
2120 	if (!test_and_clear_bit(offset, cdev->watched_lines))
2121 		return -EBUSY;
2122 
2123 	return 0;
2124 }
2125 
2126 /*
2127  * gpio_ioctl() - ioctl handler for the GPIO chardev
2128  */
gpio_ioctl(struct file * file,unsigned int cmd,unsigned long arg)2129 static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2130 {
2131 	struct gpio_chardev_data *cdev = file->private_data;
2132 	struct gpio_device *gdev = cdev->gdev;
2133 	void __user *ip = (void __user *)arg;
2134 
2135 	/* We fail any subsequent ioctl():s when the chip is gone */
2136 	if (!gdev->chip)
2137 		return -ENODEV;
2138 
2139 	/* Fill in the struct and pass to userspace */
2140 	switch (cmd) {
2141 	case GPIO_GET_CHIPINFO_IOCTL:
2142 		return chipinfo_get(cdev, ip);
2143 #ifdef CONFIG_GPIO_CDEV_V1
2144 	case GPIO_GET_LINEHANDLE_IOCTL:
2145 		return linehandle_create(gdev, ip);
2146 	case GPIO_GET_LINEEVENT_IOCTL:
2147 		return lineevent_create(gdev, ip);
2148 	case GPIO_GET_LINEINFO_IOCTL:
2149 		return lineinfo_get_v1(cdev, ip, false);
2150 	case GPIO_GET_LINEINFO_WATCH_IOCTL:
2151 		return lineinfo_get_v1(cdev, ip, true);
2152 #endif /* CONFIG_GPIO_CDEV_V1 */
2153 	case GPIO_V2_GET_LINEINFO_IOCTL:
2154 		return lineinfo_get(cdev, ip, false);
2155 	case GPIO_V2_GET_LINEINFO_WATCH_IOCTL:
2156 		return lineinfo_get(cdev, ip, true);
2157 	case GPIO_V2_GET_LINE_IOCTL:
2158 		return linereq_create(gdev, ip);
2159 	case GPIO_GET_LINEINFO_UNWATCH_IOCTL:
2160 		return lineinfo_unwatch(cdev, ip);
2161 	default:
2162 		return -EINVAL;
2163 	}
2164 }
2165 
2166 #ifdef CONFIG_COMPAT
gpio_ioctl_compat(struct file * file,unsigned int cmd,unsigned long arg)2167 static long gpio_ioctl_compat(struct file *file, unsigned int cmd,
2168 			      unsigned long arg)
2169 {
2170 	return gpio_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2171 }
2172 #endif
2173 
2174 static struct gpio_chardev_data *
to_gpio_chardev_data(struct notifier_block * nb)2175 to_gpio_chardev_data(struct notifier_block *nb)
2176 {
2177 	return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
2178 }
2179 
lineinfo_changed_notify(struct notifier_block * nb,unsigned long action,void * data)2180 static int lineinfo_changed_notify(struct notifier_block *nb,
2181 				   unsigned long action, void *data)
2182 {
2183 	struct gpio_chardev_data *cdev = to_gpio_chardev_data(nb);
2184 	struct gpio_v2_line_info_changed chg;
2185 	struct gpio_desc *desc = data;
2186 	int ret;
2187 
2188 	if (!test_bit(gpio_chip_hwgpio(desc), cdev->watched_lines))
2189 		return NOTIFY_DONE;
2190 
2191 	memset(&chg, 0, sizeof(chg));
2192 	chg.event_type = action;
2193 	chg.timestamp_ns = ktime_get_ns();
2194 	gpio_desc_to_lineinfo(desc, &chg.info);
2195 
2196 	ret = kfifo_in_spinlocked(&cdev->events, &chg, 1, &cdev->wait.lock);
2197 	if (ret)
2198 		wake_up_poll(&cdev->wait, EPOLLIN);
2199 	else
2200 		pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
2201 
2202 	return NOTIFY_OK;
2203 }
2204 
lineinfo_watch_poll(struct file * file,struct poll_table_struct * pollt)2205 static __poll_t lineinfo_watch_poll(struct file *file,
2206 				    struct poll_table_struct *pollt)
2207 {
2208 	struct gpio_chardev_data *cdev = file->private_data;
2209 	__poll_t events = 0;
2210 
2211 	if (!cdev->gdev->chip)
2212 		return EPOLLHUP | EPOLLERR;
2213 
2214 	poll_wait(file, &cdev->wait, pollt);
2215 
2216 	if (!kfifo_is_empty_spinlocked_noirqsave(&cdev->events,
2217 						 &cdev->wait.lock))
2218 		events = EPOLLIN | EPOLLRDNORM;
2219 
2220 	return events;
2221 }
2222 
lineinfo_watch_read(struct file * file,char __user * buf,size_t count,loff_t * off)2223 static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
2224 				   size_t count, loff_t *off)
2225 {
2226 	struct gpio_chardev_data *cdev = file->private_data;
2227 	struct gpio_v2_line_info_changed event;
2228 	ssize_t bytes_read = 0;
2229 	int ret;
2230 	size_t event_size;
2231 
2232 	if (!cdev->gdev->chip)
2233 		return -ENODEV;
2234 
2235 #ifndef CONFIG_GPIO_CDEV_V1
2236 	event_size = sizeof(struct gpio_v2_line_info_changed);
2237 	if (count < event_size)
2238 		return -EINVAL;
2239 #endif
2240 
2241 	do {
2242 		spin_lock(&cdev->wait.lock);
2243 		if (kfifo_is_empty(&cdev->events)) {
2244 			if (bytes_read) {
2245 				spin_unlock(&cdev->wait.lock);
2246 				return bytes_read;
2247 			}
2248 
2249 			if (file->f_flags & O_NONBLOCK) {
2250 				spin_unlock(&cdev->wait.lock);
2251 				return -EAGAIN;
2252 			}
2253 
2254 			ret = wait_event_interruptible_locked(cdev->wait,
2255 					!kfifo_is_empty(&cdev->events));
2256 			if (ret) {
2257 				spin_unlock(&cdev->wait.lock);
2258 				return ret;
2259 			}
2260 		}
2261 #ifdef CONFIG_GPIO_CDEV_V1
2262 		/* must be after kfifo check so watch_abi_version is set */
2263 		if (atomic_read(&cdev->watch_abi_version) == 2)
2264 			event_size = sizeof(struct gpio_v2_line_info_changed);
2265 		else
2266 			event_size = sizeof(struct gpioline_info_changed);
2267 		if (count < event_size) {
2268 			spin_unlock(&cdev->wait.lock);
2269 			return -EINVAL;
2270 		}
2271 #endif
2272 		ret = kfifo_out(&cdev->events, &event, 1);
2273 		spin_unlock(&cdev->wait.lock);
2274 		if (ret != 1) {
2275 			ret = -EIO;
2276 			break;
2277 			/* We should never get here. See lineevent_read(). */
2278 		}
2279 
2280 #ifdef CONFIG_GPIO_CDEV_V1
2281 		if (event_size == sizeof(struct gpio_v2_line_info_changed)) {
2282 			if (copy_to_user(buf + bytes_read, &event, event_size))
2283 				return -EFAULT;
2284 		} else {
2285 			struct gpioline_info_changed event_v1;
2286 
2287 			gpio_v2_line_info_changed_to_v1(&event, &event_v1);
2288 			if (copy_to_user(buf + bytes_read, &event_v1,
2289 					 event_size))
2290 				return -EFAULT;
2291 		}
2292 #else
2293 		if (copy_to_user(buf + bytes_read, &event, event_size))
2294 			return -EFAULT;
2295 #endif
2296 		bytes_read += event_size;
2297 	} while (count >= bytes_read + sizeof(event));
2298 
2299 	return bytes_read;
2300 }
2301 
2302 /**
2303  * gpio_chrdev_open() - open the chardev for ioctl operations
2304  * @inode: inode for this chardev
2305  * @file: file struct for storing private data
2306  * Returns 0 on success
2307  */
gpio_chrdev_open(struct inode * inode,struct file * file)2308 static int gpio_chrdev_open(struct inode *inode, struct file *file)
2309 {
2310 	struct gpio_device *gdev = container_of(inode->i_cdev,
2311 						struct gpio_device, chrdev);
2312 	struct gpio_chardev_data *cdev;
2313 	int ret = -ENOMEM;
2314 
2315 	/* Fail on open if the backing gpiochip is gone */
2316 	if (!gdev->chip)
2317 		return -ENODEV;
2318 
2319 	cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
2320 	if (!cdev)
2321 		return -ENOMEM;
2322 
2323 	cdev->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
2324 	if (!cdev->watched_lines)
2325 		goto out_free_cdev;
2326 
2327 	init_waitqueue_head(&cdev->wait);
2328 	INIT_KFIFO(cdev->events);
2329 	cdev->gdev = gdev;
2330 
2331 	cdev->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
2332 	ret = blocking_notifier_chain_register(&gdev->notifier,
2333 					       &cdev->lineinfo_changed_nb);
2334 	if (ret)
2335 		goto out_free_bitmap;
2336 
2337 	get_device(&gdev->dev);
2338 	file->private_data = cdev;
2339 
2340 	ret = nonseekable_open(inode, file);
2341 	if (ret)
2342 		goto out_unregister_notifier;
2343 
2344 	return ret;
2345 
2346 out_unregister_notifier:
2347 	blocking_notifier_chain_unregister(&gdev->notifier,
2348 					   &cdev->lineinfo_changed_nb);
2349 out_free_bitmap:
2350 	bitmap_free(cdev->watched_lines);
2351 out_free_cdev:
2352 	kfree(cdev);
2353 	return ret;
2354 }
2355 
2356 /**
2357  * gpio_chrdev_release() - close chardev after ioctl operations
2358  * @inode: inode for this chardev
2359  * @file: file struct for storing private data
2360  * Returns 0 on success
2361  */
gpio_chrdev_release(struct inode * inode,struct file * file)2362 static int gpio_chrdev_release(struct inode *inode, struct file *file)
2363 {
2364 	struct gpio_chardev_data *cdev = file->private_data;
2365 	struct gpio_device *gdev = cdev->gdev;
2366 
2367 	bitmap_free(cdev->watched_lines);
2368 	blocking_notifier_chain_unregister(&gdev->notifier,
2369 					   &cdev->lineinfo_changed_nb);
2370 	put_device(&gdev->dev);
2371 	kfree(cdev);
2372 
2373 	return 0;
2374 }
2375 
2376 static const struct file_operations gpio_fileops = {
2377 	.release = gpio_chrdev_release,
2378 	.open = gpio_chrdev_open,
2379 	.poll = lineinfo_watch_poll,
2380 	.read = lineinfo_watch_read,
2381 	.owner = THIS_MODULE,
2382 	.llseek = no_llseek,
2383 	.unlocked_ioctl = gpio_ioctl,
2384 #ifdef CONFIG_COMPAT
2385 	.compat_ioctl = gpio_ioctl_compat,
2386 #endif
2387 };
2388 
gpiolib_cdev_register(struct gpio_device * gdev,dev_t devt)2389 int gpiolib_cdev_register(struct gpio_device *gdev, dev_t devt)
2390 {
2391 	int ret;
2392 
2393 	cdev_init(&gdev->chrdev, &gpio_fileops);
2394 	gdev->chrdev.owner = THIS_MODULE;
2395 	gdev->dev.devt = MKDEV(MAJOR(devt), gdev->id);
2396 
2397 	ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
2398 	if (ret)
2399 		return ret;
2400 
2401 	chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
2402 		 MAJOR(devt), gdev->id);
2403 
2404 	return 0;
2405 }
2406 
gpiolib_cdev_unregister(struct gpio_device * gdev)2407 void gpiolib_cdev_unregister(struct gpio_device *gdev)
2408 {
2409 	cdev_device_del(&gdev->chrdev, &gdev->dev);
2410 }
2411