]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - drivers/iio/industrialio-core.c
timekeeping: export get_monotonic_coarse64 symbol
[mirror_ubuntu-hirsute-kernel.git] / drivers / iio / industrialio-core.c
CommitLineData
847ec80b
JC
1/* The industrial I/O core
2 *
3 * Copyright (c) 2008 Jonathan Cameron
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 as published by
7 * the Free Software Foundation.
8 *
9 * Based on elements of hwmon and input subsystems.
10 */
11
3176dd5d
SK
12#define pr_fmt(fmt) "iio-core: " fmt
13
847ec80b
JC
14#include <linux/kernel.h>
15#include <linux/module.h>
16#include <linux/idr.h>
17#include <linux/kdev_t.h>
18#include <linux/err.h>
19#include <linux/device.h>
20#include <linux/fs.h>
847ec80b 21#include <linux/poll.h>
ffc18afa 22#include <linux/sched.h>
4439c935 23#include <linux/wait.h>
847ec80b 24#include <linux/cdev.h>
5a0e3ad6 25#include <linux/slab.h>
8e7d9672 26#include <linux/anon_inodes.h>
e553f182 27#include <linux/debugfs.h>
08a33805 28#include <linux/mutex.h>
06458e27 29#include <linux/iio/iio.h>
df9c1c42 30#include "iio_core.h"
6aea1c36 31#include "iio_core_trigger.h"
06458e27
JC
32#include <linux/iio/sysfs.h>
33#include <linux/iio/events.h>
9e69c935 34#include <linux/iio/buffer.h>
9dd1cb30 35
99698b45 36/* IDA to assign each registered device a unique id */
b156cf70 37static DEFINE_IDA(iio_ida);
847ec80b 38
f625cb97 39static dev_t iio_devt;
847ec80b
JC
40
41#define IIO_DEV_MAX 256
5aaaeba8 42struct bus_type iio_bus_type = {
847ec80b 43 .name = "iio",
847ec80b 44};
5aaaeba8 45EXPORT_SYMBOL(iio_bus_type);
847ec80b 46
e553f182
MH
47static struct dentry *iio_debugfs_dentry;
48
c6fc8062
JC
49static const char * const iio_direction[] = {
50 [0] = "in",
51 [1] = "out",
52};
53
ade7ef7b 54static const char * const iio_chan_type_name_spec[] = {
c6fc8062 55 [IIO_VOLTAGE] = "voltage",
faf290e8
MH
56 [IIO_CURRENT] = "current",
57 [IIO_POWER] = "power",
9bff02f8 58 [IIO_ACCEL] = "accel",
41ea040c 59 [IIO_ANGL_VEL] = "anglvel",
1d892719 60 [IIO_MAGN] = "magn",
9bff02f8
BF
61 [IIO_LIGHT] = "illuminance",
62 [IIO_INTENSITY] = "intensity",
f09f2c81 63 [IIO_PROXIMITY] = "proximity",
9bff02f8 64 [IIO_TEMP] = "temp",
1d892719
JC
65 [IIO_INCLI] = "incli",
66 [IIO_ROT] = "rot",
1d892719 67 [IIO_ANGL] = "angl",
9bff02f8 68 [IIO_TIMESTAMP] = "timestamp",
66dbe704 69 [IIO_CAPACITANCE] = "capacitance",
a6b12855 70 [IIO_ALTVOLTAGE] = "altvoltage",
21cd1fab 71 [IIO_CCT] = "cct",
c4f0c693 72 [IIO_PRESSURE] = "pressure",
ac216aa2 73 [IIO_HUMIDITYRELATIVE] = "humidityrelative",
55aebeb9 74 [IIO_ACTIVITY] = "activity",
a88bfe78 75 [IIO_STEPS] = "steps",
72c66644 76 [IIO_ENERGY] = "energy",
cc3c9eec 77 [IIO_DISTANCE] = "distance",
5a1a9329 78 [IIO_VELOCITY] = "velocity",
8ff6b3bc 79 [IIO_CONCENTRATION] = "concentration",
d38d5469 80 [IIO_RESISTANCE] = "resistance",
ecb3a7cc 81 [IIO_PH] = "ph",
d409404c 82 [IIO_UVINDEX] = "uvindex",
4b9d2090 83 [IIO_ELECTRICALCONDUCTIVITY] = "electricalconductivity",
1d892719
JC
84};
85
330c6c57 86static const char * const iio_modifier_names[] = {
1d892719
JC
87 [IIO_MOD_X] = "x",
88 [IIO_MOD_Y] = "y",
89 [IIO_MOD_Z] = "z",
4b8d8015
PM
90 [IIO_MOD_X_AND_Y] = "x&y",
91 [IIO_MOD_X_AND_Z] = "x&z",
92 [IIO_MOD_Y_AND_Z] = "y&z",
93 [IIO_MOD_X_AND_Y_AND_Z] = "x&y&z",
94 [IIO_MOD_X_OR_Y] = "x|y",
95 [IIO_MOD_X_OR_Z] = "x|z",
96 [IIO_MOD_Y_OR_Z] = "y|z",
97 [IIO_MOD_X_OR_Y_OR_Z] = "x|y|z",
8f5879b2 98 [IIO_MOD_ROOT_SUM_SQUARED_X_Y] = "sqrt(x^2+y^2)",
cf82cb81 99 [IIO_MOD_SUM_SQUARED_X_Y_Z] = "x^2+y^2+z^2",
330c6c57
JC
100 [IIO_MOD_LIGHT_BOTH] = "both",
101 [IIO_MOD_LIGHT_IR] = "ir",
21cd1fab
JB
102 [IIO_MOD_LIGHT_CLEAR] = "clear",
103 [IIO_MOD_LIGHT_RED] = "red",
104 [IIO_MOD_LIGHT_GREEN] = "green",
105 [IIO_MOD_LIGHT_BLUE] = "blue",
2c5ff1f9 106 [IIO_MOD_LIGHT_UV] = "uv",
5082f405 107 [IIO_MOD_QUATERNION] = "quaternion",
638b43b3
PM
108 [IIO_MOD_TEMP_AMBIENT] = "ambient",
109 [IIO_MOD_TEMP_OBJECT] = "object",
11b8ddab
RA
110 [IIO_MOD_NORTH_MAGN] = "from_north_magnetic",
111 [IIO_MOD_NORTH_TRUE] = "from_north_true",
112 [IIO_MOD_NORTH_MAGN_TILT_COMP] = "from_north_magnetic_tilt_comp",
113 [IIO_MOD_NORTH_TRUE_TILT_COMP] = "from_north_true_tilt_comp",
55aebeb9
DB
114 [IIO_MOD_RUNNING] = "running",
115 [IIO_MOD_JOGGING] = "jogging",
116 [IIO_MOD_WALKING] = "walking",
117 [IIO_MOD_STILL] = "still",
5a1a9329 118 [IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z] = "sqrt(x^2+y^2+z^2)",
1ce87f21
LPC
119 [IIO_MOD_I] = "i",
120 [IIO_MOD_Q] = "q",
8ff6b3bc
MR
121 [IIO_MOD_CO2] = "co2",
122 [IIO_MOD_VOC] = "voc",
1d892719
JC
123};
124
125/* relies on pairs of these shared then separate */
126static const char * const iio_chan_info_postfix[] = {
75a973c7
JC
127 [IIO_CHAN_INFO_RAW] = "raw",
128 [IIO_CHAN_INFO_PROCESSED] = "input",
c8a9f805
JC
129 [IIO_CHAN_INFO_SCALE] = "scale",
130 [IIO_CHAN_INFO_OFFSET] = "offset",
131 [IIO_CHAN_INFO_CALIBSCALE] = "calibscale",
132 [IIO_CHAN_INFO_CALIBBIAS] = "calibbias",
133 [IIO_CHAN_INFO_PEAK] = "peak_raw",
134 [IIO_CHAN_INFO_PEAK_SCALE] = "peak_scale",
135 [IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW] = "quadrature_correction_raw",
136 [IIO_CHAN_INFO_AVERAGE_RAW] = "mean_raw",
df94aba8
JC
137 [IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY]
138 = "filter_low_pass_3db_frequency",
3f7f642b
MF
139 [IIO_CHAN_INFO_HIGH_PASS_FILTER_3DB_FREQUENCY]
140 = "filter_high_pass_3db_frequency",
ce85a1cb 141 [IIO_CHAN_INFO_SAMP_FREQ] = "sampling_frequency",
a6b12855
MH
142 [IIO_CHAN_INFO_FREQUENCY] = "frequency",
143 [IIO_CHAN_INFO_PHASE] = "phase",
b65d6212 144 [IIO_CHAN_INFO_HARDWAREGAIN] = "hardwaregain",
7c9ab035 145 [IIO_CHAN_INFO_HYSTERESIS] = "hysteresis",
899d90bd 146 [IIO_CHAN_INFO_INT_TIME] = "integration_time",
a88bfe78 147 [IIO_CHAN_INFO_ENABLE] = "en",
bcdf28fb 148 [IIO_CHAN_INFO_CALIBHEIGHT] = "calibheight",
d37f6836 149 [IIO_CHAN_INFO_CALIBWEIGHT] = "calibweight",
2f0ecb7c
IT
150 [IIO_CHAN_INFO_DEBOUNCE_COUNT] = "debounce_count",
151 [IIO_CHAN_INFO_DEBOUNCE_TIME] = "debounce_time",
c8a85854 152 [IIO_CHAN_INFO_CALIBEMISSIVITY] = "calibemissivity",
faaa4495 153 [IIO_CHAN_INFO_OVERSAMPLING_RATIO] = "oversampling_ratio",
1d892719
JC
154};
155
a7e57dce
SK
156/**
157 * iio_find_channel_from_si() - get channel from its scan index
158 * @indio_dev: device
159 * @si: scan index to match
160 */
5fb21c82
JC
161const struct iio_chan_spec
162*iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
163{
164 int i;
165
166 for (i = 0; i < indio_dev->num_channels; i++)
167 if (indio_dev->channels[i].scan_index == si)
168 return &indio_dev->channels[i];
169 return NULL;
170}
171
847ec80b
JC
172/* This turns up an awful lot */
173ssize_t iio_read_const_attr(struct device *dev,
174 struct device_attribute *attr,
175 char *buf)
176{
177 return sprintf(buf, "%s\n", to_iio_const_attr(attr)->string);
178}
179EXPORT_SYMBOL(iio_read_const_attr);
180
847ec80b
JC
181static int __init iio_init(void)
182{
183 int ret;
184
5aaaeba8
JC
185 /* Register sysfs bus */
186 ret = bus_register(&iio_bus_type);
847ec80b 187 if (ret < 0) {
3176dd5d 188 pr_err("could not register bus type\n");
847ec80b
JC
189 goto error_nothing;
190 }
191
9aa1a167
JC
192 ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
193 if (ret < 0) {
3176dd5d 194 pr_err("failed to allocate char dev region\n");
5aaaeba8 195 goto error_unregister_bus_type;
9aa1a167 196 }
847ec80b 197
e553f182
MH
198 iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
199
847ec80b
JC
200 return 0;
201
5aaaeba8
JC
202error_unregister_bus_type:
203 bus_unregister(&iio_bus_type);
847ec80b
JC
204error_nothing:
205 return ret;
206}
207
208static void __exit iio_exit(void)
209{
9aa1a167
JC
210 if (iio_devt)
211 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
5aaaeba8 212 bus_unregister(&iio_bus_type);
e553f182
MH
213 debugfs_remove(iio_debugfs_dentry);
214}
215
216#if defined(CONFIG_DEBUG_FS)
e553f182
MH
217static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
218 size_t count, loff_t *ppos)
219{
220 struct iio_dev *indio_dev = file->private_data;
221 char buf[20];
222 unsigned val = 0;
223 ssize_t len;
224 int ret;
225
226 ret = indio_dev->info->debugfs_reg_access(indio_dev,
227 indio_dev->cached_reg_addr,
228 0, &val);
229 if (ret)
230 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
231
232 len = snprintf(buf, sizeof(buf), "0x%X\n", val);
233
234 return simple_read_from_buffer(userbuf, count, ppos, buf, len);
235}
236
237static ssize_t iio_debugfs_write_reg(struct file *file,
238 const char __user *userbuf, size_t count, loff_t *ppos)
239{
240 struct iio_dev *indio_dev = file->private_data;
241 unsigned reg, val;
242 char buf[80];
243 int ret;
244
245 count = min_t(size_t, count, (sizeof(buf)-1));
246 if (copy_from_user(buf, userbuf, count))
247 return -EFAULT;
248
249 buf[count] = 0;
250
251 ret = sscanf(buf, "%i %i", &reg, &val);
252
253 switch (ret) {
254 case 1:
255 indio_dev->cached_reg_addr = reg;
256 break;
257 case 2:
258 indio_dev->cached_reg_addr = reg;
259 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
260 val, NULL);
261 if (ret) {
262 dev_err(indio_dev->dev.parent, "%s: write failed\n",
263 __func__);
264 return ret;
265 }
266 break;
267 default:
268 return -EINVAL;
269 }
270
271 return count;
272}
273
274static const struct file_operations iio_debugfs_reg_fops = {
5a28c873 275 .open = simple_open,
e553f182
MH
276 .read = iio_debugfs_read_reg,
277 .write = iio_debugfs_write_reg,
278};
279
280static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
281{
282 debugfs_remove_recursive(indio_dev->debugfs_dentry);
847ec80b
JC
283}
284
e553f182
MH
285static int iio_device_register_debugfs(struct iio_dev *indio_dev)
286{
287 struct dentry *d;
288
289 if (indio_dev->info->debugfs_reg_access == NULL)
290 return 0;
291
abd5a2fb 292 if (!iio_debugfs_dentry)
e553f182
MH
293 return 0;
294
295 indio_dev->debugfs_dentry =
296 debugfs_create_dir(dev_name(&indio_dev->dev),
297 iio_debugfs_dentry);
e553f182
MH
298 if (indio_dev->debugfs_dentry == NULL) {
299 dev_warn(indio_dev->dev.parent,
300 "Failed to create debugfs directory\n");
301 return -EFAULT;
302 }
303
304 d = debugfs_create_file("direct_reg_access", 0644,
305 indio_dev->debugfs_dentry,
306 indio_dev, &iio_debugfs_reg_fops);
307 if (!d) {
308 iio_device_unregister_debugfs(indio_dev);
309 return -ENOMEM;
310 }
311
312 return 0;
313}
314#else
315static int iio_device_register_debugfs(struct iio_dev *indio_dev)
316{
317 return 0;
318}
319
320static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
321{
322}
323#endif /* CONFIG_DEBUG_FS */
324
4fee7e16
LPC
325static ssize_t iio_read_channel_ext_info(struct device *dev,
326 struct device_attribute *attr,
327 char *buf)
328{
e53f5ac5 329 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
4fee7e16
LPC
330 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
331 const struct iio_chan_spec_ext_info *ext_info;
332
333 ext_info = &this_attr->c->ext_info[this_attr->address];
334
fc6d1139 335 return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
4fee7e16
LPC
336}
337
338static ssize_t iio_write_channel_ext_info(struct device *dev,
339 struct device_attribute *attr,
340 const char *buf,
341 size_t len)
342{
e53f5ac5 343 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
4fee7e16
LPC
344 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
345 const struct iio_chan_spec_ext_info *ext_info;
346
347 ext_info = &this_attr->c->ext_info[this_attr->address];
348
fc6d1139
MH
349 return ext_info->write(indio_dev, ext_info->private,
350 this_attr->c, buf, len);
4fee7e16
LPC
351}
352
5212cc8a
LPC
353ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
354 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
355{
356 const struct iio_enum *e = (const struct iio_enum *)priv;
357 unsigned int i;
358 size_t len = 0;
359
360 if (!e->num_items)
361 return 0;
362
363 for (i = 0; i < e->num_items; ++i)
74dcd439 364 len += scnprintf(buf + len, PAGE_SIZE - len, "%s ", e->items[i]);
5212cc8a
LPC
365
366 /* replace last space with a newline */
367 buf[len - 1] = '\n';
368
369 return len;
370}
371EXPORT_SYMBOL_GPL(iio_enum_available_read);
372
373ssize_t iio_enum_read(struct iio_dev *indio_dev,
374 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
375{
376 const struct iio_enum *e = (const struct iio_enum *)priv;
377 int i;
378
379 if (!e->get)
380 return -EINVAL;
381
382 i = e->get(indio_dev, chan);
383 if (i < 0)
384 return i;
385 else if (i >= e->num_items)
386 return -EINVAL;
387
598db581 388 return snprintf(buf, PAGE_SIZE, "%s\n", e->items[i]);
5212cc8a
LPC
389}
390EXPORT_SYMBOL_GPL(iio_enum_read);
391
392ssize_t iio_enum_write(struct iio_dev *indio_dev,
393 uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
394 size_t len)
395{
396 const struct iio_enum *e = (const struct iio_enum *)priv;
397 unsigned int i;
398 int ret;
399
400 if (!e->set)
401 return -EINVAL;
402
403 for (i = 0; i < e->num_items; i++) {
404 if (sysfs_streq(buf, e->items[i]))
405 break;
406 }
407
408 if (i == e->num_items)
409 return -EINVAL;
410
411 ret = e->set(indio_dev, chan, i);
412 return ret ? ret : len;
413}
414EXPORT_SYMBOL_GPL(iio_enum_write);
415
dfc57732
GB
416static const struct iio_mount_matrix iio_mount_idmatrix = {
417 .rotation = {
418 "1", "0", "0",
419 "0", "1", "0",
420 "0", "0", "1"
421 }
422};
423
424static int iio_setup_mount_idmatrix(const struct device *dev,
425 struct iio_mount_matrix *matrix)
426{
427 *matrix = iio_mount_idmatrix;
428 dev_info(dev, "mounting matrix not found: using identity...\n");
429 return 0;
430}
431
432ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
433 const struct iio_chan_spec *chan, char *buf)
434{
435 const struct iio_mount_matrix *mtx = ((iio_get_mount_matrix_t *)
436 priv)(indio_dev, chan);
437
438 if (IS_ERR(mtx))
439 return PTR_ERR(mtx);
440
441 if (!mtx)
442 mtx = &iio_mount_idmatrix;
443
444 return snprintf(buf, PAGE_SIZE, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
445 mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
446 mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
447 mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
448}
449EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
450
451/**
452 * of_iio_read_mount_matrix() - retrieve iio device mounting matrix from
453 * device-tree "mount-matrix" property
454 * @dev: device the mounting matrix property is assigned to
455 * @propname: device specific mounting matrix property name
456 * @matrix: where to store retrieved matrix
457 *
458 * If device is assigned no mounting matrix property, a default 3x3 identity
459 * matrix will be filled in.
460 *
461 * Return: 0 if success, or a negative error code on failure.
462 */
463#ifdef CONFIG_OF
464int of_iio_read_mount_matrix(const struct device *dev,
465 const char *propname,
466 struct iio_mount_matrix *matrix)
467{
468 if (dev->of_node) {
469 int err = of_property_read_string_array(dev->of_node,
470 propname, matrix->rotation,
471 ARRAY_SIZE(iio_mount_idmatrix.rotation));
472
473 if (err == ARRAY_SIZE(iio_mount_idmatrix.rotation))
474 return 0;
475
476 if (err >= 0)
477 /* Invalid number of matrix entries. */
478 return -EINVAL;
479
480 if (err != -EINVAL)
481 /* Invalid matrix declaration format. */
482 return err;
483 }
484
485 /* Matrix was not declared at all: fallback to identity. */
486 return iio_setup_mount_idmatrix(dev, matrix);
487}
488#else
489int of_iio_read_mount_matrix(const struct device *dev,
490 const char *propname,
491 struct iio_mount_matrix *matrix)
492{
493 return iio_setup_mount_idmatrix(dev, matrix);
494}
495#endif
496EXPORT_SYMBOL(of_iio_read_mount_matrix);
497
3661f3f5
LPC
498/**
499 * iio_format_value() - Formats a IIO value into its string representation
2498dcf6
CO
500 * @buf: The buffer to which the formatted value gets written
501 * @type: One of the IIO_VAL_... constants. This decides how the val
502 * and val2 parameters are formatted.
503 * @size: Number of IIO value entries contained in vals
504 * @vals: Pointer to the values, exact meaning depends on the
505 * type parameter.
506 *
507 * Return: 0 by default, a negative number on failure or the
508 * total number of characters written for a type that belongs
509 * to the IIO_VAL_... constant.
3661f3f5 510 */
9fbfb4b3 511ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
847ec80b 512{
7985e7c1 513 unsigned long long tmp;
67eedba3 514 bool scale_db = false;
1d892719 515
3661f3f5 516 switch (type) {
67eedba3 517 case IIO_VAL_INT:
9fbfb4b3 518 return sprintf(buf, "%d\n", vals[0]);
67eedba3
MH
519 case IIO_VAL_INT_PLUS_MICRO_DB:
520 scale_db = true;
521 case IIO_VAL_INT_PLUS_MICRO:
9fbfb4b3 522 if (vals[1] < 0)
8f57e4d9
MN
523 return sprintf(buf, "-%d.%06u%s\n", abs(vals[0]),
524 -vals[1], scale_db ? " dB" : "");
1d892719 525 else
9fbfb4b3 526 return sprintf(buf, "%d.%06u%s\n", vals[0], vals[1],
67eedba3
MH
527 scale_db ? " dB" : "");
528 case IIO_VAL_INT_PLUS_NANO:
9fbfb4b3 529 if (vals[1] < 0)
8f57e4d9
MN
530 return sprintf(buf, "-%d.%09u\n", abs(vals[0]),
531 -vals[1]);
71646e2c 532 else
9fbfb4b3 533 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
7985e7c1 534 case IIO_VAL_FRACTIONAL:
9fbfb4b3
SP
535 tmp = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
536 vals[1] = do_div(tmp, 1000000000LL);
537 vals[0] = tmp;
538 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
103d9fb9 539 case IIO_VAL_FRACTIONAL_LOG2:
9fbfb4b3
SP
540 tmp = (s64)vals[0] * 1000000000LL >> vals[1];
541 vals[1] = do_div(tmp, 1000000000LL);
542 vals[0] = tmp;
543 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
544 case IIO_VAL_INT_MULTIPLE:
545 {
546 int i;
547 int len = 0;
548
549 for (i = 0; i < size; ++i)
550 len += snprintf(&buf[len], PAGE_SIZE - len, "%d ",
551 vals[i]);
552 len += snprintf(&buf[len], PAGE_SIZE - len, "\n");
553 return len;
554 }
67eedba3 555 default:
1d892719 556 return 0;
67eedba3 557 }
1d892719 558}
7d2c2aca 559EXPORT_SYMBOL_GPL(iio_format_value);
1d892719 560
3661f3f5
LPC
561static ssize_t iio_read_channel_info(struct device *dev,
562 struct device_attribute *attr,
563 char *buf)
564{
565 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
566 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
9fbfb4b3
SP
567 int vals[INDIO_MAX_RAW_ELEMENTS];
568 int ret;
569 int val_len = 2;
570
571 if (indio_dev->info->read_raw_multi)
572 ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
573 INDIO_MAX_RAW_ELEMENTS,
574 vals, &val_len,
575 this_attr->address);
576 else
577 ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
578 &vals[0], &vals[1], this_attr->address);
3661f3f5
LPC
579
580 if (ret < 0)
581 return ret;
582
9fbfb4b3 583 return iio_format_value(buf, ret, val_len, vals);
3661f3f5
LPC
584}
585
6807d721
LPC
586/**
587 * iio_str_to_fixpoint() - Parse a fixed-point number from a string
588 * @str: The string to parse
589 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
590 * @integer: The integer part of the number
591 * @fract: The fractional part of the number
592 *
593 * Returns 0 on success, or a negative error code if the string could not be
594 * parsed.
595 */
596int iio_str_to_fixpoint(const char *str, int fract_mult,
597 int *integer, int *fract)
598{
599 int i = 0, f = 0;
600 bool integer_part = true, negative = false;
601
f47dff32
SN
602 if (fract_mult == 0) {
603 *fract = 0;
604
605 return kstrtoint(str, 0, integer);
606 }
607
6807d721
LPC
608 if (str[0] == '-') {
609 negative = true;
610 str++;
611 } else if (str[0] == '+') {
612 str++;
613 }
614
615 while (*str) {
616 if ('0' <= *str && *str <= '9') {
617 if (integer_part) {
618 i = i * 10 + *str - '0';
619 } else {
620 f += fract_mult * (*str - '0');
621 fract_mult /= 10;
622 }
623 } else if (*str == '\n') {
624 if (*(str + 1) == '\0')
625 break;
626 else
627 return -EINVAL;
628 } else if (*str == '.' && integer_part) {
629 integer_part = false;
630 } else {
631 return -EINVAL;
632 }
633 str++;
634 }
635
636 if (negative) {
637 if (i)
638 i = -i;
639 else
640 f = -f;
641 }
642
643 *integer = i;
644 *fract = f;
645
646 return 0;
647}
648EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
649
1d892719
JC
650static ssize_t iio_write_channel_info(struct device *dev,
651 struct device_attribute *attr,
652 const char *buf,
653 size_t len)
654{
e53f5ac5 655 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1d892719 656 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
6807d721
LPC
657 int ret, fract_mult = 100000;
658 int integer, fract;
1d892719
JC
659
660 /* Assumes decimal - precision based on number of digits */
6fe8135f 661 if (!indio_dev->info->write_raw)
1d892719 662 return -EINVAL;
5c04af04
MH
663
664 if (indio_dev->info->write_raw_get_fmt)
665 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
666 this_attr->c, this_attr->address)) {
f47dff32
SN
667 case IIO_VAL_INT:
668 fract_mult = 0;
669 break;
5c04af04
MH
670 case IIO_VAL_INT_PLUS_MICRO:
671 fract_mult = 100000;
672 break;
673 case IIO_VAL_INT_PLUS_NANO:
674 fract_mult = 100000000;
675 break;
676 default:
677 return -EINVAL;
678 }
679
6807d721
LPC
680 ret = iio_str_to_fixpoint(buf, fract_mult, &integer, &fract);
681 if (ret)
682 return ret;
1d892719 683
6fe8135f 684 ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
5c04af04 685 integer, fract, this_attr->address);
1d892719
JC
686 if (ret)
687 return ret;
688
689 return len;
690}
691
df9c1c42 692static
1d892719
JC
693int __iio_device_attr_init(struct device_attribute *dev_attr,
694 const char *postfix,
695 struct iio_chan_spec const *chan,
696 ssize_t (*readfunc)(struct device *dev,
697 struct device_attribute *attr,
698 char *buf),
699 ssize_t (*writefunc)(struct device *dev,
700 struct device_attribute *attr,
701 const char *buf,
702 size_t len),
3704432f 703 enum iio_shared_by shared_by)
1d892719 704{
3704432f 705 int ret = 0;
7bbcf7e1 706 char *name = NULL;
3704432f 707 char *full_postfix;
1d892719 708 sysfs_attr_init(&dev_attr->attr);
1d892719 709
ade7ef7b 710 /* Build up postfix of <extend_name>_<modifier>_postfix */
3704432f 711 if (chan->modified && (shared_by == IIO_SEPARATE)) {
ade7ef7b
JC
712 if (chan->extend_name)
713 full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
714 iio_modifier_names[chan
715 ->channel2],
716 chan->extend_name,
717 postfix);
718 else
719 full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
720 iio_modifier_names[chan
721 ->channel2],
722 postfix);
723 } else {
77bfa8ba 724 if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
ade7ef7b
JC
725 full_postfix = kstrdup(postfix, GFP_KERNEL);
726 else
727 full_postfix = kasprintf(GFP_KERNEL,
728 "%s_%s",
729 chan->extend_name,
730 postfix);
731 }
3704432f
JC
732 if (full_postfix == NULL)
733 return -ENOMEM;
1d892719 734
4abf6f8b 735 if (chan->differential) { /* Differential can not have modifier */
3704432f 736 switch (shared_by) {
c006ec83 737 case IIO_SHARED_BY_ALL:
7bbcf7e1 738 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
c006ec83
JC
739 break;
740 case IIO_SHARED_BY_DIR:
7bbcf7e1 741 name = kasprintf(GFP_KERNEL, "%s_%s",
c006ec83
JC
742 iio_direction[chan->output],
743 full_postfix);
744 break;
3704432f 745 case IIO_SHARED_BY_TYPE:
7bbcf7e1 746 name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
ade7ef7b
JC
747 iio_direction[chan->output],
748 iio_chan_type_name_spec[chan->type],
749 iio_chan_type_name_spec[chan->type],
750 full_postfix);
3704432f
JC
751 break;
752 case IIO_SEPARATE:
753 if (!chan->indexed) {
231bfe53 754 WARN(1, "Differential channels must be indexed\n");
3704432f
JC
755 ret = -EINVAL;
756 goto error_free_full_postfix;
757 }
7bbcf7e1 758 name = kasprintf(GFP_KERNEL,
3704432f 759 "%s_%s%d-%s%d_%s",
ade7ef7b
JC
760 iio_direction[chan->output],
761 iio_chan_type_name_spec[chan->type],
762 chan->channel,
763 iio_chan_type_name_spec[chan->type],
764 chan->channel2,
765 full_postfix);
3704432f 766 break;
ade7ef7b
JC
767 }
768 } else { /* Single ended */
3704432f 769 switch (shared_by) {
c006ec83 770 case IIO_SHARED_BY_ALL:
7bbcf7e1 771 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
c006ec83
JC
772 break;
773 case IIO_SHARED_BY_DIR:
7bbcf7e1 774 name = kasprintf(GFP_KERNEL, "%s_%s",
c006ec83
JC
775 iio_direction[chan->output],
776 full_postfix);
777 break;
3704432f 778 case IIO_SHARED_BY_TYPE:
7bbcf7e1 779 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
ade7ef7b
JC
780 iio_direction[chan->output],
781 iio_chan_type_name_spec[chan->type],
782 full_postfix);
3704432f
JC
783 break;
784
785 case IIO_SEPARATE:
786 if (chan->indexed)
7bbcf7e1 787 name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
3704432f
JC
788 iio_direction[chan->output],
789 iio_chan_type_name_spec[chan->type],
790 chan->channel,
791 full_postfix);
792 else
7bbcf7e1 793 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
3704432f
JC
794 iio_direction[chan->output],
795 iio_chan_type_name_spec[chan->type],
796 full_postfix);
797 break;
798 }
ade7ef7b 799 }
7bbcf7e1 800 if (name == NULL) {
1d892719
JC
801 ret = -ENOMEM;
802 goto error_free_full_postfix;
803 }
7bbcf7e1 804 dev_attr->attr.name = name;
1d892719
JC
805
806 if (readfunc) {
807 dev_attr->attr.mode |= S_IRUGO;
808 dev_attr->show = readfunc;
809 }
810
811 if (writefunc) {
812 dev_attr->attr.mode |= S_IWUSR;
813 dev_attr->store = writefunc;
814 }
7bbcf7e1 815
1d892719
JC
816error_free_full_postfix:
817 kfree(full_postfix);
3704432f 818
1d892719
JC
819 return ret;
820}
821
df9c1c42 822static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1d892719
JC
823{
824 kfree(dev_attr->attr.name);
825}
826
827int __iio_add_chan_devattr(const char *postfix,
1d892719
JC
828 struct iio_chan_spec const *chan,
829 ssize_t (*readfunc)(struct device *dev,
830 struct device_attribute *attr,
831 char *buf),
832 ssize_t (*writefunc)(struct device *dev,
833 struct device_attribute *attr,
834 const char *buf,
835 size_t len),
e614a54b 836 u64 mask,
3704432f 837 enum iio_shared_by shared_by,
1d892719
JC
838 struct device *dev,
839 struct list_head *attr_list)
840{
841 int ret;
842 struct iio_dev_attr *iio_attr, *t;
843
670c1103 844 iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
92825ff9
HK
845 if (iio_attr == NULL)
846 return -ENOMEM;
1d892719
JC
847 ret = __iio_device_attr_init(&iio_attr->dev_attr,
848 postfix, chan,
3704432f 849 readfunc, writefunc, shared_by);
1d892719
JC
850 if (ret)
851 goto error_iio_dev_attr_free;
852 iio_attr->c = chan;
853 iio_attr->address = mask;
854 list_for_each_entry(t, attr_list, l)
855 if (strcmp(t->dev_attr.attr.name,
856 iio_attr->dev_attr.attr.name) == 0) {
3704432f 857 if (shared_by == IIO_SEPARATE)
1d892719
JC
858 dev_err(dev, "tried to double register : %s\n",
859 t->dev_attr.attr.name);
860 ret = -EBUSY;
861 goto error_device_attr_deinit;
862 }
1d892719
JC
863 list_add(&iio_attr->l, attr_list);
864
865 return 0;
866
867error_device_attr_deinit:
868 __iio_device_attr_deinit(&iio_attr->dev_attr);
869error_iio_dev_attr_free:
870 kfree(iio_attr);
1d892719
JC
871 return ret;
872}
873
3704432f
JC
874static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
875 struct iio_chan_spec const *chan,
876 enum iio_shared_by shared_by,
877 const long *infomask)
1d892719 878{
3704432f 879 int i, ret, attrcount = 0;
1d892719 880
3704432f 881 for_each_set_bit(i, infomask, sizeof(infomask)*8) {
ef4b4856
JC
882 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
883 return -EINVAL;
8655cc49
JC
884 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
885 chan,
886 &iio_read_channel_info,
887 &iio_write_channel_info,
888 i,
3704432f 889 shared_by,
8655cc49
JC
890 &indio_dev->dev,
891 &indio_dev->channel_attr_list);
3704432f 892 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
8655cc49 893 continue;
3704432f
JC
894 else if (ret < 0)
895 return ret;
8655cc49
JC
896 attrcount++;
897 }
5f420b42 898
3704432f
JC
899 return attrcount;
900}
901
902static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
903 struct iio_chan_spec const *chan)
904{
905 int ret, attrcount = 0;
906 const struct iio_chan_spec_ext_info *ext_info;
907
908 if (chan->channel < 0)
909 return 0;
910 ret = iio_device_add_info_mask_type(indio_dev, chan,
911 IIO_SEPARATE,
912 &chan->info_mask_separate);
913 if (ret < 0)
914 return ret;
915 attrcount += ret;
916
917 ret = iio_device_add_info_mask_type(indio_dev, chan,
918 IIO_SHARED_BY_TYPE,
919 &chan->info_mask_shared_by_type);
920 if (ret < 0)
921 return ret;
922 attrcount += ret;
923
c006ec83
JC
924 ret = iio_device_add_info_mask_type(indio_dev, chan,
925 IIO_SHARED_BY_DIR,
926 &chan->info_mask_shared_by_dir);
927 if (ret < 0)
928 return ret;
929 attrcount += ret;
930
931 ret = iio_device_add_info_mask_type(indio_dev, chan,
932 IIO_SHARED_BY_ALL,
933 &chan->info_mask_shared_by_all);
934 if (ret < 0)
935 return ret;
936 attrcount += ret;
937
5f420b42
LPC
938 if (chan->ext_info) {
939 unsigned int i = 0;
940 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
941 ret = __iio_add_chan_devattr(ext_info->name,
942 chan,
943 ext_info->read ?
944 &iio_read_channel_ext_info : NULL,
945 ext_info->write ?
946 &iio_write_channel_ext_info : NULL,
947 i,
948 ext_info->shared,
949 &indio_dev->dev,
950 &indio_dev->channel_attr_list);
951 i++;
952 if (ret == -EBUSY && ext_info->shared)
953 continue;
954
955 if (ret)
3704432f 956 return ret;
5f420b42
LPC
957
958 attrcount++;
959 }
960 }
961
3704432f 962 return attrcount;
1d892719
JC
963}
964
84088ebd
LPC
965/**
966 * iio_free_chan_devattr_list() - Free a list of IIO device attributes
967 * @attr_list: List of IIO device attributes
968 *
969 * This function frees the memory allocated for each of the IIO device
c1b03ab5 970 * attributes in the list.
84088ebd
LPC
971 */
972void iio_free_chan_devattr_list(struct list_head *attr_list)
1d892719 973{
84088ebd
LPC
974 struct iio_dev_attr *p, *n;
975
976 list_for_each_entry_safe(p, n, attr_list, l) {
977 kfree(p->dev_attr.attr.name);
c1b03ab5 978 list_del(&p->l);
84088ebd
LPC
979 kfree(p);
980 }
1d892719
JC
981}
982
1b732888
JC
983static ssize_t iio_show_dev_name(struct device *dev,
984 struct device_attribute *attr,
985 char *buf)
986{
e53f5ac5 987 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
598db581 988 return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->name);
1b732888
JC
989}
990
991static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
992
f8c6f4e9 993static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1d892719 994{
26d25ae3 995 int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
84088ebd 996 struct iio_dev_attr *p;
26d25ae3 997 struct attribute **attr;
1d892719 998
26d25ae3 999 /* First count elements in any existing group */
f8c6f4e9
JC
1000 if (indio_dev->info->attrs) {
1001 attr = indio_dev->info->attrs->attrs;
26d25ae3
JC
1002 while (*attr++ != NULL)
1003 attrcount_orig++;
847ec80b 1004 }
26d25ae3 1005 attrcount = attrcount_orig;
1d892719
JC
1006 /*
1007 * New channel registration method - relies on the fact a group does
d25b3808 1008 * not need to be initialized if its name is NULL.
1d892719 1009 */
f8c6f4e9
JC
1010 if (indio_dev->channels)
1011 for (i = 0; i < indio_dev->num_channels; i++) {
1012 ret = iio_device_add_channel_sysfs(indio_dev,
1013 &indio_dev
1d892719
JC
1014 ->channels[i]);
1015 if (ret < 0)
1016 goto error_clear_attrs;
26d25ae3 1017 attrcount += ret;
1d892719 1018 }
26d25ae3 1019
f8c6f4e9 1020 if (indio_dev->name)
26d25ae3
JC
1021 attrcount++;
1022
d83fb184
TM
1023 indio_dev->chan_attr_group.attrs = kcalloc(attrcount + 1,
1024 sizeof(indio_dev->chan_attr_group.attrs[0]),
1025 GFP_KERNEL);
f8c6f4e9 1026 if (indio_dev->chan_attr_group.attrs == NULL) {
26d25ae3
JC
1027 ret = -ENOMEM;
1028 goto error_clear_attrs;
1b732888 1029 }
26d25ae3 1030 /* Copy across original attributes */
f8c6f4e9
JC
1031 if (indio_dev->info->attrs)
1032 memcpy(indio_dev->chan_attr_group.attrs,
1033 indio_dev->info->attrs->attrs,
1034 sizeof(indio_dev->chan_attr_group.attrs[0])
26d25ae3
JC
1035 *attrcount_orig);
1036 attrn = attrcount_orig;
1037 /* Add all elements from the list. */
f8c6f4e9
JC
1038 list_for_each_entry(p, &indio_dev->channel_attr_list, l)
1039 indio_dev->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1040 if (indio_dev->name)
1041 indio_dev->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
26d25ae3 1042
f8c6f4e9
JC
1043 indio_dev->groups[indio_dev->groupcounter++] =
1044 &indio_dev->chan_attr_group;
26d25ae3 1045
1d892719 1046 return 0;
1b732888 1047
1d892719 1048error_clear_attrs:
84088ebd 1049 iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
1d892719 1050
26d25ae3 1051 return ret;
847ec80b
JC
1052}
1053
f8c6f4e9 1054static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
847ec80b 1055{
1d892719 1056
84088ebd 1057 iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
f8c6f4e9 1058 kfree(indio_dev->chan_attr_group.attrs);
c1b03ab5 1059 indio_dev->chan_attr_group.attrs = NULL;
847ec80b
JC
1060}
1061
847ec80b
JC
1062static void iio_dev_release(struct device *device)
1063{
e53f5ac5 1064 struct iio_dev *indio_dev = dev_to_iio_dev(device);
735ad074 1065 if (indio_dev->modes & (INDIO_BUFFER_TRIGGERED | INDIO_EVENT_TRIGGERED))
f8c6f4e9
JC
1066 iio_device_unregister_trigger_consumer(indio_dev);
1067 iio_device_unregister_eventset(indio_dev);
1068 iio_device_unregister_sysfs(indio_dev);
e407fd65 1069
9e69c935
LPC
1070 iio_buffer_put(indio_dev->buffer);
1071
e407fd65
LPC
1072 ida_simple_remove(&iio_ida, indio_dev->id);
1073 kfree(indio_dev);
847ec80b
JC
1074}
1075
17d82b47 1076struct device_type iio_device_type = {
847ec80b
JC
1077 .name = "iio_device",
1078 .release = iio_dev_release,
1079};
1080
a7e57dce
SK
1081/**
1082 * iio_device_alloc() - allocate an iio_dev from a driver
1083 * @sizeof_priv: Space to allocate for private structure.
1084 **/
7cbb7537 1085struct iio_dev *iio_device_alloc(int sizeof_priv)
847ec80b 1086{
6f7c8ee5
JC
1087 struct iio_dev *dev;
1088 size_t alloc_size;
1089
1090 alloc_size = sizeof(struct iio_dev);
1091 if (sizeof_priv) {
1092 alloc_size = ALIGN(alloc_size, IIO_ALIGN);
1093 alloc_size += sizeof_priv;
1094 }
1095 /* ensure 32-byte alignment of whole construct ? */
1096 alloc_size += IIO_ALIGN - 1;
1097
1098 dev = kzalloc(alloc_size, GFP_KERNEL);
847ec80b
JC
1099
1100 if (dev) {
26d25ae3 1101 dev->dev.groups = dev->groups;
17d82b47 1102 dev->dev.type = &iio_device_type;
5aaaeba8 1103 dev->dev.bus = &iio_bus_type;
847ec80b
JC
1104 device_initialize(&dev->dev);
1105 dev_set_drvdata(&dev->dev, (void *)dev);
1106 mutex_init(&dev->mlock);
ac917a81 1107 mutex_init(&dev->info_exist_lock);
e407fd65 1108 INIT_LIST_HEAD(&dev->channel_attr_list);
a9e39f9e
JC
1109
1110 dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1111 if (dev->id < 0) {
1112 /* cannot use a dev_err as the name isn't available */
3176dd5d 1113 pr_err("failed to get device id\n");
a9e39f9e
JC
1114 kfree(dev);
1115 return NULL;
1116 }
1117 dev_set_name(&dev->dev, "iio:device%d", dev->id);
84b36ce5 1118 INIT_LIST_HEAD(&dev->buffer_list);
847ec80b
JC
1119 }
1120
1121 return dev;
1122}
7cbb7537 1123EXPORT_SYMBOL(iio_device_alloc);
847ec80b 1124
a7e57dce
SK
1125/**
1126 * iio_device_free() - free an iio_dev from a driver
1127 * @dev: the iio_dev associated with the device
1128 **/
7cbb7537 1129void iio_device_free(struct iio_dev *dev)
847ec80b 1130{
e407fd65
LPC
1131 if (dev)
1132 put_device(&dev->dev);
847ec80b 1133}
7cbb7537 1134EXPORT_SYMBOL(iio_device_free);
847ec80b 1135
9dabaf5e
GS
1136static void devm_iio_device_release(struct device *dev, void *res)
1137{
1138 iio_device_free(*(struct iio_dev **)res);
1139}
1140
1141static int devm_iio_device_match(struct device *dev, void *res, void *data)
1142{
1143 struct iio_dev **r = res;
1144 if (!r || !*r) {
1145 WARN_ON(!r || !*r);
1146 return 0;
1147 }
1148 return *r == data;
1149}
1150
a7e57dce
SK
1151/**
1152 * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1153 * @dev: Device to allocate iio_dev for
1154 * @sizeof_priv: Space to allocate for private structure.
1155 *
1156 * Managed iio_device_alloc. iio_dev allocated with this function is
1157 * automatically freed on driver detach.
1158 *
1159 * If an iio_dev allocated with this function needs to be freed separately,
1160 * devm_iio_device_free() must be used.
1161 *
1162 * RETURNS:
1163 * Pointer to allocated iio_dev on success, NULL on failure.
1164 */
9dabaf5e
GS
1165struct iio_dev *devm_iio_device_alloc(struct device *dev, int sizeof_priv)
1166{
1167 struct iio_dev **ptr, *iio_dev;
1168
1169 ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
1170 GFP_KERNEL);
1171 if (!ptr)
1172 return NULL;
1173
9dabaf5e
GS
1174 iio_dev = iio_device_alloc(sizeof_priv);
1175 if (iio_dev) {
1176 *ptr = iio_dev;
1177 devres_add(dev, ptr);
1178 } else {
1179 devres_free(ptr);
1180 }
1181
1182 return iio_dev;
1183}
1184EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1185
a7e57dce
SK
1186/**
1187 * devm_iio_device_free - Resource-managed iio_device_free()
1188 * @dev: Device this iio_dev belongs to
1189 * @iio_dev: the iio_dev associated with the device
1190 *
1191 * Free iio_dev allocated with devm_iio_device_alloc().
1192 */
9dabaf5e
GS
1193void devm_iio_device_free(struct device *dev, struct iio_dev *iio_dev)
1194{
1195 int rc;
1196
1197 rc = devres_release(dev, devm_iio_device_release,
1198 devm_iio_device_match, iio_dev);
1199 WARN_ON(rc);
1200}
1201EXPORT_SYMBOL_GPL(devm_iio_device_free);
1202
1aa04278 1203/**
14555b14 1204 * iio_chrdev_open() - chrdev file open for buffer access and ioctls
2498dcf6
CO
1205 * @inode: Inode structure for identifying the device in the file system
1206 * @filp: File structure for iio device used to keep and later access
1207 * private data
1208 *
1209 * Return: 0 on success or -EBUSY if the device is already opened
1aa04278
JC
1210 **/
1211static int iio_chrdev_open(struct inode *inode, struct file *filp)
1212{
f8c6f4e9 1213 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1aa04278 1214 struct iio_dev, chrdev);
bb01443e
LPC
1215
1216 if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1217 return -EBUSY;
1218
cadc2125
LPC
1219 iio_device_get(indio_dev);
1220
f8c6f4e9 1221 filp->private_data = indio_dev;
30eb82f0 1222
79335140 1223 return 0;
1aa04278
JC
1224}
1225
1226/**
14555b14 1227 * iio_chrdev_release() - chrdev file close buffer access and ioctls
2498dcf6
CO
1228 * @inode: Inode structure pointer for the char device
1229 * @filp: File structure pointer for the char device
1230 *
1231 * Return: 0 for successful release
1232 */
1aa04278
JC
1233static int iio_chrdev_release(struct inode *inode, struct file *filp)
1234{
bb01443e
LPC
1235 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1236 struct iio_dev, chrdev);
bb01443e 1237 clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
cadc2125
LPC
1238 iio_device_put(indio_dev);
1239
1aa04278
JC
1240 return 0;
1241}
1242
1243/* Somewhat of a cross file organization violation - ioctls here are actually
1244 * event related */
1245static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1246{
1247 struct iio_dev *indio_dev = filp->private_data;
1248 int __user *ip = (int __user *)arg;
1249 int fd;
1250
f18e7a06
LPC
1251 if (!indio_dev->info)
1252 return -ENODEV;
1253
1aa04278
JC
1254 if (cmd == IIO_GET_EVENT_FD_IOCTL) {
1255 fd = iio_event_getfd(indio_dev);
3f9059b7
LW
1256 if (fd < 0)
1257 return fd;
1aa04278
JC
1258 if (copy_to_user(ip, &fd, sizeof(fd)))
1259 return -EFAULT;
1260 return 0;
1261 }
1262 return -EINVAL;
1263}
1264
14555b14
JC
1265static const struct file_operations iio_buffer_fileops = {
1266 .read = iio_buffer_read_first_n_outer_addr,
1aa04278
JC
1267 .release = iio_chrdev_release,
1268 .open = iio_chrdev_open,
14555b14 1269 .poll = iio_buffer_poll_addr,
1aa04278
JC
1270 .owner = THIS_MODULE,
1271 .llseek = noop_llseek,
1272 .unlocked_ioctl = iio_ioctl,
1273 .compat_ioctl = iio_ioctl,
1274};
1275
8f5d8727
VD
1276static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1277{
1278 int i, j;
1279 const struct iio_chan_spec *channels = indio_dev->channels;
1280
1281 if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1282 return 0;
1283
1284 for (i = 0; i < indio_dev->num_channels - 1; i++) {
1285 if (channels[i].scan_index < 0)
1286 continue;
1287 for (j = i + 1; j < indio_dev->num_channels; j++)
1288 if (channels[i].scan_index == channels[j].scan_index) {
1289 dev_err(&indio_dev->dev,
1290 "Duplicate scan index %d\n",
1291 channels[i].scan_index);
1292 return -EINVAL;
1293 }
1294 }
1295
1296 return 0;
1297}
1298
0f1acee5
MH
1299static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1300
a7e57dce
SK
1301/**
1302 * iio_device_register() - register a device with the IIO subsystem
1303 * @indio_dev: Device structure filled by the device driver
1304 **/
f8c6f4e9 1305int iio_device_register(struct iio_dev *indio_dev)
847ec80b
JC
1306{
1307 int ret;
1308
17d82b47
GR
1309 /* If the calling driver did not initialize of_node, do it here */
1310 if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1311 indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1312
8f5d8727
VD
1313 ret = iio_check_unique_scan_index(indio_dev);
1314 if (ret < 0)
1315 return ret;
1316
1aa04278 1317 /* configure elements for the chrdev */
f8c6f4e9 1318 indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
847ec80b 1319
e553f182
MH
1320 ret = iio_device_register_debugfs(indio_dev);
1321 if (ret) {
1322 dev_err(indio_dev->dev.parent,
1323 "Failed to register debugfs interfaces\n");
92825ff9 1324 return ret;
e553f182 1325 }
3e1b6c95
LPC
1326
1327 ret = iio_buffer_alloc_sysfs_and_mask(indio_dev);
1328 if (ret) {
1329 dev_err(indio_dev->dev.parent,
1330 "Failed to create buffer sysfs interfaces\n");
1331 goto error_unreg_debugfs;
1332 }
1333
f8c6f4e9 1334 ret = iio_device_register_sysfs(indio_dev);
847ec80b 1335 if (ret) {
f8c6f4e9 1336 dev_err(indio_dev->dev.parent,
847ec80b 1337 "Failed to register sysfs interfaces\n");
3e1b6c95 1338 goto error_buffer_free_sysfs;
847ec80b 1339 }
f8c6f4e9 1340 ret = iio_device_register_eventset(indio_dev);
847ec80b 1341 if (ret) {
f8c6f4e9 1342 dev_err(indio_dev->dev.parent,
c849d253 1343 "Failed to register event set\n");
847ec80b
JC
1344 goto error_free_sysfs;
1345 }
735ad074 1346 if (indio_dev->modes & (INDIO_BUFFER_TRIGGERED | INDIO_EVENT_TRIGGERED))
f8c6f4e9 1347 iio_device_register_trigger_consumer(indio_dev);
847ec80b 1348
0f1acee5
MH
1349 if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1350 indio_dev->setup_ops == NULL)
1351 indio_dev->setup_ops = &noop_ring_setup_ops;
1352
f8c6f4e9
JC
1353 cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1354 indio_dev->chrdev.owner = indio_dev->info->driver_module;
0d5b7dae 1355 indio_dev->chrdev.kobj.parent = &indio_dev->dev.kobj;
f8c6f4e9 1356 ret = cdev_add(&indio_dev->chrdev, indio_dev->dev.devt, 1);
26d25ae3 1357 if (ret < 0)
0d5b7dae 1358 goto error_unreg_eventset;
847ec80b 1359
0d5b7dae
LPC
1360 ret = device_add(&indio_dev->dev);
1361 if (ret < 0)
1362 goto error_cdev_del;
1363
1364 return 0;
1365error_cdev_del:
1366 cdev_del(&indio_dev->chrdev);
26d25ae3 1367error_unreg_eventset:
f8c6f4e9 1368 iio_device_unregister_eventset(indio_dev);
26d25ae3 1369error_free_sysfs:
f8c6f4e9 1370 iio_device_unregister_sysfs(indio_dev);
3e1b6c95
LPC
1371error_buffer_free_sysfs:
1372 iio_buffer_free_sysfs_and_mask(indio_dev);
e553f182
MH
1373error_unreg_debugfs:
1374 iio_device_unregister_debugfs(indio_dev);
847ec80b
JC
1375 return ret;
1376}
1377EXPORT_SYMBOL(iio_device_register);
1378
a7e57dce
SK
1379/**
1380 * iio_device_unregister() - unregister a device from the IIO subsystem
1381 * @indio_dev: Device structure representing the device.
1382 **/
f8c6f4e9 1383void iio_device_unregister(struct iio_dev *indio_dev)
847ec80b 1384{
ac917a81 1385 mutex_lock(&indio_dev->info_exist_lock);
a87c82e4
LPC
1386
1387 device_del(&indio_dev->dev);
1388
0d5b7dae
LPC
1389 if (indio_dev->chrdev.dev)
1390 cdev_del(&indio_dev->chrdev);
bc4c9612 1391 iio_device_unregister_debugfs(indio_dev);
0d5b7dae 1392
a87c82e4
LPC
1393 iio_disable_all_buffers(indio_dev);
1394
ac917a81 1395 indio_dev->info = NULL;
d2f0a48f
LPC
1396
1397 iio_device_wakeup_eventset(indio_dev);
1398 iio_buffer_wakeup_poll(indio_dev);
1399
ac917a81 1400 mutex_unlock(&indio_dev->info_exist_lock);
3e1b6c95
LPC
1401
1402 iio_buffer_free_sysfs_and_mask(indio_dev);
847ec80b
JC
1403}
1404EXPORT_SYMBOL(iio_device_unregister);
8caa07c0
SK
1405
1406static void devm_iio_device_unreg(struct device *dev, void *res)
1407{
1408 iio_device_unregister(*(struct iio_dev **)res);
1409}
1410
1411/**
1412 * devm_iio_device_register - Resource-managed iio_device_register()
1413 * @dev: Device to allocate iio_dev for
1414 * @indio_dev: Device structure filled by the device driver
1415 *
1416 * Managed iio_device_register. The IIO device registered with this
1417 * function is automatically unregistered on driver detach. This function
1418 * calls iio_device_register() internally. Refer to that function for more
1419 * information.
1420 *
1421 * If an iio_dev registered with this function needs to be unregistered
1422 * separately, devm_iio_device_unregister() must be used.
1423 *
1424 * RETURNS:
1425 * 0 on success, negative error number on failure.
1426 */
1427int devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev)
1428{
1429 struct iio_dev **ptr;
1430 int ret;
1431
1432 ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
1433 if (!ptr)
1434 return -ENOMEM;
1435
1436 *ptr = indio_dev;
1437 ret = iio_device_register(indio_dev);
1438 if (!ret)
1439 devres_add(dev, ptr);
1440 else
1441 devres_free(ptr);
1442
1443 return ret;
1444}
1445EXPORT_SYMBOL_GPL(devm_iio_device_register);
1446
1447/**
1448 * devm_iio_device_unregister - Resource-managed iio_device_unregister()
1449 * @dev: Device this iio_dev belongs to
1450 * @indio_dev: the iio_dev associated with the device
1451 *
1452 * Unregister iio_dev registered with devm_iio_device_register().
1453 */
1454void devm_iio_device_unregister(struct device *dev, struct iio_dev *indio_dev)
1455{
1456 int rc;
1457
1458 rc = devres_release(dev, devm_iio_device_unreg,
1459 devm_iio_device_match, indio_dev);
1460 WARN_ON(rc);
1461}
1462EXPORT_SYMBOL_GPL(devm_iio_device_unregister);
1463
08a33805
AS
1464/**
1465 * iio_device_claim_direct_mode - Keep device in direct mode
1466 * @indio_dev: the iio_dev associated with the device
1467 *
1468 * If the device is in direct mode it is guaranteed to stay
1469 * that way until iio_device_release_direct_mode() is called.
1470 *
1471 * Use with iio_device_release_direct_mode()
1472 *
1473 * Returns: 0 on success, -EBUSY on failure
1474 */
1475int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
1476{
1477 mutex_lock(&indio_dev->mlock);
1478
1479 if (iio_buffer_enabled(indio_dev)) {
1480 mutex_unlock(&indio_dev->mlock);
1481 return -EBUSY;
1482 }
1483 return 0;
1484}
1485EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
1486
1487/**
1488 * iio_device_release_direct_mode - releases claim on direct mode
1489 * @indio_dev: the iio_dev associated with the device
1490 *
1491 * Release the claim. Device is no longer guaranteed to stay
1492 * in direct mode.
1493 *
1494 * Use with iio_device_claim_direct_mode()
1495 */
1496void iio_device_release_direct_mode(struct iio_dev *indio_dev)
1497{
1498 mutex_unlock(&indio_dev->mlock);
1499}
1500EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
1501
847ec80b
JC
1502subsys_initcall(iio_init);
1503module_exit(iio_exit);
1504
c8b95952 1505MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
847ec80b
JC
1506MODULE_DESCRIPTION("Industrial I/O core");
1507MODULE_LICENSE("GPL");