1 /*
2 * libiio - Library for interfacing industrial I/O (IIO) devices
3 *
4 * Copyright (C) 2014 Analog Devices, Inc.
5 * Author: Paul Cercueil <paul.cercueil@analog.com>
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * */
18
19 #include "debug.h"
20 #include "iio-private.h"
21 #include "sort.h"
22
23 #include <dirent.h>
24 #include <errno.h>
25 #include <limits.h>
26 #include <poll.h>
27 #include <stdbool.h>
28 #include <stddef.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <sys/eventfd.h>
32 #include <sys/ioctl.h>
33 #include <sys/mman.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <unistd.h>
37 #include <string.h>
38 #include <sys/utsname.h>
39 #include <time.h>
40 #include <unistd.h>
41 #include <fcntl.h>
42 #ifdef WITH_LOCAL_CONFIG
43 #include <ini.h>
44 #endif
45
46 #define DEFAULT_TIMEOUT_MS 1000
47
48 #define NB_BLOCKS 4
49
50 #define BLOCK_ALLOC_IOCTL _IOWR('i', 0xa0, struct block_alloc_req)
51 #define BLOCK_FREE_IOCTL _IO('i', 0xa1)
52 #define BLOCK_QUERY_IOCTL _IOWR('i', 0xa2, struct block)
53 #define BLOCK_ENQUEUE_IOCTL _IOWR('i', 0xa3, struct block)
54 #define BLOCK_DEQUEUE_IOCTL _IOWR('i', 0xa4, struct block)
55
56 #define BLOCK_FLAG_CYCLIC BIT(1)
57
58 /* Forward declarations */
59 static ssize_t local_read_dev_attr(const struct iio_device *dev,
60 const char *attr, char *dst, size_t len, enum iio_attr_type type);
61 static ssize_t local_read_chn_attr(const struct iio_channel *chn,
62 const char *attr, char *dst, size_t len);
63 static ssize_t local_write_dev_attr(const struct iio_device *dev,
64 const char *attr, const char *src, size_t len, enum iio_attr_type type);
65 static ssize_t local_write_chn_attr(const struct iio_channel *chn,
66 const char *attr, const char *src, size_t len);
67
68 struct block_alloc_req {
69 uint32_t type,
70 size,
71 count,
72 id;
73 };
74
75 struct block {
76 uint32_t id,
77 size,
78 bytes_used,
79 type,
80 flags,
81 offset;
82 uint64_t timestamp;
83 };
84
85 struct iio_context_pdata {
86 unsigned int rw_timeout_ms;
87 };
88
89 struct iio_device_pdata {
90 int fd;
91 bool blocking;
92 unsigned int samples_count;
93 unsigned int max_nb_blocks;
94 unsigned int allocated_nb_blocks;
95
96 struct block *blocks;
97 void **addrs;
98 int last_dequeued;
99 bool is_high_speed, cyclic, cyclic_buffer_enqueued, buffer_enabled;
100
101 int cancel_fd;
102 };
103
104 struct iio_channel_pdata {
105 char *enable_fn;
106 struct iio_channel_attr *protected_attrs;
107 unsigned int nb_protected_attrs;
108 };
109
110 static const char * const device_attrs_blacklist[] = {
111 "dev",
112 "uevent",
113 };
114
115 static const char * const buffer_attrs_reserved[] = {
116 "length",
117 "enable",
118 };
119
ioctl_nointr(int fd,unsigned long request,void * data)120 static int ioctl_nointr(int fd, unsigned long request, void *data)
121 {
122 int ret;
123
124 do {
125 ret = ioctl(fd, request, data);
126 } while (ret == -1 && errno == EINTR);
127
128 return ret;
129 }
130
local_free_channel_pdata(struct iio_channel * chn)131 static void local_free_channel_pdata(struct iio_channel *chn)
132 {
133 if (chn->pdata) {
134 free(chn->pdata->enable_fn);
135 free(chn->pdata);
136 }
137 }
138
local_free_pdata(struct iio_device * device)139 static void local_free_pdata(struct iio_device *device)
140 {
141 unsigned int i;
142
143 for (i = 0; i < device->nb_channels; i++)
144 local_free_channel_pdata(device->channels[i]);
145
146 if (device->pdata) {
147 free(device->pdata->blocks);
148 free(device->pdata->addrs);
149 free(device->pdata);
150 }
151 }
152
local_shutdown(struct iio_context * ctx)153 static void local_shutdown(struct iio_context *ctx)
154 {
155 /* Free the backend data stored in every device structure */
156 unsigned int i;
157
158 for (i = 0; i < ctx->nb_devices; i++) {
159 struct iio_device *dev = ctx->devices[i];
160
161 iio_device_close(dev);
162 local_free_pdata(dev);
163 }
164
165 free(ctx->pdata);
166 }
167
168 /** Shrinks the first nb characters of a string
169 * e.g. strcut("foobar", 4) replaces the content with "ar". */
strcut(char * str,int nb)170 static void strcut(char *str, int nb)
171 {
172 char *ptr = str + nb;
173 while (*ptr)
174 *str++ = *ptr++;
175 *str = 0;
176 }
177
set_channel_name(struct iio_channel * chn)178 static int set_channel_name(struct iio_channel *chn)
179 {
180 struct iio_channel_pdata *pdata = chn->pdata;
181 size_t prefix_len = 0;
182 const char *attr0;
183 const char *ptr;
184 unsigned int i;
185
186 if (chn->nb_attrs + pdata->nb_protected_attrs < 2)
187 return 0;
188
189 if (chn->nb_attrs)
190 attr0 = ptr = chn->attrs[0].name;
191 else
192 attr0 = ptr = pdata->protected_attrs[0].name;
193
194 while (true) {
195 bool can_fix = true;
196 size_t len;
197
198 ptr = strchr(ptr, '_');
199 if (!ptr)
200 break;
201
202 len = ptr - attr0 + 1;
203 for (i = 1; can_fix && i < chn->nb_attrs; i++)
204 can_fix = !strncmp(attr0, chn->attrs[i].name, len);
205
206 for (i = !chn->nb_attrs;
207 can_fix && i < pdata->nb_protected_attrs; i++) {
208 can_fix = !strncmp(attr0,
209 pdata->protected_attrs[i].name, len);
210 }
211
212 if (!can_fix)
213 break;
214
215 prefix_len = len;
216 ptr = ptr + 1;
217 }
218
219 if (prefix_len) {
220 char *name;
221
222 name = malloc(prefix_len);
223 if (!name)
224 return -ENOMEM;
225 strncpy(name, attr0, prefix_len - 1);
226 name[prefix_len - 1] = '\0';
227 DEBUG("Setting name of channel %s to %s\n", chn->id, name);
228 chn->name = name;
229
230 /* Shrink the attribute name */
231 for (i = 0; i < chn->nb_attrs; i++)
232 strcut(chn->attrs[i].name, prefix_len);
233 for (i = 0; i < pdata->nb_protected_attrs; i++)
234 strcut(pdata->protected_attrs[i].name, prefix_len);
235 }
236
237 return 0;
238 }
239
240 /*
241 * Used to generate the timeout parameter for operations like poll. Returns the
242 * number of ms until it is timeout_rel ms after the time specified in start. If
243 * timeout_rel is 0 returns -1 to indicate no timeout.
244 *
245 * The timeout that is specified for IIO operations is the maximum time a buffer
246 * push() or refill() operation should take before returning. poll() is used to
247 * wait for either data activity or for the timeout to elapse. poll() might get
248 * interrupted in which case it is called again or the read()/write() operation
249 * might not complete the full buffer size in one call in which case we go back
250 * to poll() again as well. Passing the same timeout as before would increase
251 * the total timeout and if repeated interruptions occur (e.g. by a timer
252 * signal) the operation might never time out or with significant delay. Hence
253 * before each poll() invocation the timeout is recalculated relative to the
254 * start of refill() or push() operation.
255 */
get_rel_timeout_ms(struct timespec * start,unsigned int timeout_rel)256 static int get_rel_timeout_ms(struct timespec *start, unsigned int timeout_rel)
257 {
258 struct timespec now;
259 int diff_ms;
260
261 if (timeout_rel == 0) /* No timeout */
262 return -1;
263
264 clock_gettime(CLOCK_MONOTONIC, &now);
265
266 diff_ms = (now.tv_sec - start->tv_sec) * 1000;
267 diff_ms += (now.tv_nsec - start->tv_nsec) / 1000000;
268
269 if (diff_ms >= timeout_rel) /* Expired */
270 return 0;
271 if (diff_ms > 0) /* Should never be false, but lets be safe */
272 timeout_rel -= diff_ms;
273 if (timeout_rel > INT_MAX)
274 return INT_MAX;
275
276 return (int) timeout_rel;
277 }
278
device_check_ready(const struct iio_device * dev,short events,struct timespec * start)279 static int device_check_ready(const struct iio_device *dev, short events,
280 struct timespec *start)
281 {
282 struct pollfd pollfd[2] = {
283 {
284 .fd = dev->pdata->fd,
285 .events = events,
286 }, {
287 .fd = dev->pdata->cancel_fd,
288 .events = POLLIN,
289 }
290 };
291 unsigned int rw_timeout_ms = dev->ctx->pdata->rw_timeout_ms;
292 int timeout_rel;
293 int ret;
294
295 if (!dev->pdata->blocking)
296 return 0;
297
298 do {
299 timeout_rel = get_rel_timeout_ms(start, rw_timeout_ms);
300 ret = poll(pollfd, 2, timeout_rel);
301 } while (ret == -1 && errno == EINTR);
302
303 if ((pollfd[1].revents & POLLIN))
304 return -EBADF;
305
306 if (ret < 0)
307 return -errno;
308 if (!ret)
309 return -ETIMEDOUT;
310 if (pollfd[0].revents & POLLNVAL)
311 return -EBADF;
312 if (!(pollfd[0].revents & events))
313 return -EIO;
314 return 0;
315 }
316
local_read(const struct iio_device * dev,void * dst,size_t len,uint32_t * mask,size_t words)317 static ssize_t local_read(const struct iio_device *dev,
318 void *dst, size_t len, uint32_t *mask, size_t words)
319 {
320 struct iio_device_pdata *pdata = dev->pdata;
321 uintptr_t ptr = (uintptr_t) dst;
322 struct timespec start;
323 ssize_t readsize;
324 ssize_t ret;
325
326 if (pdata->fd == -1)
327 return -EBADF;
328 if (words != dev->words)
329 return -EINVAL;
330
331 memcpy(mask, dev->mask, words);
332
333 if (len == 0)
334 return 0;
335
336 clock_gettime(CLOCK_MONOTONIC, &start);
337
338 while (len > 0) {
339 ret = device_check_ready(dev, POLLIN, &start);
340 if (ret < 0)
341 break;
342
343 do {
344 ret = read(pdata->fd, (void *) ptr, len);
345 } while (ret == -1 && errno == EINTR);
346
347 if (ret == -1) {
348 if (pdata->blocking && errno == EAGAIN)
349 continue;
350 ret = -errno;
351 break;
352 } else if (ret == 0) {
353 ret = -EIO;
354 break;
355 }
356
357 ptr += ret;
358 len -= ret;
359 }
360
361 readsize = (ssize_t)(ptr - (uintptr_t) dst);
362 if ((ret > 0 || ret == -EAGAIN) && (readsize > 0))
363 return readsize;
364 else
365 return ret;
366 }
367
local_write(const struct iio_device * dev,const void * src,size_t len)368 static ssize_t local_write(const struct iio_device *dev,
369 const void *src, size_t len)
370 {
371 struct iio_device_pdata *pdata = dev->pdata;
372 uintptr_t ptr = (uintptr_t) src;
373 struct timespec start;
374 ssize_t writtensize;
375 ssize_t ret;
376
377 if (pdata->fd == -1)
378 return -EBADF;
379
380 if (len == 0)
381 return 0;
382
383 clock_gettime(CLOCK_MONOTONIC, &start);
384
385 while (len > 0) {
386 ret = device_check_ready(dev, POLLOUT, &start);
387 if (ret < 0)
388 break;
389
390 do {
391 ret = write(pdata->fd, (void *) ptr, len);
392 } while (ret == -1 && errno == EINTR);
393
394 if (ret == -1) {
395 if (pdata->blocking && errno == EAGAIN)
396 continue;
397
398 ret = -errno;
399 break;
400 } else if (ret == 0) {
401 ret = -EIO;
402 break;
403 }
404
405 ptr += ret;
406 len -= ret;
407 }
408
409 writtensize = (ssize_t)(ptr - (uintptr_t) src);
410 if ((ret > 0 || ret == -EAGAIN) && (writtensize > 0))
411 return writtensize;
412 else
413 return ret;
414 }
415
local_enable_buffer(const struct iio_device * dev)416 static ssize_t local_enable_buffer(const struct iio_device *dev)
417 {
418 struct iio_device_pdata *pdata = dev->pdata;
419 ssize_t ret = 0;
420
421 if (!pdata->buffer_enabled) {
422 ret = local_write_dev_attr(dev,
423 "buffer/enable", "1", 2, false);
424 if (ret >= 0)
425 pdata->buffer_enabled = true;
426 }
427
428 return ret;
429 }
430
local_set_kernel_buffers_count(const struct iio_device * dev,unsigned int nb_blocks)431 static int local_set_kernel_buffers_count(const struct iio_device *dev,
432 unsigned int nb_blocks)
433 {
434 struct iio_device_pdata *pdata = dev->pdata;
435
436 if (pdata->fd != -1)
437 return -EBUSY;
438
439 pdata->max_nb_blocks = nb_blocks;
440
441 return 0;
442 }
443
local_get_buffer(const struct iio_device * dev,void ** addr_ptr,size_t bytes_used,uint32_t * mask,size_t words)444 static ssize_t local_get_buffer(const struct iio_device *dev,
445 void **addr_ptr, size_t bytes_used,
446 uint32_t *mask, size_t words)
447 {
448 struct block block;
449 struct iio_device_pdata *pdata = dev->pdata;
450 struct timespec start;
451 char err_str[1024];
452 int f = pdata->fd;
453 ssize_t ret;
454
455 if (!pdata->is_high_speed)
456 return -ENOSYS;
457 if (f == -1)
458 return -EBADF;
459 if (!addr_ptr)
460 return -EINVAL;
461
462 if (pdata->last_dequeued >= 0) {
463 struct block *last_block = &pdata->blocks[pdata->last_dequeued];
464
465 if (pdata->cyclic) {
466 if (pdata->cyclic_buffer_enqueued)
467 return -EBUSY;
468 pdata->blocks[0].flags |= BLOCK_FLAG_CYCLIC;
469 pdata->cyclic_buffer_enqueued = true;
470 }
471
472 last_block->bytes_used = bytes_used;
473 ret = (ssize_t) ioctl_nointr(f,
474 BLOCK_ENQUEUE_IOCTL, last_block);
475 if (ret) {
476 ret = (ssize_t) -errno;
477 iio_strerror(errno, err_str, sizeof(err_str));
478 ERROR("Unable to enqueue block: %s\n", err_str);
479 return ret;
480 }
481
482 if (pdata->cyclic) {
483 *addr_ptr = pdata->addrs[pdata->last_dequeued];
484 return (ssize_t) last_block->bytes_used;
485 }
486
487 pdata->last_dequeued = -1;
488 }
489
490 clock_gettime(CLOCK_MONOTONIC, &start);
491
492 do {
493 ret = (ssize_t) device_check_ready(dev, POLLIN | POLLOUT, &start);
494 if (ret < 0)
495 return ret;
496
497 memset(&block, 0, sizeof(block));
498 ret = (ssize_t) ioctl_nointr(f, BLOCK_DEQUEUE_IOCTL, &block);
499 } while (pdata->blocking && ret == -1 && errno == EAGAIN);
500
501 if (ret) {
502 ret = (ssize_t) -errno;
503 if ((!pdata->blocking && ret != -EAGAIN) ||
504 (pdata->blocking && ret != -ETIMEDOUT)) {
505 iio_strerror(errno, err_str, sizeof(err_str));
506 ERROR("Unable to dequeue block: %s\n", err_str);
507 }
508 return ret;
509 }
510
511 /* Requested buffer size is too big! */
512 if (pdata->last_dequeued < 0 && bytes_used != block.size)
513 return -EFBIG;
514
515 pdata->last_dequeued = block.id;
516 *addr_ptr = pdata->addrs[block.id];
517 return (ssize_t) block.bytes_used;
518 }
519
local_read_all_dev_attrs(const struct iio_device * dev,char * dst,size_t len,enum iio_attr_type type)520 static ssize_t local_read_all_dev_attrs(const struct iio_device *dev,
521 char *dst, size_t len, enum iio_attr_type type)
522 {
523 unsigned int i, nb;
524 char **attrs;
525 char *ptr = dst;
526
527 switch (type) {
528 case IIO_ATTR_TYPE_DEVICE:
529 nb = dev->nb_attrs;
530 attrs = dev->attrs;
531 break;
532 case IIO_ATTR_TYPE_DEBUG:
533 nb = dev->nb_debug_attrs;
534 attrs = dev->debug_attrs;
535 break;
536 case IIO_ATTR_TYPE_BUFFER:
537 nb = dev->nb_buffer_attrs;
538 attrs = dev->buffer_attrs;
539 break;
540 default:
541 return -EINVAL;
542 break;
543 }
544
545 for (i = 0; len >= 4 && i < nb; i++) {
546 /* Recursive! */
547 ssize_t ret = local_read_dev_attr(dev, attrs[i],
548 ptr + 4, len - 4, type);
549 *(uint32_t *) ptr = iio_htobe32(ret);
550
551 /* Align the length to 4 bytes */
552 if (ret > 0 && ret & 3)
553 ret = ((ret >> 2) + 1) << 2;
554 ptr += 4 + (ret < 0 ? 0 : ret);
555 len -= 4 + (ret < 0 ? 0 : ret);
556 }
557
558 return ptr - dst;
559 }
560
local_read_all_chn_attrs(const struct iio_channel * chn,char * dst,size_t len)561 static ssize_t local_read_all_chn_attrs(const struct iio_channel *chn,
562 char *dst, size_t len)
563 {
564 unsigned int i;
565 char *ptr = dst;
566
567 for (i = 0; len >= 4 && i < chn->nb_attrs; i++) {
568 /* Recursive! */
569 ssize_t ret = local_read_chn_attr(chn,
570 chn->attrs[i].name, ptr + 4, len - 4);
571 *(uint32_t *) ptr = iio_htobe32(ret);
572
573 /* Align the length to 4 bytes */
574 if (ret > 0 && ret & 3)
575 ret = ((ret >> 2) + 1) << 2;
576 ptr += 4 + (ret < 0 ? 0 : ret);
577 len -= 4 + (ret < 0 ? 0 : ret);
578 }
579
580 return ptr - dst;
581 }
582
local_buffer_analyze(unsigned int nb,const char * src,size_t len)583 static int local_buffer_analyze(unsigned int nb, const char *src, size_t len)
584 {
585 while (nb--) {
586 int32_t val;
587
588 if (len < 4)
589 return -EINVAL;
590
591 val = (int32_t) iio_be32toh(*(uint32_t *) src);
592 src += 4;
593 len -= 4;
594
595 if (val > 0) {
596 if ((uint32_t) val > len)
597 return -EINVAL;
598
599 /* Align the length to 4 bytes */
600 if (val & 3)
601 val = ((val >> 2) + 1) << 2;
602 len -= val;
603 src += val;
604 }
605 }
606
607 /* We should have analyzed the whole buffer by now */
608 return !len ? 0 : -EINVAL;
609 }
610
local_write_all_dev_attrs(const struct iio_device * dev,const char * src,size_t len,enum iio_attr_type type)611 static ssize_t local_write_all_dev_attrs(const struct iio_device *dev,
612 const char *src, size_t len, enum iio_attr_type type)
613 {
614 unsigned int i, nb;
615 char **attrs;
616 const char *ptr = src;
617
618 switch (type) {
619 case IIO_ATTR_TYPE_DEVICE:
620 nb = dev->nb_attrs;
621 attrs = dev->attrs;
622 break;
623 case IIO_ATTR_TYPE_DEBUG:
624 nb = dev->nb_debug_attrs;
625 attrs = dev->debug_attrs;
626 break;
627 case IIO_ATTR_TYPE_BUFFER:
628 nb = dev->nb_buffer_attrs;
629 attrs = dev->buffer_attrs;
630 break;
631 default:
632 return -EINVAL;
633 break;
634 }
635
636 /* First step: Verify that the buffer is in the correct format */
637 if (local_buffer_analyze(nb, src, len))
638 return -EINVAL;
639
640 /* Second step: write the attributes */
641 for (i = 0; i < nb; i++) {
642 int32_t val = (int32_t) iio_be32toh(*(uint32_t *) ptr);
643 ptr += 4;
644
645 if (val > 0) {
646 local_write_dev_attr(dev, attrs[i], ptr, val, type);
647
648 /* Align the length to 4 bytes */
649 if (val & 3)
650 val = ((val >> 2) + 1) << 2;
651 ptr += val;
652 }
653 }
654
655 return ptr - src;
656 }
657
local_write_all_chn_attrs(const struct iio_channel * chn,const char * src,size_t len)658 static ssize_t local_write_all_chn_attrs(const struct iio_channel *chn,
659 const char *src, size_t len)
660 {
661 unsigned int i, nb = chn->nb_attrs;
662 const char *ptr = src;
663
664 /* First step: Verify that the buffer is in the correct format */
665 if (local_buffer_analyze(nb, src, len))
666 return -EINVAL;
667
668 /* Second step: write the attributes */
669 for (i = 0; i < nb; i++) {
670 int32_t val = (int32_t) iio_be32toh(*(uint32_t *) ptr);
671 ptr += 4;
672
673 if (val > 0) {
674 local_write_chn_attr(chn, chn->attrs[i].name, ptr, val);
675
676 /* Align the length to 4 bytes */
677 if (val & 3)
678 val = ((val >> 2) + 1) << 2;
679 ptr += val;
680 }
681 }
682
683 return ptr - src;
684 }
685
local_read_dev_attr(const struct iio_device * dev,const char * attr,char * dst,size_t len,enum iio_attr_type type)686 static ssize_t local_read_dev_attr(const struct iio_device *dev,
687 const char *attr, char *dst, size_t len, enum iio_attr_type type)
688 {
689 FILE *f;
690 char buf[1024];
691 ssize_t ret;
692
693 if (!attr)
694 return local_read_all_dev_attrs(dev, dst, len, type);
695
696 switch (type) {
697 case IIO_ATTR_TYPE_DEVICE:
698 iio_snprintf(buf, sizeof(buf), "/sys/bus/iio/devices/%s/%s",
699 dev->id, attr);
700 break;
701 case IIO_ATTR_TYPE_DEBUG:
702 iio_snprintf(buf, sizeof(buf), "/sys/kernel/debug/iio/%s/%s",
703 dev->id, attr);
704 break;
705 case IIO_ATTR_TYPE_BUFFER:
706 iio_snprintf(buf, sizeof(buf), "/sys/bus/iio/devices/%s/buffer/%s",
707 dev->id, attr);
708 break;
709 default:
710 return -EINVAL;
711 }
712
713 f = fopen(buf, "re");
714 if (!f)
715 return -errno;
716
717 ret = fread(dst, 1, len, f);
718 if (ret > 0)
719 dst[ret - 1] = '\0';
720 fflush(f);
721 if (ferror(f))
722 ret = -errno;
723 fclose(f);
724 return ret ? ret : -EIO;
725 }
726
local_write_dev_attr(const struct iio_device * dev,const char * attr,const char * src,size_t len,enum iio_attr_type type)727 static ssize_t local_write_dev_attr(const struct iio_device *dev,
728 const char *attr, const char *src, size_t len, enum iio_attr_type type)
729 {
730 FILE *f;
731 char buf[1024];
732 ssize_t ret;
733
734 if (!attr)
735 return local_write_all_dev_attrs(dev, src, len, type);
736
737 switch (type) {
738 case IIO_ATTR_TYPE_DEVICE:
739 iio_snprintf(buf, sizeof(buf), "/sys/bus/iio/devices/%s/%s",
740 dev->id, attr);
741 break;
742 case IIO_ATTR_TYPE_DEBUG:
743 iio_snprintf(buf, sizeof(buf), "/sys/kernel/debug/iio/%s/%s",
744 dev->id, attr);
745 break;
746 case IIO_ATTR_TYPE_BUFFER:
747 iio_snprintf(buf, sizeof(buf), "/sys/bus/iio/devices/%s/buffer/%s",
748 dev->id, attr);
749 break;
750 default:
751 return -EINVAL;
752 }
753
754 f = fopen(buf, "we");
755 if (!f)
756 return -errno;
757
758 ret = fwrite(src, 1, len, f);
759 fflush(f);
760 if (ferror(f))
761 ret = -errno;
762 fclose(f);
763 return ret ? ret : -EIO;
764 }
765
get_filename(const struct iio_channel * chn,const char * attr)766 static const char * get_filename(const struct iio_channel *chn,
767 const char *attr)
768 {
769 unsigned int i;
770 for (i = 0; i < chn->nb_attrs; i++)
771 if (!strcmp(attr, chn->attrs[i].name))
772 return chn->attrs[i].filename;
773 return attr;
774 }
775
local_read_chn_attr(const struct iio_channel * chn,const char * attr,char * dst,size_t len)776 static ssize_t local_read_chn_attr(const struct iio_channel *chn,
777 const char *attr, char *dst, size_t len)
778 {
779 if (!attr)
780 return local_read_all_chn_attrs(chn, dst, len);
781
782 attr = get_filename(chn, attr);
783 return local_read_dev_attr(chn->dev, attr, dst, len, false);
784 }
785
local_write_chn_attr(const struct iio_channel * chn,const char * attr,const char * src,size_t len)786 static ssize_t local_write_chn_attr(const struct iio_channel *chn,
787 const char *attr, const char *src, size_t len)
788 {
789 if (!attr)
790 return local_write_all_chn_attrs(chn, src, len);
791
792 attr = get_filename(chn, attr);
793 return local_write_dev_attr(chn->dev, attr, src, len, false);
794 }
795
channel_write_state(const struct iio_channel * chn,bool en)796 static int channel_write_state(const struct iio_channel *chn, bool en)
797 {
798 ssize_t ret;
799
800 if (!chn->pdata->enable_fn) {
801 ERROR("Libiio bug: No \"en\" attribute parsed\n");
802 return -EINVAL;
803 }
804
805 ret = local_write_chn_attr(chn, chn->pdata->enable_fn, en ? "1" : "0", 2);
806 if (ret < 0)
807 return (int) ret;
808 else
809 return 0;
810 }
811
enable_high_speed(const struct iio_device * dev)812 static int enable_high_speed(const struct iio_device *dev)
813 {
814 struct block_alloc_req req;
815 struct iio_device_pdata *pdata = dev->pdata;
816 unsigned int nb_blocks;
817 unsigned int i;
818 int ret, fd = pdata->fd;
819
820 /*
821 * For the BLOCK_ALLOC_IOCTL ioctl it is not possible to distingush
822 * between an error during the allocation (e.g. incorrect size) or
823 * whether the high-speed interface is not supported. BLOCK_FREE_IOCTL does
824 * never fail if the device supports the high-speed interface, so we use it
825 * here. Calling it when no blocks are allocated the ioctl has no effect.
826 */
827 ret = ioctl_nointr(fd, BLOCK_FREE_IOCTL, NULL);
828 if (ret < 0)
829 return -ENOSYS;
830
831 if (pdata->cyclic) {
832 nb_blocks = 1;
833 DEBUG("Enabling cyclic mode\n");
834 } else {
835 nb_blocks = pdata->max_nb_blocks;
836 DEBUG("Cyclic mode not enabled\n");
837 }
838
839 pdata->blocks = calloc(nb_blocks, sizeof(*pdata->blocks));
840 if (!pdata->blocks)
841 return -ENOMEM;
842
843 pdata->addrs = calloc(nb_blocks, sizeof(*pdata->addrs));
844 if (!pdata->addrs) {
845 free(pdata->blocks);
846 pdata->blocks = NULL;
847 return -ENOMEM;
848 }
849
850 req.id = 0;
851 req.type = 0;
852 req.size = pdata->samples_count *
853 iio_device_get_sample_size_mask(dev, dev->mask, dev->words);
854 req.count = nb_blocks;
855
856 ret = ioctl_nointr(fd, BLOCK_ALLOC_IOCTL, &req);
857 if (ret < 0) {
858 ret = -errno;
859 goto err_freemem;
860 }
861
862 if (req.count == 0) {
863 ret = -ENOMEM;
864 goto err_block_free;
865 }
866
867 /* We might get less blocks than what we asked for */
868 pdata->allocated_nb_blocks = req.count;
869
870 /* mmap all the blocks */
871 for (i = 0; i < pdata->allocated_nb_blocks; i++) {
872 pdata->blocks[i].id = i;
873 ret = ioctl_nointr(fd, BLOCK_QUERY_IOCTL, &pdata->blocks[i]);
874 if (ret) {
875 ret = -errno;
876 goto err_munmap;
877 }
878
879 ret = ioctl_nointr(fd, BLOCK_ENQUEUE_IOCTL, &pdata->blocks[i]);
880 if (ret) {
881 ret = -errno;
882 goto err_munmap;
883 }
884
885 pdata->addrs[i] = mmap(0, pdata->blocks[i].size,
886 PROT_READ | PROT_WRITE,
887 MAP_SHARED, fd, pdata->blocks[i].offset);
888 if (pdata->addrs[i] == MAP_FAILED) {
889 ret = -errno;
890 goto err_munmap;
891 }
892 }
893
894 pdata->last_dequeued = -1;
895 return 0;
896
897 err_munmap:
898 for (; i > 0; i--)
899 munmap(pdata->addrs[i - 1], pdata->blocks[i - 1].size);
900 err_block_free:
901 ioctl_nointr(fd, BLOCK_FREE_IOCTL, 0);
902 pdata->allocated_nb_blocks = 0;
903 err_freemem:
904 free(pdata->addrs);
905 pdata->addrs = NULL;
906 free(pdata->blocks);
907 pdata->blocks = NULL;
908 return ret;
909 }
910
local_open(const struct iio_device * dev,size_t samples_count,bool cyclic)911 static int local_open(const struct iio_device *dev,
912 size_t samples_count, bool cyclic)
913 {
914 unsigned int i;
915 int ret;
916 char buf[1024];
917 struct iio_device_pdata *pdata = dev->pdata;
918
919 if (pdata->fd != -1)
920 return -EBUSY;
921
922 ret = local_write_dev_attr(dev, "buffer/enable", "0", 2, false);
923 if (ret < 0)
924 return ret;
925
926 iio_snprintf(buf, sizeof(buf), "%lu", (unsigned long) samples_count);
927 ret = local_write_dev_attr(dev, "buffer/length",
928 buf, strlen(buf) + 1, false);
929 if (ret < 0)
930 return ret;
931
932 pdata->cancel_fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
933 if (pdata->cancel_fd == -1)
934 return -errno;
935
936 iio_snprintf(buf, sizeof(buf), "/dev/%s", dev->id);
937 pdata->fd = open(buf, O_RDWR | O_CLOEXEC | O_NONBLOCK);
938 if (pdata->fd == -1) {
939 ret = -errno;
940 goto err_close_cancel_fd;
941 }
942
943 /* Disable channels */
944 for (i = 0; i < dev->nb_channels; i++) {
945 struct iio_channel *chn = dev->channels[i];
946 if (chn->index >= 0 && !iio_channel_is_enabled(chn)) {
947 ret = channel_write_state(chn, false);
948 if (ret < 0)
949 goto err_close;
950 }
951 }
952 /* Enable channels */
953 for (i = 0; i < dev->nb_channels; i++) {
954 struct iio_channel *chn = dev->channels[i];
955 if (chn->index >= 0 && iio_channel_is_enabled(chn)) {
956 ret = channel_write_state(chn, true);
957 if (ret < 0)
958 goto err_close;
959 }
960 }
961
962 pdata->cyclic = cyclic;
963 pdata->cyclic_buffer_enqueued = false;
964 pdata->buffer_enabled = false;
965 pdata->samples_count = samples_count;
966
967 ret = enable_high_speed(dev);
968 if (ret < 0 && ret != -ENOSYS)
969 goto err_close;
970
971 pdata->is_high_speed = !ret;
972
973 if (!pdata->is_high_speed) {
974 unsigned long size = samples_count * pdata->max_nb_blocks;
975 WARNING("High-speed mode not enabled\n");
976
977 /* Cyclic mode is only supported in high-speed mode */
978 if (cyclic) {
979 ret = -EPERM;
980 goto err_close;
981 }
982
983 /* Increase the size of the kernel buffer, when using the
984 * low-speed interface. This avoids losing samples when
985 * refilling the iio_buffer. */
986 iio_snprintf(buf, sizeof(buf), "%lu", size);
987 ret = local_write_dev_attr(dev, "buffer/length",
988 buf, strlen(buf) + 1, false);
989 if (ret < 0)
990 goto err_close;
991 }
992
993 ret = local_enable_buffer(dev);
994 if (ret < 0)
995 goto err_close;
996
997 return 0;
998 err_close:
999 close(pdata->fd);
1000 pdata->fd = -1;
1001 err_close_cancel_fd:
1002 close(pdata->cancel_fd);
1003 pdata->cancel_fd = -1;
1004 return ret;
1005 }
1006
local_close(const struct iio_device * dev)1007 static int local_close(const struct iio_device *dev)
1008 {
1009 struct iio_device_pdata *pdata = dev->pdata;
1010 unsigned int i;
1011 int ret;
1012
1013 if (pdata->fd == -1)
1014 return -EBADF;
1015
1016 if (pdata->is_high_speed) {
1017 unsigned int i;
1018 for (i = 0; i < pdata->allocated_nb_blocks; i++)
1019 munmap(pdata->addrs[i], pdata->blocks[i].size);
1020 ioctl_nointr(pdata->fd, BLOCK_FREE_IOCTL, 0);
1021 pdata->allocated_nb_blocks = 0;
1022 free(pdata->addrs);
1023 pdata->addrs = NULL;
1024 free(pdata->blocks);
1025 pdata->blocks = NULL;
1026 }
1027
1028 ret = close(pdata->fd);
1029 if (ret)
1030 return ret;
1031
1032 close(pdata->cancel_fd);
1033
1034 pdata->fd = -1;
1035 pdata->cancel_fd = -1;
1036
1037 ret = local_write_dev_attr(dev, "buffer/enable", "0", 2, false);
1038
1039 for (i = 0; i < dev->nb_channels; i++) {
1040 struct iio_channel *chn = dev->channels[i];
1041
1042 if (chn->pdata->enable_fn)
1043 channel_write_state(chn, false);
1044 }
1045
1046 return (ret < 0) ? ret : 0;
1047 }
1048
local_get_fd(const struct iio_device * dev)1049 static int local_get_fd(const struct iio_device *dev)
1050 {
1051 if (dev->pdata->fd == -1)
1052 return -EBADF;
1053 else
1054 return dev->pdata->fd;
1055 }
1056
local_set_blocking_mode(const struct iio_device * dev,bool blocking)1057 static int local_set_blocking_mode(const struct iio_device *dev, bool blocking)
1058 {
1059 if (dev->pdata->fd == -1)
1060 return -EBADF;
1061
1062 if (dev->pdata->cyclic)
1063 return -EPERM;
1064
1065 dev->pdata->blocking = blocking;
1066
1067 return 0;
1068 }
1069
local_get_trigger(const struct iio_device * dev,const struct iio_device ** trigger)1070 static int local_get_trigger(const struct iio_device *dev,
1071 const struct iio_device **trigger)
1072 {
1073 char buf[1024];
1074 unsigned int i;
1075 ssize_t nb = local_read_dev_attr(dev, "trigger/current_trigger",
1076 buf, sizeof(buf), false);
1077 if (nb < 0) {
1078 *trigger = NULL;
1079 return (int) nb;
1080 }
1081
1082 if (buf[0] == '\0') {
1083 *trigger = NULL;
1084 return 0;
1085 }
1086
1087 nb = dev->ctx->nb_devices;
1088 for (i = 0; i < (size_t) nb; i++) {
1089 const struct iio_device *cur = dev->ctx->devices[i];
1090 if (cur->name && !strcmp(cur->name, buf)) {
1091 *trigger = cur;
1092 return 0;
1093 }
1094 }
1095 return -ENXIO;
1096 }
1097
local_set_trigger(const struct iio_device * dev,const struct iio_device * trigger)1098 static int local_set_trigger(const struct iio_device *dev,
1099 const struct iio_device *trigger)
1100 {
1101 ssize_t nb;
1102 const char *value = trigger ? trigger->name : "";
1103 nb = local_write_dev_attr(dev, "trigger/current_trigger",
1104 value, strlen(value) + 1, false);
1105 if (nb < 0)
1106 return (int) nb;
1107 else
1108 return 0;
1109 }
1110
is_channel(const char * attr,bool strict)1111 static bool is_channel(const char *attr, bool strict)
1112 {
1113 char *ptr = NULL;
1114 if (!strncmp(attr, "in_timestamp_", sizeof("in_timestamp_") - 1))
1115 return true;
1116 if (!strncmp(attr, "in_", 3))
1117 ptr = strchr(attr + 3, '_');
1118 else if (!strncmp(attr, "out_", 4))
1119 ptr = strchr(attr + 4, '_');
1120 if (!ptr)
1121 return false;
1122 if (!strict)
1123 return true;
1124 if (*(ptr - 1) >= '0' && *(ptr - 1) <= '9')
1125 return true;
1126
1127 if (find_channel_modifier(ptr + 1, NULL) != IIO_NO_MOD)
1128 return true;
1129 return false;
1130 }
1131
get_channel_id(const char * attr)1132 static char * get_channel_id(const char *attr)
1133 {
1134 char *res, *ptr;
1135 size_t len;
1136
1137 attr = strchr(attr, '_') + 1;
1138 ptr = strchr(attr, '_');
1139 if (find_channel_modifier(ptr + 1, &len) != IIO_NO_MOD)
1140 ptr += len + 1;
1141
1142 res = malloc(ptr - attr + 1);
1143 if (!res)
1144 return NULL;
1145
1146 memcpy(res, attr, ptr - attr);
1147 res[ptr - attr] = 0;
1148 return res;
1149 }
1150
get_short_attr_name(struct iio_channel * chn,const char * attr)1151 static char * get_short_attr_name(struct iio_channel *chn, const char *attr)
1152 {
1153 char *ptr = strchr(attr, '_') + 1;
1154 size_t len;
1155
1156 ptr = strchr(ptr, '_') + 1;
1157 if (find_channel_modifier(ptr, &len) != IIO_NO_MOD)
1158 ptr += len + 1;
1159
1160 if (chn->name) {
1161 size_t len = strlen(chn->name);
1162 if (strncmp(chn->name, ptr, len) == 0 && ptr[len] == '_')
1163 ptr += len + 1;
1164 }
1165
1166 return iio_strdup(ptr);
1167 }
1168
read_device_name(struct iio_device * dev)1169 static int read_device_name(struct iio_device *dev)
1170 {
1171 char buf[1024];
1172 ssize_t ret = iio_device_attr_read(dev, "name", buf, sizeof(buf));
1173 if (ret < 0)
1174 return ret;
1175 else if (ret == 0)
1176 return -EIO;
1177
1178 dev->name = iio_strdup(buf);
1179 if (!dev->name)
1180 return -ENOMEM;
1181 else
1182 return 0;
1183 }
1184
add_attr_to_device(struct iio_device * dev,const char * attr)1185 static int add_attr_to_device(struct iio_device *dev, const char *attr)
1186 {
1187 char **attrs, *name;
1188 unsigned int i;
1189
1190 for (i = 0; i < ARRAY_SIZE(device_attrs_blacklist); i++)
1191 if (!strcmp(device_attrs_blacklist[i], attr))
1192 return 0;
1193
1194 if (!strcmp(attr, "name"))
1195 return read_device_name(dev);
1196
1197 name = iio_strdup(attr);
1198 if (!name)
1199 return -ENOMEM;
1200
1201 attrs = realloc(dev->attrs, (1 + dev->nb_attrs) * sizeof(char *));
1202 if (!attrs) {
1203 free(name);
1204 return -ENOMEM;
1205 }
1206
1207 attrs[dev->nb_attrs++] = name;
1208 dev->attrs = attrs;
1209 DEBUG("Added attr \'%s\' to device \'%s\'\n", attr, dev->id);
1210 return 0;
1211 }
1212
handle_protected_scan_element_attr(struct iio_channel * chn,const char * name,const char * path)1213 static int handle_protected_scan_element_attr(struct iio_channel *chn,
1214 const char *name, const char *path)
1215 {
1216 struct iio_device *dev = chn->dev;
1217 char buf[1024];
1218 int ret;
1219
1220 if (!strcmp(name, "index")) {
1221 ret = local_read_dev_attr(dev, path, buf, sizeof(buf), false);
1222 if (ret > 0)
1223 chn->index = atol(buf);
1224
1225 } else if (!strcmp(name, "type")) {
1226 ret = local_read_dev_attr(dev, path, buf, sizeof(buf), false);
1227 if (ret > 0) {
1228 char endian, sign;
1229
1230 if (strchr(buf, 'X')) {
1231 sscanf(buf, "%ce:%c%u/%uX%u>>%u", &endian, &sign,
1232 &chn->format.bits, &chn->format.length,
1233 &chn->format.repeat, &chn->format.shift);
1234 } else {
1235 chn->format.repeat = 1;
1236 sscanf(buf, "%ce:%c%u/%u>>%u", &endian, &sign,
1237 &chn->format.bits, &chn->format.length,
1238 &chn->format.shift);
1239 }
1240 chn->format.is_signed = (sign == 's' || sign == 'S');
1241 chn->format.is_fully_defined =
1242 (sign == 'S' || sign == 'U'||
1243 chn->format.bits == chn->format.length);
1244 chn->format.is_be = endian == 'b';
1245 }
1246
1247 } else if (!strcmp(name, "en")) {
1248 if (chn->pdata->enable_fn) {
1249 ERROR("Libiio bug: \"en\" attribute already parsed for channel %s!\n",
1250 chn->id);
1251 return -EINVAL;
1252 }
1253
1254 chn->pdata->enable_fn = iio_strdup(path);
1255 if (!chn->pdata->enable_fn)
1256 return -ENOMEM;
1257
1258 } else {
1259 return -EINVAL;
1260 }
1261
1262 return 0;
1263 }
1264
handle_scan_elements(struct iio_channel * chn)1265 static int handle_scan_elements(struct iio_channel *chn)
1266 {
1267 struct iio_channel_pdata *pdata = chn->pdata;
1268 unsigned int i;
1269
1270 for (i = 0; i < pdata->nb_protected_attrs; i++) {
1271 int ret = handle_protected_scan_element_attr(chn,
1272 pdata->protected_attrs[i].name,
1273 pdata->protected_attrs[i].filename);
1274 if (ret < 0)
1275 return ret;
1276 }
1277
1278 return 0;
1279 }
1280
add_protected_attr(struct iio_channel * chn,char * name,char * fn)1281 static int add_protected_attr(struct iio_channel *chn, char *name, char *fn)
1282 {
1283 struct iio_channel_pdata *pdata = chn->pdata;
1284 struct iio_channel_attr *attrs;
1285
1286 attrs = realloc(pdata->protected_attrs,
1287 (1 + pdata->nb_protected_attrs) * sizeof(*attrs));
1288 if (!attrs)
1289 return -ENOMEM;
1290
1291 attrs[pdata->nb_protected_attrs].name = name;
1292 attrs[pdata->nb_protected_attrs++].filename = fn;
1293 pdata->protected_attrs = attrs;
1294
1295 DEBUG("Add protected attr \'%s\' to channel \'%s\'\n", name, chn->id);
1296 return 0;
1297 }
1298
free_protected_attrs(struct iio_channel * chn)1299 static void free_protected_attrs(struct iio_channel *chn)
1300 {
1301 struct iio_channel_pdata *pdata = chn->pdata;
1302 unsigned int i;
1303
1304 for (i = 0; i < pdata->nb_protected_attrs; i++) {
1305 free(pdata->protected_attrs[i].name);
1306 free(pdata->protected_attrs[i].filename);
1307 }
1308
1309 free(pdata->protected_attrs);
1310 pdata->nb_protected_attrs = 0;
1311 pdata->protected_attrs = NULL;
1312 }
1313
add_attr_to_channel(struct iio_channel * chn,const char * attr,const char * path,bool is_scan_element)1314 static int add_attr_to_channel(struct iio_channel *chn,
1315 const char *attr, const char *path, bool is_scan_element)
1316 {
1317 struct iio_channel_attr *attrs;
1318 char *fn, *name = get_short_attr_name(chn, attr);
1319 if (!name)
1320 return -ENOMEM;
1321
1322 fn = iio_strdup(path);
1323 if (!fn)
1324 goto err_free_name;
1325
1326 if (is_scan_element) {
1327 int ret = add_protected_attr(chn, name, fn);
1328
1329 if (ret < 0)
1330 goto err_free_fn;
1331
1332 return 0;
1333 }
1334
1335 attrs = realloc(chn->attrs, (1 + chn->nb_attrs) *
1336 sizeof(struct iio_channel_attr));
1337 if (!attrs)
1338 goto err_free_fn;
1339
1340 attrs[chn->nb_attrs].filename = fn;
1341 attrs[chn->nb_attrs++].name = name;
1342 chn->attrs = attrs;
1343 DEBUG("Added attr \'%s\' to channel \'%s\'\n", name, chn->id);
1344 return 0;
1345
1346 err_free_fn:
1347 free(fn);
1348 err_free_name:
1349 free(name);
1350 return -ENOMEM;
1351 }
1352
add_channel_to_device(struct iio_device * dev,struct iio_channel * chn)1353 static int add_channel_to_device(struct iio_device *dev,
1354 struct iio_channel *chn)
1355 {
1356 struct iio_channel **channels = realloc(dev->channels,
1357 (dev->nb_channels + 1) * sizeof(struct iio_channel *));
1358 if (!channels)
1359 return -ENOMEM;
1360
1361 channels[dev->nb_channels++] = chn;
1362 dev->channels = channels;
1363 DEBUG("Added %s channel \'%s\' to device \'%s\'\n",
1364 chn->is_output ? "output" : "input", chn->id, dev->id);
1365
1366 return 0;
1367 }
1368
add_device_to_context(struct iio_context * ctx,struct iio_device * dev)1369 static int add_device_to_context(struct iio_context *ctx,
1370 struct iio_device *dev)
1371 {
1372 struct iio_device **devices = realloc(ctx->devices,
1373 (ctx->nb_devices + 1) * sizeof(struct iio_device *));
1374 if (!devices)
1375 return -ENOMEM;
1376
1377 devices[ctx->nb_devices++] = dev;
1378 ctx->devices = devices;
1379 DEBUG("Added device \'%s\' to context \'%s\'\n", dev->id, ctx->name);
1380 return 0;
1381 }
1382
create_channel(struct iio_device * dev,char * id,const char * attr,const char * path,bool is_scan_element)1383 static struct iio_channel *create_channel(struct iio_device *dev,
1384 char *id, const char *attr, const char *path,
1385 bool is_scan_element)
1386 {
1387 struct iio_channel *chn = zalloc(sizeof(*chn));
1388 if (!chn)
1389 return NULL;
1390
1391 chn->pdata = zalloc(sizeof(*chn->pdata));
1392 if (!chn->pdata)
1393 goto err_free_chn;
1394
1395 if (!strncmp(attr, "out_", 4))
1396 chn->is_output = true;
1397 else if (strncmp(attr, "in_", 3))
1398 goto err_free_chn_pdata;
1399
1400 chn->dev = dev;
1401 chn->id = id;
1402 chn->is_scan_element = is_scan_element;
1403 chn->index = -ENOENT;
1404
1405 if (!add_attr_to_channel(chn, attr, path, is_scan_element))
1406 return chn;
1407
1408 err_free_chn_pdata:
1409 free(chn->pdata->enable_fn);
1410 free(chn->pdata);
1411 err_free_chn:
1412 free(chn);
1413 return NULL;
1414 }
1415
add_channel(struct iio_device * dev,const char * name,const char * path,bool dir_is_scan_elements)1416 static int add_channel(struct iio_device *dev, const char *name,
1417 const char *path, bool dir_is_scan_elements)
1418 {
1419 struct iio_channel *chn;
1420 char *channel_id;
1421 unsigned int i;
1422 int ret;
1423
1424 channel_id = get_channel_id(name);
1425 if (!channel_id)
1426 return -ENOMEM;
1427
1428 for (i = 0; i < dev->nb_channels; i++) {
1429 chn = dev->channels[i];
1430 if (!strcmp(chn->id, channel_id)
1431 && chn->is_output == (name[0] == 'o')) {
1432 free(channel_id);
1433 ret = add_attr_to_channel(chn, name, path,
1434 dir_is_scan_elements);
1435 chn->is_scan_element = dir_is_scan_elements && !ret;
1436 return ret;
1437 }
1438 }
1439
1440 chn = create_channel(dev, channel_id, name, path, dir_is_scan_elements);
1441 if (!chn) {
1442 free(channel_id);
1443 return -ENXIO;
1444 }
1445
1446 iio_channel_init_finalize(chn);
1447
1448 ret = add_channel_to_device(dev, chn);
1449 if (ret) {
1450 free(chn->pdata->enable_fn);
1451 free(chn->pdata);
1452 free_channel(chn);
1453 }
1454 return ret;
1455 }
1456
1457 /*
1458 * Possible return values:
1459 * 0 = Attribute should not be moved to the channel
1460 * 1 = Attribute should be moved to the channel and it is a shared attribute
1461 * 2 = Attribute should be moved to the channel and it is a private attribute
1462 */
is_global_attr(struct iio_channel * chn,const char * attr)1463 static unsigned int is_global_attr(struct iio_channel *chn, const char *attr)
1464 {
1465 unsigned int len;
1466 char *ptr;
1467
1468 if (!chn->is_output && !strncmp(attr, "in_", 3))
1469 attr += 3;
1470 else if (chn->is_output && !strncmp(attr, "out_", 4))
1471 attr += 4;
1472 else
1473 return 0;
1474
1475 ptr = strchr(attr, '_');
1476 if (!ptr)
1477 return 0;
1478
1479 len = ptr - attr;
1480
1481 if (strncmp(chn->id, attr, len))
1482 return 0;
1483
1484 DEBUG("Found match: %s and %s\n", chn->id, attr);
1485 if (chn->id[len] >= '0' && chn->id[len] <= '9') {
1486 if (chn->name) {
1487 size_t name_len = strlen(chn->name);
1488 if (strncmp(chn->name, attr + len + 1, name_len) == 0 &&
1489 attr[len + 1 + name_len] == '_')
1490 return 2;
1491 }
1492 return 1;
1493 } else if (chn->id[len] != '_') {
1494 return 0;
1495 }
1496
1497 if (find_channel_modifier(chn->id + len + 1, NULL) != IIO_NO_MOD)
1498 return 1;
1499
1500 return 0;
1501 }
1502
detect_global_attr(struct iio_device * dev,const char * attr,unsigned int level,bool * match)1503 static int detect_global_attr(struct iio_device *dev, const char *attr,
1504 unsigned int level, bool *match)
1505 {
1506 unsigned int i;
1507
1508 *match = false;
1509 for (i = 0; i < dev->nb_channels; i++) {
1510 struct iio_channel *chn = dev->channels[i];
1511 if (is_global_attr(chn, attr) == level) {
1512 int ret;
1513 *match = true;
1514 ret = add_attr_to_channel(chn, attr, attr, false);
1515 if (ret)
1516 return ret;
1517 }
1518 }
1519
1520 return 0;
1521 }
1522
detect_and_move_global_attrs(struct iio_device * dev)1523 static int detect_and_move_global_attrs(struct iio_device *dev)
1524 {
1525 unsigned int i;
1526 char **ptr = dev->attrs;
1527
1528 for (i = 0; i < dev->nb_attrs; i++) {
1529 const char *attr = dev->attrs[i];
1530 bool match;
1531 int ret;
1532
1533 ret = detect_global_attr(dev, attr, 2, &match);
1534 if (ret)
1535 return ret;
1536
1537 if (!match) {
1538 ret = detect_global_attr(dev, attr, 1, &match);
1539 if (ret)
1540 return ret;
1541 }
1542
1543 if (match) {
1544 free(dev->attrs[i]);
1545 dev->attrs[i] = NULL;
1546 }
1547 }
1548
1549 /* Find channels without an index */
1550 for (i = 0; i < dev->nb_attrs; i++) {
1551 const char *attr = dev->attrs[i];
1552 int ret;
1553
1554 if (!dev->attrs[i])
1555 continue;
1556
1557 if (is_channel(attr, false)) {
1558 ret = add_channel(dev, attr, attr, false);
1559 if (ret)
1560 return ret;
1561
1562 free(dev->attrs[i]);
1563 dev->attrs[i] = NULL;
1564 }
1565 }
1566
1567 for (i = 0; i < dev->nb_attrs; i++) {
1568 if (dev->attrs[i])
1569 *ptr++ = dev->attrs[i];
1570 }
1571
1572 dev->nb_attrs = ptr - dev->attrs;
1573 if (!dev->nb_attrs) {
1574 free(dev->attrs);
1575 dev->attrs = NULL;
1576 }
1577
1578 return 0;
1579 }
1580
add_buffer_attr(void * d,const char * path)1581 static int add_buffer_attr(void *d, const char *path)
1582 {
1583 struct iio_device *dev = (struct iio_device *) d;
1584 const char *name = strrchr(path, '/') + 1;
1585 char **attrs, *attr;
1586 int i;
1587
1588 for (i = 0; i < ARRAY_SIZE(buffer_attrs_reserved); i++)
1589 if (!strcmp(buffer_attrs_reserved[i], name))
1590 return 0;
1591
1592 attr = iio_strdup(name);
1593 if (!attr)
1594 return -ENOMEM;
1595
1596 attrs = realloc(dev->buffer_attrs, (1 + dev->nb_buffer_attrs) * sizeof(char *));
1597 if (!attrs) {
1598 free(attr);
1599 return -ENOMEM;
1600 }
1601
1602 attrs[dev->nb_buffer_attrs++] = attr;
1603 dev->buffer_attrs = attrs;
1604 DEBUG("Added buffer attr \'%s\' to device \'%s\'\n", attr, dev->id);
1605 return 0;
1606 }
1607
add_attr_or_channel_helper(struct iio_device * dev,const char * path,bool dir_is_scan_elements)1608 static int add_attr_or_channel_helper(struct iio_device *dev,
1609 const char *path, bool dir_is_scan_elements)
1610 {
1611 char buf[1024];
1612 const char *name = strrchr(path, '/') + 1;
1613
1614 if (dir_is_scan_elements) {
1615 iio_snprintf(buf, sizeof(buf), "scan_elements/%s", name);
1616 path = buf;
1617 } else {
1618 if (!is_channel(name, true))
1619 return add_attr_to_device(dev, name);
1620 path = name;
1621 }
1622
1623 return add_channel(dev, name, path, dir_is_scan_elements);
1624 }
1625
add_attr_or_channel(void * d,const char * path)1626 static int add_attr_or_channel(void *d, const char *path)
1627 {
1628 return add_attr_or_channel_helper((struct iio_device *) d, path, false);
1629 }
1630
add_scan_element(void * d,const char * path)1631 static int add_scan_element(void *d, const char *path)
1632 {
1633 return add_attr_or_channel_helper((struct iio_device *) d, path, true);
1634 }
1635
foreach_in_dir(void * d,const char * path,bool is_dir,int (* callback)(void *,const char *))1636 static int foreach_in_dir(void *d, const char *path, bool is_dir,
1637 int (*callback)(void *, const char *))
1638 {
1639 struct dirent *entry;
1640 DIR *dir;
1641 int ret = 0;
1642
1643 dir = opendir(path);
1644 if (!dir)
1645 return -errno;
1646
1647 while (true) {
1648 struct stat st;
1649 char buf[1024];
1650
1651 errno = 0;
1652 entry = readdir(dir);
1653 if (!entry) {
1654 if (!errno)
1655 break;
1656
1657 ret = -errno;
1658 iio_strerror(errno, buf, sizeof(buf));
1659 ERROR("Unable to open directory %s: %s\n", path, buf);
1660 goto out_close_dir;
1661 }
1662
1663 iio_snprintf(buf, sizeof(buf), "%s/%s", path, entry->d_name);
1664 if (stat(buf, &st) < 0) {
1665 ret = -errno;
1666 iio_strerror(errno, buf, sizeof(buf));
1667 ERROR("Unable to stat file: %s\n", buf);
1668 goto out_close_dir;
1669 }
1670
1671 if (is_dir && S_ISDIR(st.st_mode) && entry->d_name[0] != '.')
1672 ret = callback(d, buf);
1673 else if (!is_dir && S_ISREG(st.st_mode))
1674 ret = callback(d, buf);
1675 else
1676 continue;
1677
1678 if (ret < 0)
1679 goto out_close_dir;
1680 }
1681
1682 out_close_dir:
1683 closedir(dir);
1684 return ret;
1685 }
1686
add_scan_elements(struct iio_device * dev,const char * devpath)1687 static int add_scan_elements(struct iio_device *dev, const char *devpath)
1688 {
1689 struct stat st;
1690 char buf[1024];
1691
1692 iio_snprintf(buf, sizeof(buf), "%s/scan_elements", devpath);
1693
1694 if (!stat(buf, &st) && S_ISDIR(st.st_mode)) {
1695 int ret = foreach_in_dir(dev, buf, false, add_scan_element);
1696 if (ret < 0)
1697 return ret;
1698 }
1699
1700 return 0;
1701 }
1702
add_buffer_attributes(struct iio_device * dev,const char * devpath)1703 static int add_buffer_attributes(struct iio_device *dev, const char *devpath)
1704 {
1705 struct stat st;
1706 char buf[1024];
1707
1708 iio_snprintf(buf, sizeof(buf), "%s/buffer", devpath);
1709
1710 if (!stat(buf, &st) && S_ISDIR(st.st_mode)) {
1711 int ret = foreach_in_dir(dev, buf, false, add_buffer_attr);
1712 if (ret < 0)
1713 return ret;
1714
1715 qsort(dev->buffer_attrs, dev->nb_buffer_attrs, sizeof(char *),
1716 iio_buffer_attr_compare);
1717 }
1718
1719 return 0;
1720 }
1721
create_device(void * d,const char * path)1722 static int create_device(void *d, const char *path)
1723 {
1724 uint32_t *mask = NULL;
1725 unsigned int i;
1726 int ret;
1727 struct iio_context *ctx = d;
1728 struct iio_device *dev = zalloc(sizeof(*dev));
1729 if (!dev)
1730 return -ENOMEM;
1731
1732 dev->pdata = zalloc(sizeof(*dev->pdata));
1733 if (!dev->pdata) {
1734 free(dev);
1735 return -ENOMEM;
1736 }
1737
1738 dev->pdata->fd = -1;
1739 dev->pdata->blocking = true;
1740 dev->pdata->max_nb_blocks = NB_BLOCKS;
1741
1742 dev->ctx = ctx;
1743 dev->id = iio_strdup(strrchr(path, '/') + 1);
1744 if (!dev->id) {
1745 local_free_pdata(dev);
1746 free(dev);
1747 return -ENOMEM;
1748 }
1749
1750 ret = foreach_in_dir(dev, path, false, add_attr_or_channel);
1751 if (ret < 0)
1752 goto err_free_device;
1753
1754 ret = add_buffer_attributes(dev, path);
1755 if (ret < 0)
1756 goto err_free_device;
1757
1758 ret = add_scan_elements(dev, path);
1759 if (ret < 0)
1760 goto err_free_scan_elements;
1761
1762 for (i = 0; i < dev->nb_channels; i++) {
1763 struct iio_channel *chn = dev->channels[i];
1764
1765 set_channel_name(chn);
1766 ret = handle_scan_elements(chn);
1767 free_protected_attrs(chn);
1768 if (ret < 0)
1769 goto err_free_scan_elements;
1770 }
1771
1772 ret = detect_and_move_global_attrs(dev);
1773 if (ret < 0)
1774 goto err_free_device;
1775
1776 /* sorting is done after global attrs are added */
1777 for (i = 0; i < dev->nb_channels; i++) {
1778 struct iio_channel *chn = dev->channels[i];
1779 qsort(chn->attrs, chn->nb_attrs, sizeof(struct iio_channel_attr),
1780 iio_channel_attr_compare);
1781 }
1782 qsort(dev->attrs, dev->nb_attrs, sizeof(char *),
1783 iio_device_attr_compare);
1784
1785 dev->words = (dev->nb_channels + 31) / 32;
1786 if (dev->words) {
1787 mask = calloc(dev->words, sizeof(*mask));
1788 if (!mask) {
1789 ret = -ENOMEM;
1790 goto err_free_device;
1791 }
1792 }
1793
1794 dev->mask = mask;
1795
1796 ret = add_device_to_context(ctx, dev);
1797 if (!ret)
1798 return 0;
1799
1800 err_free_scan_elements:
1801 for (i = 0; i < dev->nb_channels; i++)
1802 free_protected_attrs(dev->channels[i]);
1803 err_free_device:
1804 local_free_pdata(dev);
1805 free_device(dev);
1806 return ret;
1807 }
1808
add_debug_attr(void * d,const char * path)1809 static int add_debug_attr(void *d, const char *path)
1810 {
1811 struct iio_device *dev = d;
1812 const char *attr = strrchr(path, '/') + 1;
1813 char **attrs, *name = iio_strdup(attr);
1814 if (!name)
1815 return -ENOMEM;
1816
1817 attrs = realloc(dev->debug_attrs,
1818 (1 + dev->nb_debug_attrs) * sizeof(char *));
1819 if (!attrs) {
1820 free(name);
1821 return -ENOMEM;
1822 }
1823
1824 attrs[dev->nb_debug_attrs++] = name;
1825 dev->debug_attrs = attrs;
1826 DEBUG("Added debug attr \'%s\' to device \'%s\'\n", name, dev->id);
1827 return 0;
1828 }
1829
add_debug(void * d,const char * path)1830 static int add_debug(void *d, const char *path)
1831 {
1832 struct iio_context *ctx = d;
1833 const char *name = strrchr(path, '/') + 1;
1834 struct iio_device *dev = iio_context_find_device(ctx, name);
1835 if (!dev)
1836 return -ENODEV;
1837 else
1838 return foreach_in_dir(dev, path, false, add_debug_attr);
1839 }
1840
local_set_timeout(struct iio_context * ctx,unsigned int timeout)1841 static int local_set_timeout(struct iio_context *ctx, unsigned int timeout)
1842 {
1843 ctx->pdata->rw_timeout_ms = timeout;
1844 return 0;
1845 }
1846
local_cancel(const struct iio_device * dev)1847 static void local_cancel(const struct iio_device *dev)
1848 {
1849 struct iio_device_pdata *pdata = dev->pdata;
1850 uint64_t event = 1;
1851 int ret;
1852
1853 ret = write(pdata->cancel_fd, &event, sizeof(event));
1854 if (ret == -1) {
1855 /* If this happens something went very seriously wrong */
1856 char err_str[1024];
1857 iio_strerror(errno, err_str, sizeof(err_str));
1858 ERROR("Unable to signal cancellation event: %s\n", err_str);
1859 }
1860 }
1861
local_clone(const struct iio_context * ctx)1862 static struct iio_context * local_clone(
1863 const struct iio_context *ctx __attribute__((unused)))
1864 {
1865 return local_create_context();
1866 }
1867
1868 static const struct iio_backend_ops local_ops = {
1869 .clone = local_clone,
1870 .open = local_open,
1871 .close = local_close,
1872 .get_fd = local_get_fd,
1873 .set_blocking_mode = local_set_blocking_mode,
1874 .read = local_read,
1875 .write = local_write,
1876 .set_kernel_buffers_count = local_set_kernel_buffers_count,
1877 .get_buffer = local_get_buffer,
1878 .read_device_attr = local_read_dev_attr,
1879 .write_device_attr = local_write_dev_attr,
1880 .read_channel_attr = local_read_chn_attr,
1881 .write_channel_attr = local_write_chn_attr,
1882 .get_trigger = local_get_trigger,
1883 .set_trigger = local_set_trigger,
1884 .shutdown = local_shutdown,
1885 .set_timeout = local_set_timeout,
1886 .cancel = local_cancel,
1887 };
1888
init_data_scale(struct iio_channel * chn)1889 static void init_data_scale(struct iio_channel *chn)
1890 {
1891 char buf[1024];
1892 ssize_t ret;
1893
1894 ret = iio_channel_attr_read(chn, "scale", buf, sizeof(buf));
1895 if (ret < 0) {
1896 chn->format.with_scale = false;
1897 } else {
1898 chn->format.with_scale = true;
1899 chn->format.scale = atof(buf);
1900 }
1901 }
1902
init_scan_elements(struct iio_context * ctx)1903 static void init_scan_elements(struct iio_context *ctx)
1904 {
1905 unsigned int i, j;
1906
1907 for (i = 0; i < ctx->nb_devices; i++) {
1908 struct iio_device *dev = ctx->devices[i];
1909
1910 for (j = 0; j < dev->nb_channels; j++)
1911 init_data_scale(dev->channels[j]);
1912 }
1913 }
1914
1915 #ifdef WITH_LOCAL_CONFIG
populate_context_attrs(struct iio_context * ctx,const char * file)1916 static int populate_context_attrs(struct iio_context *ctx, const char *file)
1917 {
1918 struct INI *ini;
1919 int ret;
1920
1921 ini = ini_open(file);
1922 if (!ini) {
1923 /* INI file not present -> not an error */
1924 if (errno == ENOENT)
1925 return 0;
1926 else
1927 return -errno;
1928 }
1929
1930 while (true) {
1931 const char *section;
1932 size_t len;
1933
1934 ret = ini_next_section(ini, §ion, &len);
1935 if (ret <= 0)
1936 goto out_close_ini;
1937
1938 if (!strncmp(section, "Context Attributes", len))
1939 break;
1940 }
1941
1942 do {
1943 const char *key, *value;
1944 char *new_key, *new_val;
1945 size_t klen, vlen;
1946
1947 ret = ini_read_pair(ini, &key, &klen, &value, &vlen);
1948 if (ret <= 0)
1949 break;
1950
1951 /* Create a dup of the strings read from the INI, since they are
1952 * not NULL-terminated. */
1953 new_key = strndup(key, klen);
1954 new_val = strndup(value, vlen);
1955
1956 if (!new_key || !new_val)
1957 ret = -ENOMEM;
1958 else
1959 ret = iio_context_add_attr(ctx, new_key, new_val);
1960
1961 free(new_key);
1962 free(new_val);
1963 } while (!ret);
1964
1965 out_close_ini:
1966 ini_close(ini);
1967 return ret;
1968 }
1969 #endif
1970
local_create_context(void)1971 struct iio_context * local_create_context(void)
1972 {
1973 int ret = -ENOMEM;
1974 unsigned int len;
1975 struct utsname uts;
1976 struct iio_context *ctx = zalloc(sizeof(*ctx));
1977 if (!ctx)
1978 goto err_set_errno;
1979
1980 ctx->ops = &local_ops;
1981 ctx->name = "local";
1982
1983 ctx->pdata = zalloc(sizeof(*ctx->pdata));
1984 if (!ctx->pdata) {
1985 free(ctx);
1986 goto err_set_errno;
1987 }
1988
1989 local_set_timeout(ctx, DEFAULT_TIMEOUT_MS);
1990
1991 uname(&uts);
1992 len = strlen(uts.sysname) + strlen(uts.nodename) + strlen(uts.release)
1993 + strlen(uts.version) + strlen(uts.machine);
1994 ctx->description = malloc(len + 5); /* 4 spaces + EOF */
1995 if (!ctx->description) {
1996 free(ctx->pdata);
1997 free(ctx);
1998 goto err_set_errno;
1999 }
2000
2001 iio_snprintf(ctx->description, len + 5, "%s %s %s %s %s", uts.sysname,
2002 uts.nodename, uts.release, uts.version, uts.machine);
2003
2004 ret = foreach_in_dir(ctx, "/sys/bus/iio/devices", true, create_device);
2005 if (ret < 0)
2006 goto err_context_destroy;
2007
2008 qsort(ctx->devices, ctx->nb_devices, sizeof(struct iio_device *),
2009 iio_device_compare);
2010
2011 foreach_in_dir(ctx, "/sys/kernel/debug/iio", true, add_debug);
2012
2013 init_scan_elements(ctx);
2014
2015 #ifdef WITH_LOCAL_CONFIG
2016 ret = populate_context_attrs(ctx, "/etc/libiio.ini");
2017 if (ret < 0)
2018 goto err_context_destroy;
2019 #endif
2020
2021 ret = iio_context_add_attr(ctx, "local,kernel", uts.release);
2022 if (ret < 0)
2023 goto err_context_destroy;
2024
2025 ret = iio_context_init(ctx);
2026 if (ret < 0)
2027 goto err_context_destroy;
2028
2029 return ctx;
2030
2031 err_context_destroy:
2032 iio_context_destroy(ctx);
2033 err_set_errno:
2034 errno = -ret;
2035 return NULL;
2036 }
2037
check_device(void * d,const char * path)2038 static int check_device(void *d, const char *path)
2039 {
2040 *(bool *)d = true;
2041 return 0;
2042 }
2043
local_context_scan(struct iio_scan_result * scan_result)2044 int local_context_scan(struct iio_scan_result *scan_result)
2045 {
2046 struct iio_context_info **info;
2047 bool exists = false;
2048 char *desc, *uri;
2049 int ret;
2050
2051 ret = foreach_in_dir(&exists, "/sys/bus/iio", true, check_device);
2052 if (ret < 0 || !exists)
2053 return 0;
2054
2055 desc = iio_strdup("Local devices");
2056 if (!desc)
2057 return -ENOMEM;
2058
2059 uri = iio_strdup("local:");
2060 if (!uri)
2061 goto err_free_desc;
2062
2063 info = iio_scan_result_add(scan_result, 1);
2064 if (!info)
2065 goto err_free_uri;
2066
2067 info[0]->description = desc;
2068 info[0]->uri = uri;
2069 return 0;
2070
2071 err_free_uri:
2072 free(uri);
2073 err_free_desc:
2074 free(desc);
2075 return -ENOMEM;
2076 }
2077