1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Industrial I/O event handling
3  *
4  * Copyright (c) 2008 Jonathan Cameron
5  *
6  * Based on elements of hwmon and input subsystems.
7  */
8 
9 #include <linux/anon_inodes.h>
10 #include <linux/device.h>
11 #include <linux/fs.h>
12 #include <linux/kernel.h>
13 #include <linux/kfifo.h>
14 #include <linux/module.h>
15 #include <linux/poll.h>
16 #include <linux/sched.h>
17 #include <linux/slab.h>
18 #include <linux/uaccess.h>
19 #include <linux/wait.h>
20 #include <linux/iio/iio.h>
21 #include "iio_core.h"
22 #include <linux/iio/sysfs.h>
23 #include <linux/iio/events.h>
24 
25 /**
26  * struct iio_event_interface - chrdev interface for an event line
27  * @wait:		wait queue to allow blocking reads of events
28  * @det_events:		list of detected events
29  * @dev_attr_list:	list of event interface sysfs attribute
30  * @flags:		file operations related flags including busy flag.
31  * @group:		event interface sysfs attribute group
32  * @read_lock:		lock to protect kfifo read operations
33  */
34 struct iio_event_interface {
35 	wait_queue_head_t	wait;
36 	DECLARE_KFIFO(det_events, struct iio_event_data, 16);
37 
38 	struct list_head	dev_attr_list;
39 	unsigned long		flags;
40 	struct attribute_group	group;
41 	struct mutex		read_lock;
42 };
43 
44 bool iio_event_enabled(const struct iio_event_interface *ev_int)
45 {
46 	return !!test_bit(IIO_BUSY_BIT_POS, &ev_int->flags);
47 }
48 
49 /**
50  * iio_push_event() - try to add event to the list for userspace reading
51  * @indio_dev:		IIO device structure
52  * @ev_code:		What event
53  * @timestamp:		When the event occurred
54  *
55  * Note: The caller must make sure that this function is not running
56  * concurrently for the same indio_dev more than once.
57  *
58  * This function may be safely used as soon as a valid reference to iio_dev has
59  * been obtained via iio_device_alloc(), but any events that are submitted
60  * before iio_device_register() has successfully completed will be silently
61  * discarded.
62  **/
63 int iio_push_event(struct iio_dev *indio_dev, u64 ev_code, s64 timestamp)
64 {
65 	struct iio_event_interface *ev_int = indio_dev->event_interface;
66 	struct iio_event_data ev;
67 	int copied;
68 
69 	if (!ev_int)
70 		return 0;
71 
72 	/* Does anyone care? */
73 	if (iio_event_enabled(ev_int)) {
74 
75 		ev.id = ev_code;
76 		ev.timestamp = timestamp;
77 
78 		copied = kfifo_put(&ev_int->det_events, ev);
79 		if (copied != 0)
80 			wake_up_poll(&ev_int->wait, EPOLLIN);
81 	}
82 
83 	return 0;
84 }
85 EXPORT_SYMBOL(iio_push_event);
86 
87 /**
88  * iio_event_poll() - poll the event queue to find out if it has data
89  * @filep:	File structure pointer to identify the device
90  * @wait:	Poll table pointer to add the wait queue on
91  *
92  * Return: (EPOLLIN | EPOLLRDNORM) if data is available for reading
93  *	   or a negative error code on failure
94  */
95 static __poll_t iio_event_poll(struct file *filep,
96 			     struct poll_table_struct *wait)
97 {
98 	struct iio_dev *indio_dev = filep->private_data;
99 	struct iio_event_interface *ev_int = indio_dev->event_interface;
100 	__poll_t events = 0;
101 
102 	if (!indio_dev->info)
103 		return events;
104 
105 	poll_wait(filep, &ev_int->wait, wait);
106 
107 	if (!kfifo_is_empty(&ev_int->det_events))
108 		events = EPOLLIN | EPOLLRDNORM;
109 
110 	return events;
111 }
112 
113 static ssize_t iio_event_chrdev_read(struct file *filep,
114 				     char __user *buf,
115 				     size_t count,
116 				     loff_t *f_ps)
117 {
118 	struct iio_dev *indio_dev = filep->private_data;
119 	struct iio_event_interface *ev_int = indio_dev->event_interface;
120 	unsigned int copied;
121 	int ret;
122 
123 	if (!indio_dev->info)
124 		return -ENODEV;
125 
126 	if (count < sizeof(struct iio_event_data))
127 		return -EINVAL;
128 
129 	do {
130 		if (kfifo_is_empty(&ev_int->det_events)) {
131 			if (filep->f_flags & O_NONBLOCK)
132 				return -EAGAIN;
133 
134 			ret = wait_event_interruptible(ev_int->wait,
135 					!kfifo_is_empty(&ev_int->det_events) ||
136 					indio_dev->info == NULL);
137 			if (ret)
138 				return ret;
139 			if (indio_dev->info == NULL)
140 				return -ENODEV;
141 		}
142 
143 		if (mutex_lock_interruptible(&ev_int->read_lock))
144 			return -ERESTARTSYS;
145 		ret = kfifo_to_user(&ev_int->det_events, buf, count, &copied);
146 		mutex_unlock(&ev_int->read_lock);
147 
148 		if (ret)
149 			return ret;
150 
151 		/*
152 		 * If we couldn't read anything from the fifo (a different
153 		 * thread might have been faster) we either return -EAGAIN if
154 		 * the file descriptor is non-blocking, otherwise we go back to
155 		 * sleep and wait for more data to arrive.
156 		 */
157 		if (copied == 0 && (filep->f_flags & O_NONBLOCK))
158 			return -EAGAIN;
159 
160 	} while (copied == 0);
161 
162 	return copied;
163 }
164 
165 static int iio_event_chrdev_release(struct inode *inode, struct file *filep)
166 {
167 	struct iio_dev *indio_dev = filep->private_data;
168 	struct iio_event_interface *ev_int = indio_dev->event_interface;
169 
170 	clear_bit(IIO_BUSY_BIT_POS, &ev_int->flags);
171 
172 	iio_device_put(indio_dev);
173 
174 	return 0;
175 }
176 
177 static const struct file_operations iio_event_chrdev_fileops = {
178 	.read =  iio_event_chrdev_read,
179 	.poll =  iio_event_poll,
180 	.release = iio_event_chrdev_release,
181 	.owner = THIS_MODULE,
182 	.llseek = noop_llseek,
183 };
184 
185 int iio_event_getfd(struct iio_dev *indio_dev)
186 {
187 	struct iio_event_interface *ev_int = indio_dev->event_interface;
188 	int fd;
189 
190 	if (ev_int == NULL)
191 		return -ENODEV;
192 
193 	fd = mutex_lock_interruptible(&indio_dev->mlock);
194 	if (fd)
195 		return fd;
196 
197 	if (test_and_set_bit(IIO_BUSY_BIT_POS, &ev_int->flags)) {
198 		fd = -EBUSY;
199 		goto unlock;
200 	}
201 
202 	iio_device_get(indio_dev);
203 
204 	fd = anon_inode_getfd("iio:event", &iio_event_chrdev_fileops,
205 				indio_dev, O_RDONLY | O_CLOEXEC);
206 	if (fd < 0) {
207 		clear_bit(IIO_BUSY_BIT_POS, &ev_int->flags);
208 		iio_device_put(indio_dev);
209 	} else {
210 		kfifo_reset_out(&ev_int->det_events);
211 	}
212 
213 unlock:
214 	mutex_unlock(&indio_dev->mlock);
215 	return fd;
216 }
217 
218 static const char * const iio_ev_type_text[] = {
219 	[IIO_EV_TYPE_THRESH] = "thresh",
220 	[IIO_EV_TYPE_MAG] = "mag",
221 	[IIO_EV_TYPE_ROC] = "roc",
222 	[IIO_EV_TYPE_THRESH_ADAPTIVE] = "thresh_adaptive",
223 	[IIO_EV_TYPE_MAG_ADAPTIVE] = "mag_adaptive",
224 	[IIO_EV_TYPE_CHANGE] = "change",
225 };
226 
227 static const char * const iio_ev_dir_text[] = {
228 	[IIO_EV_DIR_EITHER] = "either",
229 	[IIO_EV_DIR_RISING] = "rising",
230 	[IIO_EV_DIR_FALLING] = "falling"
231 };
232 
233 static const char * const iio_ev_info_text[] = {
234 	[IIO_EV_INFO_ENABLE] = "en",
235 	[IIO_EV_INFO_VALUE] = "value",
236 	[IIO_EV_INFO_HYSTERESIS] = "hysteresis",
237 	[IIO_EV_INFO_PERIOD] = "period",
238 	[IIO_EV_INFO_HIGH_PASS_FILTER_3DB] = "high_pass_filter_3db",
239 	[IIO_EV_INFO_LOW_PASS_FILTER_3DB] = "low_pass_filter_3db",
240 };
241 
242 static enum iio_event_direction iio_ev_attr_dir(struct iio_dev_attr *attr)
243 {
244 	return attr->c->event_spec[attr->address & 0xffff].dir;
245 }
246 
247 static enum iio_event_type iio_ev_attr_type(struct iio_dev_attr *attr)
248 {
249 	return attr->c->event_spec[attr->address & 0xffff].type;
250 }
251 
252 static enum iio_event_info iio_ev_attr_info(struct iio_dev_attr *attr)
253 {
254 	return (attr->address >> 16) & 0xffff;
255 }
256 
257 static ssize_t iio_ev_state_store(struct device *dev,
258 				  struct device_attribute *attr,
259 				  const char *buf,
260 				  size_t len)
261 {
262 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
263 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
264 	int ret;
265 	bool val;
266 
267 	ret = strtobool(buf, &val);
268 	if (ret < 0)
269 		return ret;
270 
271 	ret = indio_dev->info->write_event_config(indio_dev,
272 		this_attr->c, iio_ev_attr_type(this_attr),
273 		iio_ev_attr_dir(this_attr), val);
274 
275 	return (ret < 0) ? ret : len;
276 }
277 
278 static ssize_t iio_ev_state_show(struct device *dev,
279 				 struct device_attribute *attr,
280 				 char *buf)
281 {
282 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
283 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
284 	int val;
285 
286 	val = indio_dev->info->read_event_config(indio_dev,
287 		this_attr->c, iio_ev_attr_type(this_attr),
288 		iio_ev_attr_dir(this_attr));
289 	if (val < 0)
290 		return val;
291 	else
292 		return sprintf(buf, "%d\n", val);
293 }
294 
295 static ssize_t iio_ev_value_show(struct device *dev,
296 				 struct device_attribute *attr,
297 				 char *buf)
298 {
299 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
300 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
301 	int val, val2, val_arr[2];
302 	int ret;
303 
304 	ret = indio_dev->info->read_event_value(indio_dev,
305 		this_attr->c, iio_ev_attr_type(this_attr),
306 		iio_ev_attr_dir(this_attr), iio_ev_attr_info(this_attr),
307 		&val, &val2);
308 	if (ret < 0)
309 		return ret;
310 	val_arr[0] = val;
311 	val_arr[1] = val2;
312 	return iio_format_value(buf, ret, 2, val_arr);
313 }
314 
315 static ssize_t iio_ev_value_store(struct device *dev,
316 				  struct device_attribute *attr,
317 				  const char *buf,
318 				  size_t len)
319 {
320 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
321 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
322 	int val, val2;
323 	int ret;
324 
325 	if (!indio_dev->info->write_event_value)
326 		return -EINVAL;
327 
328 	ret = iio_str_to_fixpoint(buf, 100000, &val, &val2);
329 	if (ret)
330 		return ret;
331 	ret = indio_dev->info->write_event_value(indio_dev,
332 		this_attr->c, iio_ev_attr_type(this_attr),
333 		iio_ev_attr_dir(this_attr), iio_ev_attr_info(this_attr),
334 		val, val2);
335 	if (ret < 0)
336 		return ret;
337 
338 	return len;
339 }
340 
341 static int iio_device_add_event(struct iio_dev *indio_dev,
342 	const struct iio_chan_spec *chan, unsigned int spec_index,
343 	enum iio_event_type type, enum iio_event_direction dir,
344 	enum iio_shared_by shared_by, const unsigned long *mask)
345 {
346 	ssize_t (*show)(struct device *, struct device_attribute *, char *);
347 	ssize_t (*store)(struct device *, struct device_attribute *,
348 		const char *, size_t);
349 	unsigned int attrcount = 0;
350 	unsigned int i;
351 	char *postfix;
352 	int ret;
353 
354 	for_each_set_bit(i, mask, sizeof(*mask)*8) {
355 		if (i >= ARRAY_SIZE(iio_ev_info_text))
356 			return -EINVAL;
357 		if (dir != IIO_EV_DIR_NONE)
358 			postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
359 					iio_ev_type_text[type],
360 					iio_ev_dir_text[dir],
361 					iio_ev_info_text[i]);
362 		else
363 			postfix = kasprintf(GFP_KERNEL, "%s_%s",
364 					iio_ev_type_text[type],
365 					iio_ev_info_text[i]);
366 		if (postfix == NULL)
367 			return -ENOMEM;
368 
369 		if (i == IIO_EV_INFO_ENABLE) {
370 			show = iio_ev_state_show;
371 			store = iio_ev_state_store;
372 		} else {
373 			show = iio_ev_value_show;
374 			store = iio_ev_value_store;
375 		}
376 
377 		ret = __iio_add_chan_devattr(postfix, chan, show, store,
378 			 (i << 16) | spec_index, shared_by, &indio_dev->dev,
379 			&indio_dev->event_interface->dev_attr_list);
380 		kfree(postfix);
381 
382 		if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
383 			continue;
384 
385 		if (ret)
386 			return ret;
387 
388 		attrcount++;
389 	}
390 
391 	return attrcount;
392 }
393 
394 static int iio_device_add_event_sysfs(struct iio_dev *indio_dev,
395 	struct iio_chan_spec const *chan)
396 {
397 	int ret = 0, i, attrcount = 0;
398 	enum iio_event_direction dir;
399 	enum iio_event_type type;
400 
401 	for (i = 0; i < chan->num_event_specs; i++) {
402 		type = chan->event_spec[i].type;
403 		dir = chan->event_spec[i].dir;
404 
405 		ret = iio_device_add_event(indio_dev, chan, i, type, dir,
406 			IIO_SEPARATE, &chan->event_spec[i].mask_separate);
407 		if (ret < 0)
408 			return ret;
409 		attrcount += ret;
410 
411 		ret = iio_device_add_event(indio_dev, chan, i, type, dir,
412 			IIO_SHARED_BY_TYPE,
413 			&chan->event_spec[i].mask_shared_by_type);
414 		if (ret < 0)
415 			return ret;
416 		attrcount += ret;
417 
418 		ret = iio_device_add_event(indio_dev, chan, i, type, dir,
419 			IIO_SHARED_BY_DIR,
420 			&chan->event_spec[i].mask_shared_by_dir);
421 		if (ret < 0)
422 			return ret;
423 		attrcount += ret;
424 
425 		ret = iio_device_add_event(indio_dev, chan, i, type, dir,
426 			IIO_SHARED_BY_ALL,
427 			&chan->event_spec[i].mask_shared_by_all);
428 		if (ret < 0)
429 			return ret;
430 		attrcount += ret;
431 	}
432 	ret = attrcount;
433 	return ret;
434 }
435 
436 static inline int __iio_add_event_config_attrs(struct iio_dev *indio_dev)
437 {
438 	int j, ret, attrcount = 0;
439 
440 	/* Dynamically created from the channels array */
441 	for (j = 0; j < indio_dev->num_channels; j++) {
442 		ret = iio_device_add_event_sysfs(indio_dev,
443 						 &indio_dev->channels[j]);
444 		if (ret < 0)
445 			return ret;
446 		attrcount += ret;
447 	}
448 	return attrcount;
449 }
450 
451 static bool iio_check_for_dynamic_events(struct iio_dev *indio_dev)
452 {
453 	int j;
454 
455 	for (j = 0; j < indio_dev->num_channels; j++) {
456 		if (indio_dev->channels[j].num_event_specs != 0)
457 			return true;
458 	}
459 	return false;
460 }
461 
462 static void iio_setup_ev_int(struct iio_event_interface *ev_int)
463 {
464 	INIT_KFIFO(ev_int->det_events);
465 	init_waitqueue_head(&ev_int->wait);
466 	mutex_init(&ev_int->read_lock);
467 }
468 
469 static const char *iio_event_group_name = "events";
470 int iio_device_register_eventset(struct iio_dev *indio_dev)
471 {
472 	struct iio_dev_attr *p;
473 	int ret = 0, attrcount_orig = 0, attrcount, attrn;
474 	struct attribute **attr;
475 
476 	if (!(indio_dev->info->event_attrs ||
477 	      iio_check_for_dynamic_events(indio_dev)))
478 		return 0;
479 
480 	indio_dev->event_interface =
481 		kzalloc(sizeof(struct iio_event_interface), GFP_KERNEL);
482 	if (indio_dev->event_interface == NULL)
483 		return -ENOMEM;
484 
485 	INIT_LIST_HEAD(&indio_dev->event_interface->dev_attr_list);
486 
487 	iio_setup_ev_int(indio_dev->event_interface);
488 	if (indio_dev->info->event_attrs != NULL) {
489 		attr = indio_dev->info->event_attrs->attrs;
490 		while (*attr++ != NULL)
491 			attrcount_orig++;
492 	}
493 	attrcount = attrcount_orig;
494 	if (indio_dev->channels) {
495 		ret = __iio_add_event_config_attrs(indio_dev);
496 		if (ret < 0)
497 			goto error_free_setup_event_lines;
498 		attrcount += ret;
499 	}
500 
501 	indio_dev->event_interface->group.name = iio_event_group_name;
502 	indio_dev->event_interface->group.attrs = kcalloc(attrcount + 1,
503 							  sizeof(indio_dev->event_interface->group.attrs[0]),
504 							  GFP_KERNEL);
505 	if (indio_dev->event_interface->group.attrs == NULL) {
506 		ret = -ENOMEM;
507 		goto error_free_setup_event_lines;
508 	}
509 	if (indio_dev->info->event_attrs)
510 		memcpy(indio_dev->event_interface->group.attrs,
511 		       indio_dev->info->event_attrs->attrs,
512 		       sizeof(indio_dev->event_interface->group.attrs[0])
513 		       *attrcount_orig);
514 	attrn = attrcount_orig;
515 	/* Add all elements from the list. */
516 	list_for_each_entry(p,
517 			    &indio_dev->event_interface->dev_attr_list,
518 			    l)
519 		indio_dev->event_interface->group.attrs[attrn++] =
520 			&p->dev_attr.attr;
521 	indio_dev->groups[indio_dev->groupcounter++] =
522 		&indio_dev->event_interface->group;
523 
524 	return 0;
525 
526 error_free_setup_event_lines:
527 	iio_free_chan_devattr_list(&indio_dev->event_interface->dev_attr_list);
528 	kfree(indio_dev->event_interface);
529 	indio_dev->event_interface = NULL;
530 	return ret;
531 }
532 
533 /**
534  * iio_device_wakeup_eventset - Wakes up the event waitqueue
535  * @indio_dev: The IIO device
536  *
537  * Wakes up the event waitqueue used for poll() and blocking read().
538  * Should usually be called when the device is unregistered.
539  */
540 void iio_device_wakeup_eventset(struct iio_dev *indio_dev)
541 {
542 	if (indio_dev->event_interface == NULL)
543 		return;
544 	wake_up(&indio_dev->event_interface->wait);
545 }
546 
547 void iio_device_unregister_eventset(struct iio_dev *indio_dev)
548 {
549 	if (indio_dev->event_interface == NULL)
550 		return;
551 	iio_free_chan_devattr_list(&indio_dev->event_interface->dev_attr_list);
552 	kfree(indio_dev->event_interface->group.attrs);
553 	kfree(indio_dev->event_interface);
554 }
555