xref: /openbmc/linux/drivers/iio/industrialio-buffer.c (revision b804e2b76ac6d5559b99588e0190ac97b5597497)
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/anon_inodes.h>
13 #include <linux/kernel.h>
14 #include <linux/export.h>
15 #include <linux/device.h>
16 #include <linux/file.h>
17 #include <linux/fs.h>
18 #include <linux/cdev.h>
19 #include <linux/slab.h>
20 #include <linux/poll.h>
21 #include <linux/sched/signal.h>
22 
23 #include <linux/iio/iio.h>
24 #include <linux/iio/iio-opaque.h>
25 #include "iio_core.h"
26 #include "iio_core_trigger.h"
27 #include <linux/iio/sysfs.h>
28 #include <linux/iio/buffer.h>
29 #include <linux/iio/buffer_impl.h>
30 
31 static const char * const iio_endian_prefix[] = {
32 	[IIO_BE] = "be",
33 	[IIO_LE] = "le",
34 };
35 
36 static bool iio_buffer_is_active(struct iio_buffer *buf)
37 {
38 	return !list_empty(&buf->buffer_list);
39 }
40 
41 static size_t iio_buffer_data_available(struct iio_buffer *buf)
42 {
43 	return buf->access->data_available(buf);
44 }
45 
46 static int iio_buffer_flush_hwfifo(struct iio_dev *indio_dev,
47 				   struct iio_buffer *buf, size_t required)
48 {
49 	if (!indio_dev->info->hwfifo_flush_to_buffer)
50 		return -ENODEV;
51 
52 	return indio_dev->info->hwfifo_flush_to_buffer(indio_dev, required);
53 }
54 
55 static bool iio_buffer_ready(struct iio_dev *indio_dev, struct iio_buffer *buf,
56 			     size_t to_wait, int to_flush)
57 {
58 	size_t avail;
59 	int flushed = 0;
60 
61 	/* wakeup if the device was unregistered */
62 	if (!indio_dev->info)
63 		return true;
64 
65 	/* drain the buffer if it was disabled */
66 	if (!iio_buffer_is_active(buf)) {
67 		to_wait = min_t(size_t, to_wait, 1);
68 		to_flush = 0;
69 	}
70 
71 	avail = iio_buffer_data_available(buf);
72 
73 	if (avail >= to_wait) {
74 		/* force a flush for non-blocking reads */
75 		if (!to_wait && avail < to_flush)
76 			iio_buffer_flush_hwfifo(indio_dev, buf,
77 						to_flush - avail);
78 		return true;
79 	}
80 
81 	if (to_flush)
82 		flushed = iio_buffer_flush_hwfifo(indio_dev, buf,
83 						  to_wait - avail);
84 	if (flushed <= 0)
85 		return false;
86 
87 	if (avail + flushed >= to_wait)
88 		return true;
89 
90 	return false;
91 }
92 
93 /**
94  * iio_buffer_read() - chrdev read for buffer access
95  * @filp:	File structure pointer for the char device
96  * @buf:	Destination buffer for iio buffer read
97  * @n:		First n bytes to read
98  * @f_ps:	Long offset provided by the user as a seek position
99  *
100  * This function relies on all buffer implementations having an
101  * iio_buffer as their first element.
102  *
103  * Return: negative values corresponding to error codes or ret != 0
104  *	   for ending the reading activity
105  **/
106 static ssize_t iio_buffer_read(struct file *filp, char __user *buf,
107 			       size_t n, loff_t *f_ps)
108 {
109 	struct iio_dev_buffer_pair *ib = filp->private_data;
110 	struct iio_buffer *rb = ib->buffer;
111 	struct iio_dev *indio_dev = ib->indio_dev;
112 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
113 	size_t datum_size;
114 	size_t to_wait;
115 	int ret = 0;
116 
117 	if (!indio_dev->info)
118 		return -ENODEV;
119 
120 	if (!rb || !rb->access->read)
121 		return -EINVAL;
122 
123 	datum_size = rb->bytes_per_datum;
124 
125 	/*
126 	 * If datum_size is 0 there will never be anything to read from the
127 	 * buffer, so signal end of file now.
128 	 */
129 	if (!datum_size)
130 		return 0;
131 
132 	if (filp->f_flags & O_NONBLOCK)
133 		to_wait = 0;
134 	else
135 		to_wait = min_t(size_t, n / datum_size, rb->watermark);
136 
137 	add_wait_queue(&rb->pollq, &wait);
138 	do {
139 		if (!indio_dev->info) {
140 			ret = -ENODEV;
141 			break;
142 		}
143 
144 		if (!iio_buffer_ready(indio_dev, rb, to_wait, n / datum_size)) {
145 			if (signal_pending(current)) {
146 				ret = -ERESTARTSYS;
147 				break;
148 			}
149 
150 			wait_woken(&wait, TASK_INTERRUPTIBLE,
151 				   MAX_SCHEDULE_TIMEOUT);
152 			continue;
153 		}
154 
155 		ret = rb->access->read(rb, n, buf);
156 		if (ret == 0 && (filp->f_flags & O_NONBLOCK))
157 			ret = -EAGAIN;
158 	} while (ret == 0);
159 	remove_wait_queue(&rb->pollq, &wait);
160 
161 	return ret;
162 }
163 
164 /**
165  * iio_buffer_poll() - poll the buffer to find out if it has data
166  * @filp:	File structure pointer for device access
167  * @wait:	Poll table structure pointer for which the driver adds
168  *		a wait queue
169  *
170  * Return: (EPOLLIN | EPOLLRDNORM) if data is available for reading
171  *	   or 0 for other cases
172  */
173 static __poll_t iio_buffer_poll(struct file *filp,
174 				struct poll_table_struct *wait)
175 {
176 	struct iio_dev_buffer_pair *ib = filp->private_data;
177 	struct iio_buffer *rb = ib->buffer;
178 	struct iio_dev *indio_dev = ib->indio_dev;
179 
180 	if (!indio_dev->info || rb == NULL)
181 		return 0;
182 
183 	poll_wait(filp, &rb->pollq, wait);
184 	if (iio_buffer_ready(indio_dev, rb, rb->watermark, 0))
185 		return EPOLLIN | EPOLLRDNORM;
186 	return 0;
187 }
188 
189 ssize_t iio_buffer_read_wrapper(struct file *filp, char __user *buf,
190 				size_t n, loff_t *f_ps)
191 {
192 	struct iio_dev_buffer_pair *ib = filp->private_data;
193 	struct iio_buffer *rb = ib->buffer;
194 
195 	/* check if buffer was opened through new API */
196 	if (test_bit(IIO_BUSY_BIT_POS, &rb->flags))
197 		return -EBUSY;
198 
199 	return iio_buffer_read(filp, buf, n, f_ps);
200 }
201 
202 __poll_t iio_buffer_poll_wrapper(struct file *filp,
203 				 struct poll_table_struct *wait)
204 {
205 	struct iio_dev_buffer_pair *ib = filp->private_data;
206 	struct iio_buffer *rb = ib->buffer;
207 
208 	/* check if buffer was opened through new API */
209 	if (test_bit(IIO_BUSY_BIT_POS, &rb->flags))
210 		return 0;
211 
212 	return iio_buffer_poll(filp, wait);
213 }
214 
215 /**
216  * iio_buffer_wakeup_poll - Wakes up the buffer waitqueue
217  * @indio_dev: The IIO device
218  *
219  * Wakes up the event waitqueue used for poll(). Should usually
220  * be called when the device is unregistered.
221  */
222 void iio_buffer_wakeup_poll(struct iio_dev *indio_dev)
223 {
224 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
225 	struct iio_buffer *buffer;
226 	unsigned int i;
227 
228 	for (i = 0; i < iio_dev_opaque->attached_buffers_cnt; i++) {
229 		buffer = iio_dev_opaque->attached_buffers[i];
230 		wake_up(&buffer->pollq);
231 	}
232 }
233 
234 void iio_buffer_init(struct iio_buffer *buffer)
235 {
236 	INIT_LIST_HEAD(&buffer->demux_list);
237 	INIT_LIST_HEAD(&buffer->buffer_list);
238 	init_waitqueue_head(&buffer->pollq);
239 	kref_init(&buffer->ref);
240 	if (!buffer->watermark)
241 		buffer->watermark = 1;
242 }
243 EXPORT_SYMBOL(iio_buffer_init);
244 
245 void iio_device_detach_buffers(struct iio_dev *indio_dev)
246 {
247 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
248 	struct iio_buffer *buffer;
249 	unsigned int i;
250 
251 	for (i = 0; i < iio_dev_opaque->attached_buffers_cnt; i++) {
252 		buffer = iio_dev_opaque->attached_buffers[i];
253 		iio_buffer_put(buffer);
254 	}
255 
256 	kfree(iio_dev_opaque->attached_buffers);
257 }
258 
259 static ssize_t iio_show_scan_index(struct device *dev,
260 				   struct device_attribute *attr,
261 				   char *buf)
262 {
263 	return sysfs_emit(buf, "%u\n", to_iio_dev_attr(attr)->c->scan_index);
264 }
265 
266 static ssize_t iio_show_fixed_type(struct device *dev,
267 				   struct device_attribute *attr,
268 				   char *buf)
269 {
270 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
271 	u8 type = this_attr->c->scan_type.endianness;
272 
273 	if (type == IIO_CPU) {
274 #ifdef __LITTLE_ENDIAN
275 		type = IIO_LE;
276 #else
277 		type = IIO_BE;
278 #endif
279 	}
280 	if (this_attr->c->scan_type.repeat > 1)
281 		return sysfs_emit(buf, "%s:%c%d/%dX%d>>%u\n",
282 		       iio_endian_prefix[type],
283 		       this_attr->c->scan_type.sign,
284 		       this_attr->c->scan_type.realbits,
285 		       this_attr->c->scan_type.storagebits,
286 		       this_attr->c->scan_type.repeat,
287 		       this_attr->c->scan_type.shift);
288 	else
289 		return sysfs_emit(buf, "%s:%c%d/%d>>%u\n",
290 		       iio_endian_prefix[type],
291 		       this_attr->c->scan_type.sign,
292 		       this_attr->c->scan_type.realbits,
293 		       this_attr->c->scan_type.storagebits,
294 		       this_attr->c->scan_type.shift);
295 }
296 
297 static ssize_t iio_scan_el_show(struct device *dev,
298 				struct device_attribute *attr,
299 				char *buf)
300 {
301 	int ret;
302 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
303 
304 	/* Ensure ret is 0 or 1. */
305 	ret = !!test_bit(to_iio_dev_attr(attr)->address,
306 		       buffer->scan_mask);
307 
308 	return sysfs_emit(buf, "%d\n", ret);
309 }
310 
311 /* Note NULL used as error indicator as it doesn't make sense. */
312 static const unsigned long *iio_scan_mask_match(const unsigned long *av_masks,
313 					  unsigned int masklength,
314 					  const unsigned long *mask,
315 					  bool strict)
316 {
317 	if (bitmap_empty(mask, masklength))
318 		return NULL;
319 	while (*av_masks) {
320 		if (strict) {
321 			if (bitmap_equal(mask, av_masks, masklength))
322 				return av_masks;
323 		} else {
324 			if (bitmap_subset(mask, av_masks, masklength))
325 				return av_masks;
326 		}
327 		av_masks += BITS_TO_LONGS(masklength);
328 	}
329 	return NULL;
330 }
331 
332 static bool iio_validate_scan_mask(struct iio_dev *indio_dev,
333 	const unsigned long *mask)
334 {
335 	if (!indio_dev->setup_ops->validate_scan_mask)
336 		return true;
337 
338 	return indio_dev->setup_ops->validate_scan_mask(indio_dev, mask);
339 }
340 
341 /**
342  * iio_scan_mask_set() - set particular bit in the scan mask
343  * @indio_dev: the iio device
344  * @buffer: the buffer whose scan mask we are interested in
345  * @bit: the bit to be set.
346  *
347  * Note that at this point we have no way of knowing what other
348  * buffers might request, hence this code only verifies that the
349  * individual buffers request is plausible.
350  */
351 static int iio_scan_mask_set(struct iio_dev *indio_dev,
352 		      struct iio_buffer *buffer, int bit)
353 {
354 	const unsigned long *mask;
355 	unsigned long *trialmask;
356 
357 	trialmask = bitmap_zalloc(indio_dev->masklength, GFP_KERNEL);
358 	if (trialmask == NULL)
359 		return -ENOMEM;
360 	if (!indio_dev->masklength) {
361 		WARN(1, "Trying to set scanmask prior to registering buffer\n");
362 		goto err_invalid_mask;
363 	}
364 	bitmap_copy(trialmask, buffer->scan_mask, indio_dev->masklength);
365 	set_bit(bit, trialmask);
366 
367 	if (!iio_validate_scan_mask(indio_dev, trialmask))
368 		goto err_invalid_mask;
369 
370 	if (indio_dev->available_scan_masks) {
371 		mask = iio_scan_mask_match(indio_dev->available_scan_masks,
372 					   indio_dev->masklength,
373 					   trialmask, false);
374 		if (!mask)
375 			goto err_invalid_mask;
376 	}
377 	bitmap_copy(buffer->scan_mask, trialmask, indio_dev->masklength);
378 
379 	bitmap_free(trialmask);
380 
381 	return 0;
382 
383 err_invalid_mask:
384 	bitmap_free(trialmask);
385 	return -EINVAL;
386 }
387 
388 static int iio_scan_mask_clear(struct iio_buffer *buffer, int bit)
389 {
390 	clear_bit(bit, buffer->scan_mask);
391 	return 0;
392 }
393 
394 static int iio_scan_mask_query(struct iio_dev *indio_dev,
395 			       struct iio_buffer *buffer, int bit)
396 {
397 	if (bit > indio_dev->masklength)
398 		return -EINVAL;
399 
400 	if (!buffer->scan_mask)
401 		return 0;
402 
403 	/* Ensure return value is 0 or 1. */
404 	return !!test_bit(bit, buffer->scan_mask);
405 };
406 
407 static ssize_t iio_scan_el_store(struct device *dev,
408 				 struct device_attribute *attr,
409 				 const char *buf,
410 				 size_t len)
411 {
412 	int ret;
413 	bool state;
414 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
415 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
416 	struct iio_buffer *buffer = this_attr->buffer;
417 
418 	ret = strtobool(buf, &state);
419 	if (ret < 0)
420 		return ret;
421 	mutex_lock(&indio_dev->mlock);
422 	if (iio_buffer_is_active(buffer)) {
423 		ret = -EBUSY;
424 		goto error_ret;
425 	}
426 	ret = iio_scan_mask_query(indio_dev, buffer, this_attr->address);
427 	if (ret < 0)
428 		goto error_ret;
429 	if (!state && ret) {
430 		ret = iio_scan_mask_clear(buffer, this_attr->address);
431 		if (ret)
432 			goto error_ret;
433 	} else if (state && !ret) {
434 		ret = iio_scan_mask_set(indio_dev, buffer, this_attr->address);
435 		if (ret)
436 			goto error_ret;
437 	}
438 
439 error_ret:
440 	mutex_unlock(&indio_dev->mlock);
441 
442 	return ret < 0 ? ret : len;
443 
444 }
445 
446 static ssize_t iio_scan_el_ts_show(struct device *dev,
447 				   struct device_attribute *attr,
448 				   char *buf)
449 {
450 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
451 
452 	return sysfs_emit(buf, "%d\n", buffer->scan_timestamp);
453 }
454 
455 static ssize_t iio_scan_el_ts_store(struct device *dev,
456 				    struct device_attribute *attr,
457 				    const char *buf,
458 				    size_t len)
459 {
460 	int ret;
461 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
462 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
463 	bool state;
464 
465 	ret = strtobool(buf, &state);
466 	if (ret < 0)
467 		return ret;
468 
469 	mutex_lock(&indio_dev->mlock);
470 	if (iio_buffer_is_active(buffer)) {
471 		ret = -EBUSY;
472 		goto error_ret;
473 	}
474 	buffer->scan_timestamp = state;
475 error_ret:
476 	mutex_unlock(&indio_dev->mlock);
477 
478 	return ret ? ret : len;
479 }
480 
481 static int iio_buffer_add_channel_sysfs(struct iio_dev *indio_dev,
482 					struct iio_buffer *buffer,
483 					const struct iio_chan_spec *chan)
484 {
485 	int ret, attrcount = 0;
486 
487 	ret = __iio_add_chan_devattr("index",
488 				     chan,
489 				     &iio_show_scan_index,
490 				     NULL,
491 				     0,
492 				     IIO_SEPARATE,
493 				     &indio_dev->dev,
494 				     buffer,
495 				     &buffer->buffer_attr_list);
496 	if (ret)
497 		return ret;
498 	attrcount++;
499 	ret = __iio_add_chan_devattr("type",
500 				     chan,
501 				     &iio_show_fixed_type,
502 				     NULL,
503 				     0,
504 				     0,
505 				     &indio_dev->dev,
506 				     buffer,
507 				     &buffer->buffer_attr_list);
508 	if (ret)
509 		return ret;
510 	attrcount++;
511 	if (chan->type != IIO_TIMESTAMP)
512 		ret = __iio_add_chan_devattr("en",
513 					     chan,
514 					     &iio_scan_el_show,
515 					     &iio_scan_el_store,
516 					     chan->scan_index,
517 					     0,
518 					     &indio_dev->dev,
519 					     buffer,
520 					     &buffer->buffer_attr_list);
521 	else
522 		ret = __iio_add_chan_devattr("en",
523 					     chan,
524 					     &iio_scan_el_ts_show,
525 					     &iio_scan_el_ts_store,
526 					     chan->scan_index,
527 					     0,
528 					     &indio_dev->dev,
529 					     buffer,
530 					     &buffer->buffer_attr_list);
531 	if (ret)
532 		return ret;
533 	attrcount++;
534 	ret = attrcount;
535 	return ret;
536 }
537 
538 static ssize_t iio_buffer_read_length(struct device *dev,
539 				      struct device_attribute *attr,
540 				      char *buf)
541 {
542 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
543 
544 	return sysfs_emit(buf, "%d\n", buffer->length);
545 }
546 
547 static ssize_t iio_buffer_write_length(struct device *dev,
548 				       struct device_attribute *attr,
549 				       const char *buf, size_t len)
550 {
551 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
552 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
553 	unsigned int val;
554 	int ret;
555 
556 	ret = kstrtouint(buf, 10, &val);
557 	if (ret)
558 		return ret;
559 
560 	if (val == buffer->length)
561 		return len;
562 
563 	mutex_lock(&indio_dev->mlock);
564 	if (iio_buffer_is_active(buffer)) {
565 		ret = -EBUSY;
566 	} else {
567 		buffer->access->set_length(buffer, val);
568 		ret = 0;
569 	}
570 	if (ret)
571 		goto out;
572 	if (buffer->length && buffer->length < buffer->watermark)
573 		buffer->watermark = buffer->length;
574 out:
575 	mutex_unlock(&indio_dev->mlock);
576 
577 	return ret ? ret : len;
578 }
579 
580 static ssize_t iio_buffer_show_enable(struct device *dev,
581 				      struct device_attribute *attr,
582 				      char *buf)
583 {
584 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
585 
586 	return sysfs_emit(buf, "%d\n", iio_buffer_is_active(buffer));
587 }
588 
589 static unsigned int iio_storage_bytes_for_si(struct iio_dev *indio_dev,
590 					     unsigned int scan_index)
591 {
592 	const struct iio_chan_spec *ch;
593 	unsigned int bytes;
594 
595 	ch = iio_find_channel_from_si(indio_dev, scan_index);
596 	bytes = ch->scan_type.storagebits / 8;
597 	if (ch->scan_type.repeat > 1)
598 		bytes *= ch->scan_type.repeat;
599 	return bytes;
600 }
601 
602 static unsigned int iio_storage_bytes_for_timestamp(struct iio_dev *indio_dev)
603 {
604 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
605 
606 	return iio_storage_bytes_for_si(indio_dev,
607 					iio_dev_opaque->scan_index_timestamp);
608 }
609 
610 static int iio_compute_scan_bytes(struct iio_dev *indio_dev,
611 				const unsigned long *mask, bool timestamp)
612 {
613 	unsigned bytes = 0;
614 	int length, i, largest = 0;
615 
616 	/* How much space will the demuxed element take? */
617 	for_each_set_bit(i, mask,
618 			 indio_dev->masklength) {
619 		length = iio_storage_bytes_for_si(indio_dev, i);
620 		bytes = ALIGN(bytes, length);
621 		bytes += length;
622 		largest = max(largest, length);
623 	}
624 
625 	if (timestamp) {
626 		length = iio_storage_bytes_for_timestamp(indio_dev);
627 		bytes = ALIGN(bytes, length);
628 		bytes += length;
629 		largest = max(largest, length);
630 	}
631 
632 	bytes = ALIGN(bytes, largest);
633 	return bytes;
634 }
635 
636 static void iio_buffer_activate(struct iio_dev *indio_dev,
637 	struct iio_buffer *buffer)
638 {
639 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
640 
641 	iio_buffer_get(buffer);
642 	list_add(&buffer->buffer_list, &iio_dev_opaque->buffer_list);
643 }
644 
645 static void iio_buffer_deactivate(struct iio_buffer *buffer)
646 {
647 	list_del_init(&buffer->buffer_list);
648 	wake_up_interruptible(&buffer->pollq);
649 	iio_buffer_put(buffer);
650 }
651 
652 static void iio_buffer_deactivate_all(struct iio_dev *indio_dev)
653 {
654 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
655 	struct iio_buffer *buffer, *_buffer;
656 
657 	list_for_each_entry_safe(buffer, _buffer,
658 			&iio_dev_opaque->buffer_list, buffer_list)
659 		iio_buffer_deactivate(buffer);
660 }
661 
662 static int iio_buffer_enable(struct iio_buffer *buffer,
663 	struct iio_dev *indio_dev)
664 {
665 	if (!buffer->access->enable)
666 		return 0;
667 	return buffer->access->enable(buffer, indio_dev);
668 }
669 
670 static int iio_buffer_disable(struct iio_buffer *buffer,
671 	struct iio_dev *indio_dev)
672 {
673 	if (!buffer->access->disable)
674 		return 0;
675 	return buffer->access->disable(buffer, indio_dev);
676 }
677 
678 static void iio_buffer_update_bytes_per_datum(struct iio_dev *indio_dev,
679 	struct iio_buffer *buffer)
680 {
681 	unsigned int bytes;
682 
683 	if (!buffer->access->set_bytes_per_datum)
684 		return;
685 
686 	bytes = iio_compute_scan_bytes(indio_dev, buffer->scan_mask,
687 		buffer->scan_timestamp);
688 
689 	buffer->access->set_bytes_per_datum(buffer, bytes);
690 }
691 
692 static int iio_buffer_request_update(struct iio_dev *indio_dev,
693 	struct iio_buffer *buffer)
694 {
695 	int ret;
696 
697 	iio_buffer_update_bytes_per_datum(indio_dev, buffer);
698 	if (buffer->access->request_update) {
699 		ret = buffer->access->request_update(buffer);
700 		if (ret) {
701 			dev_dbg(&indio_dev->dev,
702 			       "Buffer not started: buffer parameter update failed (%d)\n",
703 				ret);
704 			return ret;
705 		}
706 	}
707 
708 	return 0;
709 }
710 
711 static void iio_free_scan_mask(struct iio_dev *indio_dev,
712 	const unsigned long *mask)
713 {
714 	/* If the mask is dynamically allocated free it, otherwise do nothing */
715 	if (!indio_dev->available_scan_masks)
716 		bitmap_free(mask);
717 }
718 
719 struct iio_device_config {
720 	unsigned int mode;
721 	unsigned int watermark;
722 	const unsigned long *scan_mask;
723 	unsigned int scan_bytes;
724 	bool scan_timestamp;
725 };
726 
727 static int iio_verify_update(struct iio_dev *indio_dev,
728 	struct iio_buffer *insert_buffer, struct iio_buffer *remove_buffer,
729 	struct iio_device_config *config)
730 {
731 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
732 	unsigned long *compound_mask;
733 	const unsigned long *scan_mask;
734 	bool strict_scanmask = false;
735 	struct iio_buffer *buffer;
736 	bool scan_timestamp;
737 	unsigned int modes;
738 
739 	if (insert_buffer &&
740 	    bitmap_empty(insert_buffer->scan_mask, indio_dev->masklength)) {
741 		dev_dbg(&indio_dev->dev,
742 			"At least one scan element must be enabled first\n");
743 		return -EINVAL;
744 	}
745 
746 	memset(config, 0, sizeof(*config));
747 	config->watermark = ~0;
748 
749 	/*
750 	 * If there is just one buffer and we are removing it there is nothing
751 	 * to verify.
752 	 */
753 	if (remove_buffer && !insert_buffer &&
754 		list_is_singular(&iio_dev_opaque->buffer_list))
755 			return 0;
756 
757 	modes = indio_dev->modes;
758 
759 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list) {
760 		if (buffer == remove_buffer)
761 			continue;
762 		modes &= buffer->access->modes;
763 		config->watermark = min(config->watermark, buffer->watermark);
764 	}
765 
766 	if (insert_buffer) {
767 		modes &= insert_buffer->access->modes;
768 		config->watermark = min(config->watermark,
769 			insert_buffer->watermark);
770 	}
771 
772 	/* Definitely possible for devices to support both of these. */
773 	if ((modes & INDIO_BUFFER_TRIGGERED) && indio_dev->trig) {
774 		config->mode = INDIO_BUFFER_TRIGGERED;
775 	} else if (modes & INDIO_BUFFER_HARDWARE) {
776 		/*
777 		 * Keep things simple for now and only allow a single buffer to
778 		 * be connected in hardware mode.
779 		 */
780 		if (insert_buffer && !list_empty(&iio_dev_opaque->buffer_list))
781 			return -EINVAL;
782 		config->mode = INDIO_BUFFER_HARDWARE;
783 		strict_scanmask = true;
784 	} else if (modes & INDIO_BUFFER_SOFTWARE) {
785 		config->mode = INDIO_BUFFER_SOFTWARE;
786 	} else {
787 		/* Can only occur on first buffer */
788 		if (indio_dev->modes & INDIO_BUFFER_TRIGGERED)
789 			dev_dbg(&indio_dev->dev, "Buffer not started: no trigger\n");
790 		return -EINVAL;
791 	}
792 
793 	/* What scan mask do we actually have? */
794 	compound_mask = bitmap_zalloc(indio_dev->masklength, GFP_KERNEL);
795 	if (compound_mask == NULL)
796 		return -ENOMEM;
797 
798 	scan_timestamp = false;
799 
800 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list) {
801 		if (buffer == remove_buffer)
802 			continue;
803 		bitmap_or(compound_mask, compound_mask, buffer->scan_mask,
804 			  indio_dev->masklength);
805 		scan_timestamp |= buffer->scan_timestamp;
806 	}
807 
808 	if (insert_buffer) {
809 		bitmap_or(compound_mask, compound_mask,
810 			  insert_buffer->scan_mask, indio_dev->masklength);
811 		scan_timestamp |= insert_buffer->scan_timestamp;
812 	}
813 
814 	if (indio_dev->available_scan_masks) {
815 		scan_mask = iio_scan_mask_match(indio_dev->available_scan_masks,
816 				    indio_dev->masklength,
817 				    compound_mask,
818 				    strict_scanmask);
819 		bitmap_free(compound_mask);
820 		if (scan_mask == NULL)
821 			return -EINVAL;
822 	} else {
823 	    scan_mask = compound_mask;
824 	}
825 
826 	config->scan_bytes = iio_compute_scan_bytes(indio_dev,
827 				    scan_mask, scan_timestamp);
828 	config->scan_mask = scan_mask;
829 	config->scan_timestamp = scan_timestamp;
830 
831 	return 0;
832 }
833 
834 /**
835  * struct iio_demux_table - table describing demux memcpy ops
836  * @from:	index to copy from
837  * @to:		index to copy to
838  * @length:	how many bytes to copy
839  * @l:		list head used for management
840  */
841 struct iio_demux_table {
842 	unsigned from;
843 	unsigned to;
844 	unsigned length;
845 	struct list_head l;
846 };
847 
848 static void iio_buffer_demux_free(struct iio_buffer *buffer)
849 {
850 	struct iio_demux_table *p, *q;
851 	list_for_each_entry_safe(p, q, &buffer->demux_list, l) {
852 		list_del(&p->l);
853 		kfree(p);
854 	}
855 }
856 
857 static int iio_buffer_add_demux(struct iio_buffer *buffer,
858 	struct iio_demux_table **p, unsigned int in_loc, unsigned int out_loc,
859 	unsigned int length)
860 {
861 
862 	if (*p && (*p)->from + (*p)->length == in_loc &&
863 		(*p)->to + (*p)->length == out_loc) {
864 		(*p)->length += length;
865 	} else {
866 		*p = kmalloc(sizeof(**p), GFP_KERNEL);
867 		if (*p == NULL)
868 			return -ENOMEM;
869 		(*p)->from = in_loc;
870 		(*p)->to = out_loc;
871 		(*p)->length = length;
872 		list_add_tail(&(*p)->l, &buffer->demux_list);
873 	}
874 
875 	return 0;
876 }
877 
878 static int iio_buffer_update_demux(struct iio_dev *indio_dev,
879 				   struct iio_buffer *buffer)
880 {
881 	int ret, in_ind = -1, out_ind, length;
882 	unsigned in_loc = 0, out_loc = 0;
883 	struct iio_demux_table *p = NULL;
884 
885 	/* Clear out any old demux */
886 	iio_buffer_demux_free(buffer);
887 	kfree(buffer->demux_bounce);
888 	buffer->demux_bounce = NULL;
889 
890 	/* First work out which scan mode we will actually have */
891 	if (bitmap_equal(indio_dev->active_scan_mask,
892 			 buffer->scan_mask,
893 			 indio_dev->masklength))
894 		return 0;
895 
896 	/* Now we have the two masks, work from least sig and build up sizes */
897 	for_each_set_bit(out_ind,
898 			 buffer->scan_mask,
899 			 indio_dev->masklength) {
900 		in_ind = find_next_bit(indio_dev->active_scan_mask,
901 				       indio_dev->masklength,
902 				       in_ind + 1);
903 		while (in_ind != out_ind) {
904 			length = iio_storage_bytes_for_si(indio_dev, in_ind);
905 			/* Make sure we are aligned */
906 			in_loc = roundup(in_loc, length) + length;
907 			in_ind = find_next_bit(indio_dev->active_scan_mask,
908 					       indio_dev->masklength,
909 					       in_ind + 1);
910 		}
911 		length = iio_storage_bytes_for_si(indio_dev, in_ind);
912 		out_loc = roundup(out_loc, length);
913 		in_loc = roundup(in_loc, length);
914 		ret = iio_buffer_add_demux(buffer, &p, in_loc, out_loc, length);
915 		if (ret)
916 			goto error_clear_mux_table;
917 		out_loc += length;
918 		in_loc += length;
919 	}
920 	/* Relies on scan_timestamp being last */
921 	if (buffer->scan_timestamp) {
922 		length = iio_storage_bytes_for_timestamp(indio_dev);
923 		out_loc = roundup(out_loc, length);
924 		in_loc = roundup(in_loc, length);
925 		ret = iio_buffer_add_demux(buffer, &p, in_loc, out_loc, length);
926 		if (ret)
927 			goto error_clear_mux_table;
928 		out_loc += length;
929 		in_loc += length;
930 	}
931 	buffer->demux_bounce = kzalloc(out_loc, GFP_KERNEL);
932 	if (buffer->demux_bounce == NULL) {
933 		ret = -ENOMEM;
934 		goto error_clear_mux_table;
935 	}
936 	return 0;
937 
938 error_clear_mux_table:
939 	iio_buffer_demux_free(buffer);
940 
941 	return ret;
942 }
943 
944 static int iio_update_demux(struct iio_dev *indio_dev)
945 {
946 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
947 	struct iio_buffer *buffer;
948 	int ret;
949 
950 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list) {
951 		ret = iio_buffer_update_demux(indio_dev, buffer);
952 		if (ret < 0)
953 			goto error_clear_mux_table;
954 	}
955 	return 0;
956 
957 error_clear_mux_table:
958 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list)
959 		iio_buffer_demux_free(buffer);
960 
961 	return ret;
962 }
963 
964 static int iio_enable_buffers(struct iio_dev *indio_dev,
965 	struct iio_device_config *config)
966 {
967 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
968 	struct iio_buffer *buffer;
969 	int ret;
970 
971 	indio_dev->active_scan_mask = config->scan_mask;
972 	indio_dev->scan_timestamp = config->scan_timestamp;
973 	indio_dev->scan_bytes = config->scan_bytes;
974 	indio_dev->currentmode = config->mode;
975 
976 	iio_update_demux(indio_dev);
977 
978 	/* Wind up again */
979 	if (indio_dev->setup_ops->preenable) {
980 		ret = indio_dev->setup_ops->preenable(indio_dev);
981 		if (ret) {
982 			dev_dbg(&indio_dev->dev,
983 			       "Buffer not started: buffer preenable failed (%d)\n", ret);
984 			goto err_undo_config;
985 		}
986 	}
987 
988 	if (indio_dev->info->update_scan_mode) {
989 		ret = indio_dev->info
990 			->update_scan_mode(indio_dev,
991 					   indio_dev->active_scan_mask);
992 		if (ret < 0) {
993 			dev_dbg(&indio_dev->dev,
994 				"Buffer not started: update scan mode failed (%d)\n",
995 				ret);
996 			goto err_run_postdisable;
997 		}
998 	}
999 
1000 	if (indio_dev->info->hwfifo_set_watermark)
1001 		indio_dev->info->hwfifo_set_watermark(indio_dev,
1002 			config->watermark);
1003 
1004 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list) {
1005 		ret = iio_buffer_enable(buffer, indio_dev);
1006 		if (ret)
1007 			goto err_disable_buffers;
1008 	}
1009 
1010 	if (indio_dev->currentmode == INDIO_BUFFER_TRIGGERED) {
1011 		ret = iio_trigger_attach_poll_func(indio_dev->trig,
1012 						   indio_dev->pollfunc);
1013 		if (ret)
1014 			goto err_disable_buffers;
1015 	}
1016 
1017 	if (indio_dev->setup_ops->postenable) {
1018 		ret = indio_dev->setup_ops->postenable(indio_dev);
1019 		if (ret) {
1020 			dev_dbg(&indio_dev->dev,
1021 			       "Buffer not started: postenable failed (%d)\n", ret);
1022 			goto err_detach_pollfunc;
1023 		}
1024 	}
1025 
1026 	return 0;
1027 
1028 err_detach_pollfunc:
1029 	if (indio_dev->currentmode == INDIO_BUFFER_TRIGGERED) {
1030 		iio_trigger_detach_poll_func(indio_dev->trig,
1031 					     indio_dev->pollfunc);
1032 	}
1033 err_disable_buffers:
1034 	list_for_each_entry_continue_reverse(buffer, &iio_dev_opaque->buffer_list,
1035 					     buffer_list)
1036 		iio_buffer_disable(buffer, indio_dev);
1037 err_run_postdisable:
1038 	if (indio_dev->setup_ops->postdisable)
1039 		indio_dev->setup_ops->postdisable(indio_dev);
1040 err_undo_config:
1041 	indio_dev->currentmode = INDIO_DIRECT_MODE;
1042 	indio_dev->active_scan_mask = NULL;
1043 
1044 	return ret;
1045 }
1046 
1047 static int iio_disable_buffers(struct iio_dev *indio_dev)
1048 {
1049 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1050 	struct iio_buffer *buffer;
1051 	int ret = 0;
1052 	int ret2;
1053 
1054 	/* Wind down existing buffers - iff there are any */
1055 	if (list_empty(&iio_dev_opaque->buffer_list))
1056 		return 0;
1057 
1058 	/*
1059 	 * If things go wrong at some step in disable we still need to continue
1060 	 * to perform the other steps, otherwise we leave the device in a
1061 	 * inconsistent state. We return the error code for the first error we
1062 	 * encountered.
1063 	 */
1064 
1065 	if (indio_dev->setup_ops->predisable) {
1066 		ret2 = indio_dev->setup_ops->predisable(indio_dev);
1067 		if (ret2 && !ret)
1068 			ret = ret2;
1069 	}
1070 
1071 	if (indio_dev->currentmode == INDIO_BUFFER_TRIGGERED) {
1072 		iio_trigger_detach_poll_func(indio_dev->trig,
1073 					     indio_dev->pollfunc);
1074 	}
1075 
1076 	list_for_each_entry(buffer, &iio_dev_opaque->buffer_list, buffer_list) {
1077 		ret2 = iio_buffer_disable(buffer, indio_dev);
1078 		if (ret2 && !ret)
1079 			ret = ret2;
1080 	}
1081 
1082 	if (indio_dev->setup_ops->postdisable) {
1083 		ret2 = indio_dev->setup_ops->postdisable(indio_dev);
1084 		if (ret2 && !ret)
1085 			ret = ret2;
1086 	}
1087 
1088 	iio_free_scan_mask(indio_dev, indio_dev->active_scan_mask);
1089 	indio_dev->active_scan_mask = NULL;
1090 	indio_dev->currentmode = INDIO_DIRECT_MODE;
1091 
1092 	return ret;
1093 }
1094 
1095 static int __iio_update_buffers(struct iio_dev *indio_dev,
1096 		       struct iio_buffer *insert_buffer,
1097 		       struct iio_buffer *remove_buffer)
1098 {
1099 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1100 	struct iio_device_config new_config;
1101 	int ret;
1102 
1103 	ret = iio_verify_update(indio_dev, insert_buffer, remove_buffer,
1104 		&new_config);
1105 	if (ret)
1106 		return ret;
1107 
1108 	if (insert_buffer) {
1109 		ret = iio_buffer_request_update(indio_dev, insert_buffer);
1110 		if (ret)
1111 			goto err_free_config;
1112 	}
1113 
1114 	ret = iio_disable_buffers(indio_dev);
1115 	if (ret)
1116 		goto err_deactivate_all;
1117 
1118 	if (remove_buffer)
1119 		iio_buffer_deactivate(remove_buffer);
1120 	if (insert_buffer)
1121 		iio_buffer_activate(indio_dev, insert_buffer);
1122 
1123 	/* If no buffers in list, we are done */
1124 	if (list_empty(&iio_dev_opaque->buffer_list))
1125 		return 0;
1126 
1127 	ret = iio_enable_buffers(indio_dev, &new_config);
1128 	if (ret)
1129 		goto err_deactivate_all;
1130 
1131 	return 0;
1132 
1133 err_deactivate_all:
1134 	/*
1135 	 * We've already verified that the config is valid earlier. If things go
1136 	 * wrong in either enable or disable the most likely reason is an IO
1137 	 * error from the device. In this case there is no good recovery
1138 	 * strategy. Just make sure to disable everything and leave the device
1139 	 * in a sane state.  With a bit of luck the device might come back to
1140 	 * life again later and userspace can try again.
1141 	 */
1142 	iio_buffer_deactivate_all(indio_dev);
1143 
1144 err_free_config:
1145 	iio_free_scan_mask(indio_dev, new_config.scan_mask);
1146 	return ret;
1147 }
1148 
1149 int iio_update_buffers(struct iio_dev *indio_dev,
1150 		       struct iio_buffer *insert_buffer,
1151 		       struct iio_buffer *remove_buffer)
1152 {
1153 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1154 	int ret;
1155 
1156 	if (insert_buffer == remove_buffer)
1157 		return 0;
1158 
1159 	mutex_lock(&iio_dev_opaque->info_exist_lock);
1160 	mutex_lock(&indio_dev->mlock);
1161 
1162 	if (insert_buffer && iio_buffer_is_active(insert_buffer))
1163 		insert_buffer = NULL;
1164 
1165 	if (remove_buffer && !iio_buffer_is_active(remove_buffer))
1166 		remove_buffer = NULL;
1167 
1168 	if (!insert_buffer && !remove_buffer) {
1169 		ret = 0;
1170 		goto out_unlock;
1171 	}
1172 
1173 	if (indio_dev->info == NULL) {
1174 		ret = -ENODEV;
1175 		goto out_unlock;
1176 	}
1177 
1178 	ret = __iio_update_buffers(indio_dev, insert_buffer, remove_buffer);
1179 
1180 out_unlock:
1181 	mutex_unlock(&indio_dev->mlock);
1182 	mutex_unlock(&iio_dev_opaque->info_exist_lock);
1183 
1184 	return ret;
1185 }
1186 EXPORT_SYMBOL_GPL(iio_update_buffers);
1187 
1188 void iio_disable_all_buffers(struct iio_dev *indio_dev)
1189 {
1190 	iio_disable_buffers(indio_dev);
1191 	iio_buffer_deactivate_all(indio_dev);
1192 }
1193 
1194 static ssize_t iio_buffer_store_enable(struct device *dev,
1195 				       struct device_attribute *attr,
1196 				       const char *buf,
1197 				       size_t len)
1198 {
1199 	int ret;
1200 	bool requested_state;
1201 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1202 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1203 	bool inlist;
1204 
1205 	ret = strtobool(buf, &requested_state);
1206 	if (ret < 0)
1207 		return ret;
1208 
1209 	mutex_lock(&indio_dev->mlock);
1210 
1211 	/* Find out if it is in the list */
1212 	inlist = iio_buffer_is_active(buffer);
1213 	/* Already in desired state */
1214 	if (inlist == requested_state)
1215 		goto done;
1216 
1217 	if (requested_state)
1218 		ret = __iio_update_buffers(indio_dev, buffer, NULL);
1219 	else
1220 		ret = __iio_update_buffers(indio_dev, NULL, buffer);
1221 
1222 done:
1223 	mutex_unlock(&indio_dev->mlock);
1224 	return (ret < 0) ? ret : len;
1225 }
1226 
1227 static ssize_t iio_buffer_show_watermark(struct device *dev,
1228 					 struct device_attribute *attr,
1229 					 char *buf)
1230 {
1231 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1232 
1233 	return sysfs_emit(buf, "%u\n", buffer->watermark);
1234 }
1235 
1236 static ssize_t iio_buffer_store_watermark(struct device *dev,
1237 					  struct device_attribute *attr,
1238 					  const char *buf,
1239 					  size_t len)
1240 {
1241 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1242 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1243 	unsigned int val;
1244 	int ret;
1245 
1246 	ret = kstrtouint(buf, 10, &val);
1247 	if (ret)
1248 		return ret;
1249 	if (!val)
1250 		return -EINVAL;
1251 
1252 	mutex_lock(&indio_dev->mlock);
1253 
1254 	if (val > buffer->length) {
1255 		ret = -EINVAL;
1256 		goto out;
1257 	}
1258 
1259 	if (iio_buffer_is_active(buffer)) {
1260 		ret = -EBUSY;
1261 		goto out;
1262 	}
1263 
1264 	buffer->watermark = val;
1265 out:
1266 	mutex_unlock(&indio_dev->mlock);
1267 
1268 	return ret ? ret : len;
1269 }
1270 
1271 static ssize_t iio_dma_show_data_available(struct device *dev,
1272 						struct device_attribute *attr,
1273 						char *buf)
1274 {
1275 	struct iio_buffer *buffer = to_iio_dev_attr(attr)->buffer;
1276 
1277 	return sysfs_emit(buf, "%zu\n", iio_buffer_data_available(buffer));
1278 }
1279 
1280 static DEVICE_ATTR(length, S_IRUGO | S_IWUSR, iio_buffer_read_length,
1281 		   iio_buffer_write_length);
1282 static struct device_attribute dev_attr_length_ro = __ATTR(length,
1283 	S_IRUGO, iio_buffer_read_length, NULL);
1284 static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR,
1285 		   iio_buffer_show_enable, iio_buffer_store_enable);
1286 static DEVICE_ATTR(watermark, S_IRUGO | S_IWUSR,
1287 		   iio_buffer_show_watermark, iio_buffer_store_watermark);
1288 static struct device_attribute dev_attr_watermark_ro = __ATTR(watermark,
1289 	S_IRUGO, iio_buffer_show_watermark, NULL);
1290 static DEVICE_ATTR(data_available, S_IRUGO,
1291 		iio_dma_show_data_available, NULL);
1292 
1293 static struct attribute *iio_buffer_attrs[] = {
1294 	&dev_attr_length.attr,
1295 	&dev_attr_enable.attr,
1296 	&dev_attr_watermark.attr,
1297 	&dev_attr_data_available.attr,
1298 };
1299 
1300 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
1301 
1302 static struct attribute *iio_buffer_wrap_attr(struct iio_buffer *buffer,
1303 					      struct attribute *attr)
1304 {
1305 	struct device_attribute *dattr = to_dev_attr(attr);
1306 	struct iio_dev_attr *iio_attr;
1307 
1308 	iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
1309 	if (!iio_attr)
1310 		return NULL;
1311 
1312 	iio_attr->buffer = buffer;
1313 	memcpy(&iio_attr->dev_attr, dattr, sizeof(iio_attr->dev_attr));
1314 	iio_attr->dev_attr.attr.name = kstrdup_const(attr->name, GFP_KERNEL);
1315 	sysfs_attr_init(&iio_attr->dev_attr.attr);
1316 
1317 	list_add(&iio_attr->l, &buffer->buffer_attr_list);
1318 
1319 	return &iio_attr->dev_attr.attr;
1320 }
1321 
1322 static int iio_buffer_register_legacy_sysfs_groups(struct iio_dev *indio_dev,
1323 						   struct attribute **buffer_attrs,
1324 						   int buffer_attrcount,
1325 						   int scan_el_attrcount)
1326 {
1327 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1328 	struct attribute_group *group;
1329 	struct attribute **attrs;
1330 	int ret;
1331 
1332 	attrs = kcalloc(buffer_attrcount + 1, sizeof(*attrs), GFP_KERNEL);
1333 	if (!attrs)
1334 		return -ENOMEM;
1335 
1336 	memcpy(attrs, buffer_attrs, buffer_attrcount * sizeof(*attrs));
1337 
1338 	group = &iio_dev_opaque->legacy_buffer_group;
1339 	group->attrs = attrs;
1340 	group->name = "buffer";
1341 
1342 	ret = iio_device_register_sysfs_group(indio_dev, group);
1343 	if (ret)
1344 		goto error_free_buffer_attrs;
1345 
1346 	attrs = kcalloc(scan_el_attrcount + 1, sizeof(*attrs), GFP_KERNEL);
1347 	if (!attrs) {
1348 		ret = -ENOMEM;
1349 		goto error_free_buffer_attrs;
1350 	}
1351 
1352 	memcpy(attrs, &buffer_attrs[buffer_attrcount],
1353 	       scan_el_attrcount * sizeof(*attrs));
1354 
1355 	group = &iio_dev_opaque->legacy_scan_el_group;
1356 	group->attrs = attrs;
1357 	group->name = "scan_elements";
1358 
1359 	ret = iio_device_register_sysfs_group(indio_dev, group);
1360 	if (ret)
1361 		goto error_free_scan_el_attrs;
1362 
1363 	return 0;
1364 
1365 error_free_buffer_attrs:
1366 	kfree(iio_dev_opaque->legacy_buffer_group.attrs);
1367 error_free_scan_el_attrs:
1368 	kfree(iio_dev_opaque->legacy_scan_el_group.attrs);
1369 
1370 	return ret;
1371 }
1372 
1373 static void iio_buffer_unregister_legacy_sysfs_groups(struct iio_dev *indio_dev)
1374 {
1375 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1376 
1377 	kfree(iio_dev_opaque->legacy_buffer_group.attrs);
1378 	kfree(iio_dev_opaque->legacy_scan_el_group.attrs);
1379 }
1380 
1381 static int iio_buffer_chrdev_release(struct inode *inode, struct file *filep)
1382 {
1383 	struct iio_dev_buffer_pair *ib = filep->private_data;
1384 	struct iio_dev *indio_dev = ib->indio_dev;
1385 	struct iio_buffer *buffer = ib->buffer;
1386 
1387 	wake_up(&buffer->pollq);
1388 
1389 	kfree(ib);
1390 	clear_bit(IIO_BUSY_BIT_POS, &buffer->flags);
1391 	iio_device_put(indio_dev);
1392 
1393 	return 0;
1394 }
1395 
1396 static const struct file_operations iio_buffer_chrdev_fileops = {
1397 	.owner = THIS_MODULE,
1398 	.llseek = noop_llseek,
1399 	.read = iio_buffer_read,
1400 	.poll = iio_buffer_poll,
1401 	.release = iio_buffer_chrdev_release,
1402 };
1403 
1404 static long iio_device_buffer_getfd(struct iio_dev *indio_dev, unsigned long arg)
1405 {
1406 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1407 	int __user *ival = (int __user *)arg;
1408 	struct iio_dev_buffer_pair *ib;
1409 	struct iio_buffer *buffer;
1410 	int fd, idx, ret;
1411 
1412 	if (copy_from_user(&idx, ival, sizeof(idx)))
1413 		return -EFAULT;
1414 
1415 	if (idx >= iio_dev_opaque->attached_buffers_cnt)
1416 		return -ENODEV;
1417 
1418 	iio_device_get(indio_dev);
1419 
1420 	buffer = iio_dev_opaque->attached_buffers[idx];
1421 
1422 	if (test_and_set_bit(IIO_BUSY_BIT_POS, &buffer->flags)) {
1423 		ret = -EBUSY;
1424 		goto error_iio_dev_put;
1425 	}
1426 
1427 	ib = kzalloc(sizeof(*ib), GFP_KERNEL);
1428 	if (!ib) {
1429 		ret = -ENOMEM;
1430 		goto error_clear_busy_bit;
1431 	}
1432 
1433 	ib->indio_dev = indio_dev;
1434 	ib->buffer = buffer;
1435 
1436 	fd = anon_inode_getfd("iio:buffer", &iio_buffer_chrdev_fileops,
1437 			      ib, O_RDWR | O_CLOEXEC);
1438 	if (fd < 0) {
1439 		ret = fd;
1440 		goto error_free_ib;
1441 	}
1442 
1443 	if (copy_to_user(ival, &fd, sizeof(fd))) {
1444 		put_unused_fd(fd);
1445 		ret = -EFAULT;
1446 		goto error_free_ib;
1447 	}
1448 
1449 	return 0;
1450 
1451 error_free_ib:
1452 	kfree(ib);
1453 error_clear_busy_bit:
1454 	clear_bit(IIO_BUSY_BIT_POS, &buffer->flags);
1455 error_iio_dev_put:
1456 	iio_device_put(indio_dev);
1457 	return ret;
1458 }
1459 
1460 static long iio_device_buffer_ioctl(struct iio_dev *indio_dev, struct file *filp,
1461 				    unsigned int cmd, unsigned long arg)
1462 {
1463 	switch (cmd) {
1464 	case IIO_BUFFER_GET_FD_IOCTL:
1465 		return iio_device_buffer_getfd(indio_dev, arg);
1466 	default:
1467 		return IIO_IOCTL_UNHANDLED;
1468 	}
1469 }
1470 
1471 static int __iio_buffer_alloc_sysfs_and_mask(struct iio_buffer *buffer,
1472 					     struct iio_dev *indio_dev,
1473 					     int index)
1474 {
1475 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1476 	struct iio_dev_attr *p;
1477 	struct attribute **attr;
1478 	int ret, i, attrn, scan_el_attrcount, buffer_attrcount;
1479 	const struct iio_chan_spec *channels;
1480 
1481 	buffer_attrcount = 0;
1482 	if (buffer->attrs) {
1483 		while (buffer->attrs[buffer_attrcount] != NULL)
1484 			buffer_attrcount++;
1485 	}
1486 
1487 	scan_el_attrcount = 0;
1488 	INIT_LIST_HEAD(&buffer->buffer_attr_list);
1489 	channels = indio_dev->channels;
1490 	if (channels) {
1491 		/* new magic */
1492 		for (i = 0; i < indio_dev->num_channels; i++) {
1493 			if (channels[i].scan_index < 0)
1494 				continue;
1495 
1496 			ret = iio_buffer_add_channel_sysfs(indio_dev, buffer,
1497 							 &channels[i]);
1498 			if (ret < 0)
1499 				goto error_cleanup_dynamic;
1500 			scan_el_attrcount += ret;
1501 			if (channels[i].type == IIO_TIMESTAMP)
1502 				iio_dev_opaque->scan_index_timestamp =
1503 					channels[i].scan_index;
1504 		}
1505 		if (indio_dev->masklength && buffer->scan_mask == NULL) {
1506 			buffer->scan_mask = bitmap_zalloc(indio_dev->masklength,
1507 							  GFP_KERNEL);
1508 			if (buffer->scan_mask == NULL) {
1509 				ret = -ENOMEM;
1510 				goto error_cleanup_dynamic;
1511 			}
1512 		}
1513 	}
1514 
1515 	attrn = buffer_attrcount + scan_el_attrcount + ARRAY_SIZE(iio_buffer_attrs);
1516 	attr = kcalloc(attrn + 1, sizeof(* attr), GFP_KERNEL);
1517 	if (!attr) {
1518 		ret = -ENOMEM;
1519 		goto error_free_scan_mask;
1520 	}
1521 
1522 	memcpy(attr, iio_buffer_attrs, sizeof(iio_buffer_attrs));
1523 	if (!buffer->access->set_length)
1524 		attr[0] = &dev_attr_length_ro.attr;
1525 
1526 	if (buffer->access->flags & INDIO_BUFFER_FLAG_FIXED_WATERMARK)
1527 		attr[2] = &dev_attr_watermark_ro.attr;
1528 
1529 	if (buffer->attrs)
1530 		memcpy(&attr[ARRAY_SIZE(iio_buffer_attrs)], buffer->attrs,
1531 		       sizeof(struct attribute *) * buffer_attrcount);
1532 
1533 	buffer_attrcount += ARRAY_SIZE(iio_buffer_attrs);
1534 
1535 	for (i = 0; i < buffer_attrcount; i++) {
1536 		struct attribute *wrapped;
1537 
1538 		wrapped = iio_buffer_wrap_attr(buffer, attr[i]);
1539 		if (!wrapped) {
1540 			ret = -ENOMEM;
1541 			goto error_free_scan_mask;
1542 		}
1543 		attr[i] = wrapped;
1544 	}
1545 
1546 	attrn = 0;
1547 	list_for_each_entry(p, &buffer->buffer_attr_list, l)
1548 		attr[attrn++] = &p->dev_attr.attr;
1549 
1550 	buffer->buffer_group.name = kasprintf(GFP_KERNEL, "buffer%d", index);
1551 	if (!buffer->buffer_group.name) {
1552 		ret = -ENOMEM;
1553 		goto error_free_buffer_attrs;
1554 	}
1555 
1556 	buffer->buffer_group.attrs = attr;
1557 
1558 	ret = iio_device_register_sysfs_group(indio_dev, &buffer->buffer_group);
1559 	if (ret)
1560 		goto error_free_buffer_attr_group_name;
1561 
1562 	/* we only need to register the legacy groups for the first buffer */
1563 	if (index > 0)
1564 		return 0;
1565 
1566 	ret = iio_buffer_register_legacy_sysfs_groups(indio_dev, attr,
1567 						      buffer_attrcount,
1568 						      scan_el_attrcount);
1569 	if (ret)
1570 		goto error_free_buffer_attr_group_name;
1571 
1572 	return 0;
1573 
1574 error_free_buffer_attr_group_name:
1575 	kfree(buffer->buffer_group.name);
1576 error_free_buffer_attrs:
1577 	kfree(buffer->buffer_group.attrs);
1578 error_free_scan_mask:
1579 	bitmap_free(buffer->scan_mask);
1580 error_cleanup_dynamic:
1581 	iio_free_chan_devattr_list(&buffer->buffer_attr_list);
1582 
1583 	return ret;
1584 }
1585 
1586 static void __iio_buffer_free_sysfs_and_mask(struct iio_buffer *buffer)
1587 {
1588 	bitmap_free(buffer->scan_mask);
1589 	kfree(buffer->buffer_group.name);
1590 	kfree(buffer->buffer_group.attrs);
1591 	iio_free_chan_devattr_list(&buffer->buffer_attr_list);
1592 }
1593 
1594 int iio_buffers_alloc_sysfs_and_mask(struct iio_dev *indio_dev)
1595 {
1596 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1597 	const struct iio_chan_spec *channels;
1598 	struct iio_buffer *buffer;
1599 	int unwind_idx;
1600 	int ret, i;
1601 	size_t sz;
1602 
1603 	channels = indio_dev->channels;
1604 	if (channels) {
1605 		int ml = indio_dev->masklength;
1606 
1607 		for (i = 0; i < indio_dev->num_channels; i++)
1608 			ml = max(ml, channels[i].scan_index + 1);
1609 		indio_dev->masklength = ml;
1610 	}
1611 
1612 	if (!iio_dev_opaque->attached_buffers_cnt)
1613 		return 0;
1614 
1615 	for (i = 0; i < iio_dev_opaque->attached_buffers_cnt; i++) {
1616 		buffer = iio_dev_opaque->attached_buffers[i];
1617 		ret = __iio_buffer_alloc_sysfs_and_mask(buffer, indio_dev, i);
1618 		if (ret) {
1619 			unwind_idx = i;
1620 			goto error_unwind_sysfs_and_mask;
1621 		}
1622 	}
1623 	unwind_idx = iio_dev_opaque->attached_buffers_cnt - 1;
1624 
1625 	sz = sizeof(*(iio_dev_opaque->buffer_ioctl_handler));
1626 	iio_dev_opaque->buffer_ioctl_handler = kzalloc(sz, GFP_KERNEL);
1627 	if (!iio_dev_opaque->buffer_ioctl_handler) {
1628 		ret = -ENOMEM;
1629 		goto error_unwind_sysfs_and_mask;
1630 	}
1631 
1632 	iio_dev_opaque->buffer_ioctl_handler->ioctl = iio_device_buffer_ioctl;
1633 	iio_device_ioctl_handler_register(indio_dev,
1634 					  iio_dev_opaque->buffer_ioctl_handler);
1635 
1636 	return 0;
1637 
1638 error_unwind_sysfs_and_mask:
1639 	for (; unwind_idx >= 0; unwind_idx--) {
1640 		buffer = iio_dev_opaque->attached_buffers[unwind_idx];
1641 		__iio_buffer_free_sysfs_and_mask(buffer);
1642 	}
1643 	return ret;
1644 }
1645 
1646 void iio_buffers_free_sysfs_and_mask(struct iio_dev *indio_dev)
1647 {
1648 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1649 	struct iio_buffer *buffer;
1650 	int i;
1651 
1652 	if (!iio_dev_opaque->attached_buffers_cnt)
1653 		return;
1654 
1655 	iio_device_ioctl_handler_unregister(iio_dev_opaque->buffer_ioctl_handler);
1656 	kfree(iio_dev_opaque->buffer_ioctl_handler);
1657 
1658 	iio_buffer_unregister_legacy_sysfs_groups(indio_dev);
1659 
1660 	for (i = iio_dev_opaque->attached_buffers_cnt - 1; i >= 0; i--) {
1661 		buffer = iio_dev_opaque->attached_buffers[i];
1662 		__iio_buffer_free_sysfs_and_mask(buffer);
1663 	}
1664 }
1665 
1666 /**
1667  * iio_validate_scan_mask_onehot() - Validates that exactly one channel is selected
1668  * @indio_dev: the iio device
1669  * @mask: scan mask to be checked
1670  *
1671  * Return true if exactly one bit is set in the scan mask, false otherwise. It
1672  * can be used for devices where only one channel can be active for sampling at
1673  * a time.
1674  */
1675 bool iio_validate_scan_mask_onehot(struct iio_dev *indio_dev,
1676 	const unsigned long *mask)
1677 {
1678 	return bitmap_weight(mask, indio_dev->masklength) == 1;
1679 }
1680 EXPORT_SYMBOL_GPL(iio_validate_scan_mask_onehot);
1681 
1682 static const void *iio_demux(struct iio_buffer *buffer,
1683 				 const void *datain)
1684 {
1685 	struct iio_demux_table *t;
1686 
1687 	if (list_empty(&buffer->demux_list))
1688 		return datain;
1689 	list_for_each_entry(t, &buffer->demux_list, l)
1690 		memcpy(buffer->demux_bounce + t->to,
1691 		       datain + t->from, t->length);
1692 
1693 	return buffer->demux_bounce;
1694 }
1695 
1696 static int iio_push_to_buffer(struct iio_buffer *buffer, const void *data)
1697 {
1698 	const void *dataout = iio_demux(buffer, data);
1699 	int ret;
1700 
1701 	ret = buffer->access->store_to(buffer, dataout);
1702 	if (ret)
1703 		return ret;
1704 
1705 	/*
1706 	 * We can't just test for watermark to decide if we wake the poll queue
1707 	 * because read may request less samples than the watermark.
1708 	 */
1709 	wake_up_interruptible_poll(&buffer->pollq, EPOLLIN | EPOLLRDNORM);
1710 	return 0;
1711 }
1712 
1713 /**
1714  * iio_push_to_buffers() - push to a registered buffer.
1715  * @indio_dev:		iio_dev structure for device.
1716  * @data:		Full scan.
1717  */
1718 int iio_push_to_buffers(struct iio_dev *indio_dev, const void *data)
1719 {
1720 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1721 	int ret;
1722 	struct iio_buffer *buf;
1723 
1724 	list_for_each_entry(buf, &iio_dev_opaque->buffer_list, buffer_list) {
1725 		ret = iio_push_to_buffer(buf, data);
1726 		if (ret < 0)
1727 			return ret;
1728 	}
1729 
1730 	return 0;
1731 }
1732 EXPORT_SYMBOL_GPL(iio_push_to_buffers);
1733 
1734 /**
1735  * iio_buffer_release() - Free a buffer's resources
1736  * @ref: Pointer to the kref embedded in the iio_buffer struct
1737  *
1738  * This function is called when the last reference to the buffer has been
1739  * dropped. It will typically free all resources allocated by the buffer. Do not
1740  * call this function manually, always use iio_buffer_put() when done using a
1741  * buffer.
1742  */
1743 static void iio_buffer_release(struct kref *ref)
1744 {
1745 	struct iio_buffer *buffer = container_of(ref, struct iio_buffer, ref);
1746 
1747 	buffer->access->release(buffer);
1748 }
1749 
1750 /**
1751  * iio_buffer_get() - Grab a reference to the buffer
1752  * @buffer: The buffer to grab a reference for, may be NULL
1753  *
1754  * Returns the pointer to the buffer that was passed into the function.
1755  */
1756 struct iio_buffer *iio_buffer_get(struct iio_buffer *buffer)
1757 {
1758 	if (buffer)
1759 		kref_get(&buffer->ref);
1760 
1761 	return buffer;
1762 }
1763 EXPORT_SYMBOL_GPL(iio_buffer_get);
1764 
1765 /**
1766  * iio_buffer_put() - Release the reference to the buffer
1767  * @buffer: The buffer to release the reference for, may be NULL
1768  */
1769 void iio_buffer_put(struct iio_buffer *buffer)
1770 {
1771 	if (buffer)
1772 		kref_put(&buffer->ref, iio_buffer_release);
1773 }
1774 EXPORT_SYMBOL_GPL(iio_buffer_put);
1775 
1776 /**
1777  * iio_device_attach_buffer - Attach a buffer to a IIO device
1778  * @indio_dev: The device the buffer should be attached to
1779  * @buffer: The buffer to attach to the device
1780  *
1781  * Return 0 if successful, negative if error.
1782  *
1783  * This function attaches a buffer to a IIO device. The buffer stays attached to
1784  * the device until the device is freed. For legacy reasons, the first attached
1785  * buffer will also be assigned to 'indio_dev->buffer'.
1786  * The array allocated here, will be free'd via the iio_device_detach_buffers()
1787  * call which is handled by the iio_device_free().
1788  */
1789 int iio_device_attach_buffer(struct iio_dev *indio_dev,
1790 			     struct iio_buffer *buffer)
1791 {
1792 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1793 	struct iio_buffer **new, **old = iio_dev_opaque->attached_buffers;
1794 	unsigned int cnt = iio_dev_opaque->attached_buffers_cnt;
1795 
1796 	cnt++;
1797 
1798 	new = krealloc(old, sizeof(*new) * cnt, GFP_KERNEL);
1799 	if (!new)
1800 		return -ENOMEM;
1801 	iio_dev_opaque->attached_buffers = new;
1802 
1803 	buffer = iio_buffer_get(buffer);
1804 
1805 	/* first buffer is legacy; attach it to the IIO device directly */
1806 	if (!indio_dev->buffer)
1807 		indio_dev->buffer = buffer;
1808 
1809 	iio_dev_opaque->attached_buffers[cnt - 1] = buffer;
1810 	iio_dev_opaque->attached_buffers_cnt = cnt;
1811 
1812 	return 0;
1813 }
1814 EXPORT_SYMBOL_GPL(iio_device_attach_buffer);
1815