xref: /linux/tools/iio/iio_generic_buffer.c (revision cdd445d4b2a910ade742c3d6a86bc3fca4da9e0c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Industrialio buffer test code.
3  *
4  * Copyright (c) 2008 Jonathan Cameron
5  *
6  * This program is primarily intended as an example application.
7  * Reads the current buffer setup from sysfs and starts a short capture
8  * from the specified device, pretty printing the result after appropriate
9  * conversion.
10  *
11  * Command line parameters
12  * generic_buffer -n <device_name> -t <trigger_name>
13  * If trigger name is not specified the program assumes you want a dataready
14  * trigger associated with the device and goes looking for it.
15  */
16 
17 #include <unistd.h>
18 #include <stdlib.h>
19 #include <dirent.h>
20 #include <fcntl.h>
21 #include <stdio.h>
22 #include <errno.h>
23 #include <sys/stat.h>
24 #include <sys/dir.h>
25 #include <linux/types.h>
26 #include <string.h>
27 #include <poll.h>
28 #include <endian.h>
29 #include <float.h>
30 #include <getopt.h>
31 #include <inttypes.h>
32 #include <stdbool.h>
33 #include <signal.h>
34 #include <sys/ioctl.h>
35 #include <linux/iio/buffer.h>
36 #include "iio_utils.h"
37 
38 /**
39  * enum autochan - state for the automatic channel enabling mechanism
40  */
41 enum autochan {
42 	AUTOCHANNELS_DISABLED,
43 	AUTOCHANNELS_ENABLED,
44 	AUTOCHANNELS_ACTIVE,
45 };
46 
47 /**
48  * size_from_channelarray() - calculate the storage size of a scan
49  * @channels:		the channel info array
50  * @num_channels:	number of channels
51  *
52  * Has the side effect of filling the channels[i].location values used
53  * in processing the buffer output.
54  **/
55 static unsigned int size_from_channelarray(struct iio_channel_info *channels, int num_channels)
56 {
57 	unsigned int bytes = 0;
58 	int i = 0, max = 0;
59 	unsigned int misalignment;
60 
61 	while (i < num_channels) {
62 		if (channels[i].bytes > max)
63 			max = channels[i].bytes;
64 		if (bytes % channels[i].bytes == 0)
65 			channels[i].location = bytes;
66 		else
67 			channels[i].location = bytes - bytes % channels[i].bytes
68 					       + channels[i].bytes;
69 
70 		bytes = channels[i].location + channels[i].bytes;
71 		i++;
72 	}
73 	/*
74 	 * We want the data in next sample to also be properly aligned so
75 	 * we'll add padding at the end if needed. Adding padding only
76 	 * works for channel data which size is 2^n bytes.
77 	 */
78 	misalignment = bytes % max;
79 	if (misalignment)
80 		bytes += max - misalignment;
81 
82 	return bytes;
83 }
84 
85 static void print1byte(uint8_t input, struct iio_channel_info *info)
86 {
87 	/*
88 	 * Shift before conversion to avoid sign extension
89 	 * of left aligned data
90 	 */
91 	input >>= info->shift;
92 	input &= info->mask;
93 	switch (info->format) {
94 	case 's': {
95 		int8_t val = (int8_t)(input << (8 - info->bits_used)) >>
96 			     (8 - info->bits_used);
97 		printf("%05f ", ((float)val + info->offset) * info->scale);
98 		break;
99 	}
100 	case 'u':
101 		printf("%05f ", ((float)input + info->offset) * info->scale);
102 		break;
103 	case 'f':
104 		printf("<invalid 1-byte float> ");
105 		break;
106 	}
107 }
108 
109 static void print2byte(uint16_t input, struct iio_channel_info *info)
110 {
111 	/* First swap if incorrect endian */
112 	if (info->be)
113 		input = be16toh(input);
114 	else
115 		input = le16toh(input);
116 
117 	/*
118 	 * Shift before conversion to avoid sign extension
119 	 * of left aligned data
120 	 */
121 	input >>= info->shift;
122 	input &= info->mask;
123 	switch (info->format) {
124 	case 's': {
125 		int16_t val = (int16_t)(input << (16 - info->bits_used)) >>
126 			      (16 - info->bits_used);
127 		printf("%05f ", ((float)val + info->offset) * info->scale);
128 		break;
129 	}
130 	case 'u':
131 		printf("%05f ", ((float)input + info->offset) * info->scale);
132 		break;
133 	case 'f': {
134 #if defined(__FLT16_MAX__)
135 		union {
136 			uint16_t u;
137 			_Float16 f;
138 		} converter;
139 
140 		converter.u = input;
141 		printf("%05f ", ((float)converter.f + info->offset) * info->scale);
142 #else
143 		printf("<unsupported 2-byte float> ");
144 #endif
145 		break;
146 	}
147 	}
148 }
149 
150 static void print4byte(uint32_t input, struct iio_channel_info *info)
151 {
152 	/* First swap if incorrect endian */
153 	if (info->be)
154 		input = be32toh(input);
155 	else
156 		input = le32toh(input);
157 
158 	/*
159 	 * Shift before conversion to avoid sign extension
160 	 * of left aligned data
161 	 */
162 	input >>= info->shift;
163 	input &= info->mask;
164 	switch (info->format) {
165 	case 's': {
166 		int32_t val = (int32_t)(input << (32 - info->bits_used)) >>
167 			      (32 - info->bits_used);
168 		printf("%05f ", ((float)val + info->offset) * info->scale);
169 		break;
170 	}
171 	case 'u':
172 		printf("%05f ", ((float)input + info->offset) * info->scale);
173 		break;
174 	case 'f': {
175 		union {
176 			uint32_t u;
177 			float f;
178 		} converter;
179 
180 		converter.u = input;
181 		printf("%05f ", (converter.f + info->offset) * info->scale);
182 		break;
183 	}
184 	}
185 }
186 
187 static void print8byte(uint64_t input, struct iio_channel_info *info)
188 {
189 	/* First swap if incorrect endian */
190 	if (info->be)
191 		input = be64toh(input);
192 	else
193 		input = le64toh(input);
194 
195 	/*
196 	 * Shift before conversion to avoid sign extension
197 	 * of left aligned data
198 	 */
199 	input >>= info->shift;
200 	input &= info->mask;
201 	switch (info->format) {
202 	case 's': {
203 		int64_t val = (int64_t)(input << (64 - info->bits_used)) >>
204 			      (64 - info->bits_used);
205 		/* special case for timestamp */
206 		if (info->scale == 1.0f && info->offset == 0.0f)
207 			printf("%" PRId64 " ", val);
208 		else
209 			printf("%05f ",
210 			       ((float)val + info->offset) * info->scale);
211 		break;
212 	}
213 	case 'u':
214 		printf("%05f ", ((float)input + info->offset) * info->scale);
215 		break;
216 	case 'f': {
217 		union {
218 			uint64_t u;
219 			double f;
220 		} converter;
221 
222 		converter.u = input;
223 		printf("%05f ", (converter.f + info->offset) * info->scale);
224 		break;
225 	}
226 	}
227 }
228 
229 /**
230  * process_scan() - print out the values in SI units
231  * @data:		pointer to the start of the scan
232  * @channels:		information about the channels.
233  *			Note: size_from_channelarray must have been called first
234  *			      to fill the location offsets.
235  * @num_channels:	number of channels
236  **/
237 static void process_scan(char *data, struct iio_channel_info *channels,
238 			 int num_channels)
239 {
240 	int k;
241 
242 	for (k = 0; k < num_channels; k++)
243 		switch (channels[k].bytes) {
244 			/* only a few cases implemented so far */
245 		case 1:
246 			print1byte(*(uint8_t *)(data + channels[k].location),
247 				   &channels[k]);
248 			break;
249 		case 2:
250 			print2byte(*(uint16_t *)(data + channels[k].location),
251 				   &channels[k]);
252 			break;
253 		case 4:
254 			print4byte(*(uint32_t *)(data + channels[k].location),
255 				   &channels[k]);
256 			break;
257 		case 8:
258 			print8byte(*(uint64_t *)(data + channels[k].location),
259 				   &channels[k]);
260 			break;
261 		default:
262 			break;
263 		}
264 	printf("\n");
265 }
266 
267 static int enable_disable_all_channels(char *dev_dir_name, int buffer_idx, int enable)
268 {
269 	const struct dirent *ent;
270 	char scanelemdir[256];
271 	DIR *dp;
272 	int ret;
273 
274 	snprintf(scanelemdir, sizeof(scanelemdir),
275 		 FORMAT_SCAN_ELEMENTS_DIR, dev_dir_name, buffer_idx);
276 	scanelemdir[sizeof(scanelemdir)-1] = '\0';
277 
278 	dp = opendir(scanelemdir);
279 	if (!dp) {
280 		fprintf(stderr, "Enabling/disabling channels: can't open %s\n",
281 			scanelemdir);
282 		return -EIO;
283 	}
284 
285 	ret = -ENOENT;
286 	while (ent = readdir(dp), ent) {
287 		if (iioutils_check_suffix(ent->d_name, "_en")) {
288 			printf("%sabling: %s\n",
289 			       enable ? "En" : "Dis",
290 			       ent->d_name);
291 			ret = write_sysfs_int(ent->d_name, scanelemdir,
292 					      enable);
293 			if (ret < 0)
294 				fprintf(stderr, "Failed to enable/disable %s\n",
295 					ent->d_name);
296 		}
297 	}
298 
299 	if (closedir(dp) == -1) {
300 		perror("Enabling/disabling channels: "
301 		       "Failed to close directory");
302 		return -errno;
303 	}
304 	return 0;
305 }
306 
307 static void print_usage(void)
308 {
309 	fprintf(stderr, "Usage: generic_buffer [options]...\n"
310 		"Capture, convert and output data from IIO device buffer\n"
311 		"  -a         Auto-activate all available channels\n"
312 		"  -A         Force-activate ALL channels\n"
313 		"  -b <n>     The buffer which to open (by index), default 0\n"
314 		"  -c <n>     Do n conversions, or loop forever if n < 0\n"
315 		"  -e         Disable wait for event (new data)\n"
316 		"  -g         Use trigger-less mode\n"
317 		"  -l <n>     Set buffer length to n samples\n"
318 		"  --device-name -n <name>\n"
319 		"  --device-num -N <num>\n"
320 		"        Set device by name or number (mandatory)\n"
321 		"  --trigger-name -t <name>\n"
322 		"  --trigger-num -T <num>\n"
323 		"        Set trigger by name or number\n"
324 		"  -w <n>     Set delay between reads in us (event-less mode)\n");
325 }
326 
327 static enum autochan autochannels = AUTOCHANNELS_DISABLED;
328 static char *dev_dir_name = NULL;
329 static char *buf_dir_name = NULL;
330 static int buffer_idx = 0;
331 static bool current_trigger_set = false;
332 
333 static void cleanup(void)
334 {
335 	int ret;
336 
337 	/* Disable trigger */
338 	if (dev_dir_name && current_trigger_set) {
339 		/* Disconnect the trigger - just write a dummy name. */
340 		ret = write_sysfs_string("trigger/current_trigger",
341 					 dev_dir_name, "NULL");
342 		if (ret < 0)
343 			fprintf(stderr, "Failed to disable trigger: %s\n",
344 				strerror(-ret));
345 		current_trigger_set = false;
346 	}
347 
348 	/* Disable buffer */
349 	if (buf_dir_name) {
350 		ret = write_sysfs_int("enable", buf_dir_name, 0);
351 		if (ret < 0)
352 			fprintf(stderr, "Failed to disable buffer: %s\n",
353 				strerror(-ret));
354 	}
355 
356 	/* Disable channels if auto-enabled */
357 	if (dev_dir_name && autochannels == AUTOCHANNELS_ACTIVE) {
358 		ret = enable_disable_all_channels(dev_dir_name, buffer_idx, 0);
359 		if (ret)
360 			fprintf(stderr, "Failed to disable all channels\n");
361 		autochannels = AUTOCHANNELS_DISABLED;
362 	}
363 }
364 
365 static void sig_handler(int signum)
366 {
367 	fprintf(stderr, "Caught signal %d\n", signum);
368 	cleanup();
369 	exit(-signum);
370 }
371 
372 static void register_cleanup(void)
373 {
374 	struct sigaction sa = { .sa_handler = sig_handler };
375 	const int signums[] = { SIGINT, SIGTERM, SIGABRT };
376 	int ret, i;
377 
378 	for (i = 0; i < ARRAY_SIZE(signums); ++i) {
379 		ret = sigaction(signums[i], &sa, NULL);
380 		if (ret) {
381 			perror("Failed to register signal handler");
382 			exit(-1);
383 		}
384 	}
385 }
386 
387 static const struct option longopts[] = {
388 	{ "device-name",	1, 0, 'n' },
389 	{ "device-num",		1, 0, 'N' },
390 	{ "trigger-name",	1, 0, 't' },
391 	{ "trigger-num",	1, 0, 'T' },
392 	{ }
393 };
394 
395 int main(int argc, char **argv)
396 {
397 	long long num_loops = 2;
398 	unsigned long timedelay = 1000000;
399 	unsigned long buf_len = 128;
400 
401 	ssize_t i;
402 	unsigned long long j;
403 	unsigned long toread;
404 	int ret, c;
405 	struct stat st;
406 	int fd = -1;
407 	int buf_fd = -1;
408 
409 	int num_channels = 0;
410 	char *trigger_name = NULL, *device_name = NULL;
411 
412 	char *data = NULL;
413 	ssize_t read_size;
414 	int dev_num = -1, trig_num = -1;
415 	char *buffer_access = NULL;
416 	unsigned int scan_size;
417 	int noevents = 0;
418 	int notrigger = 0;
419 	char *dummy;
420 	bool force_autochannels = false;
421 
422 	struct iio_channel_info *channels = NULL;
423 
424 	register_cleanup();
425 
426 	while ((c = getopt_long(argc, argv, "aAb:c:egl:n:N:t:T:w:?", longopts,
427 				NULL)) != -1) {
428 		switch (c) {
429 		case 'a':
430 			autochannels = AUTOCHANNELS_ENABLED;
431 			break;
432 		case 'A':
433 			autochannels = AUTOCHANNELS_ENABLED;
434 			force_autochannels = true;
435 			break;
436 		case 'b':
437 			errno = 0;
438 			buffer_idx = strtoll(optarg, &dummy, 10);
439 			if (errno) {
440 				ret = -errno;
441 				goto error;
442 			}
443 			if (buffer_idx < 0) {
444 				ret = -ERANGE;
445 				goto error;
446 			}
447 
448 			break;
449 		case 'c':
450 			errno = 0;
451 			num_loops = strtoll(optarg, &dummy, 10);
452 			if (errno) {
453 				ret = -errno;
454 				goto error;
455 			}
456 
457 			break;
458 		case 'e':
459 			noevents = 1;
460 			break;
461 		case 'g':
462 			notrigger = 1;
463 			break;
464 		case 'l':
465 			errno = 0;
466 			buf_len = strtoul(optarg, &dummy, 10);
467 			if (errno) {
468 				ret = -errno;
469 				goto error;
470 			}
471 
472 			break;
473 		case 'n':
474 			device_name = strdup(optarg);
475 			break;
476 		case 'N':
477 			errno = 0;
478 			dev_num = strtoul(optarg, &dummy, 10);
479 			if (errno) {
480 				ret = -errno;
481 				goto error;
482 			}
483 			break;
484 		case 't':
485 			trigger_name = strdup(optarg);
486 			break;
487 		case 'T':
488 			errno = 0;
489 			trig_num = strtoul(optarg, &dummy, 10);
490 			if (errno)
491 				return -errno;
492 			break;
493 		case 'w':
494 			errno = 0;
495 			timedelay = strtoul(optarg, &dummy, 10);
496 			if (errno) {
497 				ret = -errno;
498 				goto error;
499 			}
500 			break;
501 		case '?':
502 			print_usage();
503 			ret = -1;
504 			goto error;
505 		}
506 	}
507 
508 	/* Find the device requested */
509 	if (dev_num < 0 && !device_name) {
510 		fprintf(stderr, "Device not set\n");
511 		print_usage();
512 		ret = -1;
513 		goto error;
514 	} else if (dev_num >= 0 && device_name) {
515 		fprintf(stderr, "Only one of --device-num or --device-name needs to be set\n");
516 		print_usage();
517 		ret = -1;
518 		goto error;
519 	} else if (dev_num < 0) {
520 		dev_num = find_type_by_name(device_name, "iio:device");
521 		if (dev_num < 0) {
522 			fprintf(stderr, "Failed to find the %s\n", device_name);
523 			ret = dev_num;
524 			goto error;
525 		}
526 	}
527 	printf("iio device number being used is %d\n", dev_num);
528 
529 	ret = asprintf(&dev_dir_name, "%siio:device%d", iio_dir, dev_num);
530 	if (ret < 0)
531 		return -ENOMEM;
532 	/* Fetch device_name if specified by number */
533 	if (!device_name) {
534 		device_name = malloc(IIO_MAX_NAME_LENGTH);
535 		if (!device_name) {
536 			ret = -ENOMEM;
537 			goto error;
538 		}
539 		ret = read_sysfs_string("name", dev_dir_name, device_name);
540 		if (ret < 0) {
541 			fprintf(stderr, "Failed to read name of device %d\n", dev_num);
542 			goto error;
543 		}
544 	}
545 
546 	if (notrigger) {
547 		printf("trigger-less mode selected\n");
548 	} else if (trig_num >= 0) {
549 		char *trig_dev_name;
550 		ret = asprintf(&trig_dev_name, "%strigger%d", iio_dir, trig_num);
551 		if (ret < 0) {
552 			return -ENOMEM;
553 		}
554 		trigger_name = malloc(IIO_MAX_NAME_LENGTH);
555 		if (!trigger_name) {
556 			ret = -ENOMEM;
557 			goto error;
558 		}
559 		ret = read_sysfs_string("name", trig_dev_name, trigger_name);
560 		free(trig_dev_name);
561 		if (ret < 0) {
562 			fprintf(stderr, "Failed to read trigger%d name from\n", trig_num);
563 			return ret;
564 		}
565 		printf("iio trigger number being used is %d\n", trig_num);
566 	} else {
567 		if (!trigger_name) {
568 			/*
569 			 * Build the trigger name. If it is device associated
570 			 * its name is <device_name>_dev[n] where n matches
571 			 * the device number found above.
572 			 */
573 			ret = asprintf(&trigger_name,
574 				       "%s-dev%d", device_name, dev_num);
575 			if (ret < 0) {
576 				ret = -ENOMEM;
577 				goto error;
578 			}
579 		}
580 
581 		/* Look for this "-devN" trigger */
582 		trig_num = find_type_by_name(trigger_name, "trigger");
583 		if (trig_num < 0) {
584 			/* OK try the simpler "-trigger" suffix instead */
585 			free(trigger_name);
586 			ret = asprintf(&trigger_name,
587 				       "%s-trigger", device_name);
588 			if (ret < 0) {
589 				ret = -ENOMEM;
590 				goto error;
591 			}
592 		}
593 
594 		trig_num = find_type_by_name(trigger_name, "trigger");
595 		if (trig_num < 0) {
596 			fprintf(stderr, "Failed to find the trigger %s\n",
597 				trigger_name);
598 			ret = trig_num;
599 			goto error;
600 		}
601 
602 		printf("iio trigger number being used is %d\n", trig_num);
603 	}
604 
605 	/*
606 	 * Parse the files in scan_elements to identify what channels are
607 	 * present
608 	 */
609 	ret = build_channel_array(dev_dir_name, buffer_idx, &channels, &num_channels);
610 	if (ret) {
611 		fprintf(stderr, "Problem reading scan element information\n"
612 			"diag %s\n", dev_dir_name);
613 		goto error;
614 	}
615 	if (num_channels && autochannels == AUTOCHANNELS_ENABLED &&
616 	    !force_autochannels) {
617 		fprintf(stderr, "Auto-channels selected but some channels "
618 			"are already activated in sysfs\n");
619 		fprintf(stderr, "Proceeding without activating any channels\n");
620 	}
621 
622 	if ((!num_channels && autochannels == AUTOCHANNELS_ENABLED) ||
623 	    (autochannels == AUTOCHANNELS_ENABLED && force_autochannels)) {
624 		fprintf(stderr, "Enabling all channels\n");
625 
626 		ret = enable_disable_all_channels(dev_dir_name, buffer_idx, 1);
627 		if (ret) {
628 			fprintf(stderr, "Failed to enable all channels\n");
629 			goto error;
630 		}
631 
632 		/* This flags that we need to disable the channels again */
633 		autochannels = AUTOCHANNELS_ACTIVE;
634 
635 		ret = build_channel_array(dev_dir_name, buffer_idx, &channels,
636 					  &num_channels);
637 		if (ret) {
638 			fprintf(stderr, "Problem reading scan element "
639 				"information\n"
640 				"diag %s\n", dev_dir_name);
641 			goto error;
642 		}
643 		if (!num_channels) {
644 			fprintf(stderr, "Still no channels after "
645 				"auto-enabling, giving up\n");
646 			goto error;
647 		}
648 	}
649 
650 	if (!num_channels && autochannels == AUTOCHANNELS_DISABLED) {
651 		fprintf(stderr,
652 			"No channels are enabled, we have nothing to scan.\n");
653 		fprintf(stderr, "Enable channels manually in "
654 			FORMAT_SCAN_ELEMENTS_DIR
655 			"/*_en or pass -a to autoenable channels and "
656 			"try again.\n", dev_dir_name, buffer_idx);
657 		ret = -ENOENT;
658 		goto error;
659 	}
660 
661 	/*
662 	 * Construct the directory name for the associated buffer.
663 	 * As we know that the lis3l02dq has only one buffer this may
664 	 * be built rather than found.
665 	 */
666 	ret = asprintf(&buf_dir_name,
667 		       "%siio:device%d/buffer%d", iio_dir, dev_num, buffer_idx);
668 	if (ret < 0) {
669 		ret = -ENOMEM;
670 		goto error;
671 	}
672 
673 	if (stat(buf_dir_name, &st)) {
674 		fprintf(stderr, "Could not stat() '%s', got error %d: %s\n",
675 			buf_dir_name, errno, strerror(errno));
676 		ret = -errno;
677 		goto error;
678 	}
679 
680 	if (!S_ISDIR(st.st_mode)) {
681 		fprintf(stderr, "File '%s' is not a directory\n", buf_dir_name);
682 		ret = -EFAULT;
683 		goto error;
684 	}
685 
686 	if (!notrigger) {
687 		printf("%s %s\n", dev_dir_name, trigger_name);
688 		/*
689 		 * Set the device trigger to be the data ready trigger found
690 		 * above
691 		 */
692 		ret = write_sysfs_string_and_verify("trigger/current_trigger",
693 						    dev_dir_name,
694 						    trigger_name);
695 		if (ret < 0) {
696 			fprintf(stderr,
697 				"Failed to write current_trigger file\n");
698 			goto error;
699 		}
700 	}
701 
702 	ret = asprintf(&buffer_access, "/dev/iio:device%d", dev_num);
703 	if (ret < 0) {
704 		ret = -ENOMEM;
705 		goto error;
706 	}
707 
708 	/* Attempt to open non blocking the access dev */
709 	fd = open(buffer_access, O_RDONLY | O_NONBLOCK);
710 	if (fd == -1) { /* TODO: If it isn't there make the node */
711 		ret = -errno;
712 		fprintf(stderr, "Failed to open %s\n", buffer_access);
713 		goto error;
714 	}
715 
716 	/* specify for which buffer index we want an FD */
717 	buf_fd = buffer_idx;
718 
719 	ret = ioctl(fd, IIO_BUFFER_GET_FD_IOCTL, &buf_fd);
720 	if (ret == -1 || buf_fd == -1) {
721 		ret = -errno;
722 		if (ret == -ENODEV || ret == -EINVAL)
723 			fprintf(stderr,
724 				"Device does not have this many buffers\n");
725 		else
726 			fprintf(stderr, "Failed to retrieve buffer fd\n");
727 
728 		goto error;
729 	}
730 
731 	/* Setup ring buffer parameters */
732 	ret = write_sysfs_int("length", buf_dir_name, buf_len);
733 	if (ret < 0)
734 		goto error;
735 
736 	/* Enable the buffer */
737 	ret = write_sysfs_int("enable", buf_dir_name, 1);
738 	if (ret < 0) {
739 		fprintf(stderr,
740 			"Failed to enable buffer '%s': %s\n",
741 			buf_dir_name, strerror(-ret));
742 		goto error;
743 	}
744 
745 	scan_size = size_from_channelarray(channels, num_channels);
746 
747 	size_t total_buf_len = scan_size * buf_len;
748 
749 	if (scan_size > 0 && total_buf_len / scan_size != buf_len) {
750 		ret = -EFAULT;
751 		perror("Integer overflow happened when calculate scan_size * buf_len");
752 		goto error;
753 	}
754 
755 	data = malloc(total_buf_len);
756 	if (!data) {
757 		ret = -ENOMEM;
758 		goto error;
759 	}
760 
761 	/**
762 	 * This check is being done here for sanity reasons, however it
763 	 * should be omitted under normal operation.
764 	 * If this is buffer0, we check that we get EBUSY after this point.
765 	 */
766 	if (buffer_idx == 0) {
767 		errno = 0;
768 		read_size = read(fd, data, 1);
769 		if (read_size > -1 || errno != EBUSY) {
770 			ret = -EFAULT;
771 			perror("Reading from '%s' should not be possible after ioctl()");
772 			goto error;
773 		}
774 	}
775 
776 	/* close now the main chardev FD and let the buffer FD work */
777 	if (close(fd) == -1)
778 		perror("Failed to close character device file");
779 	fd = -1;
780 
781 	for (j = 0; j < num_loops || num_loops < 0; j++) {
782 		if (!noevents) {
783 			struct pollfd pfd = {
784 				.fd = buf_fd,
785 				.events = POLLIN,
786 			};
787 
788 			ret = poll(&pfd, 1, -1);
789 			if (ret < 0) {
790 				ret = -errno;
791 				goto error;
792 			} else if (ret == 0) {
793 				continue;
794 			}
795 
796 		} else {
797 			usleep(timedelay);
798 		}
799 
800 		toread = buf_len;
801 
802 		read_size = read(buf_fd, data, toread * scan_size);
803 		if (read_size < 0) {
804 			if (errno == EAGAIN) {
805 				fprintf(stderr, "nothing available\n");
806 				continue;
807 			} else {
808 				break;
809 			}
810 		}
811 		for (i = 0; i < read_size / scan_size; i++)
812 			process_scan(data + scan_size * i, channels,
813 				     num_channels);
814 	}
815 
816 error:
817 	cleanup();
818 
819 	if (fd >= 0 && close(fd) == -1)
820 		perror("Failed to close character device");
821 	if (buf_fd >= 0 && close(buf_fd) == -1)
822 		perror("Failed to close buffer");
823 	free(buffer_access);
824 	free(data);
825 	free(buf_dir_name);
826 	for (i = num_channels - 1; i >= 0; i--) {
827 		free(channels[i].name);
828 		free(channels[i].generic_name);
829 	}
830 	free(channels);
831 	free(trigger_name);
832 	free(device_name);
833 	free(dev_dir_name);
834 
835 	return ret;
836 }
837