xref: /linux/drivers/iio/industrialio-buffer.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
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 
72 static bool iio_buffer_is_active(struct iio_buffer *buf)
73 {
74 	return !list_empty(&buf->buffer_list);
75 }
76 
77 static size_t iio_buffer_data_available(struct iio_buffer *buf)
78 {
79 	return buf->access->data_available(buf);
80 }
81 
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 
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  **/
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 
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 
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  */
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 
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 
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 
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  */
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 
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 
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 
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 
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 
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 
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. */
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 
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  */
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
1378 void iio_disable_all_buffers(struct iio_dev *indio_dev)
1379 {
1380 	iio_disable_buffers(indio_dev);
1381 	iio_buffer_deactivate_all(indio_dev);
1382 }
1383 
1384 static ssize_t enable_store(struct device *dev, struct device_attribute *attr,
1385 			    const char *buf, size_t len)
1386 {
1387 	int ret;
1388 	bool requested_state;
1389 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1390 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1391 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1392 	bool inlist;
1393 
1394 	ret = kstrtobool(buf, &requested_state);
1395 	if (ret < 0)
1396 		return ret;
1397 
1398 	guard(mutex)(&iio_dev_opaque->mlock);
1399 
1400 	/* Find out if it is in the list */
1401 	inlist = iio_buffer_is_active(buffer);
1402 	/* Already in desired state */
1403 	if (inlist == requested_state)
1404 		return len;
1405 
1406 	if (requested_state)
1407 		ret = __iio_update_buffers(indio_dev, buffer, NULL);
1408 	else
1409 		ret = __iio_update_buffers(indio_dev, NULL, buffer);
1410 	if (ret)
1411 		return ret;
1412 
1413 	return len;
1414 }
1415 
1416 static ssize_t watermark_show(struct device *dev, struct device_attribute *attr,
1417 			      char *buf)
1418 {
1419 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1420 
1421 	return sysfs_emit(buf, "%u\n", buffer->watermark);
1422 }
1423 
1424 static ssize_t watermark_store(struct device *dev,
1425 			       struct device_attribute *attr,
1426 			       const char *buf, size_t len)
1427 {
1428 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1429 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1430 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1431 	unsigned int val;
1432 	int ret;
1433 
1434 	ret = kstrtouint(buf, 10, &val);
1435 	if (ret)
1436 		return ret;
1437 	if (!val)
1438 		return -EINVAL;
1439 
1440 	guard(mutex)(&iio_dev_opaque->mlock);
1441 
1442 	if (val > buffer->length)
1443 		return -EINVAL;
1444 
1445 	if (iio_buffer_is_active(buffer))
1446 		return -EBUSY;
1447 
1448 	buffer->watermark = val;
1449 
1450 	return len;
1451 }
1452 
1453 static ssize_t data_available_show(struct device *dev,
1454 				   struct device_attribute *attr, char *buf)
1455 {
1456 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1457 
1458 	return sysfs_emit(buf, "%zu\n", iio_buffer_data_available(buffer));
1459 }
1460 
1461 static ssize_t direction_show(struct device *dev,
1462 			      struct device_attribute *attr,
1463 			      char *buf)
1464 {
1465 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1466 
1467 	switch (buffer->direction) {
1468 	case IIO_BUFFER_DIRECTION_IN:
1469 		return sysfs_emit(buf, "in\n");
1470 	case IIO_BUFFER_DIRECTION_OUT:
1471 		return sysfs_emit(buf, "out\n");
1472 	default:
1473 		return -EINVAL;
1474 	}
1475 }
1476 
1477 static DEVICE_ATTR_RW(length);
1478 static struct device_attribute dev_attr_length_ro = __ATTR_RO(length);
1479 static DEVICE_ATTR_RW(enable);
1480 static DEVICE_ATTR_RW(watermark);
1481 static struct device_attribute dev_attr_watermark_ro = __ATTR_RO(watermark);
1482 static DEVICE_ATTR_RO(data_available);
1483 static DEVICE_ATTR_RO(direction);
1484 
1485 /*
1486  * When adding new attributes here, put the at the end, at least until
1487  * the code that handles the length/length_ro & watermark/watermark_ro
1488  * assignments gets cleaned up. Otherwise these can create some weird
1489  * duplicate attributes errors under some setups.
1490  */
1491 static struct attribute *iio_buffer_attrs[] = {
1492 	&dev_attr_length.attr,
1493 	&dev_attr_enable.attr,
1494 	&dev_attr_watermark.attr,
1495 	&dev_attr_data_available.attr,
1496 	&dev_attr_direction.attr,
1497 };
1498 
1499 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
1500 
1501 static struct attribute *iio_buffer_wrap_attr(struct iio_buffer *buffer,
1502 					      struct attribute *attr)
1503 {
1504 	struct device_attribute *dattr = to_dev_attr(attr);
1505 	struct iio_dev_attr *iio_attr;
1506 
1507 	iio_attr = kzalloc_obj(*iio_attr);
1508 	if (!iio_attr)
1509 		return NULL;
1510 
1511 	iio_attr->buffer = buffer;
1512 	memcpy(&iio_attr->dev_attr, dattr, sizeof(iio_attr->dev_attr));
1513 	iio_attr->dev_attr.attr.name = kstrdup_const(attr->name, GFP_KERNEL);
1514 	if (!iio_attr->dev_attr.attr.name) {
1515 		kfree(iio_attr);
1516 		return NULL;
1517 	}
1518 
1519 	sysfs_attr_init(&iio_attr->dev_attr.attr);
1520 
1521 	list_add(&iio_attr->l, &buffer->buffer_attr_list);
1522 
1523 	return &iio_attr->dev_attr.attr;
1524 }
1525 
1526 static int iio_buffer_register_legacy_sysfs_groups(struct iio_dev *indio_dev,
1527 						   struct attribute **buffer_attrs,
1528 						   int buffer_attrcount,
1529 						   int scan_el_attrcount)
1530 {
1531 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1532 	struct attribute_group *group;
1533 	struct attribute **attrs;
1534 	int ret;
1535 
1536 	attrs = kzalloc_objs(*attrs, buffer_attrcount + 1);
1537 	if (!attrs)
1538 		return -ENOMEM;
1539 
1540 	memcpy(attrs, buffer_attrs, buffer_attrcount * sizeof(*attrs));
1541 
1542 	group = &iio_dev_opaque->legacy_buffer_group;
1543 	group->attrs = attrs;
1544 	group->name = "buffer";
1545 
1546 	ret = iio_device_register_sysfs_group(indio_dev, group);
1547 	if (ret)
1548 		goto error_free_buffer_attrs;
1549 
1550 	attrs = kzalloc_objs(*attrs, scan_el_attrcount + 1);
1551 	if (!attrs) {
1552 		ret = -ENOMEM;
1553 		goto error_free_buffer_attrs;
1554 	}
1555 
1556 	memcpy(attrs, &buffer_attrs[buffer_attrcount],
1557 	       scan_el_attrcount * sizeof(*attrs));
1558 
1559 	group = &iio_dev_opaque->legacy_scan_el_group;
1560 	group->attrs = attrs;
1561 	group->name = "scan_elements";
1562 
1563 	ret = iio_device_register_sysfs_group(indio_dev, group);
1564 	if (ret)
1565 		goto error_free_scan_el_attrs;
1566 
1567 	return 0;
1568 
1569 error_free_scan_el_attrs:
1570 	kfree(iio_dev_opaque->legacy_scan_el_group.attrs);
1571 error_free_buffer_attrs:
1572 	kfree(iio_dev_opaque->legacy_buffer_group.attrs);
1573 
1574 	return ret;
1575 }
1576 
1577 static void iio_buffer_unregister_legacy_sysfs_groups(struct iio_dev *indio_dev)
1578 {
1579 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1580 
1581 	kfree(iio_dev_opaque->legacy_buffer_group.attrs);
1582 	kfree(iio_dev_opaque->legacy_scan_el_group.attrs);
1583 }
1584 
1585 static void iio_buffer_dmabuf_release(struct kref *ref)
1586 {
1587 	struct iio_dmabuf_priv *priv = container_of(ref, struct iio_dmabuf_priv, ref);
1588 	struct dma_buf_attachment *attach = priv->attach;
1589 	struct iio_buffer *buffer = priv->buffer;
1590 	struct dma_buf *dmabuf = attach->dmabuf;
1591 
1592 	dma_buf_unmap_attachment_unlocked(attach, priv->sgt, priv->dir);
1593 
1594 	buffer->access->detach_dmabuf(buffer, priv->block);
1595 
1596 	dma_buf_detach(attach->dmabuf, attach);
1597 	dma_buf_put(dmabuf);
1598 	kfree(priv);
1599 }
1600 
1601 static void iio_buffer_dmabuf_get(struct dma_buf_attachment *attach)
1602 {
1603 	struct iio_dmabuf_priv *priv = attach->importer_priv;
1604 
1605 	kref_get(&priv->ref);
1606 }
1607 
1608 static void iio_buffer_dmabuf_put(struct dma_buf_attachment *attach)
1609 {
1610 	struct iio_dmabuf_priv *priv = attach->importer_priv;
1611 
1612 	kref_put(&priv->ref, iio_buffer_dmabuf_release);
1613 }
1614 
1615 static int iio_buffer_chrdev_release(struct inode *inode, struct file *filep)
1616 {
1617 	struct iio_dev_buffer_pair *ib = filep->private_data;
1618 	struct iio_dev *indio_dev = ib->indio_dev;
1619 	struct iio_buffer *buffer = ib->buffer;
1620 	struct iio_dmabuf_priv *priv, *tmp;
1621 
1622 	wake_up(&buffer->pollq);
1623 
1624 	/*
1625 	 * The mutex must be unlocked before iio_device_put(), which might drop the
1626 	 * last reference and free the buffer.
1627 	 */
1628 	scoped_guard(mutex, &buffer->dmabufs_mutex) {
1629 		/* Close all attached DMABUFs */
1630 		list_for_each_entry_safe(priv, tmp, &buffer->dmabufs, entry) {
1631 			list_del_init(&priv->entry);
1632 			iio_buffer_dmabuf_put(priv->attach);
1633 		}
1634 	}
1635 
1636 	kfree(ib);
1637 	clear_bit(IIO_BUSY_BIT_POS, &buffer->flags);
1638 	iio_device_put(indio_dev);
1639 
1640 	return 0;
1641 }
1642 
1643 static int iio_dma_resv_lock(struct dma_buf *dmabuf, bool nonblock)
1644 {
1645 	if (!nonblock)
1646 		return dma_resv_lock_interruptible(dmabuf->resv, NULL);
1647 
1648 	if (!dma_resv_trylock(dmabuf->resv))
1649 		return -EBUSY;
1650 
1651 	return 0;
1652 }
1653 
1654 static struct device *iio_buffer_get_dma_dev(const struct iio_dev *indio_dev,
1655 					     struct iio_buffer *buffer)
1656 {
1657 	if (buffer->access->get_dma_dev)
1658 		return buffer->access->get_dma_dev(buffer);
1659 
1660 	return indio_dev->dev.parent;
1661 }
1662 
1663 static struct dma_buf_attachment *
1664 iio_buffer_find_attachment(struct iio_dev_buffer_pair *ib,
1665 			   struct dma_buf *dmabuf, bool nonblock)
1666 {
1667 	struct iio_buffer *buffer = ib->buffer;
1668 	struct device *dma_dev = iio_buffer_get_dma_dev(ib->indio_dev, buffer);
1669 	struct dma_buf_attachment *attach = NULL;
1670 	struct iio_dmabuf_priv *priv;
1671 
1672 	guard(mutex)(&buffer->dmabufs_mutex);
1673 
1674 	list_for_each_entry(priv, &buffer->dmabufs, entry) {
1675 		if (priv->attach->dev == dma_dev
1676 		    && priv->attach->dmabuf == dmabuf) {
1677 			attach = priv->attach;
1678 			break;
1679 		}
1680 	}
1681 
1682 	if (attach)
1683 		iio_buffer_dmabuf_get(attach);
1684 
1685 	return attach ?: ERR_PTR(-EPERM);
1686 }
1687 
1688 static int iio_buffer_attach_dmabuf(struct iio_dev_buffer_pair *ib,
1689 				    int __user *user_fd, bool nonblock)
1690 {
1691 	struct iio_dev *indio_dev = ib->indio_dev;
1692 	struct iio_buffer *buffer = ib->buffer;
1693 	struct device *dma_dev = iio_buffer_get_dma_dev(indio_dev, buffer);
1694 	struct dma_buf_attachment *attach;
1695 	struct iio_dmabuf_priv *priv, *each;
1696 	struct dma_buf *dmabuf;
1697 	int err, fd;
1698 
1699 	if (!buffer->access->attach_dmabuf
1700 	    || !buffer->access->detach_dmabuf
1701 	    || !buffer->access->enqueue_dmabuf)
1702 		return -EPERM;
1703 
1704 	if (copy_from_user(&fd, user_fd, sizeof(fd)))
1705 		return -EFAULT;
1706 
1707 	priv = kzalloc_obj(*priv);
1708 	if (!priv)
1709 		return -ENOMEM;
1710 
1711 	priv->context = dma_fence_context_alloc(1);
1712 
1713 	dmabuf = dma_buf_get(fd);
1714 	if (IS_ERR(dmabuf)) {
1715 		err = PTR_ERR(dmabuf);
1716 		goto err_free_priv;
1717 	}
1718 
1719 	attach = dma_buf_attach(dmabuf, dma_dev);
1720 	if (IS_ERR(attach)) {
1721 		err = PTR_ERR(attach);
1722 		goto err_dmabuf_put;
1723 	}
1724 
1725 	err = iio_dma_resv_lock(dmabuf, nonblock);
1726 	if (err)
1727 		goto err_dmabuf_detach;
1728 
1729 	priv->dir = buffer->direction == IIO_BUFFER_DIRECTION_IN
1730 		? DMA_FROM_DEVICE : DMA_TO_DEVICE;
1731 
1732 	priv->sgt = dma_buf_map_attachment(attach, priv->dir);
1733 	if (IS_ERR(priv->sgt)) {
1734 		err = PTR_ERR(priv->sgt);
1735 		dev_err(&indio_dev->dev, "Unable to map attachment: %d\n", err);
1736 		goto err_resv_unlock;
1737 	}
1738 
1739 	kref_init(&priv->ref);
1740 	priv->buffer = buffer;
1741 	priv->attach = attach;
1742 	attach->importer_priv = priv;
1743 
1744 	priv->block = buffer->access->attach_dmabuf(buffer, attach);
1745 	if (IS_ERR(priv->block)) {
1746 		err = PTR_ERR(priv->block);
1747 		goto err_dmabuf_unmap_attachment;
1748 	}
1749 
1750 	dma_resv_unlock(dmabuf->resv);
1751 
1752 	mutex_lock(&buffer->dmabufs_mutex);
1753 
1754 	/*
1755 	 * Check whether we already have an attachment for this driver/DMABUF
1756 	 * combo. If we do, refuse to attach.
1757 	 */
1758 	list_for_each_entry(each, &buffer->dmabufs, entry) {
1759 		if (each->attach->dev == dma_dev
1760 		    && each->attach->dmabuf == dmabuf) {
1761 			/*
1762 			 * We unlocked the reservation object, so going through
1763 			 * the cleanup code would mean re-locking it first.
1764 			 * At this stage it is simpler to free the attachment
1765 			 * using iio_buffer_dma_put().
1766 			 */
1767 			mutex_unlock(&buffer->dmabufs_mutex);
1768 			iio_buffer_dmabuf_put(attach);
1769 			return -EBUSY;
1770 		}
1771 	}
1772 
1773 	/* Otherwise, add the new attachment to our dmabufs list. */
1774 	list_add(&priv->entry, &buffer->dmabufs);
1775 	mutex_unlock(&buffer->dmabufs_mutex);
1776 
1777 	return 0;
1778 
1779 err_dmabuf_unmap_attachment:
1780 	dma_buf_unmap_attachment(attach, priv->sgt, priv->dir);
1781 err_resv_unlock:
1782 	dma_resv_unlock(dmabuf->resv);
1783 err_dmabuf_detach:
1784 	dma_buf_detach(dmabuf, attach);
1785 err_dmabuf_put:
1786 	dma_buf_put(dmabuf);
1787 err_free_priv:
1788 	kfree(priv);
1789 
1790 	return err;
1791 }
1792 
1793 static int iio_buffer_detach_dmabuf(struct iio_dev_buffer_pair *ib,
1794 				    int __user *user_req, bool nonblock)
1795 {
1796 	struct iio_buffer *buffer = ib->buffer;
1797 	struct iio_dev *indio_dev = ib->indio_dev;
1798 	struct device *dma_dev = iio_buffer_get_dma_dev(indio_dev, buffer);
1799 	struct iio_dmabuf_priv *priv;
1800 	struct dma_buf *dmabuf;
1801 	int dmabuf_fd, ret = -EPERM;
1802 
1803 	if (copy_from_user(&dmabuf_fd, user_req, sizeof(dmabuf_fd)))
1804 		return -EFAULT;
1805 
1806 	dmabuf = dma_buf_get(dmabuf_fd);
1807 	if (IS_ERR(dmabuf))
1808 		return PTR_ERR(dmabuf);
1809 
1810 	guard(mutex)(&buffer->dmabufs_mutex);
1811 
1812 	list_for_each_entry(priv, &buffer->dmabufs, entry) {
1813 		if (priv->attach->dev == dma_dev
1814 		    && priv->attach->dmabuf == dmabuf) {
1815 			list_del(&priv->entry);
1816 
1817 			/* Unref the reference from iio_buffer_attach_dmabuf() */
1818 			iio_buffer_dmabuf_put(priv->attach);
1819 			ret = 0;
1820 			break;
1821 		}
1822 	}
1823 
1824 	dma_buf_put(dmabuf);
1825 
1826 	return ret;
1827 }
1828 
1829 static const char *
1830 iio_buffer_dma_fence_get_driver_name(struct dma_fence *fence)
1831 {
1832 	return "iio";
1833 }
1834 
1835 static const struct dma_fence_ops iio_buffer_dma_fence_ops = {
1836 	.get_driver_name	= iio_buffer_dma_fence_get_driver_name,
1837 	.get_timeline_name	= iio_buffer_dma_fence_get_driver_name,
1838 };
1839 
1840 static int iio_buffer_enqueue_dmabuf(struct iio_dev_buffer_pair *ib,
1841 				     struct iio_dmabuf __user *iio_dmabuf_req,
1842 				     bool nonblock)
1843 {
1844 	struct iio_buffer *buffer = ib->buffer;
1845 	struct iio_dmabuf iio_dmabuf;
1846 	struct dma_buf_attachment *attach;
1847 	struct iio_dmabuf_priv *priv;
1848 	struct iio_dma_fence *fence;
1849 	struct dma_buf *dmabuf;
1850 	unsigned long timeout;
1851 	bool cookie, cyclic, dma_to_ram;
1852 	long retl;
1853 	u32 seqno;
1854 	int ret;
1855 
1856 	if (copy_from_user(&iio_dmabuf, iio_dmabuf_req, sizeof(iio_dmabuf)))
1857 		return -EFAULT;
1858 
1859 	if (iio_dmabuf.flags & ~IIO_BUFFER_DMABUF_SUPPORTED_FLAGS)
1860 		return -EINVAL;
1861 
1862 	cyclic = iio_dmabuf.flags & IIO_BUFFER_DMABUF_CYCLIC;
1863 
1864 	/* Cyclic flag is only supported on output buffers */
1865 	if (cyclic && buffer->direction != IIO_BUFFER_DIRECTION_OUT)
1866 		return -EINVAL;
1867 
1868 	dmabuf = dma_buf_get(iio_dmabuf.fd);
1869 	if (IS_ERR(dmabuf))
1870 		return PTR_ERR(dmabuf);
1871 
1872 	if (!iio_dmabuf.bytes_used || iio_dmabuf.bytes_used > dmabuf->size) {
1873 		ret = -EINVAL;
1874 		goto err_dmabuf_put;
1875 	}
1876 
1877 	attach = iio_buffer_find_attachment(ib, dmabuf, nonblock);
1878 	if (IS_ERR(attach)) {
1879 		ret = PTR_ERR(attach);
1880 		goto err_dmabuf_put;
1881 	}
1882 
1883 	priv = attach->importer_priv;
1884 
1885 	fence = kmalloc_obj(*fence);
1886 	if (!fence) {
1887 		ret = -ENOMEM;
1888 		goto err_attachment_put;
1889 	}
1890 
1891 	spin_lock_init(&fence->lock);
1892 
1893 	fence->priv = priv;
1894 
1895 	seqno = atomic_add_return(1, &priv->seqno);
1896 
1897 	/*
1898 	 * The transfers are guaranteed to be processed in the order they are
1899 	 * enqueued, so we can use a simple incrementing sequence number for
1900 	 * the dma_fence.
1901 	 */
1902 	dma_fence_init(&fence->base, &iio_buffer_dma_fence_ops,
1903 		       &fence->lock, priv->context, seqno);
1904 
1905 	ret = iio_dma_resv_lock(dmabuf, nonblock);
1906 	if (ret)
1907 		goto err_fence_put;
1908 
1909 	timeout = nonblock ? 0 : msecs_to_jiffies(DMABUF_ENQUEUE_TIMEOUT_MS);
1910 	dma_to_ram = buffer->direction == IIO_BUFFER_DIRECTION_IN;
1911 
1912 	/* Make sure we don't have writers */
1913 	retl = dma_resv_wait_timeout(dmabuf->resv,
1914 				     dma_resv_usage_rw(dma_to_ram),
1915 				     true, timeout);
1916 	if (retl == 0)
1917 		retl = -EBUSY;
1918 	if (retl < 0) {
1919 		ret = (int)retl;
1920 		goto err_resv_unlock;
1921 	}
1922 
1923 	if (buffer->access->lock_queue)
1924 		buffer->access->lock_queue(buffer);
1925 
1926 	ret = dma_resv_reserve_fences(dmabuf->resv, 1);
1927 	if (ret)
1928 		goto err_queue_unlock;
1929 
1930 	dma_resv_add_fence(dmabuf->resv, &fence->base,
1931 			   dma_to_ram ? DMA_RESV_USAGE_WRITE : DMA_RESV_USAGE_READ);
1932 	dma_fence_put(&fence->base);
1933 	dma_resv_unlock(dmabuf->resv);
1934 
1935 	cookie = dma_fence_begin_signalling();
1936 
1937 	ret = buffer->access->enqueue_dmabuf(buffer, priv->block, &fence->base,
1938 					     priv->sgt, iio_dmabuf.bytes_used,
1939 					     cyclic);
1940 	if (ret) {
1941 		/*
1942 		 * DMABUF enqueue failed, but we already added the fence.
1943 		 * Signal the error through the fence completion mechanism.
1944 		 */
1945 		iio_buffer_signal_dmabuf_done(&fence->base, ret);
1946 	}
1947 
1948 	if (buffer->access->unlock_queue)
1949 		buffer->access->unlock_queue(buffer);
1950 
1951 	dma_fence_end_signalling(cookie);
1952 	dma_buf_put(dmabuf);
1953 
1954 	return ret;
1955 
1956 err_queue_unlock:
1957 	if (buffer->access->unlock_queue)
1958 		buffer->access->unlock_queue(buffer);
1959 err_resv_unlock:
1960 	dma_resv_unlock(dmabuf->resv);
1961 err_fence_put:
1962 	dma_fence_put(&fence->base);
1963 err_attachment_put:
1964 	iio_buffer_dmabuf_put(attach);
1965 err_dmabuf_put:
1966 	dma_buf_put(dmabuf);
1967 
1968 	return ret;
1969 }
1970 
1971 static void iio_buffer_cleanup(struct work_struct *work)
1972 {
1973 	struct iio_dma_fence *fence =
1974 		container_of(work, struct iio_dma_fence, work);
1975 	struct iio_dmabuf_priv *priv = fence->priv;
1976 	struct dma_buf_attachment *attach = priv->attach;
1977 
1978 	dma_fence_put(&fence->base);
1979 	iio_buffer_dmabuf_put(attach);
1980 }
1981 
1982 void iio_buffer_signal_dmabuf_done(struct dma_fence *fence, int ret)
1983 {
1984 	struct iio_dma_fence *iio_fence =
1985 		container_of(fence, struct iio_dma_fence, base);
1986 	bool cookie = dma_fence_begin_signalling();
1987 
1988 	/*
1989 	 * Get a reference to the fence, so that it's not freed as soon as
1990 	 * it's signaled.
1991 	 */
1992 	dma_fence_get(fence);
1993 
1994 	fence->error = ret;
1995 	dma_fence_signal(fence);
1996 	dma_fence_end_signalling(cookie);
1997 
1998 	/*
1999 	 * The fence will be unref'd in iio_buffer_cleanup.
2000 	 * It can't be done here, as the unref functions might try to lock the
2001 	 * resv object, which can deadlock.
2002 	 */
2003 	INIT_WORK(&iio_fence->work, iio_buffer_cleanup);
2004 	schedule_work(&iio_fence->work);
2005 }
2006 EXPORT_SYMBOL_GPL(iio_buffer_signal_dmabuf_done);
2007 
2008 static long iio_buffer_chrdev_ioctl(struct file *filp,
2009 				    unsigned int cmd, unsigned long arg)
2010 {
2011 	struct iio_dev_buffer_pair *ib = filp->private_data;
2012 	void __user *_arg = (void __user *)arg;
2013 	bool nonblock = filp->f_flags & O_NONBLOCK;
2014 
2015 	switch (cmd) {
2016 	case IIO_BUFFER_DMABUF_ATTACH_IOCTL:
2017 		return iio_buffer_attach_dmabuf(ib, _arg, nonblock);
2018 	case IIO_BUFFER_DMABUF_DETACH_IOCTL:
2019 		return iio_buffer_detach_dmabuf(ib, _arg, nonblock);
2020 	case IIO_BUFFER_DMABUF_ENQUEUE_IOCTL:
2021 		return iio_buffer_enqueue_dmabuf(ib, _arg, nonblock);
2022 	default:
2023 		return -EINVAL;
2024 	}
2025 }
2026 
2027 static const struct file_operations iio_buffer_chrdev_fileops = {
2028 	.owner = THIS_MODULE,
2029 	.llseek = noop_llseek,
2030 	.read = iio_buffer_read,
2031 	.write = iio_buffer_write,
2032 	.unlocked_ioctl = iio_buffer_chrdev_ioctl,
2033 	.compat_ioctl = compat_ptr_ioctl,
2034 	.poll = iio_buffer_poll,
2035 	.release = iio_buffer_chrdev_release,
2036 };
2037 
2038 static long iio_device_buffer_getfd(struct iio_dev *indio_dev, unsigned long arg)
2039 {
2040 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2041 	int __user *ival = (int __user *)arg;
2042 	struct iio_dev_buffer_pair *ib;
2043 	struct iio_buffer *buffer;
2044 	int fd, idx, ret;
2045 
2046 	if (copy_from_user(&idx, ival, sizeof(idx)))
2047 		return -EFAULT;
2048 
2049 	if (idx >= iio_dev_opaque->attached_buffers_cnt)
2050 		return -ENODEV;
2051 
2052 	iio_device_get(indio_dev);
2053 
2054 	buffer = iio_dev_opaque->attached_buffers[idx];
2055 
2056 	if (test_and_set_bit(IIO_BUSY_BIT_POS, &buffer->flags)) {
2057 		ret = -EBUSY;
2058 		goto error_iio_dev_put;
2059 	}
2060 
2061 	ib = kzalloc_obj(*ib);
2062 	if (!ib) {
2063 		ret = -ENOMEM;
2064 		goto error_clear_busy_bit;
2065 	}
2066 
2067 	ib->indio_dev = indio_dev;
2068 	ib->buffer = buffer;
2069 
2070 	fd = anon_inode_getfd("iio:buffer", &iio_buffer_chrdev_fileops,
2071 			      ib, O_RDWR | O_CLOEXEC);
2072 	if (fd < 0) {
2073 		ret = fd;
2074 		goto error_free_ib;
2075 	}
2076 
2077 	if (copy_to_user(ival, &fd, sizeof(fd))) {
2078 		/*
2079 		 * "Leak" the fd, as there's not much we can do about this
2080 		 * anyway. 'fd' might have been closed already, as
2081 		 * anon_inode_getfd() called fd_install() on it, which made
2082 		 * it reachable by userland.
2083 		 *
2084 		 * Instead of allowing a malicious user to play tricks with
2085 		 * us, rely on the process exit path to do any necessary
2086 		 * cleanup, as in releasing the file, if still needed.
2087 		 */
2088 		return -EFAULT;
2089 	}
2090 
2091 	return 0;
2092 
2093 error_free_ib:
2094 	kfree(ib);
2095 error_clear_busy_bit:
2096 	clear_bit(IIO_BUSY_BIT_POS, &buffer->flags);
2097 error_iio_dev_put:
2098 	iio_device_put(indio_dev);
2099 	return ret;
2100 }
2101 
2102 static long iio_device_buffer_ioctl(struct iio_dev *indio_dev, struct file *filp,
2103 				    unsigned int cmd, unsigned long arg)
2104 {
2105 	switch (cmd) {
2106 	case IIO_BUFFER_GET_FD_IOCTL:
2107 		return iio_device_buffer_getfd(indio_dev, arg);
2108 	default:
2109 		return IIO_IOCTL_UNHANDLED;
2110 	}
2111 }
2112 
2113 static int iio_channel_validate_scan_type(struct device *dev, int ch,
2114 					  const struct iio_scan_type *scan_type)
2115 {
2116 	/* Verify that sample bits fit into storage */
2117 	if (scan_type->storagebits < scan_type->realbits + scan_type->shift) {
2118 		dev_err(dev,
2119 			"Channel %d storagebits (%d) < shifted realbits (%d + %d)\n",
2120 			ch, scan_type->storagebits,
2121 			scan_type->realbits,
2122 			scan_type->shift);
2123 		return -EINVAL;
2124 	}
2125 
2126 	return 0;
2127 }
2128 
2129 static int __iio_buffer_alloc_sysfs_and_mask(struct iio_buffer *buffer,
2130 					     struct iio_dev *indio_dev,
2131 					     int index)
2132 {
2133 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2134 	unsigned int masklength = iio_get_masklength(indio_dev);
2135 	struct iio_dev_attr *p;
2136 	const struct iio_dev_attr *id_attr;
2137 	struct attribute **attr;
2138 	int ret, i, attrn, scan_el_attrcount, buffer_attrcount;
2139 	const struct iio_chan_spec *channels;
2140 
2141 	buffer_attrcount = 0;
2142 	if (buffer->attrs) {
2143 		while (buffer->attrs[buffer_attrcount])
2144 			buffer_attrcount++;
2145 	}
2146 	buffer_attrcount += ARRAY_SIZE(iio_buffer_attrs);
2147 
2148 	scan_el_attrcount = 0;
2149 	INIT_LIST_HEAD(&buffer->buffer_attr_list);
2150 	channels = indio_dev->channels;
2151 	if (channels) {
2152 		/* new magic */
2153 		for (i = 0; i < indio_dev->num_channels; i++) {
2154 			const struct iio_scan_type *scan_type;
2155 
2156 			if (channels[i].scan_index < 0)
2157 				continue;
2158 
2159 			if (channels[i].has_ext_scan_type) {
2160 				int j;
2161 
2162 				/*
2163 				 * get_current_scan_type is required when using
2164 				 * extended scan types.
2165 				 */
2166 				if (!indio_dev->info->get_current_scan_type) {
2167 					ret = -EINVAL;
2168 					goto error_cleanup_dynamic;
2169 				}
2170 
2171 				for (j = 0; j < channels[i].num_ext_scan_type; j++) {
2172 					scan_type = &channels[i].ext_scan_type[j];
2173 
2174 					ret = iio_channel_validate_scan_type(
2175 						&indio_dev->dev, i, scan_type);
2176 					if (ret)
2177 						goto error_cleanup_dynamic;
2178 				}
2179 			} else {
2180 				scan_type = &channels[i].scan_type;
2181 
2182 				ret = iio_channel_validate_scan_type(
2183 						&indio_dev->dev, i, scan_type);
2184 				if (ret)
2185 					goto error_cleanup_dynamic;
2186 			}
2187 
2188 			ret = iio_buffer_add_channel_sysfs(indio_dev, buffer,
2189 							   &channels[i]);
2190 			if (ret < 0)
2191 				goto error_cleanup_dynamic;
2192 			scan_el_attrcount += ret;
2193 			if (channels[i].type == IIO_TIMESTAMP)
2194 				iio_dev_opaque->scan_index_timestamp =
2195 					channels[i].scan_index;
2196 		}
2197 		if (masklength && !buffer->scan_mask) {
2198 			buffer->scan_mask = bitmap_zalloc(masklength,
2199 							  GFP_KERNEL);
2200 			if (!buffer->scan_mask) {
2201 				ret = -ENOMEM;
2202 				goto error_cleanup_dynamic;
2203 			}
2204 		}
2205 	}
2206 
2207 	attrn = buffer_attrcount + scan_el_attrcount;
2208 	attr = kzalloc_objs(*attr, attrn + 1);
2209 	if (!attr) {
2210 		ret = -ENOMEM;
2211 		goto error_free_scan_mask;
2212 	}
2213 
2214 	memcpy(attr, iio_buffer_attrs, sizeof(iio_buffer_attrs));
2215 	if (!buffer->access->set_length)
2216 		attr[0] = &dev_attr_length_ro.attr;
2217 
2218 	if (buffer->access->flags & INDIO_BUFFER_FLAG_FIXED_WATERMARK)
2219 		attr[2] = &dev_attr_watermark_ro.attr;
2220 
2221 	if (buffer->attrs)
2222 		for (i = 0, id_attr = buffer->attrs[i];
2223 		     (id_attr = buffer->attrs[i]); i++)
2224 			attr[ARRAY_SIZE(iio_buffer_attrs) + i] =
2225 				(struct attribute *)&id_attr->dev_attr.attr;
2226 
2227 	buffer->buffer_group.attrs = attr;
2228 
2229 	for (i = 0; i < buffer_attrcount; i++) {
2230 		struct attribute *wrapped;
2231 
2232 		wrapped = iio_buffer_wrap_attr(buffer, attr[i]);
2233 		if (!wrapped) {
2234 			ret = -ENOMEM;
2235 			goto error_free_buffer_attrs;
2236 		}
2237 		attr[i] = wrapped;
2238 	}
2239 
2240 	attrn = 0;
2241 	list_for_each_entry(p, &buffer->buffer_attr_list, l)
2242 		attr[attrn++] = &p->dev_attr.attr;
2243 
2244 	buffer->buffer_group.name = kasprintf(GFP_KERNEL, "buffer%d", index);
2245 	if (!buffer->buffer_group.name) {
2246 		ret = -ENOMEM;
2247 		goto error_free_buffer_attrs;
2248 	}
2249 
2250 	ret = iio_device_register_sysfs_group(indio_dev, &buffer->buffer_group);
2251 	if (ret)
2252 		goto error_free_buffer_attr_group_name;
2253 
2254 	/* we only need to register the legacy groups for the first buffer */
2255 	if (index > 0)
2256 		return 0;
2257 
2258 	ret = iio_buffer_register_legacy_sysfs_groups(indio_dev, attr,
2259 						      buffer_attrcount,
2260 						      scan_el_attrcount);
2261 	if (ret)
2262 		goto error_free_buffer_attr_group_name;
2263 
2264 	return 0;
2265 
2266 error_free_buffer_attr_group_name:
2267 	kfree(buffer->buffer_group.name);
2268 error_free_buffer_attrs:
2269 	kfree(buffer->buffer_group.attrs);
2270 error_free_scan_mask:
2271 	bitmap_free(buffer->scan_mask);
2272 error_cleanup_dynamic:
2273 	iio_free_chan_devattr_list(&buffer->buffer_attr_list);
2274 
2275 	return ret;
2276 }
2277 
2278 static void __iio_buffer_free_sysfs_and_mask(struct iio_buffer *buffer,
2279 					     struct iio_dev *indio_dev,
2280 					     int index)
2281 {
2282 	if (index == 0)
2283 		iio_buffer_unregister_legacy_sysfs_groups(indio_dev);
2284 	bitmap_free(buffer->scan_mask);
2285 	kfree(buffer->buffer_group.name);
2286 	kfree(buffer->buffer_group.attrs);
2287 	iio_free_chan_devattr_list(&buffer->buffer_attr_list);
2288 }
2289 
2290 int iio_buffers_alloc_sysfs_and_mask(struct iio_dev *indio_dev)
2291 {
2292 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2293 	const struct iio_chan_spec *channels;
2294 	struct iio_buffer *buffer;
2295 	int ret, i, idx;
2296 	size_t sz;
2297 
2298 	channels = indio_dev->channels;
2299 	if (channels) {
2300 		int ml = 0;
2301 
2302 		for (i = 0; i < indio_dev->num_channels; i++)
2303 			ml = max(ml, channels[i].scan_index + 1);
2304 		ACCESS_PRIVATE(indio_dev, masklength) = ml;
2305 	}
2306 
2307 	if (!iio_dev_opaque->attached_buffers_cnt)
2308 		return 0;
2309 
2310 	for (idx = 0; idx < iio_dev_opaque->attached_buffers_cnt; idx++) {
2311 		buffer = iio_dev_opaque->attached_buffers[idx];
2312 		ret = __iio_buffer_alloc_sysfs_and_mask(buffer, indio_dev, idx);
2313 		if (ret)
2314 			goto error_unwind_sysfs_and_mask;
2315 	}
2316 
2317 	sz = sizeof(*iio_dev_opaque->buffer_ioctl_handler);
2318 	iio_dev_opaque->buffer_ioctl_handler = kzalloc(sz, GFP_KERNEL);
2319 	if (!iio_dev_opaque->buffer_ioctl_handler) {
2320 		ret = -ENOMEM;
2321 		goto error_unwind_sysfs_and_mask;
2322 	}
2323 
2324 	iio_dev_opaque->buffer_ioctl_handler->ioctl = iio_device_buffer_ioctl;
2325 	iio_device_ioctl_handler_register(indio_dev,
2326 					  iio_dev_opaque->buffer_ioctl_handler);
2327 
2328 	return 0;
2329 
2330 error_unwind_sysfs_and_mask:
2331 	while (idx--) {
2332 		buffer = iio_dev_opaque->attached_buffers[idx];
2333 		__iio_buffer_free_sysfs_and_mask(buffer, indio_dev, idx);
2334 	}
2335 	return ret;
2336 }
2337 
2338 void iio_buffers_free_sysfs_and_mask(struct iio_dev *indio_dev)
2339 {
2340 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2341 	struct iio_buffer *buffer;
2342 	int i;
2343 
2344 	if (!iio_dev_opaque->attached_buffers_cnt)
2345 		return;
2346 
2347 	iio_device_ioctl_handler_unregister(iio_dev_opaque->buffer_ioctl_handler);
2348 	kfree(iio_dev_opaque->buffer_ioctl_handler);
2349 
2350 	for (i = iio_dev_opaque->attached_buffers_cnt - 1; i >= 0; i--) {
2351 		buffer = iio_dev_opaque->attached_buffers[i];
2352 		__iio_buffer_free_sysfs_and_mask(buffer, indio_dev, i);
2353 	}
2354 }
2355 
2356 /**
2357  * iio_validate_scan_mask_onehot() - Validates that exactly one channel is selected
2358  * @indio_dev: the iio device
2359  * @mask: scan mask to be checked
2360  *
2361  * Return true if exactly one bit is set in the scan mask, false otherwise. It
2362  * can be used for devices where only one channel can be active for sampling at
2363  * a time.
2364  */
2365 bool iio_validate_scan_mask_onehot(struct iio_dev *indio_dev,
2366 				   const unsigned long *mask)
2367 {
2368 	return bitmap_weight(mask, iio_get_masklength(indio_dev)) == 1;
2369 }
2370 EXPORT_SYMBOL_GPL(iio_validate_scan_mask_onehot);
2371 
2372 static const void *iio_demux(struct iio_buffer *buffer,
2373 			     const void *datain)
2374 {
2375 	struct iio_demux_table *t;
2376 
2377 	if (list_empty(&buffer->demux_list))
2378 		return datain;
2379 	list_for_each_entry(t, &buffer->demux_list, l)
2380 		memcpy(buffer->demux_bounce + t->to,
2381 		       datain + t->from, t->length);
2382 
2383 	return buffer->demux_bounce;
2384 }
2385 
2386 static int iio_push_to_buffer(struct iio_buffer *buffer, const void *data)
2387 {
2388 	const void *dataout = iio_demux(buffer, data);
2389 	int ret;
2390 
2391 	ret = buffer->access->store_to(buffer, dataout);
2392 	if (ret)
2393 		return ret;
2394 
2395 	/*
2396 	 * We can't just test for watermark to decide if we wake the poll queue
2397 	 * because read may request less samples than the watermark.
2398 	 */
2399 	wake_up_interruptible_poll(&buffer->pollq, EPOLLIN | EPOLLRDNORM);
2400 	return 0;
2401 }
2402 
2403 /**
2404  * iio_push_to_buffers() - push to a registered buffer.
2405  * @indio_dev:		iio_dev structure for device.
2406  * @data:		Full scan.
2407  *
2408  * Context: Any context.
2409  * Return: 0 on success, negative error code on failure.
2410  */
2411 int iio_push_to_buffers(struct iio_dev *indio_dev, const void *data)
2412 {
2413 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2414 	int ret;
2415 	struct iio_buffer *buf;
2416 
2417 	list_for_each_entry(buf, &iio_dev_opaque->buffer_list, buffer_list) {
2418 		ret = iio_push_to_buffer(buf, data);
2419 		if (ret < 0)
2420 			return ret;
2421 	}
2422 
2423 	return 0;
2424 }
2425 EXPORT_SYMBOL_GPL(iio_push_to_buffers);
2426 
2427 /**
2428  * iio_push_to_buffers_with_ts_unaligned() - push to registered buffer,
2429  *    no alignment or space requirements.
2430  * @indio_dev:		iio_dev structure for device.
2431  * @data:		channel data excluding the timestamp.
2432  * @data_sz:		size of data.
2433  * @timestamp:		timestamp for the sample data.
2434  *
2435  * This special variant of iio_push_to_buffers_with_timestamp() does
2436  * not require space for the timestamp, or 8 byte alignment of data.
2437  * It does however require an allocation on first call and additional
2438  * copies on all calls, so should be avoided if possible.
2439  *
2440  * Context: May sleep.
2441  * Return: 0 on success, negative error code on failure.
2442  */
2443 int iio_push_to_buffers_with_ts_unaligned(struct iio_dev *indio_dev,
2444 					  const void *data,
2445 					  size_t data_sz,
2446 					  s64 timestamp)
2447 {
2448 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2449 
2450 	might_sleep();
2451 
2452 	/*
2453 	 * Conservative estimate - we can always safely copy the minimum
2454 	 * of either the data provided or the length of the destination buffer.
2455 	 * This relaxed limit allows the calling drivers to be lax about
2456 	 * tracking the size of the data they are pushing, at the cost of
2457 	 * unnecessary copying of padding.
2458 	 */
2459 	data_sz = min_t(size_t, indio_dev->scan_bytes, data_sz);
2460 	if (iio_dev_opaque->bounce_buffer_size !=  indio_dev->scan_bytes) {
2461 		void *bb;
2462 
2463 		bb = devm_krealloc(&indio_dev->dev,
2464 				   iio_dev_opaque->bounce_buffer,
2465 				   indio_dev->scan_bytes, GFP_KERNEL);
2466 		if (!bb)
2467 			return -ENOMEM;
2468 		iio_dev_opaque->bounce_buffer = bb;
2469 		iio_dev_opaque->bounce_buffer_size = indio_dev->scan_bytes;
2470 	}
2471 	memcpy(iio_dev_opaque->bounce_buffer, data, data_sz);
2472 	return iio_push_to_buffers_with_timestamp(indio_dev,
2473 						  iio_dev_opaque->bounce_buffer,
2474 						  timestamp);
2475 }
2476 EXPORT_SYMBOL_GPL(iio_push_to_buffers_with_ts_unaligned);
2477 
2478 /**
2479  * iio_buffer_release() - Free a buffer's resources
2480  * @ref: Pointer to the kref embedded in the iio_buffer struct
2481  *
2482  * This function is called when the last reference to the buffer has been
2483  * dropped. It will typically free all resources allocated by the buffer. Do not
2484  * call this function manually, always use iio_buffer_put() when done using a
2485  * buffer.
2486  */
2487 static void iio_buffer_release(struct kref *ref)
2488 {
2489 	struct iio_buffer *buffer = container_of(ref, struct iio_buffer, ref);
2490 
2491 	mutex_destroy(&buffer->dmabufs_mutex);
2492 	buffer->access->release(buffer);
2493 }
2494 
2495 /**
2496  * iio_buffer_get() - Grab a reference to the buffer
2497  * @buffer: The buffer to grab a reference for, may be NULL
2498  *
2499  * Returns the pointer to the buffer that was passed into the function.
2500  */
2501 struct iio_buffer *iio_buffer_get(struct iio_buffer *buffer)
2502 {
2503 	if (buffer)
2504 		kref_get(&buffer->ref);
2505 
2506 	return buffer;
2507 }
2508 EXPORT_SYMBOL_GPL(iio_buffer_get);
2509 
2510 /**
2511  * iio_buffer_put() - Release the reference to the buffer
2512  * @buffer: The buffer to release the reference for, may be NULL
2513  */
2514 void iio_buffer_put(struct iio_buffer *buffer)
2515 {
2516 	if (buffer)
2517 		kref_put(&buffer->ref, iio_buffer_release);
2518 }
2519 EXPORT_SYMBOL_GPL(iio_buffer_put);
2520 
2521 /**
2522  * iio_device_attach_buffer - Attach a buffer to a IIO device
2523  * @indio_dev: The device the buffer should be attached to
2524  * @buffer: The buffer to attach to the device
2525  *
2526  * Return 0 if successful, negative if error.
2527  *
2528  * This function attaches a buffer to a IIO device. The buffer stays attached to
2529  * the device until the device is freed. For legacy reasons, the first attached
2530  * buffer will also be assigned to 'indio_dev->buffer'.
2531  * The array allocated here, will be free'd via the iio_device_detach_buffers()
2532  * call which is handled by the iio_device_free().
2533  */
2534 int iio_device_attach_buffer(struct iio_dev *indio_dev,
2535 			     struct iio_buffer *buffer)
2536 {
2537 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2538 	struct iio_buffer **new, **old = iio_dev_opaque->attached_buffers;
2539 	unsigned int cnt = iio_dev_opaque->attached_buffers_cnt;
2540 
2541 	cnt++;
2542 
2543 	new = krealloc(old, sizeof(*new) * cnt, GFP_KERNEL);
2544 	if (!new)
2545 		return -ENOMEM;
2546 	iio_dev_opaque->attached_buffers = new;
2547 
2548 	buffer = iio_buffer_get(buffer);
2549 
2550 	/* first buffer is legacy; attach it to the IIO device directly */
2551 	if (!indio_dev->buffer)
2552 		indio_dev->buffer = buffer;
2553 
2554 	iio_dev_opaque->attached_buffers[cnt - 1] = buffer;
2555 	iio_dev_opaque->attached_buffers_cnt = cnt;
2556 
2557 	return 0;
2558 }
2559 EXPORT_SYMBOL_GPL(iio_device_attach_buffer);
2560