xref: /linux/drivers/iio/industrialio-buffer.c (revision d5a821f66047c2effd06147b84775f9b2ce0f4aa)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* The industrial I/O core
3  *
4  * Copyright (c) 2008 Jonathan Cameron
5  *
6  * Handling of buffer allocation / resizing.
7  *
8  * Things to look at here.
9  * - Better memory allocation techniques?
10  * - Alternative access techniques?
11  */
12 #include <linux/atomic.h>
13 #include <linux/anon_inodes.h>
14 #include <linux/cleanup.h>
15 #include <linux/kernel.h>
16 #include <linux/export.h>
17 #include <linux/device.h>
18 #include <linux/dma-buf.h>
19 #include <linux/dma-fence.h>
20 #include <linux/dma-resv.h>
21 #include <linux/file.h>
22 #include <linux/fs.h>
23 #include <linux/cdev.h>
24 #include <linux/slab.h>
25 #include <linux/mm.h>
26 #include <linux/poll.h>
27 #include <linux/sched/signal.h>
28 
29 #include <linux/iio/iio.h>
30 #include <linux/iio/iio-opaque.h>
31 #include "iio_core.h"
32 #include "iio_core_trigger.h"
33 #include <linux/iio/sysfs.h>
34 #include <linux/iio/buffer.h>
35 #include <linux/iio/buffer_impl.h>
36 
37 #define DMABUF_ENQUEUE_TIMEOUT_MS 5000
38 
39 MODULE_IMPORT_NS("DMA_BUF");
40 
41 struct iio_dmabuf_priv {
42 	struct list_head entry;
43 	struct kref ref;
44 
45 	struct iio_buffer *buffer;
46 	struct iio_dma_buffer_block *block;
47 
48 	u64 context;
49 
50 	struct dma_buf_attachment *attach;
51 	struct sg_table *sgt;
52 	enum dma_data_direction dir;
53 	atomic_t seqno;
54 };
55 
56 struct iio_dma_fence {
57 	/*
58 	 * Must remain the first member so the default release callback can pass
59 	 * the fence directly to dma_fence_free().
60 	 */
61 	struct dma_fence base;
62 	spinlock_t lock; /* protects base */
63 	struct iio_dmabuf_priv *priv;
64 	struct work_struct work;
65 };
66 
67 static const char * const iio_endian_prefix[] = {
68 	[IIO_BE] = "be",
69 	[IIO_LE] = "le",
70 };
71 
iio_buffer_is_active(struct iio_buffer * buf)72 static bool iio_buffer_is_active(struct iio_buffer *buf)
73 {
74 	return !list_empty(&buf->buffer_list);
75 }
76 
iio_buffer_data_available(struct iio_buffer * buf)77 static size_t iio_buffer_data_available(struct iio_buffer *buf)
78 {
79 	return buf->access->data_available(buf);
80 }
81 
iio_buffer_flush_hwfifo(struct iio_dev * indio_dev,struct iio_buffer * buf,size_t required)82 static int iio_buffer_flush_hwfifo(struct iio_dev *indio_dev,
83 				   struct iio_buffer *buf, size_t required)
84 {
85 	if (!indio_dev->info->hwfifo_flush_to_buffer)
86 		return -ENODEV;
87 
88 	return indio_dev->info->hwfifo_flush_to_buffer(indio_dev, required);
89 }
90 
iio_buffer_ready(struct iio_dev * indio_dev,struct iio_buffer * buf,size_t to_wait,int to_flush)91 static bool iio_buffer_ready(struct iio_dev *indio_dev, struct iio_buffer *buf,
92 			     size_t to_wait, int to_flush)
93 {
94 	size_t avail;
95 	int flushed = 0;
96 
97 	/* wakeup if the device was unregistered */
98 	if (!indio_dev->info)
99 		return true;
100 
101 	/* drain the buffer if it was disabled */
102 	if (!iio_buffer_is_active(buf)) {
103 		to_wait = min_t(size_t, to_wait, 1);
104 		to_flush = 0;
105 	}
106 
107 	avail = iio_buffer_data_available(buf);
108 
109 	if (avail >= to_wait) {
110 		/* force a flush for non-blocking reads */
111 		if (!to_wait && avail < to_flush)
112 			iio_buffer_flush_hwfifo(indio_dev, buf,
113 						to_flush - avail);
114 		return true;
115 	}
116 
117 	if (to_flush)
118 		flushed = iio_buffer_flush_hwfifo(indio_dev, buf,
119 						  to_wait - avail);
120 	if (flushed <= 0)
121 		return false;
122 
123 	if (avail + flushed >= to_wait)
124 		return true;
125 
126 	return false;
127 }
128 
129 /**
130  * iio_buffer_read() - chrdev read for buffer access
131  * @filp:	File structure pointer for the char device
132  * @buf:	Destination buffer for iio buffer read
133  * @n:		First n bytes to read
134  * @f_ps:	Long offset provided by the user as a seek position
135  *
136  * This function relies on all buffer implementations having an
137  * iio_buffer as their first element.
138  *
139  * Return: negative values corresponding to error codes or ret != 0
140  *	   for ending the reading activity
141  **/
iio_buffer_read(struct file * filp,char __user * buf,size_t n,loff_t * f_ps)142 static ssize_t iio_buffer_read(struct file *filp, char __user *buf,
143 			       size_t n, loff_t *f_ps)
144 {
145 	struct iio_dev_buffer_pair *ib = filp->private_data;
146 	struct iio_buffer *rb = ib->buffer;
147 	struct iio_dev *indio_dev = ib->indio_dev;
148 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
149 	size_t datum_size;
150 	size_t to_wait;
151 	int ret = 0;
152 
153 	if (!indio_dev->info)
154 		return -ENODEV;
155 
156 	if (!rb || !rb->access->read)
157 		return -EINVAL;
158 
159 	if (rb->direction != IIO_BUFFER_DIRECTION_IN)
160 		return -EPERM;
161 
162 	datum_size = rb->bytes_per_datum;
163 
164 	/*
165 	 * If datum_size is 0 there will never be anything to read from the
166 	 * buffer, so signal end of file now.
167 	 */
168 	if (!datum_size)
169 		return 0;
170 
171 	if (filp->f_flags & O_NONBLOCK)
172 		to_wait = 0;
173 	else
174 		to_wait = min_t(size_t, n / datum_size, rb->watermark);
175 
176 	add_wait_queue(&rb->pollq, &wait);
177 	do {
178 		if (!indio_dev->info) {
179 			ret = -ENODEV;
180 			break;
181 		}
182 
183 		if (!iio_buffer_ready(indio_dev, rb, to_wait, n / datum_size)) {
184 			if (signal_pending(current)) {
185 				ret = -ERESTARTSYS;
186 				break;
187 			}
188 
189 			wait_woken(&wait, TASK_INTERRUPTIBLE,
190 				   MAX_SCHEDULE_TIMEOUT);
191 			continue;
192 		}
193 
194 		ret = rb->access->read(rb, n, buf);
195 		if (ret == 0 && (filp->f_flags & O_NONBLOCK))
196 			ret = -EAGAIN;
197 	} while (ret == 0);
198 	remove_wait_queue(&rb->pollq, &wait);
199 
200 	return ret;
201 }
202 
iio_buffer_space_available(struct iio_buffer * buf)203 static size_t iio_buffer_space_available(struct iio_buffer *buf)
204 {
205 	if (buf->access->space_available)
206 		return buf->access->space_available(buf);
207 
208 	return SIZE_MAX;
209 }
210 
iio_buffer_write(struct file * filp,const char __user * buf,size_t n,loff_t * f_ps)211 static ssize_t iio_buffer_write(struct file *filp, const char __user *buf,
212 				size_t n, loff_t *f_ps)
213 {
214 	struct iio_dev_buffer_pair *ib = filp->private_data;
215 	struct iio_buffer *rb = ib->buffer;
216 	struct iio_dev *indio_dev = ib->indio_dev;
217 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
218 	int ret = 0;
219 	size_t written;
220 
221 	if (!indio_dev->info)
222 		return -ENODEV;
223 
224 	if (!rb || !rb->access->write)
225 		return -EINVAL;
226 
227 	if (rb->direction != IIO_BUFFER_DIRECTION_OUT)
228 		return -EPERM;
229 
230 	written = 0;
231 	add_wait_queue(&rb->pollq, &wait);
232 	do {
233 		if (!indio_dev->info) {
234 			ret = -ENODEV;
235 			break;
236 		}
237 
238 		if (!iio_buffer_space_available(rb)) {
239 			if (signal_pending(current)) {
240 				ret = -ERESTARTSYS;
241 				break;
242 			}
243 
244 			if (filp->f_flags & O_NONBLOCK) {
245 				if (!written)
246 					ret = -EAGAIN;
247 				break;
248 			}
249 
250 			wait_woken(&wait, TASK_INTERRUPTIBLE,
251 				   MAX_SCHEDULE_TIMEOUT);
252 			continue;
253 		}
254 
255 		ret = rb->access->write(rb, n - written, buf + written);
256 		if (ret < 0)
257 			break;
258 
259 		written += ret;
260 
261 	} while (written != n);
262 	remove_wait_queue(&rb->pollq, &wait);
263 
264 	return ret < 0 ? ret : written;
265 }
266 
267 /**
268  * iio_buffer_poll() - poll the buffer to find out if it has data
269  * @filp:	File structure pointer for device access
270  * @wait:	Poll table structure pointer for which the driver adds
271  *		a wait queue
272  *
273  * Return: (EPOLLIN | EPOLLRDNORM) if data is available for reading
274  *	   or 0 for other cases
275  */
iio_buffer_poll(struct file * filp,struct poll_table_struct * wait)276 static __poll_t iio_buffer_poll(struct file *filp,
277 				struct poll_table_struct *wait)
278 {
279 	struct iio_dev_buffer_pair *ib = filp->private_data;
280 	struct iio_buffer *rb = ib->buffer;
281 	struct iio_dev *indio_dev = ib->indio_dev;
282 
283 	if (!indio_dev->info || !rb)
284 		return 0;
285 
286 	poll_wait(filp, &rb->pollq, wait);
287 
288 	switch (rb->direction) {
289 	case IIO_BUFFER_DIRECTION_IN:
290 		if (iio_buffer_ready(indio_dev, rb, rb->watermark, 0))
291 			return EPOLLIN | EPOLLRDNORM;
292 		break;
293 	case IIO_BUFFER_DIRECTION_OUT:
294 		if (iio_buffer_space_available(rb))
295 			return EPOLLOUT | EPOLLWRNORM;
296 		break;
297 	}
298 
299 	return 0;
300 }
301 
iio_buffer_read_wrapper(struct file * filp,char __user * buf,size_t n,loff_t * f_ps)302 ssize_t iio_buffer_read_wrapper(struct file *filp, char __user *buf,
303 				size_t n, loff_t *f_ps)
304 {
305 	struct iio_dev_buffer_pair *ib = filp->private_data;
306 	struct iio_buffer *rb = ib->buffer;
307 
308 	/* check if buffer was opened through new API */
309 	if (test_bit(IIO_BUSY_BIT_POS, &rb->flags))
310 		return -EBUSY;
311 
312 	return iio_buffer_read(filp, buf, n, f_ps);
313 }
314 
iio_buffer_write_wrapper(struct file * filp,const char __user * buf,size_t n,loff_t * f_ps)315 ssize_t iio_buffer_write_wrapper(struct file *filp, const char __user *buf,
316 				 size_t n, loff_t *f_ps)
317 {
318 	struct iio_dev_buffer_pair *ib = filp->private_data;
319 	struct iio_buffer *rb = ib->buffer;
320 
321 	/* check if buffer was opened through new API */
322 	if (test_bit(IIO_BUSY_BIT_POS, &rb->flags))
323 		return -EBUSY;
324 
325 	return iio_buffer_write(filp, buf, n, f_ps);
326 }
327 
iio_buffer_poll_wrapper(struct file * filp,struct poll_table_struct * wait)328 __poll_t iio_buffer_poll_wrapper(struct file *filp,
329 				 struct poll_table_struct *wait)
330 {
331 	struct iio_dev_buffer_pair *ib = filp->private_data;
332 	struct iio_buffer *rb = ib->buffer;
333 
334 	/* check if buffer was opened through new API */
335 	if (test_bit(IIO_BUSY_BIT_POS, &rb->flags))
336 		return 0;
337 
338 	return iio_buffer_poll(filp, wait);
339 }
340 
341 /**
342  * iio_buffer_wakeup_poll - Wakes up the buffer waitqueue
343  * @indio_dev: The IIO device
344  *
345  * Wakes up the event waitqueue used for poll(). Should usually
346  * be called when the device is unregistered.
347  */
iio_buffer_wakeup_poll(struct iio_dev * indio_dev)348 void iio_buffer_wakeup_poll(struct iio_dev *indio_dev)
349 {
350 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
351 	struct iio_buffer *buffer;
352 	unsigned int i;
353 
354 	for (i = 0; i < iio_dev_opaque->attached_buffers_cnt; i++) {
355 		buffer = iio_dev_opaque->attached_buffers[i];
356 		wake_up(&buffer->pollq);
357 	}
358 }
359 
iio_pop_from_buffer(struct iio_buffer * buffer,void * data)360 int iio_pop_from_buffer(struct iio_buffer *buffer, void *data)
361 {
362 	if (!buffer || !buffer->access || !buffer->access->remove_from)
363 		return -EINVAL;
364 
365 	return buffer->access->remove_from(buffer, data);
366 }
367 EXPORT_SYMBOL_GPL(iio_pop_from_buffer);
368 
iio_buffer_init(struct iio_buffer * buffer)369 void iio_buffer_init(struct iio_buffer *buffer)
370 {
371 	INIT_LIST_HEAD(&buffer->demux_list);
372 	INIT_LIST_HEAD(&buffer->buffer_list);
373 	INIT_LIST_HEAD(&buffer->dmabufs);
374 	mutex_init(&buffer->dmabufs_mutex);
375 	init_waitqueue_head(&buffer->pollq);
376 	kref_init(&buffer->ref);
377 	if (!buffer->watermark)
378 		buffer->watermark = 1;
379 }
380 EXPORT_SYMBOL(iio_buffer_init);
381 
iio_device_detach_buffers(struct iio_dev * indio_dev)382 void iio_device_detach_buffers(struct iio_dev *indio_dev)
383 {
384 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
385 	struct iio_buffer *buffer;
386 	unsigned int i;
387 
388 	for (i = 0; i < iio_dev_opaque->attached_buffers_cnt; i++) {
389 		buffer = iio_dev_opaque->attached_buffers[i];
390 		iio_buffer_put(buffer);
391 	}
392 
393 	kfree(iio_dev_opaque->attached_buffers);
394 }
395 
iio_show_scan_index(struct device * dev,struct device_attribute * attr,char * buf)396 static ssize_t iio_show_scan_index(struct device *dev,
397 				   struct device_attribute *attr,
398 				   char *buf)
399 {
400 	return sysfs_emit(buf, "%u\n", to_iio_dev_attr(attr)->c->scan_index);
401 }
402 
iio_show_fixed_type(struct device * dev,struct device_attribute * attr,char * buf)403 static ssize_t iio_show_fixed_type(struct device *dev,
404 				   struct device_attribute *attr,
405 				   char *buf)
406 {
407 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
408 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
409 	const struct iio_scan_type *scan_type;
410 	u8 type;
411 
412 	scan_type = iio_get_current_scan_type(indio_dev, this_attr->c);
413 	if (IS_ERR(scan_type))
414 		return PTR_ERR(scan_type);
415 
416 	type = scan_type->endianness;
417 
418 	if (type == IIO_CPU) {
419 #ifdef __LITTLE_ENDIAN
420 		type = IIO_LE;
421 #else
422 		type = IIO_BE;
423 #endif
424 	}
425 	if (scan_type->repeat > 1)
426 		return sysfs_emit(buf, "%s:%c%d/%dX%d>>%u\n",
427 		       iio_endian_prefix[type],
428 		       scan_type->sign,
429 		       scan_type->realbits,
430 		       scan_type->storagebits,
431 		       scan_type->repeat,
432 		       scan_type->shift);
433 	else
434 		return sysfs_emit(buf, "%s:%c%d/%d>>%u\n",
435 		       iio_endian_prefix[type],
436 		       scan_type->sign,
437 		       scan_type->realbits,
438 		       scan_type->storagebits,
439 		       scan_type->shift);
440 }
441 
iio_scan_el_show(struct device * dev,struct device_attribute * attr,char * buf)442 static ssize_t iio_scan_el_show(struct device *dev,
443 				struct device_attribute *attr,
444 				char *buf)
445 {
446 	int ret;
447 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
448 
449 	/* Ensure ret is 0 or 1. */
450 	ret = !!test_bit(to_iio_dev_attr(attr)->address,
451 		       buffer->scan_mask);
452 
453 	return sysfs_emit(buf, "%d\n", ret);
454 }
455 
456 /* Note NULL used as error indicator as it doesn't make sense. */
iio_scan_mask_match(const unsigned long * av_masks,unsigned int masklength,const unsigned long * mask,bool strict)457 static const unsigned long *iio_scan_mask_match(const unsigned long *av_masks,
458 						unsigned int masklength,
459 						const unsigned long *mask,
460 						bool strict)
461 {
462 	if (bitmap_empty(mask, masklength))
463 		return NULL;
464 	/*
465 	 * The condition here do not handle multi-long masks correctly.
466 	 * It only checks the first long to be zero, and will use such mask
467 	 * as a terminator even if there was bits set after the first long.
468 	 *
469 	 * Correct check would require using:
470 	 * while (!bitmap_empty(av_masks, masklength))
471 	 * instead. This is potentially hazardous because the
472 	 * avaliable_scan_masks is a zero terminated array of longs - and
473 	 * using the proper bitmap_empty() check for multi-long wide masks
474 	 * would require the array to be terminated with multiple zero longs -
475 	 * which is not such an usual pattern.
476 	 *
477 	 * As writing of this no multi-long wide masks were found in-tree, so
478 	 * the simple while (*av_masks) check is working.
479 	 */
480 	while (*av_masks) {
481 		if (strict) {
482 			if (bitmap_equal(mask, av_masks, masklength))
483 				return av_masks;
484 		} else {
485 			if (bitmap_subset(mask, av_masks, masklength))
486 				return av_masks;
487 		}
488 		av_masks += BITS_TO_LONGS(masklength);
489 	}
490 	return NULL;
491 }
492 
iio_validate_scan_mask(struct iio_dev * indio_dev,const unsigned long * mask)493 static bool iio_validate_scan_mask(struct iio_dev *indio_dev,
494 				   const unsigned long *mask)
495 {
496 	if (!indio_dev->setup_ops->validate_scan_mask)
497 		return true;
498 
499 	return indio_dev->setup_ops->validate_scan_mask(indio_dev, mask);
500 }
501 
502 /**
503  * iio_scan_mask_set() - set particular bit in the scan mask
504  * @indio_dev: the iio device
505  * @buffer: the buffer whose scan mask we are interested in
506  * @bit: the bit to be set.
507  *
508  * Note that at this point we have no way of knowing what other
509  * buffers might request, hence this code only verifies that the
510  * individual buffers request is plausible.
511  */
iio_scan_mask_set(struct iio_dev * indio_dev,struct iio_buffer * buffer,int bit)512 static int iio_scan_mask_set(struct iio_dev *indio_dev,
513 			     struct iio_buffer *buffer, int bit)
514 {
515 	unsigned int masklength = iio_get_masklength(indio_dev);
516 	const unsigned long *mask;
517 	unsigned long *trialmask;
518 
519 	if (!masklength) {
520 		WARN(1, "Trying to set scanmask prior to registering buffer\n");
521 		return -EINVAL;
522 	}
523 
524 	trialmask = bitmap_alloc(masklength, GFP_KERNEL);
525 	if (!trialmask)
526 		return -ENOMEM;
527 	bitmap_copy(trialmask, buffer->scan_mask, masklength);
528 	set_bit(bit, trialmask);
529 
530 	if (!iio_validate_scan_mask(indio_dev, trialmask))
531 		goto err_invalid_mask;
532 
533 	if (indio_dev->available_scan_masks) {
534 		mask = iio_scan_mask_match(indio_dev->available_scan_masks,
535 					   masklength, trialmask, false);
536 		if (!mask)
537 			goto err_invalid_mask;
538 	}
539 	bitmap_copy(buffer->scan_mask, trialmask, masklength);
540 
541 	bitmap_free(trialmask);
542 
543 	return 0;
544 
545 err_invalid_mask:
546 	bitmap_free(trialmask);
547 	return -EINVAL;
548 }
549 
iio_scan_mask_clear(struct iio_buffer * buffer,int bit)550 static int iio_scan_mask_clear(struct iio_buffer *buffer, int bit)
551 {
552 	clear_bit(bit, buffer->scan_mask);
553 	return 0;
554 }
555 
iio_scan_mask_query(struct iio_dev * indio_dev,struct iio_buffer * buffer,int bit)556 static int iio_scan_mask_query(struct iio_dev *indio_dev,
557 			       struct iio_buffer *buffer, int bit)
558 {
559 	if (bit > iio_get_masklength(indio_dev))
560 		return -EINVAL;
561 
562 	if (!buffer->scan_mask)
563 		return 0;
564 
565 	/* Ensure return value is 0 or 1. */
566 	return !!test_bit(bit, buffer->scan_mask);
567 };
568 
iio_scan_el_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)569 static ssize_t iio_scan_el_store(struct device *dev,
570 				 struct device_attribute *attr,
571 				 const char *buf,
572 				 size_t len)
573 {
574 	int ret;
575 	bool state;
576 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
577 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
578 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
579 	struct iio_buffer *buffer = this_attr->buffer;
580 
581 	ret = kstrtobool(buf, &state);
582 	if (ret < 0)
583 		return ret;
584 
585 	guard(mutex)(&iio_dev_opaque->mlock);
586 	if (iio_buffer_is_active(buffer))
587 		return -EBUSY;
588 
589 	ret = iio_scan_mask_query(indio_dev, buffer, this_attr->address);
590 	if (ret < 0)
591 		return ret;
592 
593 	if (state && ret)
594 		return len;
595 
596 	if (state)
597 		ret = iio_scan_mask_set(indio_dev, buffer, this_attr->address);
598 	else
599 		ret = iio_scan_mask_clear(buffer, this_attr->address);
600 	if (ret)
601 		return ret;
602 
603 	return len;
604 }
605 
iio_scan_el_ts_show(struct device * dev,struct device_attribute * attr,char * buf)606 static ssize_t iio_scan_el_ts_show(struct device *dev,
607 				   struct device_attribute *attr,
608 				   char *buf)
609 {
610 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
611 
612 	return sysfs_emit(buf, "%d\n", buffer->scan_timestamp);
613 }
614 
iio_scan_el_ts_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)615 static ssize_t iio_scan_el_ts_store(struct device *dev,
616 				    struct device_attribute *attr,
617 				    const char *buf,
618 				    size_t len)
619 {
620 	int ret;
621 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
622 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
623 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
624 	bool state;
625 
626 	ret = kstrtobool(buf, &state);
627 	if (ret < 0)
628 		return ret;
629 
630 	guard(mutex)(&iio_dev_opaque->mlock);
631 	if (iio_buffer_is_active(buffer))
632 		return -EBUSY;
633 
634 	buffer->scan_timestamp = state;
635 
636 	return len;
637 }
638 
iio_buffer_add_channel_sysfs(struct iio_dev * indio_dev,struct iio_buffer * buffer,const struct iio_chan_spec * chan)639 static int iio_buffer_add_channel_sysfs(struct iio_dev *indio_dev,
640 					struct iio_buffer *buffer,
641 					const struct iio_chan_spec *chan)
642 {
643 	int ret, attrcount = 0;
644 
645 	ret = __iio_add_chan_devattr("index",
646 				     chan,
647 				     &iio_show_scan_index,
648 				     NULL,
649 				     0,
650 				     IIO_SEPARATE,
651 				     &indio_dev->dev,
652 				     buffer,
653 				     &buffer->buffer_attr_list);
654 	if (ret)
655 		return ret;
656 	attrcount++;
657 	ret = __iio_add_chan_devattr("type",
658 				     chan,
659 				     &iio_show_fixed_type,
660 				     NULL,
661 				     0,
662 				     IIO_SEPARATE,
663 				     &indio_dev->dev,
664 				     buffer,
665 				     &buffer->buffer_attr_list);
666 	if (ret)
667 		return ret;
668 	attrcount++;
669 	if (chan->type != IIO_TIMESTAMP)
670 		ret = __iio_add_chan_devattr("en",
671 					     chan,
672 					     &iio_scan_el_show,
673 					     &iio_scan_el_store,
674 					     chan->scan_index,
675 					     IIO_SEPARATE,
676 					     &indio_dev->dev,
677 					     buffer,
678 					     &buffer->buffer_attr_list);
679 	else
680 		ret = __iio_add_chan_devattr("en",
681 					     chan,
682 					     &iio_scan_el_ts_show,
683 					     &iio_scan_el_ts_store,
684 					     chan->scan_index,
685 					     IIO_SEPARATE,
686 					     &indio_dev->dev,
687 					     buffer,
688 					     &buffer->buffer_attr_list);
689 	if (ret)
690 		return ret;
691 	attrcount++;
692 	ret = attrcount;
693 	return ret;
694 }
695 
length_show(struct device * dev,struct device_attribute * attr,char * buf)696 static ssize_t length_show(struct device *dev, struct device_attribute *attr,
697 			   char *buf)
698 {
699 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
700 
701 	return sysfs_emit(buf, "%d\n", buffer->length);
702 }
703 
length_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)704 static ssize_t length_store(struct device *dev, struct device_attribute *attr,
705 			    const char *buf, size_t len)
706 {
707 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
708 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
709 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
710 	unsigned int val;
711 	int ret;
712 
713 	ret = kstrtouint(buf, 10, &val);
714 	if (ret)
715 		return ret;
716 
717 	if (val == buffer->length)
718 		return len;
719 
720 	guard(mutex)(&iio_dev_opaque->mlock);
721 	if (iio_buffer_is_active(buffer))
722 		return -EBUSY;
723 
724 	buffer->access->set_length(buffer, val);
725 
726 	if (buffer->length && buffer->length < buffer->watermark)
727 		buffer->watermark = buffer->length;
728 
729 	return len;
730 }
731 
enable_show(struct device * dev,struct device_attribute * attr,char * buf)732 static ssize_t enable_show(struct device *dev, struct device_attribute *attr,
733 			   char *buf)
734 {
735 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
736 
737 	return sysfs_emit(buf, "%d\n", iio_buffer_is_active(buffer));
738 }
739 
iio_storage_bytes_for_si(struct iio_dev * indio_dev,unsigned int scan_index)740 static int iio_storage_bytes_for_si(struct iio_dev *indio_dev,
741 				    unsigned int scan_index)
742 {
743 	const struct iio_chan_spec *ch;
744 	const struct iio_scan_type *scan_type;
745 	unsigned int bytes;
746 
747 	ch = iio_find_channel_from_si(indio_dev, scan_index);
748 	scan_type = iio_get_current_scan_type(indio_dev, ch);
749 	if (IS_ERR(scan_type))
750 		return PTR_ERR(scan_type);
751 
752 	bytes = scan_type->storagebits / 8;
753 
754 	if (scan_type->repeat > 1)
755 		bytes *= roundup_pow_of_two(scan_type->repeat);
756 
757 	return bytes;
758 }
759 
iio_storage_bytes_for_timestamp(struct iio_dev * indio_dev)760 static int iio_storage_bytes_for_timestamp(struct iio_dev *indio_dev)
761 {
762 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
763 
764 	return iio_storage_bytes_for_si(indio_dev,
765 					iio_dev_opaque->scan_index_timestamp);
766 }
767 
iio_compute_scan_bytes(struct iio_dev * indio_dev,const unsigned long * mask,bool timestamp,unsigned int * scan_bytes,unsigned int * timestamp_offset)768 static int iio_compute_scan_bytes(struct iio_dev *indio_dev,
769 				  const unsigned long *mask, bool timestamp,
770 				  unsigned int *scan_bytes,
771 				  unsigned int *timestamp_offset)
772 {
773 	unsigned int bytes = 0;
774 	int length, i, largest = 0;
775 
776 	/* How much space will the demuxed element take? */
777 	for_each_set_bit(i, mask, iio_get_masklength(indio_dev)) {
778 		length = iio_storage_bytes_for_si(indio_dev, i);
779 		if (length < 0)
780 			return length;
781 
782 		bytes = ALIGN(bytes, length);
783 		bytes += length;
784 		largest = max(largest, length);
785 	}
786 
787 	if (timestamp) {
788 		length = iio_storage_bytes_for_timestamp(indio_dev);
789 		if (length < 0)
790 			return length;
791 
792 		bytes = ALIGN(bytes, length);
793 
794 		if (timestamp_offset)
795 			*timestamp_offset = bytes;
796 
797 		bytes += length;
798 		largest = max(largest, length);
799 	}
800 
801 	*scan_bytes = ALIGN(bytes, largest);
802 
803 	return 0;
804 }
805 
iio_buffer_activate(struct iio_dev * indio_dev,struct iio_buffer * buffer)806 static void iio_buffer_activate(struct iio_dev *indio_dev,
807 				struct iio_buffer *buffer)
808 {
809 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
810 
811 	iio_buffer_get(buffer);
812 	list_add(&buffer->buffer_list, &iio_dev_opaque->buffer_list);
813 }
814 
iio_buffer_deactivate(struct iio_buffer * buffer)815 static void iio_buffer_deactivate(struct iio_buffer *buffer)
816 {
817 	list_del_init(&buffer->buffer_list);
818 	wake_up_interruptible(&buffer->pollq);
819 	iio_buffer_put(buffer);
820 }
821 
iio_buffer_deactivate_all(struct iio_dev * indio_dev)822 static void iio_buffer_deactivate_all(struct iio_dev *indio_dev)
823 {
824 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
825 	struct iio_buffer *buffer, *_buffer;
826 
827 	list_for_each_entry_safe(buffer, _buffer,
828 				 &iio_dev_opaque->buffer_list, buffer_list)
829 		iio_buffer_deactivate(buffer);
830 }
831 
iio_buffer_enable(struct iio_buffer * buffer,struct iio_dev * indio_dev)832 static int iio_buffer_enable(struct iio_buffer *buffer,
833 			     struct iio_dev *indio_dev)
834 {
835 	if (!buffer->access->enable)
836 		return 0;
837 	return buffer->access->enable(buffer, indio_dev);
838 }
839 
iio_buffer_disable(struct iio_buffer * buffer,struct iio_dev * indio_dev)840 static int iio_buffer_disable(struct iio_buffer *buffer,
841 			      struct iio_dev *indio_dev)
842 {
843 	if (!buffer->access->disable)
844 		return 0;
845 	return buffer->access->disable(buffer, indio_dev);
846 }
847 
iio_buffer_update_bytes_per_datum(struct iio_dev * indio_dev,struct iio_buffer * buffer)848 static int iio_buffer_update_bytes_per_datum(struct iio_dev *indio_dev,
849 					     struct iio_buffer *buffer)
850 {
851 	unsigned int bytes;
852 	int ret;
853 
854 	if (!buffer->access->set_bytes_per_datum)
855 		return 0;
856 
857 	ret = iio_compute_scan_bytes(indio_dev, buffer->scan_mask,
858 				     buffer->scan_timestamp, &bytes, NULL);
859 	if (ret)
860 		return ret;
861 
862 	buffer->access->set_bytes_per_datum(buffer, bytes);
863 
864 	return 0;
865 }
866 
iio_buffer_request_update(struct iio_dev * indio_dev,struct iio_buffer * buffer)867 static int iio_buffer_request_update(struct iio_dev *indio_dev,
868 				     struct iio_buffer *buffer)
869 {
870 	int ret;
871 
872 	ret = iio_buffer_update_bytes_per_datum(indio_dev, buffer);
873 	if (ret)
874 		return ret;
875 
876 	if (buffer->access->request_update) {
877 		ret = buffer->access->request_update(buffer);
878 		if (ret) {
879 			dev_dbg(&indio_dev->dev,
880 				"Buffer not started: buffer parameter update failed (%d)\n",
881 				ret);
882 			return ret;
883 		}
884 	}
885 
886 	return 0;
887 }
888 
iio_free_scan_mask(struct iio_dev * indio_dev,const unsigned long * mask)889 static void iio_free_scan_mask(struct iio_dev *indio_dev,
890 			       const unsigned long *mask)
891 {
892 	/* If the mask is dynamically allocated free it, otherwise do nothing */
893 	if (!indio_dev->available_scan_masks)
894 		bitmap_free(mask);
895 }
896 
897 struct iio_device_config {
898 	unsigned int mode;
899 	unsigned int watermark;
900 	const unsigned long *scan_mask;
901 	unsigned int scan_bytes;
902 	unsigned int scan_timestamp_offset;
903 	bool scan_timestamp;
904 };
905 
iio_verify_update(struct iio_dev * indio_dev,struct iio_buffer * insert_buffer,struct iio_buffer * remove_buffer,struct iio_device_config * config)906 static int iio_verify_update(struct iio_dev *indio_dev,
907 			     struct iio_buffer *insert_buffer,
908 			     struct iio_buffer *remove_buffer,
909 			     struct iio_device_config *config)
910 {
911 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
912 	unsigned int masklength = iio_get_masklength(indio_dev);
913 	unsigned long *compound_mask;
914 	const unsigned long *scan_mask;
915 	bool strict_scanmask = false;
916 	struct iio_buffer *buffer;
917 	bool scan_timestamp;
918 	unsigned int modes;
919 	int ret;
920 
921 	if (insert_buffer &&
922 	    bitmap_empty(insert_buffer->scan_mask, masklength)) {
923 		dev_dbg(&indio_dev->dev,
924 			"At least one scan element must be enabled first\n");
925 		return -EINVAL;
926 	}
927 
928 	memset(config, 0, sizeof(*config));
929 	config->watermark = ~0;
930 
931 	/*
932 	 * If there is just one buffer and we are removing it there is nothing
933 	 * to verify.
934 	 */
935 	if (remove_buffer && !insert_buffer &&
936 	    list_is_singular(&iio_dev_opaque->buffer_list))
937 		return 0;
938 
939 	modes = indio_dev->modes;
940 
941 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list) {
942 		if (buffer == remove_buffer)
943 			continue;
944 		modes &= buffer->access->modes;
945 		config->watermark = min(config->watermark, buffer->watermark);
946 	}
947 
948 	if (insert_buffer) {
949 		modes &= insert_buffer->access->modes;
950 		config->watermark = min(config->watermark,
951 					insert_buffer->watermark);
952 	}
953 
954 	/* Definitely possible for devices to support both of these. */
955 	if ((modes & INDIO_BUFFER_TRIGGERED) && indio_dev->trig) {
956 		config->mode = INDIO_BUFFER_TRIGGERED;
957 	} else if (modes & INDIO_BUFFER_HARDWARE) {
958 		/*
959 		 * Keep things simple for now and only allow a single buffer to
960 		 * be connected in hardware mode.
961 		 */
962 		if (insert_buffer && !list_empty(&iio_dev_opaque->buffer_list))
963 			return -EINVAL;
964 		config->mode = INDIO_BUFFER_HARDWARE;
965 		strict_scanmask = true;
966 	} else if (modes & INDIO_BUFFER_SOFTWARE) {
967 		config->mode = INDIO_BUFFER_SOFTWARE;
968 	} else {
969 		/* Can only occur on first buffer */
970 		if (indio_dev->modes & INDIO_BUFFER_TRIGGERED)
971 			dev_dbg(&indio_dev->dev, "Buffer not started: no trigger\n");
972 		return -EINVAL;
973 	}
974 
975 	/* What scan mask do we actually have? */
976 	compound_mask = bitmap_zalloc(masklength, GFP_KERNEL);
977 	if (!compound_mask)
978 		return -ENOMEM;
979 
980 	scan_timestamp = false;
981 
982 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list) {
983 		if (buffer == remove_buffer)
984 			continue;
985 		bitmap_or(compound_mask, compound_mask, buffer->scan_mask,
986 			  masklength);
987 		scan_timestamp |= buffer->scan_timestamp;
988 	}
989 
990 	if (insert_buffer) {
991 		bitmap_or(compound_mask, compound_mask,
992 			  insert_buffer->scan_mask, masklength);
993 		scan_timestamp |= insert_buffer->scan_timestamp;
994 	}
995 
996 	if (indio_dev->available_scan_masks) {
997 		scan_mask = iio_scan_mask_match(indio_dev->available_scan_masks,
998 						masklength, compound_mask,
999 						strict_scanmask);
1000 		bitmap_free(compound_mask);
1001 		if (!scan_mask)
1002 			return -EINVAL;
1003 	} else {
1004 		scan_mask = compound_mask;
1005 	}
1006 
1007 	ret = iio_compute_scan_bytes(indio_dev, scan_mask, scan_timestamp,
1008 				     &config->scan_bytes,
1009 				     &config->scan_timestamp_offset);
1010 	if (ret)
1011 		return ret;
1012 
1013 	config->scan_mask = scan_mask;
1014 	config->scan_timestamp = scan_timestamp;
1015 
1016 	return 0;
1017 }
1018 
1019 /**
1020  * struct iio_demux_table - table describing demux memcpy ops
1021  * @from:	index to copy from
1022  * @to:		index to copy to
1023  * @length:	how many bytes to copy
1024  * @l:		list head used for management
1025  */
1026 struct iio_demux_table {
1027 	unsigned int from;
1028 	unsigned int to;
1029 	unsigned int length;
1030 	struct list_head l;
1031 };
1032 
iio_buffer_demux_free(struct iio_buffer * buffer)1033 static void iio_buffer_demux_free(struct iio_buffer *buffer)
1034 {
1035 	struct iio_demux_table *p, *q;
1036 
1037 	list_for_each_entry_safe(p, q, &buffer->demux_list, l) {
1038 		list_del(&p->l);
1039 		kfree(p);
1040 	}
1041 }
1042 
iio_buffer_add_demux(struct iio_buffer * buffer,struct iio_demux_table ** p,unsigned int in_loc,unsigned int out_loc,unsigned int length)1043 static int iio_buffer_add_demux(struct iio_buffer *buffer,
1044 				struct iio_demux_table **p, unsigned int in_loc,
1045 				unsigned int out_loc,
1046 				unsigned int length)
1047 {
1048 	if (*p && (*p)->from + (*p)->length == in_loc &&
1049 	    (*p)->to + (*p)->length == out_loc) {
1050 		(*p)->length += length;
1051 	} else {
1052 		*p = kmalloc_obj(**p);
1053 		if (!(*p))
1054 			return -ENOMEM;
1055 		(*p)->from = in_loc;
1056 		(*p)->to = out_loc;
1057 		(*p)->length = length;
1058 		list_add_tail(&(*p)->l, &buffer->demux_list);
1059 	}
1060 
1061 	return 0;
1062 }
1063 
iio_buffer_update_demux(struct iio_dev * indio_dev,struct iio_buffer * buffer)1064 static int iio_buffer_update_demux(struct iio_dev *indio_dev,
1065 				   struct iio_buffer *buffer)
1066 {
1067 	unsigned int masklength = iio_get_masklength(indio_dev);
1068 	int ret, in_ind = -1, out_ind, length;
1069 	unsigned int in_loc = 0, out_loc = 0;
1070 	struct iio_demux_table *p = NULL;
1071 
1072 	/* Clear out any old demux */
1073 	iio_buffer_demux_free(buffer);
1074 	kfree(buffer->demux_bounce);
1075 	buffer->demux_bounce = NULL;
1076 
1077 	/* First work out which scan mode we will actually have */
1078 	if (bitmap_equal(indio_dev->active_scan_mask,
1079 			 buffer->scan_mask, masklength))
1080 		return 0;
1081 
1082 	/* Now we have the two masks, work from least sig and build up sizes */
1083 	for_each_set_bit(out_ind, buffer->scan_mask, masklength) {
1084 		in_ind = find_next_bit(indio_dev->active_scan_mask,
1085 				       masklength, in_ind + 1);
1086 		while (in_ind != out_ind) {
1087 			ret = iio_storage_bytes_for_si(indio_dev, in_ind);
1088 			if (ret < 0)
1089 				goto error_clear_mux_table;
1090 
1091 			length = ret;
1092 			/* Make sure we are aligned */
1093 			in_loc = roundup(in_loc, length) + length;
1094 			in_ind = find_next_bit(indio_dev->active_scan_mask,
1095 					       masklength, in_ind + 1);
1096 		}
1097 		ret = iio_storage_bytes_for_si(indio_dev, in_ind);
1098 		if (ret < 0)
1099 			goto error_clear_mux_table;
1100 
1101 		length = ret;
1102 		out_loc = roundup(out_loc, length);
1103 		in_loc = roundup(in_loc, length);
1104 		ret = iio_buffer_add_demux(buffer, &p, in_loc, out_loc, length);
1105 		if (ret)
1106 			goto error_clear_mux_table;
1107 		out_loc += length;
1108 		in_loc += length;
1109 	}
1110 	/* Relies on scan_timestamp being last */
1111 	if (buffer->scan_timestamp) {
1112 		ret = iio_storage_bytes_for_timestamp(indio_dev);
1113 		if (ret < 0)
1114 			goto error_clear_mux_table;
1115 
1116 		length = ret;
1117 		out_loc = roundup(out_loc, length);
1118 		in_loc = roundup(in_loc, length);
1119 		ret = iio_buffer_add_demux(buffer, &p, in_loc, out_loc, length);
1120 		if (ret)
1121 			goto error_clear_mux_table;
1122 		out_loc += length;
1123 	}
1124 	buffer->demux_bounce = kzalloc(out_loc, GFP_KERNEL);
1125 	if (!buffer->demux_bounce) {
1126 		ret = -ENOMEM;
1127 		goto error_clear_mux_table;
1128 	}
1129 	return 0;
1130 
1131 error_clear_mux_table:
1132 	iio_buffer_demux_free(buffer);
1133 
1134 	return ret;
1135 }
1136 
iio_update_demux(struct iio_dev * indio_dev)1137 static int iio_update_demux(struct iio_dev *indio_dev)
1138 {
1139 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1140 	struct iio_buffer *buffer;
1141 	int ret;
1142 
1143 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list) {
1144 		ret = iio_buffer_update_demux(indio_dev, buffer);
1145 		if (ret < 0)
1146 			goto error_clear_mux_table;
1147 	}
1148 	return 0;
1149 
1150 error_clear_mux_table:
1151 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list)
1152 		iio_buffer_demux_free(buffer);
1153 
1154 	return ret;
1155 }
1156 
iio_enable_buffers(struct iio_dev * indio_dev,struct iio_device_config * config)1157 static int iio_enable_buffers(struct iio_dev *indio_dev,
1158 			      struct iio_device_config *config)
1159 {
1160 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1161 	struct iio_buffer *buffer, *tmp = NULL;
1162 	int ret;
1163 
1164 	indio_dev->active_scan_mask = config->scan_mask;
1165 	ACCESS_PRIVATE(indio_dev, scan_timestamp) = config->scan_timestamp;
1166 	indio_dev->scan_bytes = config->scan_bytes;
1167 	ACCESS_PRIVATE(indio_dev, scan_timestamp_offset) = config->scan_timestamp_offset;
1168 	iio_dev_opaque->currentmode = config->mode;
1169 
1170 	iio_update_demux(indio_dev);
1171 
1172 	/* Wind up again */
1173 	if (indio_dev->setup_ops->preenable) {
1174 		ret = indio_dev->setup_ops->preenable(indio_dev);
1175 		if (ret) {
1176 			dev_dbg(&indio_dev->dev,
1177 				"Buffer not started: buffer preenable failed (%d)\n", ret);
1178 			goto err_undo_config;
1179 		}
1180 	}
1181 
1182 	if (indio_dev->info->update_scan_mode) {
1183 		ret = indio_dev->info
1184 			->update_scan_mode(indio_dev,
1185 					   indio_dev->active_scan_mask);
1186 		if (ret < 0) {
1187 			dev_dbg(&indio_dev->dev,
1188 				"Buffer not started: update scan mode failed (%d)\n",
1189 				ret);
1190 			goto err_run_postdisable;
1191 		}
1192 	}
1193 
1194 	if (indio_dev->info->hwfifo_set_watermark)
1195 		indio_dev->info->hwfifo_set_watermark(indio_dev,
1196 			config->watermark);
1197 
1198 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list) {
1199 		ret = iio_buffer_enable(buffer, indio_dev);
1200 		if (ret) {
1201 			tmp = buffer;
1202 			goto err_disable_buffers;
1203 		}
1204 	}
1205 
1206 	if (iio_dev_opaque->currentmode == INDIO_BUFFER_TRIGGERED) {
1207 		ret = iio_trigger_attach_poll_func(indio_dev->trig,
1208 						   indio_dev->pollfunc);
1209 		if (ret)
1210 			goto err_disable_buffers;
1211 	}
1212 
1213 	if (indio_dev->setup_ops->postenable) {
1214 		ret = indio_dev->setup_ops->postenable(indio_dev);
1215 		if (ret) {
1216 			dev_dbg(&indio_dev->dev,
1217 				"Buffer not started: postenable failed (%d)\n", ret);
1218 			goto err_detach_pollfunc;
1219 		}
1220 	}
1221 
1222 	return 0;
1223 
1224 err_detach_pollfunc:
1225 	if (iio_dev_opaque->currentmode == INDIO_BUFFER_TRIGGERED) {
1226 		iio_trigger_detach_poll_func(indio_dev->trig,
1227 					     indio_dev->pollfunc);
1228 	}
1229 err_disable_buffers:
1230 	buffer = list_prepare_entry(tmp, &iio_dev_opaque->buffer_list, buffer_list);
1231 	list_for_each_entry_continue_reverse(buffer, &iio_dev_opaque->buffer_list,
1232 					     buffer_list)
1233 		iio_buffer_disable(buffer, indio_dev);
1234 err_run_postdisable:
1235 	if (indio_dev->setup_ops->postdisable)
1236 		indio_dev->setup_ops->postdisable(indio_dev);
1237 err_undo_config:
1238 	iio_dev_opaque->currentmode = INDIO_DIRECT_MODE;
1239 	indio_dev->active_scan_mask = NULL;
1240 
1241 	return ret;
1242 }
1243 
iio_disable_buffers(struct iio_dev * indio_dev)1244 static int iio_disable_buffers(struct iio_dev *indio_dev)
1245 {
1246 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1247 	struct iio_buffer *buffer;
1248 	int ret = 0;
1249 	int ret2;
1250 
1251 	/* Wind down existing buffers - iff there are any */
1252 	if (list_empty(&iio_dev_opaque->buffer_list))
1253 		return 0;
1254 
1255 	/*
1256 	 * If things go wrong at some step in disable we still need to continue
1257 	 * to perform the other steps, otherwise we leave the device in a
1258 	 * inconsistent state. We return the error code for the first error we
1259 	 * encountered.
1260 	 */
1261 
1262 	if (indio_dev->setup_ops->predisable) {
1263 		ret2 = indio_dev->setup_ops->predisable(indio_dev);
1264 		if (ret2 && !ret)
1265 			ret = ret2;
1266 	}
1267 
1268 	if (iio_dev_opaque->currentmode == INDIO_BUFFER_TRIGGERED) {
1269 		iio_trigger_detach_poll_func(indio_dev->trig,
1270 					     indio_dev->pollfunc);
1271 	}
1272 
1273 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list) {
1274 		ret2 = iio_buffer_disable(buffer, indio_dev);
1275 		if (ret2 && !ret)
1276 			ret = ret2;
1277 	}
1278 
1279 	if (indio_dev->setup_ops->postdisable) {
1280 		ret2 = indio_dev->setup_ops->postdisable(indio_dev);
1281 		if (ret2 && !ret)
1282 			ret = ret2;
1283 	}
1284 
1285 	iio_free_scan_mask(indio_dev, indio_dev->active_scan_mask);
1286 	indio_dev->active_scan_mask = NULL;
1287 	iio_dev_opaque->currentmode = INDIO_DIRECT_MODE;
1288 
1289 	return ret;
1290 }
1291 
__iio_update_buffers(struct iio_dev * indio_dev,struct iio_buffer * insert_buffer,struct iio_buffer * remove_buffer)1292 static int __iio_update_buffers(struct iio_dev *indio_dev,
1293 				struct iio_buffer *insert_buffer,
1294 				struct iio_buffer *remove_buffer)
1295 {
1296 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1297 	struct iio_device_config new_config;
1298 	int ret;
1299 
1300 	ret = iio_verify_update(indio_dev, insert_buffer, remove_buffer,
1301 				&new_config);
1302 	if (ret)
1303 		return ret;
1304 
1305 	if (insert_buffer) {
1306 		ret = iio_buffer_request_update(indio_dev, insert_buffer);
1307 		if (ret)
1308 			goto err_free_config;
1309 	}
1310 
1311 	ret = iio_disable_buffers(indio_dev);
1312 	if (ret)
1313 		goto err_deactivate_all;
1314 
1315 	if (remove_buffer)
1316 		iio_buffer_deactivate(remove_buffer);
1317 	if (insert_buffer)
1318 		iio_buffer_activate(indio_dev, insert_buffer);
1319 
1320 	/* If no buffers in list, we are done */
1321 	if (list_empty(&iio_dev_opaque->buffer_list))
1322 		return 0;
1323 
1324 	ret = iio_enable_buffers(indio_dev, &new_config);
1325 	if (ret)
1326 		goto err_deactivate_all;
1327 
1328 	return 0;
1329 
1330 err_deactivate_all:
1331 	/*
1332 	 * We've already verified that the config is valid earlier. If things go
1333 	 * wrong in either enable or disable the most likely reason is an IO
1334 	 * error from the device. In this case there is no good recovery
1335 	 * strategy. Just make sure to disable everything and leave the device
1336 	 * in a sane state.  With a bit of luck the device might come back to
1337 	 * life again later and userspace can try again.
1338 	 */
1339 	iio_buffer_deactivate_all(indio_dev);
1340 
1341 err_free_config:
1342 	iio_free_scan_mask(indio_dev, new_config.scan_mask);
1343 	return ret;
1344 }
1345 
iio_update_buffers(struct iio_dev * indio_dev,struct iio_buffer * insert_buffer,struct iio_buffer * remove_buffer)1346 int iio_update_buffers(struct iio_dev *indio_dev,
1347 		       struct iio_buffer *insert_buffer,
1348 		       struct iio_buffer *remove_buffer)
1349 {
1350 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1351 
1352 	if (insert_buffer == remove_buffer)
1353 		return 0;
1354 
1355 	if (insert_buffer &&
1356 	    insert_buffer->direction == IIO_BUFFER_DIRECTION_OUT)
1357 		return -EINVAL;
1358 
1359 	guard(mutex)(&iio_dev_opaque->info_exist_lock);
1360 	guard(mutex)(&iio_dev_opaque->mlock);
1361 
1362 	if (insert_buffer && iio_buffer_is_active(insert_buffer))
1363 		insert_buffer = NULL;
1364 
1365 	if (remove_buffer && !iio_buffer_is_active(remove_buffer))
1366 		remove_buffer = NULL;
1367 
1368 	if (!insert_buffer && !remove_buffer)
1369 		return 0;
1370 
1371 	if (!indio_dev->info)
1372 		return -ENODEV;
1373 
1374 	return __iio_update_buffers(indio_dev, insert_buffer, remove_buffer);
1375 }
1376 EXPORT_SYMBOL_GPL(iio_update_buffers);
1377 
iio_disable_all_buffers(struct iio_dev * indio_dev)1378 void iio_disable_all_buffers(struct iio_dev *indio_dev)
1379 {
1380 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1381 
1382 	guard(mutex)(&iio_dev_opaque->mlock);
1383 
1384 	iio_disable_buffers(indio_dev);
1385 	iio_buffer_deactivate_all(indio_dev);
1386 }
1387 
enable_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1388 static ssize_t enable_store(struct device *dev, struct device_attribute *attr,
1389 			    const char *buf, size_t len)
1390 {
1391 	int ret;
1392 	bool requested_state;
1393 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1394 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1395 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1396 	bool inlist;
1397 
1398 	ret = kstrtobool(buf, &requested_state);
1399 	if (ret < 0)
1400 		return ret;
1401 
1402 	guard(mutex)(&iio_dev_opaque->mlock);
1403 
1404 	/* Find out if it is in the list */
1405 	inlist = iio_buffer_is_active(buffer);
1406 	/* Already in desired state */
1407 	if (inlist == requested_state)
1408 		return len;
1409 
1410 	if (requested_state)
1411 		ret = __iio_update_buffers(indio_dev, buffer, NULL);
1412 	else
1413 		ret = __iio_update_buffers(indio_dev, NULL, buffer);
1414 	if (ret)
1415 		return ret;
1416 
1417 	return len;
1418 }
1419 
watermark_show(struct device * dev,struct device_attribute * attr,char * buf)1420 static ssize_t watermark_show(struct device *dev, struct device_attribute *attr,
1421 			      char *buf)
1422 {
1423 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1424 
1425 	return sysfs_emit(buf, "%u\n", buffer->watermark);
1426 }
1427 
watermark_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1428 static ssize_t watermark_store(struct device *dev,
1429 			       struct device_attribute *attr,
1430 			       const char *buf, size_t len)
1431 {
1432 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1433 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1434 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1435 	unsigned int val;
1436 	int ret;
1437 
1438 	ret = kstrtouint(buf, 10, &val);
1439 	if (ret)
1440 		return ret;
1441 	if (!val)
1442 		return -EINVAL;
1443 
1444 	guard(mutex)(&iio_dev_opaque->mlock);
1445 
1446 	if (val > buffer->length)
1447 		return -EINVAL;
1448 
1449 	if (iio_buffer_is_active(buffer))
1450 		return -EBUSY;
1451 
1452 	buffer->watermark = val;
1453 
1454 	return len;
1455 }
1456 
data_available_show(struct device * dev,struct device_attribute * attr,char * buf)1457 static ssize_t data_available_show(struct device *dev,
1458 				   struct device_attribute *attr, char *buf)
1459 {
1460 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1461 
1462 	return sysfs_emit(buf, "%zu\n", iio_buffer_data_available(buffer));
1463 }
1464 
direction_show(struct device * dev,struct device_attribute * attr,char * buf)1465 static ssize_t direction_show(struct device *dev,
1466 			      struct device_attribute *attr,
1467 			      char *buf)
1468 {
1469 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1470 
1471 	switch (buffer->direction) {
1472 	case IIO_BUFFER_DIRECTION_IN:
1473 		return sysfs_emit(buf, "in\n");
1474 	case IIO_BUFFER_DIRECTION_OUT:
1475 		return sysfs_emit(buf, "out\n");
1476 	default:
1477 		return -EINVAL;
1478 	}
1479 }
1480 
1481 static DEVICE_ATTR_RW(length);
1482 static struct device_attribute dev_attr_length_ro = __ATTR_RO(length);
1483 static DEVICE_ATTR_RW(enable);
1484 static DEVICE_ATTR_RW(watermark);
1485 static struct device_attribute dev_attr_watermark_ro = __ATTR_RO(watermark);
1486 static DEVICE_ATTR_RO(data_available);
1487 static DEVICE_ATTR_RO(direction);
1488 
1489 /*
1490  * When adding new attributes here, put the at the end, at least until
1491  * the code that handles the length/length_ro & watermark/watermark_ro
1492  * assignments gets cleaned up. Otherwise these can create some weird
1493  * duplicate attributes errors under some setups.
1494  */
1495 static struct attribute *iio_buffer_attrs[] = {
1496 	&dev_attr_length.attr,
1497 	&dev_attr_enable.attr,
1498 	&dev_attr_watermark.attr,
1499 	&dev_attr_data_available.attr,
1500 	&dev_attr_direction.attr,
1501 };
1502 
1503 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
1504 
iio_buffer_wrap_attr(struct iio_buffer * buffer,struct attribute * attr)1505 static struct attribute *iio_buffer_wrap_attr(struct iio_buffer *buffer,
1506 					      struct attribute *attr)
1507 {
1508 	struct device_attribute *dattr = to_dev_attr(attr);
1509 	struct iio_dev_attr *iio_attr;
1510 
1511 	iio_attr = kzalloc_obj(*iio_attr);
1512 	if (!iio_attr)
1513 		return NULL;
1514 
1515 	iio_attr->buffer = buffer;
1516 	memcpy(&iio_attr->dev_attr, dattr, sizeof(iio_attr->dev_attr));
1517 	iio_attr->dev_attr.attr.name = kstrdup_const(attr->name, GFP_KERNEL);
1518 	if (!iio_attr->dev_attr.attr.name) {
1519 		kfree(iio_attr);
1520 		return NULL;
1521 	}
1522 
1523 	sysfs_attr_init(&iio_attr->dev_attr.attr);
1524 
1525 	list_add(&iio_attr->l, &buffer->buffer_attr_list);
1526 
1527 	return &iio_attr->dev_attr.attr;
1528 }
1529 
iio_buffer_register_legacy_sysfs_groups(struct iio_dev * indio_dev,struct attribute ** buffer_attrs,int buffer_attrcount,int scan_el_attrcount)1530 static int iio_buffer_register_legacy_sysfs_groups(struct iio_dev *indio_dev,
1531 						   struct attribute **buffer_attrs,
1532 						   int buffer_attrcount,
1533 						   int scan_el_attrcount)
1534 {
1535 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1536 	struct attribute_group *group;
1537 	struct attribute **attrs;
1538 	int ret;
1539 
1540 	attrs = kzalloc_objs(*attrs, buffer_attrcount + 1);
1541 	if (!attrs)
1542 		return -ENOMEM;
1543 
1544 	memcpy(attrs, buffer_attrs, buffer_attrcount * sizeof(*attrs));
1545 
1546 	group = &iio_dev_opaque->legacy_buffer_group;
1547 	group->attrs = attrs;
1548 	group->name = "buffer";
1549 
1550 	ret = iio_device_register_sysfs_group(indio_dev, group);
1551 	if (ret)
1552 		goto error_free_buffer_attrs;
1553 
1554 	attrs = kzalloc_objs(*attrs, scan_el_attrcount + 1);
1555 	if (!attrs) {
1556 		ret = -ENOMEM;
1557 		goto error_free_buffer_attrs;
1558 	}
1559 
1560 	memcpy(attrs, &buffer_attrs[buffer_attrcount],
1561 	       scan_el_attrcount * sizeof(*attrs));
1562 
1563 	group = &iio_dev_opaque->legacy_scan_el_group;
1564 	group->attrs = attrs;
1565 	group->name = "scan_elements";
1566 
1567 	ret = iio_device_register_sysfs_group(indio_dev, group);
1568 	if (ret)
1569 		goto error_free_scan_el_attrs;
1570 
1571 	return 0;
1572 
1573 error_free_scan_el_attrs:
1574 	kfree(iio_dev_opaque->legacy_scan_el_group.attrs);
1575 error_free_buffer_attrs:
1576 	kfree(iio_dev_opaque->legacy_buffer_group.attrs);
1577 
1578 	return ret;
1579 }
1580 
iio_buffer_unregister_legacy_sysfs_groups(struct iio_dev * indio_dev)1581 static void iio_buffer_unregister_legacy_sysfs_groups(struct iio_dev *indio_dev)
1582 {
1583 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1584 
1585 	kfree(iio_dev_opaque->legacy_buffer_group.attrs);
1586 	kfree(iio_dev_opaque->legacy_scan_el_group.attrs);
1587 }
1588 
iio_buffer_dmabuf_release(struct kref * ref)1589 static void iio_buffer_dmabuf_release(struct kref *ref)
1590 {
1591 	struct iio_dmabuf_priv *priv = container_of(ref, struct iio_dmabuf_priv, ref);
1592 	struct dma_buf_attachment *attach = priv->attach;
1593 	struct iio_buffer *buffer = priv->buffer;
1594 	struct dma_buf *dmabuf = attach->dmabuf;
1595 
1596 	dma_buf_unmap_attachment_unlocked(attach, priv->sgt, priv->dir);
1597 
1598 	buffer->access->detach_dmabuf(buffer, priv->block);
1599 
1600 	dma_buf_detach(attach->dmabuf, attach);
1601 	dma_buf_put(dmabuf);
1602 	kfree(priv);
1603 }
1604 
iio_buffer_dmabuf_get(struct dma_buf_attachment * attach)1605 static void iio_buffer_dmabuf_get(struct dma_buf_attachment *attach)
1606 {
1607 	struct iio_dmabuf_priv *priv = attach->importer_priv;
1608 
1609 	kref_get(&priv->ref);
1610 }
1611 
iio_buffer_dmabuf_put(struct dma_buf_attachment * attach)1612 static void iio_buffer_dmabuf_put(struct dma_buf_attachment *attach)
1613 {
1614 	struct iio_dmabuf_priv *priv = attach->importer_priv;
1615 
1616 	kref_put(&priv->ref, iio_buffer_dmabuf_release);
1617 }
1618 
iio_buffer_chrdev_release(struct inode * inode,struct file * filep)1619 static int iio_buffer_chrdev_release(struct inode *inode, struct file *filep)
1620 {
1621 	struct iio_dev_buffer_pair *ib = filep->private_data;
1622 	struct iio_dev *indio_dev = ib->indio_dev;
1623 	struct iio_buffer *buffer = ib->buffer;
1624 	struct iio_dmabuf_priv *priv, *tmp;
1625 
1626 	wake_up(&buffer->pollq);
1627 
1628 	/*
1629 	 * The mutex must be unlocked before iio_device_put(), which might drop the
1630 	 * last reference and free the buffer.
1631 	 */
1632 	scoped_guard(mutex, &buffer->dmabufs_mutex) {
1633 		/* Close all attached DMABUFs */
1634 		list_for_each_entry_safe(priv, tmp, &buffer->dmabufs, entry) {
1635 			list_del_init(&priv->entry);
1636 			iio_buffer_dmabuf_put(priv->attach);
1637 		}
1638 	}
1639 
1640 	kfree(ib);
1641 	clear_bit(IIO_BUSY_BIT_POS, &buffer->flags);
1642 	iio_device_put(indio_dev);
1643 
1644 	return 0;
1645 }
1646 
iio_dma_resv_lock(struct dma_buf * dmabuf,bool nonblock)1647 static int iio_dma_resv_lock(struct dma_buf *dmabuf, bool nonblock)
1648 {
1649 	if (!nonblock)
1650 		return dma_resv_lock_interruptible(dmabuf->resv, NULL);
1651 
1652 	if (!dma_resv_trylock(dmabuf->resv))
1653 		return -EBUSY;
1654 
1655 	return 0;
1656 }
1657 
iio_buffer_get_dma_dev(const struct iio_dev * indio_dev,struct iio_buffer * buffer)1658 static struct device *iio_buffer_get_dma_dev(const struct iio_dev *indio_dev,
1659 					     struct iio_buffer *buffer)
1660 {
1661 	if (buffer->access->get_dma_dev)
1662 		return buffer->access->get_dma_dev(buffer);
1663 
1664 	return indio_dev->dev.parent;
1665 }
1666 
1667 static struct dma_buf_attachment *
iio_buffer_find_attachment(struct iio_dev_buffer_pair * ib,struct dma_buf * dmabuf,bool nonblock)1668 iio_buffer_find_attachment(struct iio_dev_buffer_pair *ib,
1669 			   struct dma_buf *dmabuf, bool nonblock)
1670 {
1671 	struct iio_buffer *buffer = ib->buffer;
1672 	struct device *dma_dev = iio_buffer_get_dma_dev(ib->indio_dev, buffer);
1673 	struct dma_buf_attachment *attach = NULL;
1674 	struct iio_dmabuf_priv *priv;
1675 
1676 	guard(mutex)(&buffer->dmabufs_mutex);
1677 
1678 	list_for_each_entry(priv, &buffer->dmabufs, entry) {
1679 		if (priv->attach->dev == dma_dev
1680 		    && priv->attach->dmabuf == dmabuf) {
1681 			attach = priv->attach;
1682 			break;
1683 		}
1684 	}
1685 
1686 	if (attach)
1687 		iio_buffer_dmabuf_get(attach);
1688 
1689 	return attach ?: ERR_PTR(-EPERM);
1690 }
1691 
iio_buffer_attach_dmabuf(struct iio_dev_buffer_pair * ib,int __user * user_fd,bool nonblock)1692 static int iio_buffer_attach_dmabuf(struct iio_dev_buffer_pair *ib,
1693 				    int __user *user_fd, bool nonblock)
1694 {
1695 	struct iio_dev *indio_dev = ib->indio_dev;
1696 	struct iio_buffer *buffer = ib->buffer;
1697 	struct device *dma_dev = iio_buffer_get_dma_dev(indio_dev, buffer);
1698 	struct dma_buf_attachment *attach;
1699 	struct iio_dmabuf_priv *priv, *each;
1700 	struct dma_buf *dmabuf;
1701 	int err, fd;
1702 
1703 	if (!buffer->access->attach_dmabuf
1704 	    || !buffer->access->detach_dmabuf
1705 	    || !buffer->access->enqueue_dmabuf)
1706 		return -EPERM;
1707 
1708 	if (copy_from_user(&fd, user_fd, sizeof(fd)))
1709 		return -EFAULT;
1710 
1711 	priv = kzalloc_obj(*priv);
1712 	if (!priv)
1713 		return -ENOMEM;
1714 
1715 	priv->context = dma_fence_context_alloc(1);
1716 
1717 	dmabuf = dma_buf_get(fd);
1718 	if (IS_ERR(dmabuf)) {
1719 		err = PTR_ERR(dmabuf);
1720 		goto err_free_priv;
1721 	}
1722 
1723 	attach = dma_buf_attach(dmabuf, dma_dev);
1724 	if (IS_ERR(attach)) {
1725 		err = PTR_ERR(attach);
1726 		goto err_dmabuf_put;
1727 	}
1728 
1729 	err = iio_dma_resv_lock(dmabuf, nonblock);
1730 	if (err)
1731 		goto err_dmabuf_detach;
1732 
1733 	priv->dir = buffer->direction == IIO_BUFFER_DIRECTION_IN
1734 		? DMA_FROM_DEVICE : DMA_TO_DEVICE;
1735 
1736 	priv->sgt = dma_buf_map_attachment(attach, priv->dir);
1737 	if (IS_ERR(priv->sgt)) {
1738 		err = PTR_ERR(priv->sgt);
1739 		dev_err(&indio_dev->dev, "Unable to map attachment: %d\n", err);
1740 		goto err_resv_unlock;
1741 	}
1742 
1743 	kref_init(&priv->ref);
1744 	priv->buffer = buffer;
1745 	priv->attach = attach;
1746 	attach->importer_priv = priv;
1747 
1748 	priv->block = buffer->access->attach_dmabuf(buffer, attach);
1749 	if (IS_ERR(priv->block)) {
1750 		err = PTR_ERR(priv->block);
1751 		goto err_dmabuf_unmap_attachment;
1752 	}
1753 
1754 	dma_resv_unlock(dmabuf->resv);
1755 
1756 	mutex_lock(&buffer->dmabufs_mutex);
1757 
1758 	/*
1759 	 * Check whether we already have an attachment for this driver/DMABUF
1760 	 * combo. If we do, refuse to attach.
1761 	 */
1762 	list_for_each_entry(each, &buffer->dmabufs, entry) {
1763 		if (each->attach->dev == dma_dev
1764 		    && each->attach->dmabuf == dmabuf) {
1765 			/*
1766 			 * We unlocked the reservation object, so going through
1767 			 * the cleanup code would mean re-locking it first.
1768 			 * At this stage it is simpler to free the attachment
1769 			 * using iio_buffer_dma_put().
1770 			 */
1771 			mutex_unlock(&buffer->dmabufs_mutex);
1772 			iio_buffer_dmabuf_put(attach);
1773 			return -EBUSY;
1774 		}
1775 	}
1776 
1777 	/* Otherwise, add the new attachment to our dmabufs list. */
1778 	list_add(&priv->entry, &buffer->dmabufs);
1779 	mutex_unlock(&buffer->dmabufs_mutex);
1780 
1781 	return 0;
1782 
1783 err_dmabuf_unmap_attachment:
1784 	dma_buf_unmap_attachment(attach, priv->sgt, priv->dir);
1785 err_resv_unlock:
1786 	dma_resv_unlock(dmabuf->resv);
1787 err_dmabuf_detach:
1788 	dma_buf_detach(dmabuf, attach);
1789 err_dmabuf_put:
1790 	dma_buf_put(dmabuf);
1791 err_free_priv:
1792 	kfree(priv);
1793 
1794 	return err;
1795 }
1796 
iio_buffer_detach_dmabuf(struct iio_dev_buffer_pair * ib,int __user * user_req,bool nonblock)1797 static int iio_buffer_detach_dmabuf(struct iio_dev_buffer_pair *ib,
1798 				    int __user *user_req, bool nonblock)
1799 {
1800 	struct iio_buffer *buffer = ib->buffer;
1801 	struct iio_dev *indio_dev = ib->indio_dev;
1802 	struct device *dma_dev = iio_buffer_get_dma_dev(indio_dev, buffer);
1803 	struct iio_dmabuf_priv *priv;
1804 	struct dma_buf *dmabuf;
1805 	int dmabuf_fd, ret = -EPERM;
1806 
1807 	if (copy_from_user(&dmabuf_fd, user_req, sizeof(dmabuf_fd)))
1808 		return -EFAULT;
1809 
1810 	dmabuf = dma_buf_get(dmabuf_fd);
1811 	if (IS_ERR(dmabuf))
1812 		return PTR_ERR(dmabuf);
1813 
1814 	guard(mutex)(&buffer->dmabufs_mutex);
1815 
1816 	list_for_each_entry(priv, &buffer->dmabufs, entry) {
1817 		if (priv->attach->dev == dma_dev
1818 		    && priv->attach->dmabuf == dmabuf) {
1819 			list_del(&priv->entry);
1820 
1821 			/* Unref the reference from iio_buffer_attach_dmabuf() */
1822 			iio_buffer_dmabuf_put(priv->attach);
1823 			ret = 0;
1824 			break;
1825 		}
1826 	}
1827 
1828 	dma_buf_put(dmabuf);
1829 
1830 	return ret;
1831 }
1832 
1833 static const char *
iio_buffer_dma_fence_get_driver_name(struct dma_fence * fence)1834 iio_buffer_dma_fence_get_driver_name(struct dma_fence *fence)
1835 {
1836 	return "iio";
1837 }
1838 
1839 static const struct dma_fence_ops iio_buffer_dma_fence_ops = {
1840 	.get_driver_name	= iio_buffer_dma_fence_get_driver_name,
1841 	.get_timeline_name	= iio_buffer_dma_fence_get_driver_name,
1842 };
1843 
iio_buffer_enqueue_dmabuf(struct iio_dev_buffer_pair * ib,struct iio_dmabuf __user * iio_dmabuf_req,bool nonblock)1844 static int iio_buffer_enqueue_dmabuf(struct iio_dev_buffer_pair *ib,
1845 				     struct iio_dmabuf __user *iio_dmabuf_req,
1846 				     bool nonblock)
1847 {
1848 	struct iio_buffer *buffer = ib->buffer;
1849 	struct iio_dmabuf iio_dmabuf;
1850 	struct dma_buf_attachment *attach;
1851 	struct iio_dmabuf_priv *priv;
1852 	struct iio_dma_fence *fence;
1853 	struct dma_buf *dmabuf;
1854 	unsigned long timeout;
1855 	bool cookie, cyclic, dma_to_ram;
1856 	long retl;
1857 	u32 seqno;
1858 	int ret;
1859 
1860 	if (copy_from_user(&iio_dmabuf, iio_dmabuf_req, sizeof(iio_dmabuf)))
1861 		return -EFAULT;
1862 
1863 	if (iio_dmabuf.flags & ~IIO_BUFFER_DMABUF_SUPPORTED_FLAGS)
1864 		return -EINVAL;
1865 
1866 	cyclic = iio_dmabuf.flags & IIO_BUFFER_DMABUF_CYCLIC;
1867 
1868 	/* Cyclic flag is only supported on output buffers */
1869 	if (cyclic && buffer->direction != IIO_BUFFER_DIRECTION_OUT)
1870 		return -EINVAL;
1871 
1872 	dmabuf = dma_buf_get(iio_dmabuf.fd);
1873 	if (IS_ERR(dmabuf))
1874 		return PTR_ERR(dmabuf);
1875 
1876 	if (!iio_dmabuf.bytes_used || iio_dmabuf.bytes_used > dmabuf->size) {
1877 		ret = -EINVAL;
1878 		goto err_dmabuf_put;
1879 	}
1880 
1881 	attach = iio_buffer_find_attachment(ib, dmabuf, nonblock);
1882 	if (IS_ERR(attach)) {
1883 		ret = PTR_ERR(attach);
1884 		goto err_dmabuf_put;
1885 	}
1886 
1887 	priv = attach->importer_priv;
1888 
1889 	fence = kmalloc_obj(*fence);
1890 	if (!fence) {
1891 		ret = -ENOMEM;
1892 		goto err_attachment_put;
1893 	}
1894 
1895 	spin_lock_init(&fence->lock);
1896 
1897 	fence->priv = priv;
1898 
1899 	seqno = atomic_add_return(1, &priv->seqno);
1900 
1901 	/*
1902 	 * The transfers are guaranteed to be processed in the order they are
1903 	 * enqueued, so we can use a simple incrementing sequence number for
1904 	 * the dma_fence.
1905 	 */
1906 	dma_fence_init(&fence->base, &iio_buffer_dma_fence_ops,
1907 		       &fence->lock, priv->context, seqno);
1908 
1909 	ret = iio_dma_resv_lock(dmabuf, nonblock);
1910 	if (ret)
1911 		goto err_fence_put;
1912 
1913 	timeout = nonblock ? 0 : msecs_to_jiffies(DMABUF_ENQUEUE_TIMEOUT_MS);
1914 	dma_to_ram = buffer->direction == IIO_BUFFER_DIRECTION_IN;
1915 
1916 	/* Make sure we don't have writers */
1917 	retl = dma_resv_wait_timeout(dmabuf->resv,
1918 				     dma_resv_usage_rw(dma_to_ram),
1919 				     true, timeout);
1920 	if (retl == 0)
1921 		retl = -EBUSY;
1922 	if (retl < 0) {
1923 		ret = (int)retl;
1924 		goto err_resv_unlock;
1925 	}
1926 
1927 	if (buffer->access->lock_queue)
1928 		buffer->access->lock_queue(buffer);
1929 
1930 	ret = dma_resv_reserve_fences(dmabuf->resv, 1);
1931 	if (ret)
1932 		goto err_queue_unlock;
1933 
1934 	dma_resv_add_fence(dmabuf->resv, &fence->base,
1935 			   dma_to_ram ? DMA_RESV_USAGE_WRITE : DMA_RESV_USAGE_READ);
1936 	dma_fence_put(&fence->base);
1937 	dma_resv_unlock(dmabuf->resv);
1938 
1939 	cookie = dma_fence_begin_signalling();
1940 
1941 	ret = buffer->access->enqueue_dmabuf(buffer, priv->block, &fence->base,
1942 					     priv->sgt, iio_dmabuf.bytes_used,
1943 					     cyclic);
1944 	if (ret) {
1945 		/*
1946 		 * DMABUF enqueue failed, but we already added the fence.
1947 		 * Signal the error through the fence completion mechanism.
1948 		 */
1949 		iio_buffer_signal_dmabuf_done(&fence->base, ret);
1950 	}
1951 
1952 	if (buffer->access->unlock_queue)
1953 		buffer->access->unlock_queue(buffer);
1954 
1955 	dma_fence_end_signalling(cookie);
1956 	dma_buf_put(dmabuf);
1957 
1958 	return ret;
1959 
1960 err_queue_unlock:
1961 	if (buffer->access->unlock_queue)
1962 		buffer->access->unlock_queue(buffer);
1963 err_resv_unlock:
1964 	dma_resv_unlock(dmabuf->resv);
1965 err_fence_put:
1966 	dma_fence_put(&fence->base);
1967 err_attachment_put:
1968 	iio_buffer_dmabuf_put(attach);
1969 err_dmabuf_put:
1970 	dma_buf_put(dmabuf);
1971 
1972 	return ret;
1973 }
1974 
iio_buffer_cleanup(struct work_struct * work)1975 static void iio_buffer_cleanup(struct work_struct *work)
1976 {
1977 	struct iio_dma_fence *fence =
1978 		container_of(work, struct iio_dma_fence, work);
1979 	struct iio_dmabuf_priv *priv = fence->priv;
1980 	struct dma_buf_attachment *attach = priv->attach;
1981 
1982 	dma_fence_put(&fence->base);
1983 	iio_buffer_dmabuf_put(attach);
1984 }
1985 
iio_buffer_signal_dmabuf_done(struct dma_fence * fence,int ret)1986 void iio_buffer_signal_dmabuf_done(struct dma_fence *fence, int ret)
1987 {
1988 	struct iio_dma_fence *iio_fence =
1989 		container_of(fence, struct iio_dma_fence, base);
1990 	bool cookie = dma_fence_begin_signalling();
1991 
1992 	/*
1993 	 * Get a reference to the fence, so that it's not freed as soon as
1994 	 * it's signaled.
1995 	 */
1996 	dma_fence_get(fence);
1997 
1998 	fence->error = ret;
1999 	dma_fence_signal(fence);
2000 	dma_fence_end_signalling(cookie);
2001 
2002 	/*
2003 	 * The fence will be unref'd in iio_buffer_cleanup.
2004 	 * It can't be done here, as the unref functions might try to lock the
2005 	 * resv object, which can deadlock.
2006 	 */
2007 	INIT_WORK(&iio_fence->work, iio_buffer_cleanup);
2008 	schedule_work(&iio_fence->work);
2009 }
2010 EXPORT_SYMBOL_GPL(iio_buffer_signal_dmabuf_done);
2011 
iio_buffer_chrdev_ioctl(struct file * filp,unsigned int cmd,unsigned long arg)2012 static long iio_buffer_chrdev_ioctl(struct file *filp,
2013 				    unsigned int cmd, unsigned long arg)
2014 {
2015 	struct iio_dev_buffer_pair *ib = filp->private_data;
2016 	void __user *_arg = (void __user *)arg;
2017 	bool nonblock = filp->f_flags & O_NONBLOCK;
2018 
2019 	switch (cmd) {
2020 	case IIO_BUFFER_DMABUF_ATTACH_IOCTL:
2021 		return iio_buffer_attach_dmabuf(ib, _arg, nonblock);
2022 	case IIO_BUFFER_DMABUF_DETACH_IOCTL:
2023 		return iio_buffer_detach_dmabuf(ib, _arg, nonblock);
2024 	case IIO_BUFFER_DMABUF_ENQUEUE_IOCTL:
2025 		return iio_buffer_enqueue_dmabuf(ib, _arg, nonblock);
2026 	default:
2027 		return -EINVAL;
2028 	}
2029 }
2030 
2031 static const struct file_operations iio_buffer_chrdev_fileops = {
2032 	.owner = THIS_MODULE,
2033 	.llseek = noop_llseek,
2034 	.read = iio_buffer_read,
2035 	.write = iio_buffer_write,
2036 	.unlocked_ioctl = iio_buffer_chrdev_ioctl,
2037 	.compat_ioctl = compat_ptr_ioctl,
2038 	.poll = iio_buffer_poll,
2039 	.release = iio_buffer_chrdev_release,
2040 };
2041 
iio_device_buffer_getfd(struct iio_dev * indio_dev,unsigned long arg)2042 static long iio_device_buffer_getfd(struct iio_dev *indio_dev, unsigned long arg)
2043 {
2044 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2045 	int __user *ival = (int __user *)arg;
2046 	struct iio_dev_buffer_pair *ib;
2047 	struct iio_buffer *buffer;
2048 	int fd, idx, ret;
2049 
2050 	if (copy_from_user(&idx, ival, sizeof(idx)))
2051 		return -EFAULT;
2052 
2053 	if (idx >= iio_dev_opaque->attached_buffers_cnt)
2054 		return -ENODEV;
2055 
2056 	iio_device_get(indio_dev);
2057 
2058 	buffer = iio_dev_opaque->attached_buffers[idx];
2059 
2060 	if (test_and_set_bit(IIO_BUSY_BIT_POS, &buffer->flags)) {
2061 		ret = -EBUSY;
2062 		goto error_iio_dev_put;
2063 	}
2064 
2065 	ib = kzalloc_obj(*ib);
2066 	if (!ib) {
2067 		ret = -ENOMEM;
2068 		goto error_clear_busy_bit;
2069 	}
2070 
2071 	ib->indio_dev = indio_dev;
2072 	ib->buffer = buffer;
2073 
2074 	fd = anon_inode_getfd("iio:buffer", &iio_buffer_chrdev_fileops,
2075 			      ib, O_RDWR | O_CLOEXEC);
2076 	if (fd < 0) {
2077 		ret = fd;
2078 		goto error_free_ib;
2079 	}
2080 
2081 	if (copy_to_user(ival, &fd, sizeof(fd))) {
2082 		/*
2083 		 * "Leak" the fd, as there's not much we can do about this
2084 		 * anyway. 'fd' might have been closed already, as
2085 		 * anon_inode_getfd() called fd_install() on it, which made
2086 		 * it reachable by userland.
2087 		 *
2088 		 * Instead of allowing a malicious user to play tricks with
2089 		 * us, rely on the process exit path to do any necessary
2090 		 * cleanup, as in releasing the file, if still needed.
2091 		 */
2092 		return -EFAULT;
2093 	}
2094 
2095 	return 0;
2096 
2097 error_free_ib:
2098 	kfree(ib);
2099 error_clear_busy_bit:
2100 	clear_bit(IIO_BUSY_BIT_POS, &buffer->flags);
2101 error_iio_dev_put:
2102 	iio_device_put(indio_dev);
2103 	return ret;
2104 }
2105 
iio_device_buffer_ioctl(struct iio_dev * indio_dev,struct file * filp,unsigned int cmd,unsigned long arg)2106 static long iio_device_buffer_ioctl(struct iio_dev *indio_dev, struct file *filp,
2107 				    unsigned int cmd, unsigned long arg)
2108 {
2109 	switch (cmd) {
2110 	case IIO_BUFFER_GET_FD_IOCTL:
2111 		return iio_device_buffer_getfd(indio_dev, arg);
2112 	default:
2113 		return IIO_IOCTL_UNHANDLED;
2114 	}
2115 }
2116 
iio_channel_validate_scan_type(struct device * dev,int ch,const struct iio_scan_type * scan_type)2117 static int iio_channel_validate_scan_type(struct device *dev, int ch,
2118 					  const struct iio_scan_type *scan_type)
2119 {
2120 	/* Verify that sample bits fit into storage */
2121 	if (scan_type->storagebits < scan_type->realbits + scan_type->shift) {
2122 		dev_err(dev,
2123 			"Channel %d storagebits (%d) < shifted realbits (%d + %d)\n",
2124 			ch, scan_type->storagebits,
2125 			scan_type->realbits,
2126 			scan_type->shift);
2127 		return -EINVAL;
2128 	}
2129 
2130 	return 0;
2131 }
2132 
__iio_buffer_alloc_sysfs_and_mask(struct iio_buffer * buffer,struct iio_dev * indio_dev,int index)2133 static int __iio_buffer_alloc_sysfs_and_mask(struct iio_buffer *buffer,
2134 					     struct iio_dev *indio_dev,
2135 					     int index)
2136 {
2137 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2138 	unsigned int masklength = iio_get_masklength(indio_dev);
2139 	struct iio_dev_attr *p;
2140 	const struct iio_dev_attr *id_attr;
2141 	struct attribute **attr;
2142 	int ret, i, attrn, scan_el_attrcount, buffer_attrcount;
2143 	const struct iio_chan_spec *channels;
2144 
2145 	buffer_attrcount = 0;
2146 	if (buffer->attrs) {
2147 		while (buffer->attrs[buffer_attrcount])
2148 			buffer_attrcount++;
2149 	}
2150 	buffer_attrcount += ARRAY_SIZE(iio_buffer_attrs);
2151 
2152 	scan_el_attrcount = 0;
2153 	INIT_LIST_HEAD(&buffer->buffer_attr_list);
2154 	channels = indio_dev->channels;
2155 	if (channels) {
2156 		/* new magic */
2157 		for (i = 0; i < indio_dev->num_channels; i++) {
2158 			const struct iio_scan_type *scan_type;
2159 
2160 			if (channels[i].scan_index < 0)
2161 				continue;
2162 
2163 			if (channels[i].has_ext_scan_type) {
2164 				int j;
2165 
2166 				/*
2167 				 * get_current_scan_type is required when using
2168 				 * extended scan types.
2169 				 */
2170 				if (!indio_dev->info->get_current_scan_type) {
2171 					ret = -EINVAL;
2172 					goto error_cleanup_dynamic;
2173 				}
2174 
2175 				for (j = 0; j < channels[i].num_ext_scan_type; j++) {
2176 					scan_type = &channels[i].ext_scan_type[j];
2177 
2178 					ret = iio_channel_validate_scan_type(
2179 						&indio_dev->dev, i, scan_type);
2180 					if (ret)
2181 						goto error_cleanup_dynamic;
2182 				}
2183 			} else {
2184 				scan_type = &channels[i].scan_type;
2185 
2186 				ret = iio_channel_validate_scan_type(
2187 						&indio_dev->dev, i, scan_type);
2188 				if (ret)
2189 					goto error_cleanup_dynamic;
2190 			}
2191 
2192 			ret = iio_buffer_add_channel_sysfs(indio_dev, buffer,
2193 							   &channels[i]);
2194 			if (ret < 0)
2195 				goto error_cleanup_dynamic;
2196 			scan_el_attrcount += ret;
2197 			if (channels[i].type == IIO_TIMESTAMP)
2198 				iio_dev_opaque->scan_index_timestamp =
2199 					channels[i].scan_index;
2200 		}
2201 		if (masklength && !buffer->scan_mask) {
2202 			buffer->scan_mask = bitmap_zalloc(masklength,
2203 							  GFP_KERNEL);
2204 			if (!buffer->scan_mask) {
2205 				ret = -ENOMEM;
2206 				goto error_cleanup_dynamic;
2207 			}
2208 		}
2209 	}
2210 
2211 	attrn = buffer_attrcount + scan_el_attrcount;
2212 	attr = kzalloc_objs(*attr, attrn + 1);
2213 	if (!attr) {
2214 		ret = -ENOMEM;
2215 		goto error_free_scan_mask;
2216 	}
2217 
2218 	memcpy(attr, iio_buffer_attrs, sizeof(iio_buffer_attrs));
2219 	if (!buffer->access->set_length)
2220 		attr[0] = &dev_attr_length_ro.attr;
2221 
2222 	if (buffer->access->flags & INDIO_BUFFER_FLAG_FIXED_WATERMARK)
2223 		attr[2] = &dev_attr_watermark_ro.attr;
2224 
2225 	if (buffer->attrs)
2226 		for (i = 0, id_attr = buffer->attrs[i];
2227 		     (id_attr = buffer->attrs[i]); i++)
2228 			attr[ARRAY_SIZE(iio_buffer_attrs) + i] =
2229 				(struct attribute *)&id_attr->dev_attr.attr;
2230 
2231 	buffer->buffer_group.attrs = attr;
2232 
2233 	for (i = 0; i < buffer_attrcount; i++) {
2234 		struct attribute *wrapped;
2235 
2236 		wrapped = iio_buffer_wrap_attr(buffer, attr[i]);
2237 		if (!wrapped) {
2238 			ret = -ENOMEM;
2239 			goto error_free_buffer_attrs;
2240 		}
2241 		attr[i] = wrapped;
2242 	}
2243 
2244 	attrn = 0;
2245 	list_for_each_entry(p, &buffer->buffer_attr_list, l)
2246 		attr[attrn++] = &p->dev_attr.attr;
2247 
2248 	buffer->buffer_group.name = kasprintf(GFP_KERNEL, "buffer%d", index);
2249 	if (!buffer->buffer_group.name) {
2250 		ret = -ENOMEM;
2251 		goto error_free_buffer_attrs;
2252 	}
2253 
2254 	ret = iio_device_register_sysfs_group(indio_dev, &buffer->buffer_group);
2255 	if (ret)
2256 		goto error_free_buffer_attr_group_name;
2257 
2258 	/* we only need to register the legacy groups for the first buffer */
2259 	if (index > 0)
2260 		return 0;
2261 
2262 	ret = iio_buffer_register_legacy_sysfs_groups(indio_dev, attr,
2263 						      buffer_attrcount,
2264 						      scan_el_attrcount);
2265 	if (ret)
2266 		goto error_free_buffer_attr_group_name;
2267 
2268 	return 0;
2269 
2270 error_free_buffer_attr_group_name:
2271 	kfree(buffer->buffer_group.name);
2272 error_free_buffer_attrs:
2273 	kfree(buffer->buffer_group.attrs);
2274 error_free_scan_mask:
2275 	bitmap_free(buffer->scan_mask);
2276 error_cleanup_dynamic:
2277 	iio_free_chan_devattr_list(&buffer->buffer_attr_list);
2278 
2279 	return ret;
2280 }
2281 
__iio_buffer_free_sysfs_and_mask(struct iio_buffer * buffer,struct iio_dev * indio_dev,int index)2282 static void __iio_buffer_free_sysfs_and_mask(struct iio_buffer *buffer,
2283 					     struct iio_dev *indio_dev,
2284 					     int index)
2285 {
2286 	if (index == 0)
2287 		iio_buffer_unregister_legacy_sysfs_groups(indio_dev);
2288 	bitmap_free(buffer->scan_mask);
2289 	kfree(buffer->buffer_group.name);
2290 	kfree(buffer->buffer_group.attrs);
2291 	iio_free_chan_devattr_list(&buffer->buffer_attr_list);
2292 }
2293 
iio_buffers_alloc_sysfs_and_mask(struct iio_dev * indio_dev)2294 int iio_buffers_alloc_sysfs_and_mask(struct iio_dev *indio_dev)
2295 {
2296 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2297 	const struct iio_chan_spec *channels;
2298 	struct iio_buffer *buffer;
2299 	int ret, i, idx;
2300 	size_t sz;
2301 
2302 	channels = indio_dev->channels;
2303 	if (channels) {
2304 		int ml = 0;
2305 
2306 		for (i = 0; i < indio_dev->num_channels; i++)
2307 			ml = max(ml, channels[i].scan_index + 1);
2308 		ACCESS_PRIVATE(indio_dev, masklength) = ml;
2309 	}
2310 
2311 	if (!iio_dev_opaque->attached_buffers_cnt)
2312 		return 0;
2313 
2314 	for (idx = 0; idx < iio_dev_opaque->attached_buffers_cnt; idx++) {
2315 		buffer = iio_dev_opaque->attached_buffers[idx];
2316 		ret = __iio_buffer_alloc_sysfs_and_mask(buffer, indio_dev, idx);
2317 		if (ret)
2318 			goto error_unwind_sysfs_and_mask;
2319 	}
2320 
2321 	sz = sizeof(*iio_dev_opaque->buffer_ioctl_handler);
2322 	iio_dev_opaque->buffer_ioctl_handler = kzalloc(sz, GFP_KERNEL);
2323 	if (!iio_dev_opaque->buffer_ioctl_handler) {
2324 		ret = -ENOMEM;
2325 		goto error_unwind_sysfs_and_mask;
2326 	}
2327 
2328 	iio_dev_opaque->buffer_ioctl_handler->ioctl = iio_device_buffer_ioctl;
2329 	iio_device_ioctl_handler_register(indio_dev,
2330 					  iio_dev_opaque->buffer_ioctl_handler);
2331 
2332 	return 0;
2333 
2334 error_unwind_sysfs_and_mask:
2335 	while (idx--) {
2336 		buffer = iio_dev_opaque->attached_buffers[idx];
2337 		__iio_buffer_free_sysfs_and_mask(buffer, indio_dev, idx);
2338 	}
2339 	return ret;
2340 }
2341 
iio_buffers_free_sysfs_and_mask(struct iio_dev * indio_dev)2342 void iio_buffers_free_sysfs_and_mask(struct iio_dev *indio_dev)
2343 {
2344 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2345 	struct iio_buffer *buffer;
2346 	int i;
2347 
2348 	if (!iio_dev_opaque->attached_buffers_cnt)
2349 		return;
2350 
2351 	iio_device_ioctl_handler_unregister(iio_dev_opaque->buffer_ioctl_handler);
2352 	kfree(iio_dev_opaque->buffer_ioctl_handler);
2353 
2354 	for (i = iio_dev_opaque->attached_buffers_cnt - 1; i >= 0; i--) {
2355 		buffer = iio_dev_opaque->attached_buffers[i];
2356 		__iio_buffer_free_sysfs_and_mask(buffer, indio_dev, i);
2357 	}
2358 }
2359 
2360 /**
2361  * iio_validate_scan_mask_onehot() - Validates that exactly one channel is selected
2362  * @indio_dev: the iio device
2363  * @mask: scan mask to be checked
2364  *
2365  * Return true if exactly one bit is set in the scan mask, false otherwise. It
2366  * can be used for devices where only one channel can be active for sampling at
2367  * a time.
2368  */
iio_validate_scan_mask_onehot(struct iio_dev * indio_dev,const unsigned long * mask)2369 bool iio_validate_scan_mask_onehot(struct iio_dev *indio_dev,
2370 				   const unsigned long *mask)
2371 {
2372 	return bitmap_weight(mask, iio_get_masklength(indio_dev)) == 1;
2373 }
2374 EXPORT_SYMBOL_GPL(iio_validate_scan_mask_onehot);
2375 
iio_demux(struct iio_buffer * buffer,const void * datain)2376 static const void *iio_demux(struct iio_buffer *buffer,
2377 			     const void *datain)
2378 {
2379 	struct iio_demux_table *t;
2380 
2381 	if (list_empty(&buffer->demux_list))
2382 		return datain;
2383 	list_for_each_entry(t, &buffer->demux_list, l)
2384 		memcpy(buffer->demux_bounce + t->to,
2385 		       datain + t->from, t->length);
2386 
2387 	return buffer->demux_bounce;
2388 }
2389 
iio_push_to_buffer(struct iio_buffer * buffer,const void * data)2390 static int iio_push_to_buffer(struct iio_buffer *buffer, const void *data)
2391 {
2392 	const void *dataout = iio_demux(buffer, data);
2393 	int ret;
2394 
2395 	ret = buffer->access->store_to(buffer, dataout);
2396 	if (ret)
2397 		return ret;
2398 
2399 	/*
2400 	 * We can't just test for watermark to decide if we wake the poll queue
2401 	 * because read may request less samples than the watermark.
2402 	 */
2403 	wake_up_interruptible_poll(&buffer->pollq, EPOLLIN | EPOLLRDNORM);
2404 	return 0;
2405 }
2406 
2407 /**
2408  * iio_push_to_buffers() - push to a registered buffer.
2409  * @indio_dev:		iio_dev structure for device.
2410  * @data:		Full scan.
2411  *
2412  * Context: Any context.
2413  * Return: 0 on success, negative error code on failure.
2414  */
iio_push_to_buffers(struct iio_dev * indio_dev,const void * data)2415 int iio_push_to_buffers(struct iio_dev *indio_dev, const void *data)
2416 {
2417 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2418 	int ret;
2419 	struct iio_buffer *buf;
2420 
2421 	list_for_each_entry(buf, &iio_dev_opaque->buffer_list, buffer_list) {
2422 		ret = iio_push_to_buffer(buf, data);
2423 		if (ret < 0)
2424 			return ret;
2425 	}
2426 
2427 	return 0;
2428 }
2429 EXPORT_SYMBOL_GPL(iio_push_to_buffers);
2430 
2431 /**
2432  * iio_push_to_buffers_with_ts_unaligned() - push to registered buffer,
2433  *    no alignment or space requirements.
2434  * @indio_dev:		iio_dev structure for device.
2435  * @data:		channel data excluding the timestamp.
2436  * @data_sz:		size of data.
2437  * @timestamp:		timestamp for the sample data.
2438  *
2439  * This special variant of iio_push_to_buffers_with_timestamp() does
2440  * not require space for the timestamp, or 8 byte alignment of data.
2441  * It does however require an allocation on first call and additional
2442  * copies on all calls, so should be avoided if possible.
2443  *
2444  * Context: May sleep.
2445  * Return: 0 on success, negative error code on failure.
2446  */
iio_push_to_buffers_with_ts_unaligned(struct iio_dev * indio_dev,const void * data,size_t data_sz,s64 timestamp)2447 int iio_push_to_buffers_with_ts_unaligned(struct iio_dev *indio_dev,
2448 					  const void *data,
2449 					  size_t data_sz,
2450 					  s64 timestamp)
2451 {
2452 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2453 
2454 	might_sleep();
2455 
2456 	/*
2457 	 * Conservative estimate - we can always safely copy the minimum
2458 	 * of either the data provided or the length of the destination buffer.
2459 	 * This relaxed limit allows the calling drivers to be lax about
2460 	 * tracking the size of the data they are pushing, at the cost of
2461 	 * unnecessary copying of padding.
2462 	 */
2463 	data_sz = min_t(size_t, indio_dev->scan_bytes, data_sz);
2464 	if (iio_dev_opaque->bounce_buffer_size !=  indio_dev->scan_bytes) {
2465 		void *bb;
2466 
2467 		bb = devm_krealloc(&indio_dev->dev,
2468 				   iio_dev_opaque->bounce_buffer,
2469 				   indio_dev->scan_bytes,
2470 				   GFP_KERNEL | __GFP_ZERO);
2471 		if (!bb)
2472 			return -ENOMEM;
2473 		iio_dev_opaque->bounce_buffer = bb;
2474 		iio_dev_opaque->bounce_buffer_size = indio_dev->scan_bytes;
2475 	}
2476 	memcpy(iio_dev_opaque->bounce_buffer, data, data_sz);
2477 	return iio_push_to_buffers_with_timestamp(indio_dev,
2478 						  iio_dev_opaque->bounce_buffer,
2479 						  timestamp);
2480 }
2481 EXPORT_SYMBOL_GPL(iio_push_to_buffers_with_ts_unaligned);
2482 
2483 /**
2484  * iio_buffer_release() - Free a buffer's resources
2485  * @ref: Pointer to the kref embedded in the iio_buffer struct
2486  *
2487  * This function is called when the last reference to the buffer has been
2488  * dropped. It will typically free all resources allocated by the buffer. Do not
2489  * call this function manually, always use iio_buffer_put() when done using a
2490  * buffer.
2491  */
iio_buffer_release(struct kref * ref)2492 static void iio_buffer_release(struct kref *ref)
2493 {
2494 	struct iio_buffer *buffer = container_of(ref, struct iio_buffer, ref);
2495 
2496 	mutex_destroy(&buffer->dmabufs_mutex);
2497 	buffer->access->release(buffer);
2498 }
2499 
2500 /**
2501  * iio_buffer_get() - Grab a reference to the buffer
2502  * @buffer: The buffer to grab a reference for, may be NULL
2503  *
2504  * Returns the pointer to the buffer that was passed into the function.
2505  */
iio_buffer_get(struct iio_buffer * buffer)2506 struct iio_buffer *iio_buffer_get(struct iio_buffer *buffer)
2507 {
2508 	if (buffer)
2509 		kref_get(&buffer->ref);
2510 
2511 	return buffer;
2512 }
2513 EXPORT_SYMBOL_GPL(iio_buffer_get);
2514 
2515 /**
2516  * iio_buffer_put() - Release the reference to the buffer
2517  * @buffer: The buffer to release the reference for, may be NULL
2518  */
iio_buffer_put(struct iio_buffer * buffer)2519 void iio_buffer_put(struct iio_buffer *buffer)
2520 {
2521 	if (buffer)
2522 		kref_put(&buffer->ref, iio_buffer_release);
2523 }
2524 EXPORT_SYMBOL_GPL(iio_buffer_put);
2525 
2526 /**
2527  * iio_device_attach_buffer - Attach a buffer to a IIO device
2528  * @indio_dev: The device the buffer should be attached to
2529  * @buffer: The buffer to attach to the device
2530  *
2531  * Return 0 if successful, negative if error.
2532  *
2533  * This function attaches a buffer to a IIO device. The buffer stays attached to
2534  * the device until the device is freed. For legacy reasons, the first attached
2535  * buffer will also be assigned to 'indio_dev->buffer'.
2536  * The array allocated here, will be free'd via the iio_device_detach_buffers()
2537  * call which is handled by the iio_device_free().
2538  */
iio_device_attach_buffer(struct iio_dev * indio_dev,struct iio_buffer * buffer)2539 int iio_device_attach_buffer(struct iio_dev *indio_dev,
2540 			     struct iio_buffer *buffer)
2541 {
2542 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2543 	struct iio_buffer **new, **old = iio_dev_opaque->attached_buffers;
2544 	unsigned int cnt = iio_dev_opaque->attached_buffers_cnt;
2545 
2546 	cnt++;
2547 
2548 	new = krealloc(old, sizeof(*new) * cnt, GFP_KERNEL);
2549 	if (!new)
2550 		return -ENOMEM;
2551 	iio_dev_opaque->attached_buffers = new;
2552 
2553 	buffer = iio_buffer_get(buffer);
2554 
2555 	/* first buffer is legacy; attach it to the IIO device directly */
2556 	if (!indio_dev->buffer)
2557 		indio_dev->buffer = buffer;
2558 
2559 	iio_dev_opaque->attached_buffers[cnt - 1] = buffer;
2560 	iio_dev_opaque->attached_buffers_cnt = cnt;
2561 
2562 	return 0;
2563 }
2564 EXPORT_SYMBOL_GPL(iio_device_attach_buffer);
2565