lan743x: fix ethernet frame cutoff issue
[linux-2.6-microblaze.git] / drivers / iio / industrialio-core.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* The industrial I/O core
3  *
4  * Copyright (c) 2008 Jonathan Cameron
5  *
6  * Based on elements of hwmon and input subsystems.
7  */
8
9 #define pr_fmt(fmt) "iio-core: " fmt
10
11 #include <linux/kernel.h>
12 #include <linux/module.h>
13 #include <linux/idr.h>
14 #include <linux/kdev_t.h>
15 #include <linux/err.h>
16 #include <linux/device.h>
17 #include <linux/fs.h>
18 #include <linux/poll.h>
19 #include <linux/property.h>
20 #include <linux/sched.h>
21 #include <linux/wait.h>
22 #include <linux/cdev.h>
23 #include <linux/slab.h>
24 #include <linux/anon_inodes.h>
25 #include <linux/debugfs.h>
26 #include <linux/mutex.h>
27 #include <linux/iio/iio.h>
28 #include <linux/iio/iio-opaque.h>
29 #include "iio_core.h"
30 #include "iio_core_trigger.h"
31 #include <linux/iio/sysfs.h>
32 #include <linux/iio/events.h>
33 #include <linux/iio/buffer.h>
34 #include <linux/iio/buffer_impl.h>
35
36 /* IDA to assign each registered device a unique id */
37 static DEFINE_IDA(iio_ida);
38
39 static dev_t iio_devt;
40
41 #define IIO_DEV_MAX 256
42 struct bus_type iio_bus_type = {
43         .name = "iio",
44 };
45 EXPORT_SYMBOL(iio_bus_type);
46
47 static struct dentry *iio_debugfs_dentry;
48
49 static const char * const iio_direction[] = {
50         [0] = "in",
51         [1] = "out",
52 };
53
54 static const char * const iio_chan_type_name_spec[] = {
55         [IIO_VOLTAGE] = "voltage",
56         [IIO_CURRENT] = "current",
57         [IIO_POWER] = "power",
58         [IIO_ACCEL] = "accel",
59         [IIO_ANGL_VEL] = "anglvel",
60         [IIO_MAGN] = "magn",
61         [IIO_LIGHT] = "illuminance",
62         [IIO_INTENSITY] = "intensity",
63         [IIO_PROXIMITY] = "proximity",
64         [IIO_TEMP] = "temp",
65         [IIO_INCLI] = "incli",
66         [IIO_ROT] = "rot",
67         [IIO_ANGL] = "angl",
68         [IIO_TIMESTAMP] = "timestamp",
69         [IIO_CAPACITANCE] = "capacitance",
70         [IIO_ALTVOLTAGE] = "altvoltage",
71         [IIO_CCT] = "cct",
72         [IIO_PRESSURE] = "pressure",
73         [IIO_HUMIDITYRELATIVE] = "humidityrelative",
74         [IIO_ACTIVITY] = "activity",
75         [IIO_STEPS] = "steps",
76         [IIO_ENERGY] = "energy",
77         [IIO_DISTANCE] = "distance",
78         [IIO_VELOCITY] = "velocity",
79         [IIO_CONCENTRATION] = "concentration",
80         [IIO_RESISTANCE] = "resistance",
81         [IIO_PH] = "ph",
82         [IIO_UVINDEX] = "uvindex",
83         [IIO_ELECTRICALCONDUCTIVITY] = "electricalconductivity",
84         [IIO_COUNT] = "count",
85         [IIO_INDEX] = "index",
86         [IIO_GRAVITY]  = "gravity",
87         [IIO_POSITIONRELATIVE]  = "positionrelative",
88         [IIO_PHASE] = "phase",
89         [IIO_MASSCONCENTRATION] = "massconcentration",
90 };
91
92 static const char * const iio_modifier_names[] = {
93         [IIO_MOD_X] = "x",
94         [IIO_MOD_Y] = "y",
95         [IIO_MOD_Z] = "z",
96         [IIO_MOD_X_AND_Y] = "x&y",
97         [IIO_MOD_X_AND_Z] = "x&z",
98         [IIO_MOD_Y_AND_Z] = "y&z",
99         [IIO_MOD_X_AND_Y_AND_Z] = "x&y&z",
100         [IIO_MOD_X_OR_Y] = "x|y",
101         [IIO_MOD_X_OR_Z] = "x|z",
102         [IIO_MOD_Y_OR_Z] = "y|z",
103         [IIO_MOD_X_OR_Y_OR_Z] = "x|y|z",
104         [IIO_MOD_ROOT_SUM_SQUARED_X_Y] = "sqrt(x^2+y^2)",
105         [IIO_MOD_SUM_SQUARED_X_Y_Z] = "x^2+y^2+z^2",
106         [IIO_MOD_LIGHT_BOTH] = "both",
107         [IIO_MOD_LIGHT_IR] = "ir",
108         [IIO_MOD_LIGHT_CLEAR] = "clear",
109         [IIO_MOD_LIGHT_RED] = "red",
110         [IIO_MOD_LIGHT_GREEN] = "green",
111         [IIO_MOD_LIGHT_BLUE] = "blue",
112         [IIO_MOD_LIGHT_UV] = "uv",
113         [IIO_MOD_LIGHT_DUV] = "duv",
114         [IIO_MOD_QUATERNION] = "quaternion",
115         [IIO_MOD_TEMP_AMBIENT] = "ambient",
116         [IIO_MOD_TEMP_OBJECT] = "object",
117         [IIO_MOD_NORTH_MAGN] = "from_north_magnetic",
118         [IIO_MOD_NORTH_TRUE] = "from_north_true",
119         [IIO_MOD_NORTH_MAGN_TILT_COMP] = "from_north_magnetic_tilt_comp",
120         [IIO_MOD_NORTH_TRUE_TILT_COMP] = "from_north_true_tilt_comp",
121         [IIO_MOD_RUNNING] = "running",
122         [IIO_MOD_JOGGING] = "jogging",
123         [IIO_MOD_WALKING] = "walking",
124         [IIO_MOD_STILL] = "still",
125         [IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z] = "sqrt(x^2+y^2+z^2)",
126         [IIO_MOD_I] = "i",
127         [IIO_MOD_Q] = "q",
128         [IIO_MOD_CO2] = "co2",
129         [IIO_MOD_VOC] = "voc",
130         [IIO_MOD_PM1] = "pm1",
131         [IIO_MOD_PM2P5] = "pm2p5",
132         [IIO_MOD_PM4] = "pm4",
133         [IIO_MOD_PM10] = "pm10",
134         [IIO_MOD_ETHANOL] = "ethanol",
135         [IIO_MOD_H2] = "h2",
136         [IIO_MOD_O2] = "o2",
137 };
138
139 /* relies on pairs of these shared then separate */
140 static const char * const iio_chan_info_postfix[] = {
141         [IIO_CHAN_INFO_RAW] = "raw",
142         [IIO_CHAN_INFO_PROCESSED] = "input",
143         [IIO_CHAN_INFO_SCALE] = "scale",
144         [IIO_CHAN_INFO_OFFSET] = "offset",
145         [IIO_CHAN_INFO_CALIBSCALE] = "calibscale",
146         [IIO_CHAN_INFO_CALIBBIAS] = "calibbias",
147         [IIO_CHAN_INFO_PEAK] = "peak_raw",
148         [IIO_CHAN_INFO_PEAK_SCALE] = "peak_scale",
149         [IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW] = "quadrature_correction_raw",
150         [IIO_CHAN_INFO_AVERAGE_RAW] = "mean_raw",
151         [IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY]
152         = "filter_low_pass_3db_frequency",
153         [IIO_CHAN_INFO_HIGH_PASS_FILTER_3DB_FREQUENCY]
154         = "filter_high_pass_3db_frequency",
155         [IIO_CHAN_INFO_SAMP_FREQ] = "sampling_frequency",
156         [IIO_CHAN_INFO_FREQUENCY] = "frequency",
157         [IIO_CHAN_INFO_PHASE] = "phase",
158         [IIO_CHAN_INFO_HARDWAREGAIN] = "hardwaregain",
159         [IIO_CHAN_INFO_HYSTERESIS] = "hysteresis",
160         [IIO_CHAN_INFO_INT_TIME] = "integration_time",
161         [IIO_CHAN_INFO_ENABLE] = "en",
162         [IIO_CHAN_INFO_CALIBHEIGHT] = "calibheight",
163         [IIO_CHAN_INFO_CALIBWEIGHT] = "calibweight",
164         [IIO_CHAN_INFO_DEBOUNCE_COUNT] = "debounce_count",
165         [IIO_CHAN_INFO_DEBOUNCE_TIME] = "debounce_time",
166         [IIO_CHAN_INFO_CALIBEMISSIVITY] = "calibemissivity",
167         [IIO_CHAN_INFO_OVERSAMPLING_RATIO] = "oversampling_ratio",
168         [IIO_CHAN_INFO_THERMOCOUPLE_TYPE] = "thermocouple_type",
169         [IIO_CHAN_INFO_CALIBAMBIENT] = "calibambient",
170 };
171
172 /**
173  * iio_sysfs_match_string_with_gaps - matches given string in an array with gaps
174  * @array: array of strings
175  * @n: number of strings in the array
176  * @str: string to match with
177  *
178  * Returns index of @str in the @array or -EINVAL, similar to match_string().
179  * Uses sysfs_streq instead of strcmp for matching.
180  *
181  * This routine will look for a string in an array of strings.
182  * The search will continue until the element is found or the n-th element
183  * is reached, regardless of any NULL elements in the array.
184  */
185 static int iio_sysfs_match_string_with_gaps(const char * const *array, size_t n,
186                                             const char *str)
187 {
188         const char *item;
189         int index;
190
191         for (index = 0; index < n; index++) {
192                 item = array[index];
193                 if (!item)
194                         continue;
195                 if (sysfs_streq(item, str))
196                         return index;
197         }
198
199         return -EINVAL;
200 }
201
202 #if defined(CONFIG_DEBUG_FS)
203 /*
204  * There's also a CONFIG_DEBUG_FS guard in include/linux/iio/iio.h for
205  * iio_get_debugfs_dentry() to make it inline if CONFIG_DEBUG_FS is undefined
206  */
207 struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev)
208 {
209         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
210         return iio_dev_opaque->debugfs_dentry;
211 }
212 EXPORT_SYMBOL_GPL(iio_get_debugfs_dentry);
213 #endif
214
215 /**
216  * iio_find_channel_from_si() - get channel from its scan index
217  * @indio_dev:          device
218  * @si:                 scan index to match
219  */
220 const struct iio_chan_spec
221 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
222 {
223         int i;
224
225         for (i = 0; i < indio_dev->num_channels; i++)
226                 if (indio_dev->channels[i].scan_index == si)
227                         return &indio_dev->channels[i];
228         return NULL;
229 }
230
231 /* This turns up an awful lot */
232 ssize_t iio_read_const_attr(struct device *dev,
233                             struct device_attribute *attr,
234                             char *buf)
235 {
236         return sprintf(buf, "%s\n", to_iio_const_attr(attr)->string);
237 }
238 EXPORT_SYMBOL(iio_read_const_attr);
239
240 /**
241  * iio_device_set_clock() - Set current timestamping clock for the device
242  * @indio_dev: IIO device structure containing the device
243  * @clock_id: timestamping clock posix identifier to set.
244  */
245 int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
246 {
247         int ret;
248         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
249         const struct iio_event_interface *ev_int = iio_dev_opaque->event_interface;
250
251         ret = mutex_lock_interruptible(&indio_dev->mlock);
252         if (ret)
253                 return ret;
254         if ((ev_int && iio_event_enabled(ev_int)) ||
255             iio_buffer_enabled(indio_dev)) {
256                 mutex_unlock(&indio_dev->mlock);
257                 return -EBUSY;
258         }
259         indio_dev->clock_id = clock_id;
260         mutex_unlock(&indio_dev->mlock);
261
262         return 0;
263 }
264 EXPORT_SYMBOL(iio_device_set_clock);
265
266 /**
267  * iio_get_time_ns() - utility function to get a time stamp for events etc
268  * @indio_dev: device
269  */
270 s64 iio_get_time_ns(const struct iio_dev *indio_dev)
271 {
272         struct timespec64 tp;
273
274         switch (iio_device_get_clock(indio_dev)) {
275         case CLOCK_REALTIME:
276                 return ktime_get_real_ns();
277         case CLOCK_MONOTONIC:
278                 return ktime_get_ns();
279         case CLOCK_MONOTONIC_RAW:
280                 return ktime_get_raw_ns();
281         case CLOCK_REALTIME_COARSE:
282                 return ktime_to_ns(ktime_get_coarse_real());
283         case CLOCK_MONOTONIC_COARSE:
284                 ktime_get_coarse_ts64(&tp);
285                 return timespec64_to_ns(&tp);
286         case CLOCK_BOOTTIME:
287                 return ktime_get_boottime_ns();
288         case CLOCK_TAI:
289                 return ktime_get_clocktai_ns();
290         default:
291                 BUG();
292         }
293 }
294 EXPORT_SYMBOL(iio_get_time_ns);
295
296 /**
297  * iio_get_time_res() - utility function to get time stamp clock resolution in
298  *                      nano seconds.
299  * @indio_dev: device
300  */
301 unsigned int iio_get_time_res(const struct iio_dev *indio_dev)
302 {
303         switch (iio_device_get_clock(indio_dev)) {
304         case CLOCK_REALTIME:
305         case CLOCK_MONOTONIC:
306         case CLOCK_MONOTONIC_RAW:
307         case CLOCK_BOOTTIME:
308         case CLOCK_TAI:
309                 return hrtimer_resolution;
310         case CLOCK_REALTIME_COARSE:
311         case CLOCK_MONOTONIC_COARSE:
312                 return LOW_RES_NSEC;
313         default:
314                 BUG();
315         }
316 }
317 EXPORT_SYMBOL(iio_get_time_res);
318
319 static int __init iio_init(void)
320 {
321         int ret;
322
323         /* Register sysfs bus */
324         ret  = bus_register(&iio_bus_type);
325         if (ret < 0) {
326                 pr_err("could not register bus type\n");
327                 goto error_nothing;
328         }
329
330         ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
331         if (ret < 0) {
332                 pr_err("failed to allocate char dev region\n");
333                 goto error_unregister_bus_type;
334         }
335
336         iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
337
338         return 0;
339
340 error_unregister_bus_type:
341         bus_unregister(&iio_bus_type);
342 error_nothing:
343         return ret;
344 }
345
346 static void __exit iio_exit(void)
347 {
348         if (iio_devt)
349                 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
350         bus_unregister(&iio_bus_type);
351         debugfs_remove(iio_debugfs_dentry);
352 }
353
354 #if defined(CONFIG_DEBUG_FS)
355 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
356                               size_t count, loff_t *ppos)
357 {
358         struct iio_dev *indio_dev = file->private_data;
359         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
360         unsigned val = 0;
361         int ret;
362
363         if (*ppos > 0)
364                 return simple_read_from_buffer(userbuf, count, ppos,
365                                                iio_dev_opaque->read_buf,
366                                                iio_dev_opaque->read_buf_len);
367
368         ret = indio_dev->info->debugfs_reg_access(indio_dev,
369                                                   iio_dev_opaque->cached_reg_addr,
370                                                   0, &val);
371         if (ret) {
372                 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
373                 return ret;
374         }
375
376         iio_dev_opaque->read_buf_len = snprintf(iio_dev_opaque->read_buf,
377                                               sizeof(iio_dev_opaque->read_buf),
378                                               "0x%X\n", val);
379
380         return simple_read_from_buffer(userbuf, count, ppos,
381                                        iio_dev_opaque->read_buf,
382                                        iio_dev_opaque->read_buf_len);
383 }
384
385 static ssize_t iio_debugfs_write_reg(struct file *file,
386                      const char __user *userbuf, size_t count, loff_t *ppos)
387 {
388         struct iio_dev *indio_dev = file->private_data;
389         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
390         unsigned reg, val;
391         char buf[80];
392         int ret;
393
394         count = min_t(size_t, count, (sizeof(buf)-1));
395         if (copy_from_user(buf, userbuf, count))
396                 return -EFAULT;
397
398         buf[count] = 0;
399
400         ret = sscanf(buf, "%i %i", &reg, &val);
401
402         switch (ret) {
403         case 1:
404                 iio_dev_opaque->cached_reg_addr = reg;
405                 break;
406         case 2:
407                 iio_dev_opaque->cached_reg_addr = reg;
408                 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
409                                                           val, NULL);
410                 if (ret) {
411                         dev_err(indio_dev->dev.parent, "%s: write failed\n",
412                                 __func__);
413                         return ret;
414                 }
415                 break;
416         default:
417                 return -EINVAL;
418         }
419
420         return count;
421 }
422
423 static const struct file_operations iio_debugfs_reg_fops = {
424         .open = simple_open,
425         .read = iio_debugfs_read_reg,
426         .write = iio_debugfs_write_reg,
427 };
428
429 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
430 {
431         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
432         debugfs_remove_recursive(iio_dev_opaque->debugfs_dentry);
433 }
434
435 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
436 {
437         struct iio_dev_opaque *iio_dev_opaque;
438
439         if (indio_dev->info->debugfs_reg_access == NULL)
440                 return;
441
442         if (!iio_debugfs_dentry)
443                 return;
444
445         iio_dev_opaque = to_iio_dev_opaque(indio_dev);
446
447         iio_dev_opaque->debugfs_dentry =
448                 debugfs_create_dir(dev_name(&indio_dev->dev),
449                                    iio_debugfs_dentry);
450
451         debugfs_create_file("direct_reg_access", 0644,
452                             iio_dev_opaque->debugfs_dentry, indio_dev,
453                             &iio_debugfs_reg_fops);
454 }
455 #else
456 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
457 {
458 }
459
460 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
461 {
462 }
463 #endif /* CONFIG_DEBUG_FS */
464
465 static ssize_t iio_read_channel_ext_info(struct device *dev,
466                                      struct device_attribute *attr,
467                                      char *buf)
468 {
469         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
470         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
471         const struct iio_chan_spec_ext_info *ext_info;
472
473         ext_info = &this_attr->c->ext_info[this_attr->address];
474
475         return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
476 }
477
478 static ssize_t iio_write_channel_ext_info(struct device *dev,
479                                      struct device_attribute *attr,
480                                      const char *buf,
481                                          size_t len)
482 {
483         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
484         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
485         const struct iio_chan_spec_ext_info *ext_info;
486
487         ext_info = &this_attr->c->ext_info[this_attr->address];
488
489         return ext_info->write(indio_dev, ext_info->private,
490                                this_attr->c, buf, len);
491 }
492
493 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
494         uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
495 {
496         const struct iio_enum *e = (const struct iio_enum *)priv;
497         unsigned int i;
498         size_t len = 0;
499
500         if (!e->num_items)
501                 return 0;
502
503         for (i = 0; i < e->num_items; ++i) {
504                 if (!e->items[i])
505                         continue;
506                 len += scnprintf(buf + len, PAGE_SIZE - len, "%s ", e->items[i]);
507         }
508
509         /* replace last space with a newline */
510         buf[len - 1] = '\n';
511
512         return len;
513 }
514 EXPORT_SYMBOL_GPL(iio_enum_available_read);
515
516 ssize_t iio_enum_read(struct iio_dev *indio_dev,
517         uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
518 {
519         const struct iio_enum *e = (const struct iio_enum *)priv;
520         int i;
521
522         if (!e->get)
523                 return -EINVAL;
524
525         i = e->get(indio_dev, chan);
526         if (i < 0)
527                 return i;
528         else if (i >= e->num_items || !e->items[i])
529                 return -EINVAL;
530
531         return snprintf(buf, PAGE_SIZE, "%s\n", e->items[i]);
532 }
533 EXPORT_SYMBOL_GPL(iio_enum_read);
534
535 ssize_t iio_enum_write(struct iio_dev *indio_dev,
536         uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
537         size_t len)
538 {
539         const struct iio_enum *e = (const struct iio_enum *)priv;
540         int ret;
541
542         if (!e->set)
543                 return -EINVAL;
544
545         ret = iio_sysfs_match_string_with_gaps(e->items, e->num_items, buf);
546         if (ret < 0)
547                 return ret;
548
549         ret = e->set(indio_dev, chan, ret);
550         return ret ? ret : len;
551 }
552 EXPORT_SYMBOL_GPL(iio_enum_write);
553
554 static const struct iio_mount_matrix iio_mount_idmatrix = {
555         .rotation = {
556                 "1", "0", "0",
557                 "0", "1", "0",
558                 "0", "0", "1"
559         }
560 };
561
562 static int iio_setup_mount_idmatrix(const struct device *dev,
563                                     struct iio_mount_matrix *matrix)
564 {
565         *matrix = iio_mount_idmatrix;
566         dev_info(dev, "mounting matrix not found: using identity...\n");
567         return 0;
568 }
569
570 ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
571                               const struct iio_chan_spec *chan, char *buf)
572 {
573         const struct iio_mount_matrix *mtx = ((iio_get_mount_matrix_t *)
574                                               priv)(indio_dev, chan);
575
576         if (IS_ERR(mtx))
577                 return PTR_ERR(mtx);
578
579         if (!mtx)
580                 mtx = &iio_mount_idmatrix;
581
582         return snprintf(buf, PAGE_SIZE, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
583                         mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
584                         mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
585                         mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
586 }
587 EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
588
589 /**
590  * iio_read_mount_matrix() - retrieve iio device mounting matrix from
591  *                           device "mount-matrix" property
592  * @dev:        device the mounting matrix property is assigned to
593  * @propname:   device specific mounting matrix property name
594  * @matrix:     where to store retrieved matrix
595  *
596  * If device is assigned no mounting matrix property, a default 3x3 identity
597  * matrix will be filled in.
598  *
599  * Return: 0 if success, or a negative error code on failure.
600  */
601 int iio_read_mount_matrix(struct device *dev, const char *propname,
602                           struct iio_mount_matrix *matrix)
603 {
604         size_t len = ARRAY_SIZE(iio_mount_idmatrix.rotation);
605         int err;
606
607         err = device_property_read_string_array(dev, propname,
608                                                 matrix->rotation, len);
609         if (err == len)
610                 return 0;
611
612         if (err >= 0)
613                 /* Invalid number of matrix entries. */
614                 return -EINVAL;
615
616         if (err != -EINVAL)
617                 /* Invalid matrix declaration format. */
618                 return err;
619
620         /* Matrix was not declared at all: fallback to identity. */
621         return iio_setup_mount_idmatrix(dev, matrix);
622 }
623 EXPORT_SYMBOL(iio_read_mount_matrix);
624
625 static ssize_t __iio_format_value(char *buf, size_t len, unsigned int type,
626                                   int size, const int *vals)
627 {
628         unsigned long long tmp;
629         int tmp0, tmp1;
630         s64 tmp2;
631         bool scale_db = false;
632
633         switch (type) {
634         case IIO_VAL_INT:
635                 return scnprintf(buf, len, "%d", vals[0]);
636         case IIO_VAL_INT_PLUS_MICRO_DB:
637                 scale_db = true;
638                 fallthrough;
639         case IIO_VAL_INT_PLUS_MICRO:
640                 if (vals[1] < 0)
641                         return scnprintf(buf, len, "-%d.%06u%s", abs(vals[0]),
642                                         -vals[1], scale_db ? " dB" : "");
643                 else
644                         return scnprintf(buf, len, "%d.%06u%s", vals[0], vals[1],
645                                         scale_db ? " dB" : "");
646         case IIO_VAL_INT_PLUS_NANO:
647                 if (vals[1] < 0)
648                         return scnprintf(buf, len, "-%d.%09u", abs(vals[0]),
649                                         -vals[1]);
650                 else
651                         return scnprintf(buf, len, "%d.%09u", vals[0], vals[1]);
652         case IIO_VAL_FRACTIONAL:
653                 tmp2 = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
654                 tmp1 = vals[1];
655                 tmp0 = (int)div_s64_rem(tmp2, 1000000000, &tmp1);
656                 if ((tmp2 < 0) && (tmp0 == 0))
657                         return snprintf(buf, len, "-0.%09u", abs(tmp1));
658                 else
659                         return snprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
660         case IIO_VAL_FRACTIONAL_LOG2:
661                 tmp = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
662                 tmp0 = (int)div_s64_rem(tmp, 1000000000LL, &tmp1);
663                 return scnprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
664         case IIO_VAL_INT_MULTIPLE:
665         {
666                 int i;
667                 int l = 0;
668
669                 for (i = 0; i < size; ++i) {
670                         l += scnprintf(&buf[l], len - l, "%d ", vals[i]);
671                         if (l >= len)
672                                 break;
673                 }
674                 return l;
675         }
676         case IIO_VAL_CHAR:
677                 return scnprintf(buf, len, "%c", (char)vals[0]);
678         default:
679                 return 0;
680         }
681 }
682
683 /**
684  * iio_format_value() - Formats a IIO value into its string representation
685  * @buf:        The buffer to which the formatted value gets written
686  *              which is assumed to be big enough (i.e. PAGE_SIZE).
687  * @type:       One of the IIO_VAL_* constants. This decides how the val
688  *              and val2 parameters are formatted.
689  * @size:       Number of IIO value entries contained in vals
690  * @vals:       Pointer to the values, exact meaning depends on the
691  *              type parameter.
692  *
693  * Return: 0 by default, a negative number on failure or the
694  *         total number of characters written for a type that belongs
695  *         to the IIO_VAL_* constant.
696  */
697 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
698 {
699         ssize_t len;
700
701         len = __iio_format_value(buf, PAGE_SIZE, type, size, vals);
702         if (len >= PAGE_SIZE - 1)
703                 return -EFBIG;
704
705         return len + sprintf(buf + len, "\n");
706 }
707 EXPORT_SYMBOL_GPL(iio_format_value);
708
709 static ssize_t iio_read_channel_label(struct device *dev,
710                                       struct device_attribute *attr,
711                                       char *buf)
712 {
713         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
714         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
715
716         if (!indio_dev->info->read_label)
717                 return -EINVAL;
718
719         return indio_dev->info->read_label(indio_dev, this_attr->c, buf);
720 }
721
722 static ssize_t iio_read_channel_info(struct device *dev,
723                                      struct device_attribute *attr,
724                                      char *buf)
725 {
726         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
727         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
728         int vals[INDIO_MAX_RAW_ELEMENTS];
729         int ret;
730         int val_len = 2;
731
732         if (indio_dev->info->read_raw_multi)
733                 ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
734                                                         INDIO_MAX_RAW_ELEMENTS,
735                                                         vals, &val_len,
736                                                         this_attr->address);
737         else
738                 ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
739                                     &vals[0], &vals[1], this_attr->address);
740
741         if (ret < 0)
742                 return ret;
743
744         return iio_format_value(buf, ret, val_len, vals);
745 }
746
747 static ssize_t iio_format_list(char *buf, const int *vals, int type, int length,
748                                const char *prefix, const char *suffix)
749 {
750         ssize_t len;
751         int stride;
752         int i;
753
754         switch (type) {
755         case IIO_VAL_INT:
756                 stride = 1;
757                 break;
758         default:
759                 stride = 2;
760                 break;
761         }
762
763         len = scnprintf(buf, PAGE_SIZE, prefix);
764
765         for (i = 0; i <= length - stride; i += stride) {
766                 if (i != 0) {
767                         len += scnprintf(buf + len, PAGE_SIZE - len, " ");
768                         if (len >= PAGE_SIZE)
769                                 return -EFBIG;
770                 }
771
772                 len += __iio_format_value(buf + len, PAGE_SIZE - len, type,
773                                           stride, &vals[i]);
774                 if (len >= PAGE_SIZE)
775                         return -EFBIG;
776         }
777
778         len += scnprintf(buf + len, PAGE_SIZE - len, "%s\n", suffix);
779
780         return len;
781 }
782
783 static ssize_t iio_format_avail_list(char *buf, const int *vals,
784                                      int type, int length)
785 {
786
787         return iio_format_list(buf, vals, type, length, "", "");
788 }
789
790 static ssize_t iio_format_avail_range(char *buf, const int *vals, int type)
791 {
792         return iio_format_list(buf, vals, type, 3, "[", "]");
793 }
794
795 static ssize_t iio_read_channel_info_avail(struct device *dev,
796                                            struct device_attribute *attr,
797                                            char *buf)
798 {
799         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
800         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
801         const int *vals;
802         int ret;
803         int length;
804         int type;
805
806         ret = indio_dev->info->read_avail(indio_dev, this_attr->c,
807                                           &vals, &type, &length,
808                                           this_attr->address);
809
810         if (ret < 0)
811                 return ret;
812         switch (ret) {
813         case IIO_AVAIL_LIST:
814                 return iio_format_avail_list(buf, vals, type, length);
815         case IIO_AVAIL_RANGE:
816                 return iio_format_avail_range(buf, vals, type);
817         default:
818                 return -EINVAL;
819         }
820 }
821
822 /**
823  * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
824  * @str: The string to parse
825  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
826  * @integer: The integer part of the number
827  * @fract: The fractional part of the number
828  * @scale_db: True if this should parse as dB
829  *
830  * Returns 0 on success, or a negative error code if the string could not be
831  * parsed.
832  */
833 static int __iio_str_to_fixpoint(const char *str, int fract_mult,
834                                  int *integer, int *fract, bool scale_db)
835 {
836         int i = 0, f = 0;
837         bool integer_part = true, negative = false;
838
839         if (fract_mult == 0) {
840                 *fract = 0;
841
842                 return kstrtoint(str, 0, integer);
843         }
844
845         if (str[0] == '-') {
846                 negative = true;
847                 str++;
848         } else if (str[0] == '+') {
849                 str++;
850         }
851
852         while (*str) {
853                 if ('0' <= *str && *str <= '9') {
854                         if (integer_part) {
855                                 i = i * 10 + *str - '0';
856                         } else {
857                                 f += fract_mult * (*str - '0');
858                                 fract_mult /= 10;
859                         }
860                 } else if (*str == '\n') {
861                         if (*(str + 1) == '\0')
862                                 break;
863                         else
864                                 return -EINVAL;
865                 } else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
866                         /* Ignore the dB suffix */
867                         str += sizeof(" dB") - 1;
868                         continue;
869                 } else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
870                         /* Ignore the dB suffix */
871                         str += sizeof("dB") - 1;
872                         continue;
873                 } else if (*str == '.' && integer_part) {
874                         integer_part = false;
875                 } else {
876                         return -EINVAL;
877                 }
878                 str++;
879         }
880
881         if (negative) {
882                 if (i)
883                         i = -i;
884                 else
885                         f = -f;
886         }
887
888         *integer = i;
889         *fract = f;
890
891         return 0;
892 }
893
894 /**
895  * iio_str_to_fixpoint() - Parse a fixed-point number from a string
896  * @str: The string to parse
897  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
898  * @integer: The integer part of the number
899  * @fract: The fractional part of the number
900  *
901  * Returns 0 on success, or a negative error code if the string could not be
902  * parsed.
903  */
904 int iio_str_to_fixpoint(const char *str, int fract_mult,
905                         int *integer, int *fract)
906 {
907         return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
908 }
909 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
910
911 static ssize_t iio_write_channel_info(struct device *dev,
912                                       struct device_attribute *attr,
913                                       const char *buf,
914                                       size_t len)
915 {
916         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
917         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
918         int ret, fract_mult = 100000;
919         int integer, fract = 0;
920         bool is_char = false;
921         bool scale_db = false;
922
923         /* Assumes decimal - precision based on number of digits */
924         if (!indio_dev->info->write_raw)
925                 return -EINVAL;
926
927         if (indio_dev->info->write_raw_get_fmt)
928                 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
929                         this_attr->c, this_attr->address)) {
930                 case IIO_VAL_INT:
931                         fract_mult = 0;
932                         break;
933                 case IIO_VAL_INT_PLUS_MICRO_DB:
934                         scale_db = true;
935                         fallthrough;
936                 case IIO_VAL_INT_PLUS_MICRO:
937                         fract_mult = 100000;
938                         break;
939                 case IIO_VAL_INT_PLUS_NANO:
940                         fract_mult = 100000000;
941                         break;
942                 case IIO_VAL_CHAR:
943                         is_char = true;
944                         break;
945                 default:
946                         return -EINVAL;
947                 }
948
949         if (is_char) {
950                 char ch;
951
952                 if (sscanf(buf, "%c", &ch) != 1)
953                         return -EINVAL;
954                 integer = ch;
955         } else {
956                 ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
957                                             scale_db);
958                 if (ret)
959                         return ret;
960         }
961
962         ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
963                                          integer, fract, this_attr->address);
964         if (ret)
965                 return ret;
966
967         return len;
968 }
969
970 static
971 int __iio_device_attr_init(struct device_attribute *dev_attr,
972                            const char *postfix,
973                            struct iio_chan_spec const *chan,
974                            ssize_t (*readfunc)(struct device *dev,
975                                                struct device_attribute *attr,
976                                                char *buf),
977                            ssize_t (*writefunc)(struct device *dev,
978                                                 struct device_attribute *attr,
979                                                 const char *buf,
980                                                 size_t len),
981                            enum iio_shared_by shared_by)
982 {
983         int ret = 0;
984         char *name = NULL;
985         char *full_postfix;
986         sysfs_attr_init(&dev_attr->attr);
987
988         /* Build up postfix of <extend_name>_<modifier>_postfix */
989         if (chan->modified && (shared_by == IIO_SEPARATE)) {
990                 if (chan->extend_name)
991                         full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
992                                                  iio_modifier_names[chan
993                                                                     ->channel2],
994                                                  chan->extend_name,
995                                                  postfix);
996                 else
997                         full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
998                                                  iio_modifier_names[chan
999                                                                     ->channel2],
1000                                                  postfix);
1001         } else {
1002                 if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
1003                         full_postfix = kstrdup(postfix, GFP_KERNEL);
1004                 else
1005                         full_postfix = kasprintf(GFP_KERNEL,
1006                                                  "%s_%s",
1007                                                  chan->extend_name,
1008                                                  postfix);
1009         }
1010         if (full_postfix == NULL)
1011                 return -ENOMEM;
1012
1013         if (chan->differential) { /* Differential can not have modifier */
1014                 switch (shared_by) {
1015                 case IIO_SHARED_BY_ALL:
1016                         name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1017                         break;
1018                 case IIO_SHARED_BY_DIR:
1019                         name = kasprintf(GFP_KERNEL, "%s_%s",
1020                                                 iio_direction[chan->output],
1021                                                 full_postfix);
1022                         break;
1023                 case IIO_SHARED_BY_TYPE:
1024                         name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
1025                                             iio_direction[chan->output],
1026                                             iio_chan_type_name_spec[chan->type],
1027                                             iio_chan_type_name_spec[chan->type],
1028                                             full_postfix);
1029                         break;
1030                 case IIO_SEPARATE:
1031                         if (!chan->indexed) {
1032                                 WARN(1, "Differential channels must be indexed\n");
1033                                 ret = -EINVAL;
1034                                 goto error_free_full_postfix;
1035                         }
1036                         name = kasprintf(GFP_KERNEL,
1037                                             "%s_%s%d-%s%d_%s",
1038                                             iio_direction[chan->output],
1039                                             iio_chan_type_name_spec[chan->type],
1040                                             chan->channel,
1041                                             iio_chan_type_name_spec[chan->type],
1042                                             chan->channel2,
1043                                             full_postfix);
1044                         break;
1045                 }
1046         } else { /* Single ended */
1047                 switch (shared_by) {
1048                 case IIO_SHARED_BY_ALL:
1049                         name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1050                         break;
1051                 case IIO_SHARED_BY_DIR:
1052                         name = kasprintf(GFP_KERNEL, "%s_%s",
1053                                                 iio_direction[chan->output],
1054                                                 full_postfix);
1055                         break;
1056                 case IIO_SHARED_BY_TYPE:
1057                         name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1058                                             iio_direction[chan->output],
1059                                             iio_chan_type_name_spec[chan->type],
1060                                             full_postfix);
1061                         break;
1062
1063                 case IIO_SEPARATE:
1064                         if (chan->indexed)
1065                                 name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
1066                                                     iio_direction[chan->output],
1067                                                     iio_chan_type_name_spec[chan->type],
1068                                                     chan->channel,
1069                                                     full_postfix);
1070                         else
1071                                 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1072                                                     iio_direction[chan->output],
1073                                                     iio_chan_type_name_spec[chan->type],
1074                                                     full_postfix);
1075                         break;
1076                 }
1077         }
1078         if (name == NULL) {
1079                 ret = -ENOMEM;
1080                 goto error_free_full_postfix;
1081         }
1082         dev_attr->attr.name = name;
1083
1084         if (readfunc) {
1085                 dev_attr->attr.mode |= S_IRUGO;
1086                 dev_attr->show = readfunc;
1087         }
1088
1089         if (writefunc) {
1090                 dev_attr->attr.mode |= S_IWUSR;
1091                 dev_attr->store = writefunc;
1092         }
1093
1094 error_free_full_postfix:
1095         kfree(full_postfix);
1096
1097         return ret;
1098 }
1099
1100 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1101 {
1102         kfree(dev_attr->attr.name);
1103 }
1104
1105 int __iio_add_chan_devattr(const char *postfix,
1106                            struct iio_chan_spec const *chan,
1107                            ssize_t (*readfunc)(struct device *dev,
1108                                                struct device_attribute *attr,
1109                                                char *buf),
1110                            ssize_t (*writefunc)(struct device *dev,
1111                                                 struct device_attribute *attr,
1112                                                 const char *buf,
1113                                                 size_t len),
1114                            u64 mask,
1115                            enum iio_shared_by shared_by,
1116                            struct device *dev,
1117                            struct list_head *attr_list)
1118 {
1119         int ret;
1120         struct iio_dev_attr *iio_attr, *t;
1121
1122         iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
1123         if (iio_attr == NULL)
1124                 return -ENOMEM;
1125         ret = __iio_device_attr_init(&iio_attr->dev_attr,
1126                                      postfix, chan,
1127                                      readfunc, writefunc, shared_by);
1128         if (ret)
1129                 goto error_iio_dev_attr_free;
1130         iio_attr->c = chan;
1131         iio_attr->address = mask;
1132         list_for_each_entry(t, attr_list, l)
1133                 if (strcmp(t->dev_attr.attr.name,
1134                            iio_attr->dev_attr.attr.name) == 0) {
1135                         if (shared_by == IIO_SEPARATE)
1136                                 dev_err(dev, "tried to double register : %s\n",
1137                                         t->dev_attr.attr.name);
1138                         ret = -EBUSY;
1139                         goto error_device_attr_deinit;
1140                 }
1141         list_add(&iio_attr->l, attr_list);
1142
1143         return 0;
1144
1145 error_device_attr_deinit:
1146         __iio_device_attr_deinit(&iio_attr->dev_attr);
1147 error_iio_dev_attr_free:
1148         kfree(iio_attr);
1149         return ret;
1150 }
1151
1152 static int iio_device_add_channel_label(struct iio_dev *indio_dev,
1153                                          struct iio_chan_spec const *chan)
1154 {
1155         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1156         int ret;
1157
1158         if (!indio_dev->info->read_label)
1159                 return 0;
1160
1161         ret = __iio_add_chan_devattr("label",
1162                                      chan,
1163                                      &iio_read_channel_label,
1164                                      NULL,
1165                                      0,
1166                                      IIO_SEPARATE,
1167                                      &indio_dev->dev,
1168                                      &iio_dev_opaque->channel_attr_list);
1169         if (ret < 0)
1170                 return ret;
1171
1172         return 1;
1173 }
1174
1175 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
1176                                          struct iio_chan_spec const *chan,
1177                                          enum iio_shared_by shared_by,
1178                                          const long *infomask)
1179 {
1180         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1181         int i, ret, attrcount = 0;
1182
1183         for_each_set_bit(i, infomask, sizeof(*infomask)*8) {
1184                 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1185                         return -EINVAL;
1186                 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
1187                                              chan,
1188                                              &iio_read_channel_info,
1189                                              &iio_write_channel_info,
1190                                              i,
1191                                              shared_by,
1192                                              &indio_dev->dev,
1193                                              &iio_dev_opaque->channel_attr_list);
1194                 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1195                         continue;
1196                 else if (ret < 0)
1197                         return ret;
1198                 attrcount++;
1199         }
1200
1201         return attrcount;
1202 }
1203
1204 static int iio_device_add_info_mask_type_avail(struct iio_dev *indio_dev,
1205                                                struct iio_chan_spec const *chan,
1206                                                enum iio_shared_by shared_by,
1207                                                const long *infomask)
1208 {
1209         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1210         int i, ret, attrcount = 0;
1211         char *avail_postfix;
1212
1213         for_each_set_bit(i, infomask, sizeof(*infomask) * 8) {
1214                 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1215                         return -EINVAL;
1216                 avail_postfix = kasprintf(GFP_KERNEL,
1217                                           "%s_available",
1218                                           iio_chan_info_postfix[i]);
1219                 if (!avail_postfix)
1220                         return -ENOMEM;
1221
1222                 ret = __iio_add_chan_devattr(avail_postfix,
1223                                              chan,
1224                                              &iio_read_channel_info_avail,
1225                                              NULL,
1226                                              i,
1227                                              shared_by,
1228                                              &indio_dev->dev,
1229                                              &iio_dev_opaque->channel_attr_list);
1230                 kfree(avail_postfix);
1231                 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1232                         continue;
1233                 else if (ret < 0)
1234                         return ret;
1235                 attrcount++;
1236         }
1237
1238         return attrcount;
1239 }
1240
1241 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
1242                                         struct iio_chan_spec const *chan)
1243 {
1244         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1245         int ret, attrcount = 0;
1246         const struct iio_chan_spec_ext_info *ext_info;
1247
1248         if (chan->channel < 0)
1249                 return 0;
1250         ret = iio_device_add_info_mask_type(indio_dev, chan,
1251                                             IIO_SEPARATE,
1252                                             &chan->info_mask_separate);
1253         if (ret < 0)
1254                 return ret;
1255         attrcount += ret;
1256
1257         ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1258                                                   IIO_SEPARATE,
1259                                                   &chan->
1260                                                   info_mask_separate_available);
1261         if (ret < 0)
1262                 return ret;
1263         attrcount += ret;
1264
1265         ret = iio_device_add_info_mask_type(indio_dev, chan,
1266                                             IIO_SHARED_BY_TYPE,
1267                                             &chan->info_mask_shared_by_type);
1268         if (ret < 0)
1269                 return ret;
1270         attrcount += ret;
1271
1272         ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1273                                                   IIO_SHARED_BY_TYPE,
1274                                                   &chan->
1275                                                   info_mask_shared_by_type_available);
1276         if (ret < 0)
1277                 return ret;
1278         attrcount += ret;
1279
1280         ret = iio_device_add_info_mask_type(indio_dev, chan,
1281                                             IIO_SHARED_BY_DIR,
1282                                             &chan->info_mask_shared_by_dir);
1283         if (ret < 0)
1284                 return ret;
1285         attrcount += ret;
1286
1287         ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1288                                                   IIO_SHARED_BY_DIR,
1289                                                   &chan->info_mask_shared_by_dir_available);
1290         if (ret < 0)
1291                 return ret;
1292         attrcount += ret;
1293
1294         ret = iio_device_add_info_mask_type(indio_dev, chan,
1295                                             IIO_SHARED_BY_ALL,
1296                                             &chan->info_mask_shared_by_all);
1297         if (ret < 0)
1298                 return ret;
1299         attrcount += ret;
1300
1301         ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1302                                                   IIO_SHARED_BY_ALL,
1303                                                   &chan->info_mask_shared_by_all_available);
1304         if (ret < 0)
1305                 return ret;
1306         attrcount += ret;
1307
1308         ret = iio_device_add_channel_label(indio_dev, chan);
1309         if (ret < 0)
1310                 return ret;
1311         attrcount += ret;
1312
1313         if (chan->ext_info) {
1314                 unsigned int i = 0;
1315                 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1316                         ret = __iio_add_chan_devattr(ext_info->name,
1317                                         chan,
1318                                         ext_info->read ?
1319                                             &iio_read_channel_ext_info : NULL,
1320                                         ext_info->write ?
1321                                             &iio_write_channel_ext_info : NULL,
1322                                         i,
1323                                         ext_info->shared,
1324                                         &indio_dev->dev,
1325                                         &iio_dev_opaque->channel_attr_list);
1326                         i++;
1327                         if (ret == -EBUSY && ext_info->shared)
1328                                 continue;
1329
1330                         if (ret)
1331                                 return ret;
1332
1333                         attrcount++;
1334                 }
1335         }
1336
1337         return attrcount;
1338 }
1339
1340 /**
1341  * iio_free_chan_devattr_list() - Free a list of IIO device attributes
1342  * @attr_list: List of IIO device attributes
1343  *
1344  * This function frees the memory allocated for each of the IIO device
1345  * attributes in the list.
1346  */
1347 void iio_free_chan_devattr_list(struct list_head *attr_list)
1348 {
1349         struct iio_dev_attr *p, *n;
1350
1351         list_for_each_entry_safe(p, n, attr_list, l) {
1352                 kfree(p->dev_attr.attr.name);
1353                 list_del(&p->l);
1354                 kfree(p);
1355         }
1356 }
1357
1358 static ssize_t iio_show_dev_name(struct device *dev,
1359                                  struct device_attribute *attr,
1360                                  char *buf)
1361 {
1362         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1363         return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->name);
1364 }
1365
1366 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
1367
1368 static ssize_t iio_show_dev_label(struct device *dev,
1369                                  struct device_attribute *attr,
1370                                  char *buf)
1371 {
1372         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1373         return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->label);
1374 }
1375
1376 static DEVICE_ATTR(label, S_IRUGO, iio_show_dev_label, NULL);
1377
1378 static ssize_t iio_show_timestamp_clock(struct device *dev,
1379                                         struct device_attribute *attr,
1380                                         char *buf)
1381 {
1382         const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1383         const clockid_t clk = iio_device_get_clock(indio_dev);
1384         const char *name;
1385         ssize_t sz;
1386
1387         switch (clk) {
1388         case CLOCK_REALTIME:
1389                 name = "realtime\n";
1390                 sz = sizeof("realtime\n");
1391                 break;
1392         case CLOCK_MONOTONIC:
1393                 name = "monotonic\n";
1394                 sz = sizeof("monotonic\n");
1395                 break;
1396         case CLOCK_MONOTONIC_RAW:
1397                 name = "monotonic_raw\n";
1398                 sz = sizeof("monotonic_raw\n");
1399                 break;
1400         case CLOCK_REALTIME_COARSE:
1401                 name = "realtime_coarse\n";
1402                 sz = sizeof("realtime_coarse\n");
1403                 break;
1404         case CLOCK_MONOTONIC_COARSE:
1405                 name = "monotonic_coarse\n";
1406                 sz = sizeof("monotonic_coarse\n");
1407                 break;
1408         case CLOCK_BOOTTIME:
1409                 name = "boottime\n";
1410                 sz = sizeof("boottime\n");
1411                 break;
1412         case CLOCK_TAI:
1413                 name = "tai\n";
1414                 sz = sizeof("tai\n");
1415                 break;
1416         default:
1417                 BUG();
1418         }
1419
1420         memcpy(buf, name, sz);
1421         return sz;
1422 }
1423
1424 static ssize_t iio_store_timestamp_clock(struct device *dev,
1425                                          struct device_attribute *attr,
1426                                          const char *buf, size_t len)
1427 {
1428         clockid_t clk;
1429         int ret;
1430
1431         if (sysfs_streq(buf, "realtime"))
1432                 clk = CLOCK_REALTIME;
1433         else if (sysfs_streq(buf, "monotonic"))
1434                 clk = CLOCK_MONOTONIC;
1435         else if (sysfs_streq(buf, "monotonic_raw"))
1436                 clk = CLOCK_MONOTONIC_RAW;
1437         else if (sysfs_streq(buf, "realtime_coarse"))
1438                 clk = CLOCK_REALTIME_COARSE;
1439         else if (sysfs_streq(buf, "monotonic_coarse"))
1440                 clk = CLOCK_MONOTONIC_COARSE;
1441         else if (sysfs_streq(buf, "boottime"))
1442                 clk = CLOCK_BOOTTIME;
1443         else if (sysfs_streq(buf, "tai"))
1444                 clk = CLOCK_TAI;
1445         else
1446                 return -EINVAL;
1447
1448         ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1449         if (ret)
1450                 return ret;
1451
1452         return len;
1453 }
1454
1455 static DEVICE_ATTR(current_timestamp_clock, S_IRUGO | S_IWUSR,
1456                    iio_show_timestamp_clock, iio_store_timestamp_clock);
1457
1458 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1459 {
1460         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1461         int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
1462         struct iio_dev_attr *p;
1463         struct attribute **attr, *clk = NULL;
1464
1465         /* First count elements in any existing group */
1466         if (indio_dev->info->attrs) {
1467                 attr = indio_dev->info->attrs->attrs;
1468                 while (*attr++ != NULL)
1469                         attrcount_orig++;
1470         }
1471         attrcount = attrcount_orig;
1472         /*
1473          * New channel registration method - relies on the fact a group does
1474          * not need to be initialized if its name is NULL.
1475          */
1476         if (indio_dev->channels)
1477                 for (i = 0; i < indio_dev->num_channels; i++) {
1478                         const struct iio_chan_spec *chan =
1479                                 &indio_dev->channels[i];
1480
1481                         if (chan->type == IIO_TIMESTAMP)
1482                                 clk = &dev_attr_current_timestamp_clock.attr;
1483
1484                         ret = iio_device_add_channel_sysfs(indio_dev, chan);
1485                         if (ret < 0)
1486                                 goto error_clear_attrs;
1487                         attrcount += ret;
1488                 }
1489
1490         if (iio_dev_opaque->event_interface)
1491                 clk = &dev_attr_current_timestamp_clock.attr;
1492
1493         if (indio_dev->name)
1494                 attrcount++;
1495         if (indio_dev->label)
1496                 attrcount++;
1497         if (clk)
1498                 attrcount++;
1499
1500         iio_dev_opaque->chan_attr_group.attrs =
1501                 kcalloc(attrcount + 1,
1502                         sizeof(iio_dev_opaque->chan_attr_group.attrs[0]),
1503                         GFP_KERNEL);
1504         if (iio_dev_opaque->chan_attr_group.attrs == NULL) {
1505                 ret = -ENOMEM;
1506                 goto error_clear_attrs;
1507         }
1508         /* Copy across original attributes */
1509         if (indio_dev->info->attrs) {
1510                 memcpy(iio_dev_opaque->chan_attr_group.attrs,
1511                        indio_dev->info->attrs->attrs,
1512                        sizeof(iio_dev_opaque->chan_attr_group.attrs[0])
1513                        *attrcount_orig);
1514                 iio_dev_opaque->chan_attr_group.is_visible =
1515                         indio_dev->info->attrs->is_visible;
1516         }
1517         attrn = attrcount_orig;
1518         /* Add all elements from the list. */
1519         list_for_each_entry(p, &iio_dev_opaque->channel_attr_list, l)
1520                 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1521         if (indio_dev->name)
1522                 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
1523         if (indio_dev->label)
1524                 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_label.attr;
1525         if (clk)
1526                 iio_dev_opaque->chan_attr_group.attrs[attrn++] = clk;
1527
1528         indio_dev->groups[indio_dev->groupcounter++] =
1529                 &iio_dev_opaque->chan_attr_group;
1530
1531         return 0;
1532
1533 error_clear_attrs:
1534         iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1535
1536         return ret;
1537 }
1538
1539 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1540 {
1541         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1542
1543         iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1544         kfree(iio_dev_opaque->chan_attr_group.attrs);
1545         iio_dev_opaque->chan_attr_group.attrs = NULL;
1546 }
1547
1548 static void iio_dev_release(struct device *device)
1549 {
1550         struct iio_dev *indio_dev = dev_to_iio_dev(device);
1551         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1552
1553         if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1554                 iio_device_unregister_trigger_consumer(indio_dev);
1555         iio_device_unregister_eventset(indio_dev);
1556         iio_device_unregister_sysfs(indio_dev);
1557
1558         iio_buffer_put(indio_dev->buffer);
1559
1560         ida_simple_remove(&iio_ida, indio_dev->id);
1561         kfree(iio_dev_opaque);
1562 }
1563
1564 struct device_type iio_device_type = {
1565         .name = "iio_device",
1566         .release = iio_dev_release,
1567 };
1568
1569 /**
1570  * iio_device_alloc() - allocate an iio_dev from a driver
1571  * @parent:             Parent device.
1572  * @sizeof_priv:        Space to allocate for private structure.
1573  **/
1574 struct iio_dev *iio_device_alloc(struct device *parent, int sizeof_priv)
1575 {
1576         struct iio_dev_opaque *iio_dev_opaque;
1577         struct iio_dev *dev;
1578         size_t alloc_size;
1579
1580         alloc_size = sizeof(struct iio_dev_opaque);
1581         if (sizeof_priv) {
1582                 alloc_size = ALIGN(alloc_size, IIO_ALIGN);
1583                 alloc_size += sizeof_priv;
1584         }
1585
1586         iio_dev_opaque = kzalloc(alloc_size, GFP_KERNEL);
1587         if (!iio_dev_opaque)
1588                 return NULL;
1589
1590         dev = &iio_dev_opaque->indio_dev;
1591         dev->priv = (char *)iio_dev_opaque +
1592                 ALIGN(sizeof(struct iio_dev_opaque), IIO_ALIGN);
1593
1594         dev->dev.parent = parent;
1595         dev->dev.groups = dev->groups;
1596         dev->dev.type = &iio_device_type;
1597         dev->dev.bus = &iio_bus_type;
1598         device_initialize(&dev->dev);
1599         dev_set_drvdata(&dev->dev, (void *)dev);
1600         mutex_init(&dev->mlock);
1601         mutex_init(&dev->info_exist_lock);
1602         INIT_LIST_HEAD(&iio_dev_opaque->channel_attr_list);
1603
1604         dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1605         if (dev->id < 0) {
1606                 /* cannot use a dev_err as the name isn't available */
1607                 pr_err("failed to get device id\n");
1608                 kfree(iio_dev_opaque);
1609                 return NULL;
1610         }
1611         dev_set_name(&dev->dev, "iio:device%d", dev->id);
1612         INIT_LIST_HEAD(&iio_dev_opaque->buffer_list);
1613         INIT_LIST_HEAD(&iio_dev_opaque->ioctl_handlers);
1614
1615         return dev;
1616 }
1617 EXPORT_SYMBOL(iio_device_alloc);
1618
1619 /**
1620  * iio_device_free() - free an iio_dev from a driver
1621  * @dev:                the iio_dev associated with the device
1622  **/
1623 void iio_device_free(struct iio_dev *dev)
1624 {
1625         if (dev)
1626                 put_device(&dev->dev);
1627 }
1628 EXPORT_SYMBOL(iio_device_free);
1629
1630 static void devm_iio_device_release(struct device *dev, void *res)
1631 {
1632         iio_device_free(*(struct iio_dev **)res);
1633 }
1634
1635 /**
1636  * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1637  * @parent:             Device to allocate iio_dev for, and parent for this IIO device
1638  * @sizeof_priv:        Space to allocate for private structure.
1639  *
1640  * Managed iio_device_alloc. iio_dev allocated with this function is
1641  * automatically freed on driver detach.
1642  *
1643  * RETURNS:
1644  * Pointer to allocated iio_dev on success, NULL on failure.
1645  */
1646 struct iio_dev *devm_iio_device_alloc(struct device *parent, int sizeof_priv)
1647 {
1648         struct iio_dev **ptr, *iio_dev;
1649
1650         ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
1651                            GFP_KERNEL);
1652         if (!ptr)
1653                 return NULL;
1654
1655         iio_dev = iio_device_alloc(parent, sizeof_priv);
1656         if (iio_dev) {
1657                 *ptr = iio_dev;
1658                 devres_add(parent, ptr);
1659         } else {
1660                 devres_free(ptr);
1661         }
1662
1663         return iio_dev;
1664 }
1665 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1666
1667 /**
1668  * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1669  * @inode:      Inode structure for identifying the device in the file system
1670  * @filp:       File structure for iio device used to keep and later access
1671  *              private data
1672  *
1673  * Return: 0 on success or -EBUSY if the device is already opened
1674  **/
1675 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1676 {
1677         struct iio_dev *indio_dev = container_of(inode->i_cdev,
1678                                                 struct iio_dev, chrdev);
1679
1680         if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1681                 return -EBUSY;
1682
1683         iio_device_get(indio_dev);
1684
1685         filp->private_data = indio_dev;
1686
1687         return 0;
1688 }
1689
1690 /**
1691  * iio_chrdev_release() - chrdev file close buffer access and ioctls
1692  * @inode:      Inode structure pointer for the char device
1693  * @filp:       File structure pointer for the char device
1694  *
1695  * Return: 0 for successful release
1696  */
1697 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1698 {
1699         struct iio_dev *indio_dev = container_of(inode->i_cdev,
1700                                                 struct iio_dev, chrdev);
1701         clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1702         iio_device_put(indio_dev);
1703
1704         return 0;
1705 }
1706
1707 void iio_device_ioctl_handler_register(struct iio_dev *indio_dev,
1708                                        struct iio_ioctl_handler *h)
1709 {
1710         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1711
1712         list_add_tail(&h->entry, &iio_dev_opaque->ioctl_handlers);
1713 }
1714
1715 void iio_device_ioctl_handler_unregister(struct iio_ioctl_handler *h)
1716 {
1717         list_del(&h->entry);
1718 }
1719
1720 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1721 {
1722         struct iio_dev *indio_dev = filp->private_data;
1723         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1724         struct iio_ioctl_handler *h;
1725         int ret = -ENODEV;
1726
1727         mutex_lock(&indio_dev->info_exist_lock);
1728
1729         /**
1730          * The NULL check here is required to prevent crashing when a device
1731          * is being removed while userspace would still have open file handles
1732          * to try to access this device.
1733          */
1734         if (!indio_dev->info)
1735                 goto out_unlock;
1736
1737         ret = -EINVAL;
1738         list_for_each_entry(h, &iio_dev_opaque->ioctl_handlers, entry) {
1739                 ret = h->ioctl(indio_dev, filp, cmd, arg);
1740                 if (ret != IIO_IOCTL_UNHANDLED)
1741                         break;
1742         }
1743
1744         if (ret == IIO_IOCTL_UNHANDLED)
1745                 ret = -EINVAL;
1746
1747 out_unlock:
1748         mutex_unlock(&indio_dev->info_exist_lock);
1749
1750         return ret;
1751 }
1752
1753 static const struct file_operations iio_buffer_fileops = {
1754         .owner = THIS_MODULE,
1755         .llseek = noop_llseek,
1756         .read = iio_buffer_read_outer_addr,
1757         .poll = iio_buffer_poll_addr,
1758         .unlocked_ioctl = iio_ioctl,
1759         .compat_ioctl = compat_ptr_ioctl,
1760         .open = iio_chrdev_open,
1761         .release = iio_chrdev_release,
1762 };
1763
1764 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1765 {
1766         int i, j;
1767         const struct iio_chan_spec *channels = indio_dev->channels;
1768
1769         if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1770                 return 0;
1771
1772         for (i = 0; i < indio_dev->num_channels - 1; i++) {
1773                 if (channels[i].scan_index < 0)
1774                         continue;
1775                 for (j = i + 1; j < indio_dev->num_channels; j++)
1776                         if (channels[i].scan_index == channels[j].scan_index) {
1777                                 dev_err(&indio_dev->dev,
1778                                         "Duplicate scan index %d\n",
1779                                         channels[i].scan_index);
1780                                 return -EINVAL;
1781                         }
1782         }
1783
1784         return 0;
1785 }
1786
1787 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1788
1789 int __iio_device_register(struct iio_dev *indio_dev, struct module *this_mod)
1790 {
1791         int ret;
1792
1793         if (!indio_dev->info)
1794                 return -EINVAL;
1795
1796         indio_dev->driver_module = this_mod;
1797         /* If the calling driver did not initialize of_node, do it here */
1798         if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1799                 indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1800
1801         indio_dev->label = of_get_property(indio_dev->dev.of_node, "label",
1802                                            NULL);
1803
1804         ret = iio_check_unique_scan_index(indio_dev);
1805         if (ret < 0)
1806                 return ret;
1807
1808         /* configure elements for the chrdev */
1809         indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
1810
1811         iio_device_register_debugfs(indio_dev);
1812
1813         ret = iio_buffer_alloc_sysfs_and_mask(indio_dev);
1814         if (ret) {
1815                 dev_err(indio_dev->dev.parent,
1816                         "Failed to create buffer sysfs interfaces\n");
1817                 goto error_unreg_debugfs;
1818         }
1819
1820         ret = iio_device_register_sysfs(indio_dev);
1821         if (ret) {
1822                 dev_err(indio_dev->dev.parent,
1823                         "Failed to register sysfs interfaces\n");
1824                 goto error_buffer_free_sysfs;
1825         }
1826         ret = iio_device_register_eventset(indio_dev);
1827         if (ret) {
1828                 dev_err(indio_dev->dev.parent,
1829                         "Failed to register event set\n");
1830                 goto error_free_sysfs;
1831         }
1832         if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1833                 iio_device_register_trigger_consumer(indio_dev);
1834
1835         if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1836                 indio_dev->setup_ops == NULL)
1837                 indio_dev->setup_ops = &noop_ring_setup_ops;
1838
1839         cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1840
1841         indio_dev->chrdev.owner = this_mod;
1842
1843         ret = cdev_device_add(&indio_dev->chrdev, &indio_dev->dev);
1844         if (ret < 0)
1845                 goto error_unreg_eventset;
1846
1847         return 0;
1848
1849 error_unreg_eventset:
1850         iio_device_unregister_eventset(indio_dev);
1851 error_free_sysfs:
1852         iio_device_unregister_sysfs(indio_dev);
1853 error_buffer_free_sysfs:
1854         iio_buffer_free_sysfs_and_mask(indio_dev);
1855 error_unreg_debugfs:
1856         iio_device_unregister_debugfs(indio_dev);
1857         return ret;
1858 }
1859 EXPORT_SYMBOL(__iio_device_register);
1860
1861 /**
1862  * iio_device_unregister() - unregister a device from the IIO subsystem
1863  * @indio_dev:          Device structure representing the device.
1864  **/
1865 void iio_device_unregister(struct iio_dev *indio_dev)
1866 {
1867         struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1868         struct iio_ioctl_handler *h, *t;
1869
1870         cdev_device_del(&indio_dev->chrdev, &indio_dev->dev);
1871
1872         mutex_lock(&indio_dev->info_exist_lock);
1873
1874         iio_device_unregister_debugfs(indio_dev);
1875
1876         iio_disable_all_buffers(indio_dev);
1877
1878         indio_dev->info = NULL;
1879
1880         list_for_each_entry_safe(h, t, &iio_dev_opaque->ioctl_handlers, entry)
1881                 list_del(&h->entry);
1882
1883         iio_device_wakeup_eventset(indio_dev);
1884         iio_buffer_wakeup_poll(indio_dev);
1885
1886         mutex_unlock(&indio_dev->info_exist_lock);
1887
1888         iio_buffer_free_sysfs_and_mask(indio_dev);
1889 }
1890 EXPORT_SYMBOL(iio_device_unregister);
1891
1892 static void devm_iio_device_unreg(struct device *dev, void *res)
1893 {
1894         iio_device_unregister(*(struct iio_dev **)res);
1895 }
1896
1897 int __devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev,
1898                                struct module *this_mod)
1899 {
1900         struct iio_dev **ptr;
1901         int ret;
1902
1903         ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
1904         if (!ptr)
1905                 return -ENOMEM;
1906
1907         *ptr = indio_dev;
1908         ret = __iio_device_register(indio_dev, this_mod);
1909         if (!ret)
1910                 devres_add(dev, ptr);
1911         else
1912                 devres_free(ptr);
1913
1914         return ret;
1915 }
1916 EXPORT_SYMBOL_GPL(__devm_iio_device_register);
1917
1918 /**
1919  * iio_device_claim_direct_mode - Keep device in direct mode
1920  * @indio_dev:  the iio_dev associated with the device
1921  *
1922  * If the device is in direct mode it is guaranteed to stay
1923  * that way until iio_device_release_direct_mode() is called.
1924  *
1925  * Use with iio_device_release_direct_mode()
1926  *
1927  * Returns: 0 on success, -EBUSY on failure
1928  */
1929 int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
1930 {
1931         mutex_lock(&indio_dev->mlock);
1932
1933         if (iio_buffer_enabled(indio_dev)) {
1934                 mutex_unlock(&indio_dev->mlock);
1935                 return -EBUSY;
1936         }
1937         return 0;
1938 }
1939 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
1940
1941 /**
1942  * iio_device_release_direct_mode - releases claim on direct mode
1943  * @indio_dev:  the iio_dev associated with the device
1944  *
1945  * Release the claim. Device is no longer guaranteed to stay
1946  * in direct mode.
1947  *
1948  * Use with iio_device_claim_direct_mode()
1949  */
1950 void iio_device_release_direct_mode(struct iio_dev *indio_dev)
1951 {
1952         mutex_unlock(&indio_dev->mlock);
1953 }
1954 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
1955
1956 subsys_initcall(iio_init);
1957 module_exit(iio_exit);
1958
1959 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1960 MODULE_DESCRIPTION("Industrial I/O core");
1961 MODULE_LICENSE("GPL");