1 // SPDX-License-Identifier: GPL-2.0-only
3 * The industrial I/O core
5 * Copyright (c) 2008 Jonathan Cameron
7 * Based on elements of hwmon and input subsystems.
10 #define pr_fmt(fmt) "iio-core: " fmt
12 #include <linux/anon_inodes.h>
13 #include <linux/cdev.h>
14 #include <linux/cleanup.h>
15 #include <linux/debugfs.h>
16 #include <linux/device.h>
17 #include <linux/err.h>
19 #include <linux/idr.h>
20 #include <linux/kdev_t.h>
21 #include <linux/kernel.h>
22 #include <linux/module.h>
23 #include <linux/mutex.h>
24 #include <linux/poll.h>
25 #include <linux/property.h>
26 #include <linux/sched.h>
27 #include <linux/slab.h>
28 #include <linux/wait.h>
30 #include <linux/iio/buffer.h>
31 #include <linux/iio/buffer_impl.h>
32 #include <linux/iio/events.h>
33 #include <linux/iio/iio-opaque.h>
34 #include <linux/iio/iio.h>
35 #include <linux/iio/sysfs.h>
38 #include "iio_core_trigger.h"
40 /* IDA to assign each registered device a unique id */
41 static DEFINE_IDA(iio_ida
);
43 static dev_t iio_devt
;
45 #define IIO_DEV_MAX 256
46 const struct bus_type iio_bus_type
= {
49 EXPORT_SYMBOL(iio_bus_type
);
51 static struct dentry
*iio_debugfs_dentry
;
53 static const char * const iio_direction
[] = {
58 static const char * const iio_chan_type_name_spec
[] = {
59 [IIO_VOLTAGE
] = "voltage",
60 [IIO_CURRENT
] = "current",
61 [IIO_POWER
] = "power",
62 [IIO_ACCEL
] = "accel",
63 [IIO_ANGL_VEL
] = "anglvel",
65 [IIO_LIGHT
] = "illuminance",
66 [IIO_INTENSITY
] = "intensity",
67 [IIO_PROXIMITY
] = "proximity",
69 [IIO_INCLI
] = "incli",
72 [IIO_TIMESTAMP
] = "timestamp",
73 [IIO_CAPACITANCE
] = "capacitance",
74 [IIO_ALTVOLTAGE
] = "altvoltage",
76 [IIO_PRESSURE
] = "pressure",
77 [IIO_HUMIDITYRELATIVE
] = "humidityrelative",
78 [IIO_ACTIVITY
] = "activity",
79 [IIO_STEPS
] = "steps",
80 [IIO_ENERGY
] = "energy",
81 [IIO_DISTANCE
] = "distance",
82 [IIO_VELOCITY
] = "velocity",
83 [IIO_CONCENTRATION
] = "concentration",
84 [IIO_RESISTANCE
] = "resistance",
86 [IIO_UVINDEX
] = "uvindex",
87 [IIO_ELECTRICALCONDUCTIVITY
] = "electricalconductivity",
88 [IIO_COUNT
] = "count",
89 [IIO_INDEX
] = "index",
90 [IIO_GRAVITY
] = "gravity",
91 [IIO_POSITIONRELATIVE
] = "positionrelative",
92 [IIO_PHASE
] = "phase",
93 [IIO_MASSCONCENTRATION
] = "massconcentration",
94 [IIO_DELTA_ANGL
] = "deltaangl",
95 [IIO_DELTA_VELOCITY
] = "deltavelocity",
96 [IIO_COLORTEMP
] = "colortemp",
97 [IIO_CHROMATICITY
] = "chromaticity",
100 static const char * const iio_modifier_names
[] = {
104 [IIO_MOD_X_AND_Y
] = "x&y",
105 [IIO_MOD_X_AND_Z
] = "x&z",
106 [IIO_MOD_Y_AND_Z
] = "y&z",
107 [IIO_MOD_X_AND_Y_AND_Z
] = "x&y&z",
108 [IIO_MOD_X_OR_Y
] = "x|y",
109 [IIO_MOD_X_OR_Z
] = "x|z",
110 [IIO_MOD_Y_OR_Z
] = "y|z",
111 [IIO_MOD_X_OR_Y_OR_Z
] = "x|y|z",
112 [IIO_MOD_ROOT_SUM_SQUARED_X_Y
] = "sqrt(x^2+y^2)",
113 [IIO_MOD_SUM_SQUARED_X_Y_Z
] = "x^2+y^2+z^2",
114 [IIO_MOD_LIGHT_BOTH
] = "both",
115 [IIO_MOD_LIGHT_IR
] = "ir",
116 [IIO_MOD_LIGHT_CLEAR
] = "clear",
117 [IIO_MOD_LIGHT_RED
] = "red",
118 [IIO_MOD_LIGHT_GREEN
] = "green",
119 [IIO_MOD_LIGHT_BLUE
] = "blue",
120 [IIO_MOD_LIGHT_UV
] = "uv",
121 [IIO_MOD_LIGHT_UVA
] = "uva",
122 [IIO_MOD_LIGHT_UVB
] = "uvb",
123 [IIO_MOD_LIGHT_DUV
] = "duv",
124 [IIO_MOD_QUATERNION
] = "quaternion",
125 [IIO_MOD_TEMP_AMBIENT
] = "ambient",
126 [IIO_MOD_TEMP_OBJECT
] = "object",
127 [IIO_MOD_NORTH_MAGN
] = "from_north_magnetic",
128 [IIO_MOD_NORTH_TRUE
] = "from_north_true",
129 [IIO_MOD_NORTH_MAGN_TILT_COMP
] = "from_north_magnetic_tilt_comp",
130 [IIO_MOD_NORTH_TRUE_TILT_COMP
] = "from_north_true_tilt_comp",
131 [IIO_MOD_RUNNING
] = "running",
132 [IIO_MOD_JOGGING
] = "jogging",
133 [IIO_MOD_WALKING
] = "walking",
134 [IIO_MOD_STILL
] = "still",
135 [IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z
] = "sqrt(x^2+y^2+z^2)",
138 [IIO_MOD_CO2
] = "co2",
139 [IIO_MOD_VOC
] = "voc",
140 [IIO_MOD_PM1
] = "pm1",
141 [IIO_MOD_PM2P5
] = "pm2p5",
142 [IIO_MOD_PM4
] = "pm4",
143 [IIO_MOD_PM10
] = "pm10",
144 [IIO_MOD_ETHANOL
] = "ethanol",
147 [IIO_MOD_LINEAR_X
] = "linear_x",
148 [IIO_MOD_LINEAR_Y
] = "linear_y",
149 [IIO_MOD_LINEAR_Z
] = "linear_z",
150 [IIO_MOD_PITCH
] = "pitch",
151 [IIO_MOD_YAW
] = "yaw",
152 [IIO_MOD_ROLL
] = "roll",
155 /* relies on pairs of these shared then separate */
156 static const char * const iio_chan_info_postfix
[] = {
157 [IIO_CHAN_INFO_RAW
] = "raw",
158 [IIO_CHAN_INFO_PROCESSED
] = "input",
159 [IIO_CHAN_INFO_SCALE
] = "scale",
160 [IIO_CHAN_INFO_OFFSET
] = "offset",
161 [IIO_CHAN_INFO_CALIBSCALE
] = "calibscale",
162 [IIO_CHAN_INFO_CALIBBIAS
] = "calibbias",
163 [IIO_CHAN_INFO_PEAK
] = "peak_raw",
164 [IIO_CHAN_INFO_PEAK_SCALE
] = "peak_scale",
165 [IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW
] = "quadrature_correction_raw",
166 [IIO_CHAN_INFO_AVERAGE_RAW
] = "mean_raw",
167 [IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY
]
168 = "filter_low_pass_3db_frequency",
169 [IIO_CHAN_INFO_HIGH_PASS_FILTER_3DB_FREQUENCY
]
170 = "filter_high_pass_3db_frequency",
171 [IIO_CHAN_INFO_SAMP_FREQ
] = "sampling_frequency",
172 [IIO_CHAN_INFO_FREQUENCY
] = "frequency",
173 [IIO_CHAN_INFO_PHASE
] = "phase",
174 [IIO_CHAN_INFO_HARDWAREGAIN
] = "hardwaregain",
175 [IIO_CHAN_INFO_HYSTERESIS
] = "hysteresis",
176 [IIO_CHAN_INFO_HYSTERESIS_RELATIVE
] = "hysteresis_relative",
177 [IIO_CHAN_INFO_INT_TIME
] = "integration_time",
178 [IIO_CHAN_INFO_ENABLE
] = "en",
179 [IIO_CHAN_INFO_CALIBHEIGHT
] = "calibheight",
180 [IIO_CHAN_INFO_CALIBWEIGHT
] = "calibweight",
181 [IIO_CHAN_INFO_DEBOUNCE_COUNT
] = "debounce_count",
182 [IIO_CHAN_INFO_DEBOUNCE_TIME
] = "debounce_time",
183 [IIO_CHAN_INFO_CALIBEMISSIVITY
] = "calibemissivity",
184 [IIO_CHAN_INFO_OVERSAMPLING_RATIO
] = "oversampling_ratio",
185 [IIO_CHAN_INFO_THERMOCOUPLE_TYPE
] = "thermocouple_type",
186 [IIO_CHAN_INFO_CALIBAMBIENT
] = "calibambient",
187 [IIO_CHAN_INFO_ZEROPOINT
] = "zeropoint",
188 [IIO_CHAN_INFO_TROUGH
] = "trough_raw",
191 * iio_device_id() - query the unique ID for the device
192 * @indio_dev: Device structure whose ID is being queried
194 * The IIO device ID is a unique index used for example for the naming
195 * of the character device /dev/iio\:device[ID].
197 * Returns: Unique ID for the device.
199 int iio_device_id(struct iio_dev
*indio_dev
)
201 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
203 return iio_dev_opaque
->id
;
205 EXPORT_SYMBOL_GPL(iio_device_id
);
208 * iio_buffer_enabled() - helper function to test if the buffer is enabled
209 * @indio_dev: IIO device structure for device
211 * Returns: True, if the buffer is enabled.
213 bool iio_buffer_enabled(struct iio_dev
*indio_dev
)
215 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
217 return iio_dev_opaque
->currentmode
& INDIO_ALL_BUFFER_MODES
;
219 EXPORT_SYMBOL_GPL(iio_buffer_enabled
);
221 #if defined(CONFIG_DEBUG_FS)
223 * There's also a CONFIG_DEBUG_FS guard in include/linux/iio/iio.h for
224 * iio_get_debugfs_dentry() to make it inline if CONFIG_DEBUG_FS is undefined
226 struct dentry
*iio_get_debugfs_dentry(struct iio_dev
*indio_dev
)
228 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
230 return iio_dev_opaque
->debugfs_dentry
;
232 EXPORT_SYMBOL_GPL(iio_get_debugfs_dentry
);
236 * iio_find_channel_from_si() - get channel from its scan index
238 * @si: scan index to match
241 * Constant pointer to iio_chan_spec, if scan index matches, NULL on failure.
243 const struct iio_chan_spec
244 *iio_find_channel_from_si(struct iio_dev
*indio_dev
, int si
)
248 for (i
= 0; i
< indio_dev
->num_channels
; i
++)
249 if (indio_dev
->channels
[i
].scan_index
== si
)
250 return &indio_dev
->channels
[i
];
254 /* This turns up an awful lot */
255 ssize_t
iio_read_const_attr(struct device
*dev
,
256 struct device_attribute
*attr
,
259 return sysfs_emit(buf
, "%s\n", to_iio_const_attr(attr
)->string
);
261 EXPORT_SYMBOL(iio_read_const_attr
);
264 * iio_device_set_clock() - Set current timestamping clock for the device
265 * @indio_dev: IIO device structure containing the device
266 * @clock_id: timestamping clock POSIX identifier to set.
268 * Returns: 0 on success, or a negative error code.
270 int iio_device_set_clock(struct iio_dev
*indio_dev
, clockid_t clock_id
)
273 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
274 const struct iio_event_interface
*ev_int
= iio_dev_opaque
->event_interface
;
276 ret
= mutex_lock_interruptible(&iio_dev_opaque
->mlock
);
279 if ((ev_int
&& iio_event_enabled(ev_int
)) ||
280 iio_buffer_enabled(indio_dev
)) {
281 mutex_unlock(&iio_dev_opaque
->mlock
);
284 iio_dev_opaque
->clock_id
= clock_id
;
285 mutex_unlock(&iio_dev_opaque
->mlock
);
289 EXPORT_SYMBOL(iio_device_set_clock
);
292 * iio_device_get_clock() - Retrieve current timestamping clock for the device
293 * @indio_dev: IIO device structure containing the device
295 * Returns: Clock ID of the current timestamping clock for the device.
297 clockid_t
iio_device_get_clock(const struct iio_dev
*indio_dev
)
299 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
301 return iio_dev_opaque
->clock_id
;
303 EXPORT_SYMBOL(iio_device_get_clock
);
306 * iio_get_time_ns() - utility function to get a time stamp for events etc
309 * Returns: Timestamp of the event in nanoseconds.
311 s64
iio_get_time_ns(const struct iio_dev
*indio_dev
)
313 struct timespec64 tp
;
315 switch (iio_device_get_clock(indio_dev
)) {
317 return ktime_get_real_ns();
318 case CLOCK_MONOTONIC
:
319 return ktime_get_ns();
320 case CLOCK_MONOTONIC_RAW
:
321 return ktime_get_raw_ns();
322 case CLOCK_REALTIME_COARSE
:
323 return ktime_to_ns(ktime_get_coarse_real());
324 case CLOCK_MONOTONIC_COARSE
:
325 ktime_get_coarse_ts64(&tp
);
326 return timespec64_to_ns(&tp
);
328 return ktime_get_boottime_ns();
330 return ktime_get_clocktai_ns();
335 EXPORT_SYMBOL(iio_get_time_ns
);
337 static int __init
iio_init(void)
341 /* Register sysfs bus */
342 ret
= bus_register(&iio_bus_type
);
344 pr_err("could not register bus type\n");
348 ret
= alloc_chrdev_region(&iio_devt
, 0, IIO_DEV_MAX
, "iio");
350 pr_err("failed to allocate char dev region\n");
351 goto error_unregister_bus_type
;
354 iio_debugfs_dentry
= debugfs_create_dir("iio", NULL
);
358 error_unregister_bus_type
:
359 bus_unregister(&iio_bus_type
);
364 static void __exit
iio_exit(void)
367 unregister_chrdev_region(iio_devt
, IIO_DEV_MAX
);
368 bus_unregister(&iio_bus_type
);
369 debugfs_remove(iio_debugfs_dentry
);
372 #if defined(CONFIG_DEBUG_FS)
373 static ssize_t
iio_debugfs_read_reg(struct file
*file
, char __user
*userbuf
,
374 size_t count
, loff_t
*ppos
)
376 struct iio_dev
*indio_dev
= file
->private_data
;
377 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
378 unsigned int val
= 0;
382 return simple_read_from_buffer(userbuf
, count
, ppos
,
383 iio_dev_opaque
->read_buf
,
384 iio_dev_opaque
->read_buf_len
);
386 ret
= indio_dev
->info
->debugfs_reg_access(indio_dev
,
387 iio_dev_opaque
->cached_reg_addr
,
390 dev_err(indio_dev
->dev
.parent
, "%s: read failed\n", __func__
);
394 iio_dev_opaque
->read_buf_len
= snprintf(iio_dev_opaque
->read_buf
,
395 sizeof(iio_dev_opaque
->read_buf
),
398 return simple_read_from_buffer(userbuf
, count
, ppos
,
399 iio_dev_opaque
->read_buf
,
400 iio_dev_opaque
->read_buf_len
);
403 static ssize_t
iio_debugfs_write_reg(struct file
*file
,
404 const char __user
*userbuf
, size_t count
, loff_t
*ppos
)
406 struct iio_dev
*indio_dev
= file
->private_data
;
407 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
408 unsigned int reg
, val
;
412 count
= min(count
, sizeof(buf
) - 1);
413 if (copy_from_user(buf
, userbuf
, count
))
418 ret
= sscanf(buf
, "%i %i", ®
, &val
);
422 iio_dev_opaque
->cached_reg_addr
= reg
;
425 iio_dev_opaque
->cached_reg_addr
= reg
;
426 ret
= indio_dev
->info
->debugfs_reg_access(indio_dev
, reg
,
429 dev_err(indio_dev
->dev
.parent
, "%s: write failed\n",
441 static const struct file_operations iio_debugfs_reg_fops
= {
443 .read
= iio_debugfs_read_reg
,
444 .write
= iio_debugfs_write_reg
,
447 static void iio_device_unregister_debugfs(struct iio_dev
*indio_dev
)
449 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
451 debugfs_remove_recursive(iio_dev_opaque
->debugfs_dentry
);
454 static void iio_device_register_debugfs(struct iio_dev
*indio_dev
)
456 struct iio_dev_opaque
*iio_dev_opaque
;
458 if (indio_dev
->info
->debugfs_reg_access
== NULL
)
461 if (!iio_debugfs_dentry
)
464 iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
466 iio_dev_opaque
->debugfs_dentry
=
467 debugfs_create_dir(dev_name(&indio_dev
->dev
),
470 debugfs_create_file("direct_reg_access", 0644,
471 iio_dev_opaque
->debugfs_dentry
, indio_dev
,
472 &iio_debugfs_reg_fops
);
475 static void iio_device_register_debugfs(struct iio_dev
*indio_dev
)
479 static void iio_device_unregister_debugfs(struct iio_dev
*indio_dev
)
482 #endif /* CONFIG_DEBUG_FS */
484 static ssize_t
iio_read_channel_ext_info(struct device
*dev
,
485 struct device_attribute
*attr
,
488 struct iio_dev
*indio_dev
= dev_to_iio_dev(dev
);
489 struct iio_dev_attr
*this_attr
= to_iio_dev_attr(attr
);
490 const struct iio_chan_spec_ext_info
*ext_info
;
492 ext_info
= &this_attr
->c
->ext_info
[this_attr
->address
];
494 return ext_info
->read(indio_dev
, ext_info
->private, this_attr
->c
, buf
);
497 static ssize_t
iio_write_channel_ext_info(struct device
*dev
,
498 struct device_attribute
*attr
,
499 const char *buf
, size_t len
)
501 struct iio_dev
*indio_dev
= dev_to_iio_dev(dev
);
502 struct iio_dev_attr
*this_attr
= to_iio_dev_attr(attr
);
503 const struct iio_chan_spec_ext_info
*ext_info
;
505 ext_info
= &this_attr
->c
->ext_info
[this_attr
->address
];
507 return ext_info
->write(indio_dev
, ext_info
->private,
508 this_attr
->c
, buf
, len
);
511 ssize_t
iio_enum_available_read(struct iio_dev
*indio_dev
,
512 uintptr_t priv
, const struct iio_chan_spec
*chan
, char *buf
)
514 const struct iio_enum
*e
= (const struct iio_enum
*)priv
;
521 for (i
= 0; i
< e
->num_items
; ++i
) {
524 len
+= sysfs_emit_at(buf
, len
, "%s ", e
->items
[i
]);
527 /* replace last space with a newline */
532 EXPORT_SYMBOL_GPL(iio_enum_available_read
);
534 ssize_t
iio_enum_read(struct iio_dev
*indio_dev
,
535 uintptr_t priv
, const struct iio_chan_spec
*chan
, char *buf
)
537 const struct iio_enum
*e
= (const struct iio_enum
*)priv
;
543 i
= e
->get(indio_dev
, chan
);
546 if (i
>= e
->num_items
|| !e
->items
[i
])
549 return sysfs_emit(buf
, "%s\n", e
->items
[i
]);
551 EXPORT_SYMBOL_GPL(iio_enum_read
);
553 ssize_t
iio_enum_write(struct iio_dev
*indio_dev
,
554 uintptr_t priv
, const struct iio_chan_spec
*chan
, const char *buf
,
557 const struct iio_enum
*e
= (const struct iio_enum
*)priv
;
563 ret
= __sysfs_match_string(e
->items
, e
->num_items
, buf
);
567 ret
= e
->set(indio_dev
, chan
, ret
);
568 return ret
? ret
: len
;
570 EXPORT_SYMBOL_GPL(iio_enum_write
);
572 static const struct iio_mount_matrix iio_mount_idmatrix
= {
580 static int iio_setup_mount_idmatrix(const struct device
*dev
,
581 struct iio_mount_matrix
*matrix
)
583 *matrix
= iio_mount_idmatrix
;
584 dev_info(dev
, "mounting matrix not found: using identity...\n");
588 ssize_t
iio_show_mount_matrix(struct iio_dev
*indio_dev
, uintptr_t priv
,
589 const struct iio_chan_spec
*chan
, char *buf
)
591 const struct iio_mount_matrix
*mtx
;
593 mtx
= ((iio_get_mount_matrix_t
*)priv
)(indio_dev
, chan
);
598 mtx
= &iio_mount_idmatrix
;
600 return sysfs_emit(buf
, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
601 mtx
->rotation
[0], mtx
->rotation
[1], mtx
->rotation
[2],
602 mtx
->rotation
[3], mtx
->rotation
[4], mtx
->rotation
[5],
603 mtx
->rotation
[6], mtx
->rotation
[7], mtx
->rotation
[8]);
605 EXPORT_SYMBOL_GPL(iio_show_mount_matrix
);
608 * iio_read_mount_matrix() - retrieve iio device mounting matrix from
609 * device "mount-matrix" property
610 * @dev: device the mounting matrix property is assigned to
611 * @matrix: where to store retrieved matrix
613 * If device is assigned no mounting matrix property, a default 3x3 identity
614 * matrix will be filled in.
616 * Returns: 0 if success, or a negative error code on failure.
618 int iio_read_mount_matrix(struct device
*dev
, struct iio_mount_matrix
*matrix
)
620 size_t len
= ARRAY_SIZE(iio_mount_idmatrix
.rotation
);
623 err
= device_property_read_string_array(dev
, "mount-matrix", matrix
->rotation
, len
);
628 /* Invalid number of matrix entries. */
632 /* Invalid matrix declaration format. */
635 /* Matrix was not declared at all: fallback to identity. */
636 return iio_setup_mount_idmatrix(dev
, matrix
);
638 EXPORT_SYMBOL(iio_read_mount_matrix
);
640 static ssize_t
__iio_format_value(char *buf
, size_t offset
, unsigned int type
,
641 int size
, const int *vals
)
645 bool scale_db
= false;
649 return sysfs_emit_at(buf
, offset
, "%d", vals
[0]);
650 case IIO_VAL_INT_PLUS_MICRO_DB
:
653 case IIO_VAL_INT_PLUS_MICRO
:
655 return sysfs_emit_at(buf
, offset
, "-%d.%06u%s",
656 abs(vals
[0]), -vals
[1],
657 scale_db
? " dB" : "");
659 return sysfs_emit_at(buf
, offset
, "%d.%06u%s", vals
[0],
660 vals
[1], scale_db
? " dB" : "");
661 case IIO_VAL_INT_PLUS_NANO
:
663 return sysfs_emit_at(buf
, offset
, "-%d.%09u",
664 abs(vals
[0]), -vals
[1]);
666 return sysfs_emit_at(buf
, offset
, "%d.%09u", vals
[0],
668 case IIO_VAL_FRACTIONAL
:
669 tmp2
= div_s64((s64
)vals
[0] * 1000000000LL, vals
[1]);
670 tmp0
= (int)div_s64_rem(tmp2
, 1000000000, &tmp1
);
671 if ((tmp2
< 0) && (tmp0
== 0))
672 return sysfs_emit_at(buf
, offset
, "-0.%09u", abs(tmp1
));
674 return sysfs_emit_at(buf
, offset
, "%d.%09u", tmp0
,
676 case IIO_VAL_FRACTIONAL_LOG2
:
677 tmp2
= shift_right((s64
)vals
[0] * 1000000000LL, vals
[1]);
678 tmp0
= (int)div_s64_rem(tmp2
, 1000000000LL, &tmp1
);
679 if (tmp0
== 0 && tmp2
< 0)
680 return sysfs_emit_at(buf
, offset
, "-0.%09u", abs(tmp1
));
682 return sysfs_emit_at(buf
, offset
, "%d.%09u", tmp0
,
684 case IIO_VAL_INT_MULTIPLE
:
689 for (i
= 0; i
< size
; ++i
)
690 l
+= sysfs_emit_at(buf
, offset
+ l
, "%d ", vals
[i
]);
694 return sysfs_emit_at(buf
, offset
, "%c", (char)vals
[0]);
696 tmp2
= (s64
)((((u64
)vals
[1]) << 32) | (u32
)vals
[0]);
697 return sysfs_emit_at(buf
, offset
, "%lld", tmp2
);
704 * iio_format_value() - Formats a IIO value into its string representation
705 * @buf: The buffer to which the formatted value gets written
706 * which is assumed to be big enough (i.e. PAGE_SIZE).
707 * @type: One of the IIO_VAL_* constants. This decides how the val
708 * and val2 parameters are formatted.
709 * @size: Number of IIO value entries contained in vals
710 * @vals: Pointer to the values, exact meaning depends on the
714 * 0 by default, a negative number on failure or the total number of characters
715 * written for a type that belongs to the IIO_VAL_* constant.
717 ssize_t
iio_format_value(char *buf
, unsigned int type
, int size
, int *vals
)
721 len
= __iio_format_value(buf
, 0, type
, size
, vals
);
722 if (len
>= PAGE_SIZE
- 1)
725 return len
+ sysfs_emit_at(buf
, len
, "\n");
727 EXPORT_SYMBOL_GPL(iio_format_value
);
729 ssize_t
do_iio_read_channel_label(struct iio_dev
*indio_dev
,
730 const struct iio_chan_spec
*c
,
733 if (indio_dev
->info
->read_label
)
734 return indio_dev
->info
->read_label(indio_dev
, c
, buf
);
737 return sysfs_emit(buf
, "%s\n", c
->extend_name
);
742 static ssize_t
iio_read_channel_label(struct device
*dev
,
743 struct device_attribute
*attr
,
746 return do_iio_read_channel_label(dev_to_iio_dev(dev
),
747 to_iio_dev_attr(attr
)->c
, buf
);
750 static ssize_t
iio_read_channel_info(struct device
*dev
,
751 struct device_attribute
*attr
,
754 struct iio_dev
*indio_dev
= dev_to_iio_dev(dev
);
755 struct iio_dev_attr
*this_attr
= to_iio_dev_attr(attr
);
756 int vals
[INDIO_MAX_RAW_ELEMENTS
];
760 if (indio_dev
->info
->read_raw_multi
)
761 ret
= indio_dev
->info
->read_raw_multi(indio_dev
, this_attr
->c
,
762 INDIO_MAX_RAW_ELEMENTS
,
765 else if (indio_dev
->info
->read_raw
)
766 ret
= indio_dev
->info
->read_raw(indio_dev
, this_attr
->c
,
767 &vals
[0], &vals
[1], this_attr
->address
);
774 return iio_format_value(buf
, ret
, val_len
, vals
);
777 static ssize_t
iio_format_list(char *buf
, const int *vals
, int type
, int length
,
778 const char *prefix
, const char *suffix
)
793 len
= sysfs_emit(buf
, prefix
);
795 for (i
= 0; i
<= length
- stride
; i
+= stride
) {
797 len
+= sysfs_emit_at(buf
, len
, " ");
798 if (len
>= PAGE_SIZE
)
802 len
+= __iio_format_value(buf
, len
, type
, stride
, &vals
[i
]);
803 if (len
>= PAGE_SIZE
)
807 len
+= sysfs_emit_at(buf
, len
, "%s\n", suffix
);
812 static ssize_t
iio_format_avail_list(char *buf
, const int *vals
,
813 int type
, int length
)
816 return iio_format_list(buf
, vals
, type
, length
, "", "");
819 static ssize_t
iio_format_avail_range(char *buf
, const int *vals
, int type
)
824 * length refers to the array size , not the number of elements.
825 * The purpose is to print the range [min , step ,max] so length should
826 * be 3 in case of int, and 6 for other types.
837 return iio_format_list(buf
, vals
, type
, length
, "[", "]");
840 static ssize_t
iio_read_channel_info_avail(struct device
*dev
,
841 struct device_attribute
*attr
,
844 struct iio_dev
*indio_dev
= dev_to_iio_dev(dev
);
845 struct iio_dev_attr
*this_attr
= to_iio_dev_attr(attr
);
851 if (!indio_dev
->info
->read_avail
)
854 ret
= indio_dev
->info
->read_avail(indio_dev
, this_attr
->c
,
855 &vals
, &type
, &length
,
862 return iio_format_avail_list(buf
, vals
, type
, length
);
863 case IIO_AVAIL_RANGE
:
864 return iio_format_avail_range(buf
, vals
, type
);
871 * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
872 * @str: The string to parse
873 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
874 * @integer: The integer part of the number
875 * @fract: The fractional part of the number
876 * @scale_db: True if this should parse as dB
879 * 0 on success, or a negative error code if the string could not be parsed.
881 static int __iio_str_to_fixpoint(const char *str
, int fract_mult
,
882 int *integer
, int *fract
, bool scale_db
)
885 bool integer_part
= true, negative
= false;
887 if (fract_mult
== 0) {
890 return kstrtoint(str
, 0, integer
);
896 } else if (str
[0] == '+') {
901 if ('0' <= *str
&& *str
<= '9') {
903 i
= i
* 10 + *str
- '0';
905 f
+= fract_mult
* (*str
- '0');
908 } else if (*str
== '\n') {
909 if (*(str
+ 1) == '\0')
912 } else if (!strncmp(str
, " dB", sizeof(" dB") - 1) && scale_db
) {
913 /* Ignore the dB suffix */
914 str
+= sizeof(" dB") - 1;
916 } else if (!strncmp(str
, "dB", sizeof("dB") - 1) && scale_db
) {
917 /* Ignore the dB suffix */
918 str
+= sizeof("dB") - 1;
920 } else if (*str
== '.' && integer_part
) {
921 integer_part
= false;
942 * iio_str_to_fixpoint() - Parse a fixed-point number from a string
943 * @str: The string to parse
944 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
945 * @integer: The integer part of the number
946 * @fract: The fractional part of the number
949 * 0 on success, or a negative error code if the string could not be parsed.
951 int iio_str_to_fixpoint(const char *str
, int fract_mult
,
952 int *integer
, int *fract
)
954 return __iio_str_to_fixpoint(str
, fract_mult
, integer
, fract
, false);
956 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint
);
958 static ssize_t
iio_write_channel_info(struct device
*dev
,
959 struct device_attribute
*attr
,
963 struct iio_dev
*indio_dev
= dev_to_iio_dev(dev
);
964 struct iio_dev_attr
*this_attr
= to_iio_dev_attr(attr
);
965 int ret
, fract_mult
= 100000;
966 int integer
, fract
= 0;
967 bool is_char
= false;
968 bool scale_db
= false;
970 /* Assumes decimal - precision based on number of digits */
971 if (!indio_dev
->info
->write_raw
)
974 if (indio_dev
->info
->write_raw_get_fmt
)
975 switch (indio_dev
->info
->write_raw_get_fmt(indio_dev
,
976 this_attr
->c
, this_attr
->address
)) {
980 case IIO_VAL_INT_PLUS_MICRO_DB
:
983 case IIO_VAL_INT_PLUS_MICRO
:
986 case IIO_VAL_INT_PLUS_NANO
:
987 fract_mult
= 100000000;
999 if (sscanf(buf
, "%c", &ch
) != 1)
1003 ret
= __iio_str_to_fixpoint(buf
, fract_mult
, &integer
, &fract
,
1009 ret
= indio_dev
->info
->write_raw(indio_dev
, this_attr
->c
,
1010 integer
, fract
, this_attr
->address
);
1018 int __iio_device_attr_init(struct device_attribute
*dev_attr
,
1019 const char *postfix
,
1020 struct iio_chan_spec
const *chan
,
1021 ssize_t (*readfunc
)(struct device
*dev
,
1022 struct device_attribute
*attr
,
1024 ssize_t (*writefunc
)(struct device
*dev
,
1025 struct device_attribute
*attr
,
1028 enum iio_shared_by shared_by
)
1034 sysfs_attr_init(&dev_attr
->attr
);
1036 /* Build up postfix of <extend_name>_<modifier>_postfix */
1037 if (chan
->modified
&& (shared_by
== IIO_SEPARATE
)) {
1038 if (chan
->extend_name
)
1039 full_postfix
= kasprintf(GFP_KERNEL
, "%s_%s_%s",
1040 iio_modifier_names
[chan
->channel2
],
1044 full_postfix
= kasprintf(GFP_KERNEL
, "%s_%s",
1045 iio_modifier_names
[chan
->channel2
],
1048 if (chan
->extend_name
== NULL
|| shared_by
!= IIO_SEPARATE
)
1049 full_postfix
= kstrdup(postfix
, GFP_KERNEL
);
1051 full_postfix
= kasprintf(GFP_KERNEL
,
1056 if (full_postfix
== NULL
)
1059 if (chan
->differential
) { /* Differential can not have modifier */
1060 switch (shared_by
) {
1061 case IIO_SHARED_BY_ALL
:
1062 name
= kasprintf(GFP_KERNEL
, "%s", full_postfix
);
1064 case IIO_SHARED_BY_DIR
:
1065 name
= kasprintf(GFP_KERNEL
, "%s_%s",
1066 iio_direction
[chan
->output
],
1069 case IIO_SHARED_BY_TYPE
:
1070 name
= kasprintf(GFP_KERNEL
, "%s_%s-%s_%s",
1071 iio_direction
[chan
->output
],
1072 iio_chan_type_name_spec
[chan
->type
],
1073 iio_chan_type_name_spec
[chan
->type
],
1077 if (!chan
->indexed
) {
1078 WARN(1, "Differential channels must be indexed\n");
1080 goto error_free_full_postfix
;
1082 name
= kasprintf(GFP_KERNEL
,
1084 iio_direction
[chan
->output
],
1085 iio_chan_type_name_spec
[chan
->type
],
1087 iio_chan_type_name_spec
[chan
->type
],
1092 } else { /* Single ended */
1093 switch (shared_by
) {
1094 case IIO_SHARED_BY_ALL
:
1095 name
= kasprintf(GFP_KERNEL
, "%s", full_postfix
);
1097 case IIO_SHARED_BY_DIR
:
1098 name
= kasprintf(GFP_KERNEL
, "%s_%s",
1099 iio_direction
[chan
->output
],
1102 case IIO_SHARED_BY_TYPE
:
1103 name
= kasprintf(GFP_KERNEL
, "%s_%s_%s",
1104 iio_direction
[chan
->output
],
1105 iio_chan_type_name_spec
[chan
->type
],
1111 name
= kasprintf(GFP_KERNEL
, "%s_%s%d_%s",
1112 iio_direction
[chan
->output
],
1113 iio_chan_type_name_spec
[chan
->type
],
1117 name
= kasprintf(GFP_KERNEL
, "%s_%s_%s",
1118 iio_direction
[chan
->output
],
1119 iio_chan_type_name_spec
[chan
->type
],
1126 goto error_free_full_postfix
;
1128 dev_attr
->attr
.name
= name
;
1131 dev_attr
->attr
.mode
|= 0444;
1132 dev_attr
->show
= readfunc
;
1136 dev_attr
->attr
.mode
|= 0200;
1137 dev_attr
->store
= writefunc
;
1140 error_free_full_postfix
:
1141 kfree(full_postfix
);
1146 static void __iio_device_attr_deinit(struct device_attribute
*dev_attr
)
1148 kfree(dev_attr
->attr
.name
);
1151 int __iio_add_chan_devattr(const char *postfix
,
1152 struct iio_chan_spec
const *chan
,
1153 ssize_t (*readfunc
)(struct device
*dev
,
1154 struct device_attribute
*attr
,
1156 ssize_t (*writefunc
)(struct device
*dev
,
1157 struct device_attribute
*attr
,
1161 enum iio_shared_by shared_by
,
1163 struct iio_buffer
*buffer
,
1164 struct list_head
*attr_list
)
1167 struct iio_dev_attr
*iio_attr
, *t
;
1169 iio_attr
= kzalloc(sizeof(*iio_attr
), GFP_KERNEL
);
1170 if (iio_attr
== NULL
)
1172 ret
= __iio_device_attr_init(&iio_attr
->dev_attr
,
1174 readfunc
, writefunc
, shared_by
);
1176 goto error_iio_dev_attr_free
;
1178 iio_attr
->address
= mask
;
1179 iio_attr
->buffer
= buffer
;
1180 list_for_each_entry(t
, attr_list
, l
)
1181 if (strcmp(t
->dev_attr
.attr
.name
,
1182 iio_attr
->dev_attr
.attr
.name
) == 0) {
1183 if (shared_by
== IIO_SEPARATE
)
1184 dev_err(dev
, "tried to double register : %s\n",
1185 t
->dev_attr
.attr
.name
);
1187 goto error_device_attr_deinit
;
1189 list_add(&iio_attr
->l
, attr_list
);
1193 error_device_attr_deinit
:
1194 __iio_device_attr_deinit(&iio_attr
->dev_attr
);
1195 error_iio_dev_attr_free
:
1200 static int iio_device_add_channel_label(struct iio_dev
*indio_dev
,
1201 struct iio_chan_spec
const *chan
)
1203 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
1206 if (!indio_dev
->info
->read_label
&& !chan
->extend_name
)
1209 ret
= __iio_add_chan_devattr("label",
1211 &iio_read_channel_label
,
1217 &iio_dev_opaque
->channel_attr_list
);
1224 static int iio_device_add_info_mask_type(struct iio_dev
*indio_dev
,
1225 struct iio_chan_spec
const *chan
,
1226 enum iio_shared_by shared_by
,
1227 const long *infomask
)
1229 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
1230 int i
, ret
, attrcount
= 0;
1232 for_each_set_bit(i
, infomask
, sizeof(*infomask
)*8) {
1233 if (i
>= ARRAY_SIZE(iio_chan_info_postfix
))
1235 ret
= __iio_add_chan_devattr(iio_chan_info_postfix
[i
],
1237 &iio_read_channel_info
,
1238 &iio_write_channel_info
,
1243 &iio_dev_opaque
->channel_attr_list
);
1244 if ((ret
== -EBUSY
) && (shared_by
!= IIO_SEPARATE
))
1254 static int iio_device_add_info_mask_type_avail(struct iio_dev
*indio_dev
,
1255 struct iio_chan_spec
const *chan
,
1256 enum iio_shared_by shared_by
,
1257 const long *infomask
)
1259 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
1260 int i
, ret
, attrcount
= 0;
1261 char *avail_postfix
;
1263 for_each_set_bit(i
, infomask
, sizeof(*infomask
) * 8) {
1264 if (i
>= ARRAY_SIZE(iio_chan_info_postfix
))
1266 avail_postfix
= kasprintf(GFP_KERNEL
,
1268 iio_chan_info_postfix
[i
]);
1272 ret
= __iio_add_chan_devattr(avail_postfix
,
1274 &iio_read_channel_info_avail
,
1280 &iio_dev_opaque
->channel_attr_list
);
1281 kfree(avail_postfix
);
1282 if ((ret
== -EBUSY
) && (shared_by
!= IIO_SEPARATE
))
1292 static int iio_device_add_channel_sysfs(struct iio_dev
*indio_dev
,
1293 struct iio_chan_spec
const *chan
)
1295 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
1296 int ret
, attrcount
= 0;
1297 const struct iio_chan_spec_ext_info
*ext_info
;
1299 if (chan
->channel
< 0)
1301 ret
= iio_device_add_info_mask_type(indio_dev
, chan
,
1303 &chan
->info_mask_separate
);
1308 ret
= iio_device_add_info_mask_type_avail(indio_dev
, chan
,
1310 &chan
->info_mask_separate_available
);
1315 ret
= iio_device_add_info_mask_type(indio_dev
, chan
,
1317 &chan
->info_mask_shared_by_type
);
1322 ret
= iio_device_add_info_mask_type_avail(indio_dev
, chan
,
1324 &chan
->info_mask_shared_by_type_available
);
1329 ret
= iio_device_add_info_mask_type(indio_dev
, chan
,
1331 &chan
->info_mask_shared_by_dir
);
1336 ret
= iio_device_add_info_mask_type_avail(indio_dev
, chan
,
1338 &chan
->info_mask_shared_by_dir_available
);
1343 ret
= iio_device_add_info_mask_type(indio_dev
, chan
,
1345 &chan
->info_mask_shared_by_all
);
1350 ret
= iio_device_add_info_mask_type_avail(indio_dev
, chan
,
1352 &chan
->info_mask_shared_by_all_available
);
1357 ret
= iio_device_add_channel_label(indio_dev
, chan
);
1362 if (chan
->ext_info
) {
1365 for (ext_info
= chan
->ext_info
; ext_info
->name
; ext_info
++) {
1366 ret
= __iio_add_chan_devattr(ext_info
->name
,
1369 &iio_read_channel_ext_info
: NULL
,
1371 &iio_write_channel_ext_info
: NULL
,
1376 &iio_dev_opaque
->channel_attr_list
);
1378 if (ret
== -EBUSY
&& ext_info
->shared
)
1392 * iio_free_chan_devattr_list() - Free a list of IIO device attributes
1393 * @attr_list: List of IIO device attributes
1395 * This function frees the memory allocated for each of the IIO device
1396 * attributes in the list.
1398 void iio_free_chan_devattr_list(struct list_head
*attr_list
)
1400 struct iio_dev_attr
*p
, *n
;
1402 list_for_each_entry_safe(p
, n
, attr_list
, l
) {
1403 kfree_const(p
->dev_attr
.attr
.name
);
1409 static ssize_t
name_show(struct device
*dev
, struct device_attribute
*attr
,
1412 struct iio_dev
*indio_dev
= dev_to_iio_dev(dev
);
1414 return sysfs_emit(buf
, "%s\n", indio_dev
->name
);
1417 static DEVICE_ATTR_RO(name
);
1419 static ssize_t
label_show(struct device
*dev
, struct device_attribute
*attr
,
1422 struct iio_dev
*indio_dev
= dev_to_iio_dev(dev
);
1424 return sysfs_emit(buf
, "%s\n", indio_dev
->label
);
1427 static DEVICE_ATTR_RO(label
);
1429 static const char * const clock_names
[] = {
1430 [CLOCK_REALTIME
] = "realtime",
1431 [CLOCK_MONOTONIC
] = "monotonic",
1432 [CLOCK_PROCESS_CPUTIME_ID
] = "process_cputime_id",
1433 [CLOCK_THREAD_CPUTIME_ID
] = "thread_cputime_id",
1434 [CLOCK_MONOTONIC_RAW
] = "monotonic_raw",
1435 [CLOCK_REALTIME_COARSE
] = "realtime_coarse",
1436 [CLOCK_MONOTONIC_COARSE
] = "monotonic_coarse",
1437 [CLOCK_BOOTTIME
] = "boottime",
1438 [CLOCK_REALTIME_ALARM
] = "realtime_alarm",
1439 [CLOCK_BOOTTIME_ALARM
] = "boottime_alarm",
1440 [CLOCK_SGI_CYCLE
] = "sgi_cycle",
1441 [CLOCK_TAI
] = "tai",
1444 static ssize_t
current_timestamp_clock_show(struct device
*dev
,
1445 struct device_attribute
*attr
,
1448 const struct iio_dev
*indio_dev
= dev_to_iio_dev(dev
);
1449 const clockid_t clk
= iio_device_get_clock(indio_dev
);
1452 case CLOCK_REALTIME
:
1453 case CLOCK_MONOTONIC
:
1454 case CLOCK_MONOTONIC_RAW
:
1455 case CLOCK_REALTIME_COARSE
:
1456 case CLOCK_MONOTONIC_COARSE
:
1457 case CLOCK_BOOTTIME
:
1464 return sysfs_emit(buf
, "%s\n", clock_names
[clk
]);
1467 static ssize_t
current_timestamp_clock_store(struct device
*dev
,
1468 struct device_attribute
*attr
,
1469 const char *buf
, size_t len
)
1474 ret
= sysfs_match_string(clock_names
, buf
);
1480 case CLOCK_REALTIME
:
1481 case CLOCK_MONOTONIC
:
1482 case CLOCK_MONOTONIC_RAW
:
1483 case CLOCK_REALTIME_COARSE
:
1484 case CLOCK_MONOTONIC_COARSE
:
1485 case CLOCK_BOOTTIME
:
1492 ret
= iio_device_set_clock(dev_to_iio_dev(dev
), clk
);
1499 int iio_device_register_sysfs_group(struct iio_dev
*indio_dev
,
1500 const struct attribute_group
*group
)
1502 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
1503 const struct attribute_group
**new, **old
= iio_dev_opaque
->groups
;
1504 unsigned int cnt
= iio_dev_opaque
->groupcounter
;
1506 new = krealloc_array(old
, cnt
+ 2, sizeof(*new), GFP_KERNEL
);
1510 new[iio_dev_opaque
->groupcounter
++] = group
;
1511 new[iio_dev_opaque
->groupcounter
] = NULL
;
1513 iio_dev_opaque
->groups
= new;
1518 static DEVICE_ATTR_RW(current_timestamp_clock
);
1520 static int iio_device_register_sysfs(struct iio_dev
*indio_dev
)
1522 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
1523 int i
, ret
= 0, attrcount
, attrn
, attrcount_orig
= 0;
1524 struct iio_dev_attr
*p
;
1525 struct attribute
**attr
, *clk
= NULL
;
1527 /* First count elements in any existing group */
1528 if (indio_dev
->info
->attrs
) {
1529 attr
= indio_dev
->info
->attrs
->attrs
;
1530 while (*attr
++ != NULL
)
1533 attrcount
= attrcount_orig
;
1535 * New channel registration method - relies on the fact a group does
1536 * not need to be initialized if its name is NULL.
1538 if (indio_dev
->channels
)
1539 for (i
= 0; i
< indio_dev
->num_channels
; i
++) {
1540 const struct iio_chan_spec
*chan
=
1541 &indio_dev
->channels
[i
];
1543 if (chan
->type
== IIO_TIMESTAMP
)
1544 clk
= &dev_attr_current_timestamp_clock
.attr
;
1546 ret
= iio_device_add_channel_sysfs(indio_dev
, chan
);
1548 goto error_clear_attrs
;
1552 if (iio_dev_opaque
->event_interface
)
1553 clk
= &dev_attr_current_timestamp_clock
.attr
;
1555 if (indio_dev
->name
)
1557 if (indio_dev
->label
)
1562 iio_dev_opaque
->chan_attr_group
.attrs
=
1563 kcalloc(attrcount
+ 1,
1564 sizeof(iio_dev_opaque
->chan_attr_group
.attrs
[0]),
1566 if (iio_dev_opaque
->chan_attr_group
.attrs
== NULL
) {
1568 goto error_clear_attrs
;
1570 /* Copy across original attributes, and point to original binary attributes */
1571 if (indio_dev
->info
->attrs
) {
1572 memcpy(iio_dev_opaque
->chan_attr_group
.attrs
,
1573 indio_dev
->info
->attrs
->attrs
,
1574 sizeof(iio_dev_opaque
->chan_attr_group
.attrs
[0])
1576 iio_dev_opaque
->chan_attr_group
.is_visible
=
1577 indio_dev
->info
->attrs
->is_visible
;
1578 iio_dev_opaque
->chan_attr_group
.bin_attrs
=
1579 indio_dev
->info
->attrs
->bin_attrs
;
1581 attrn
= attrcount_orig
;
1582 /* Add all elements from the list. */
1583 list_for_each_entry(p
, &iio_dev_opaque
->channel_attr_list
, l
)
1584 iio_dev_opaque
->chan_attr_group
.attrs
[attrn
++] = &p
->dev_attr
.attr
;
1585 if (indio_dev
->name
)
1586 iio_dev_opaque
->chan_attr_group
.attrs
[attrn
++] = &dev_attr_name
.attr
;
1587 if (indio_dev
->label
)
1588 iio_dev_opaque
->chan_attr_group
.attrs
[attrn
++] = &dev_attr_label
.attr
;
1590 iio_dev_opaque
->chan_attr_group
.attrs
[attrn
++] = clk
;
1592 ret
= iio_device_register_sysfs_group(indio_dev
,
1593 &iio_dev_opaque
->chan_attr_group
);
1595 goto error_free_chan_attrs
;
1599 error_free_chan_attrs
:
1600 kfree(iio_dev_opaque
->chan_attr_group
.attrs
);
1601 iio_dev_opaque
->chan_attr_group
.attrs
= NULL
;
1603 iio_free_chan_devattr_list(&iio_dev_opaque
->channel_attr_list
);
1608 static void iio_device_unregister_sysfs(struct iio_dev
*indio_dev
)
1610 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
1612 iio_free_chan_devattr_list(&iio_dev_opaque
->channel_attr_list
);
1613 kfree(iio_dev_opaque
->chan_attr_group
.attrs
);
1614 iio_dev_opaque
->chan_attr_group
.attrs
= NULL
;
1615 kfree(iio_dev_opaque
->groups
);
1616 iio_dev_opaque
->groups
= NULL
;
1619 static void iio_dev_release(struct device
*device
)
1621 struct iio_dev
*indio_dev
= dev_to_iio_dev(device
);
1622 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
1624 if (indio_dev
->modes
& INDIO_ALL_TRIGGERED_MODES
)
1625 iio_device_unregister_trigger_consumer(indio_dev
);
1626 iio_device_unregister_eventset(indio_dev
);
1627 iio_device_unregister_sysfs(indio_dev
);
1629 iio_device_detach_buffers(indio_dev
);
1631 lockdep_unregister_key(&iio_dev_opaque
->mlock_key
);
1633 ida_free(&iio_ida
, iio_dev_opaque
->id
);
1634 kfree(iio_dev_opaque
);
1637 const struct device_type iio_device_type
= {
1638 .name
= "iio_device",
1639 .release
= iio_dev_release
,
1643 * iio_device_alloc() - allocate an iio_dev from a driver
1644 * @parent: Parent device.
1645 * @sizeof_priv: Space to allocate for private structure.
1648 * Pointer to allocated iio_dev on success, NULL on failure.
1650 struct iio_dev
*iio_device_alloc(struct device
*parent
, int sizeof_priv
)
1652 struct iio_dev_opaque
*iio_dev_opaque
;
1653 struct iio_dev
*indio_dev
;
1657 alloc_size
= ALIGN(sizeof(*iio_dev_opaque
), IIO_DMA_MINALIGN
) + sizeof_priv
;
1659 alloc_size
= sizeof(*iio_dev_opaque
);
1661 iio_dev_opaque
= kzalloc(alloc_size
, GFP_KERNEL
);
1662 if (!iio_dev_opaque
)
1665 indio_dev
= &iio_dev_opaque
->indio_dev
;
1668 indio_dev
->priv
= (char *)iio_dev_opaque
+
1669 ALIGN(sizeof(*iio_dev_opaque
), IIO_DMA_MINALIGN
);
1671 indio_dev
->dev
.parent
= parent
;
1672 indio_dev
->dev
.type
= &iio_device_type
;
1673 indio_dev
->dev
.bus
= &iio_bus_type
;
1674 device_initialize(&indio_dev
->dev
);
1675 mutex_init(&iio_dev_opaque
->mlock
);
1676 mutex_init(&iio_dev_opaque
->info_exist_lock
);
1677 INIT_LIST_HEAD(&iio_dev_opaque
->channel_attr_list
);
1679 iio_dev_opaque
->id
= ida_alloc(&iio_ida
, GFP_KERNEL
);
1680 if (iio_dev_opaque
->id
< 0) {
1681 /* cannot use a dev_err as the name isn't available */
1682 pr_err("failed to get device id\n");
1683 kfree(iio_dev_opaque
);
1687 if (dev_set_name(&indio_dev
->dev
, "iio:device%d", iio_dev_opaque
->id
)) {
1688 ida_free(&iio_ida
, iio_dev_opaque
->id
);
1689 kfree(iio_dev_opaque
);
1693 INIT_LIST_HEAD(&iio_dev_opaque
->buffer_list
);
1694 INIT_LIST_HEAD(&iio_dev_opaque
->ioctl_handlers
);
1696 lockdep_register_key(&iio_dev_opaque
->mlock_key
);
1697 lockdep_set_class(&iio_dev_opaque
->mlock
, &iio_dev_opaque
->mlock_key
);
1701 EXPORT_SYMBOL(iio_device_alloc
);
1704 * iio_device_free() - free an iio_dev from a driver
1705 * @dev: the iio_dev associated with the device
1707 void iio_device_free(struct iio_dev
*dev
)
1710 put_device(&dev
->dev
);
1712 EXPORT_SYMBOL(iio_device_free
);
1714 static void devm_iio_device_release(void *iio_dev
)
1716 iio_device_free(iio_dev
);
1720 * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1721 * @parent: Device to allocate iio_dev for, and parent for this IIO device
1722 * @sizeof_priv: Space to allocate for private structure.
1724 * Managed iio_device_alloc. iio_dev allocated with this function is
1725 * automatically freed on driver detach.
1728 * Pointer to allocated iio_dev on success, NULL on failure.
1730 struct iio_dev
*devm_iio_device_alloc(struct device
*parent
, int sizeof_priv
)
1732 struct iio_dev
*iio_dev
;
1735 iio_dev
= iio_device_alloc(parent
, sizeof_priv
);
1739 ret
= devm_add_action_or_reset(parent
, devm_iio_device_release
,
1746 EXPORT_SYMBOL_GPL(devm_iio_device_alloc
);
1749 * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1750 * @inode: Inode structure for identifying the device in the file system
1751 * @filp: File structure for iio device used to keep and later access
1754 * Returns: 0 on success or -EBUSY if the device is already opened
1756 static int iio_chrdev_open(struct inode
*inode
, struct file
*filp
)
1758 struct iio_dev_opaque
*iio_dev_opaque
=
1759 container_of(inode
->i_cdev
, struct iio_dev_opaque
, chrdev
);
1760 struct iio_dev
*indio_dev
= &iio_dev_opaque
->indio_dev
;
1761 struct iio_dev_buffer_pair
*ib
;
1763 if (test_and_set_bit(IIO_BUSY_BIT_POS
, &iio_dev_opaque
->flags
))
1766 iio_device_get(indio_dev
);
1768 ib
= kmalloc(sizeof(*ib
), GFP_KERNEL
);
1770 iio_device_put(indio_dev
);
1771 clear_bit(IIO_BUSY_BIT_POS
, &iio_dev_opaque
->flags
);
1775 ib
->indio_dev
= indio_dev
;
1776 ib
->buffer
= indio_dev
->buffer
;
1778 filp
->private_data
= ib
;
1784 * iio_chrdev_release() - chrdev file close buffer access and ioctls
1785 * @inode: Inode structure pointer for the char device
1786 * @filp: File structure pointer for the char device
1788 * Returns: 0 for successful release.
1790 static int iio_chrdev_release(struct inode
*inode
, struct file
*filp
)
1792 struct iio_dev_buffer_pair
*ib
= filp
->private_data
;
1793 struct iio_dev_opaque
*iio_dev_opaque
=
1794 container_of(inode
->i_cdev
, struct iio_dev_opaque
, chrdev
);
1795 struct iio_dev
*indio_dev
= &iio_dev_opaque
->indio_dev
;
1798 clear_bit(IIO_BUSY_BIT_POS
, &iio_dev_opaque
->flags
);
1799 iio_device_put(indio_dev
);
1804 void iio_device_ioctl_handler_register(struct iio_dev
*indio_dev
,
1805 struct iio_ioctl_handler
*h
)
1807 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
1809 list_add_tail(&h
->entry
, &iio_dev_opaque
->ioctl_handlers
);
1812 void iio_device_ioctl_handler_unregister(struct iio_ioctl_handler
*h
)
1814 list_del(&h
->entry
);
1817 static long iio_ioctl(struct file
*filp
, unsigned int cmd
, unsigned long arg
)
1819 struct iio_dev_buffer_pair
*ib
= filp
->private_data
;
1820 struct iio_dev
*indio_dev
= ib
->indio_dev
;
1821 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
1822 struct iio_ioctl_handler
*h
;
1825 guard(mutex
)(&iio_dev_opaque
->info_exist_lock
);
1827 * The NULL check here is required to prevent crashing when a device
1828 * is being removed while userspace would still have open file handles
1829 * to try to access this device.
1831 if (!indio_dev
->info
)
1834 list_for_each_entry(h
, &iio_dev_opaque
->ioctl_handlers
, entry
) {
1835 ret
= h
->ioctl(indio_dev
, filp
, cmd
, arg
);
1836 if (ret
!= IIO_IOCTL_UNHANDLED
)
1843 static const struct file_operations iio_buffer_fileops
= {
1844 .owner
= THIS_MODULE
,
1845 .llseek
= noop_llseek
,
1846 .read
= iio_buffer_read_outer_addr
,
1847 .write
= iio_buffer_write_outer_addr
,
1848 .poll
= iio_buffer_poll_addr
,
1849 .unlocked_ioctl
= iio_ioctl
,
1850 .compat_ioctl
= compat_ptr_ioctl
,
1851 .open
= iio_chrdev_open
,
1852 .release
= iio_chrdev_release
,
1855 static const struct file_operations iio_event_fileops
= {
1856 .owner
= THIS_MODULE
,
1857 .llseek
= noop_llseek
,
1858 .unlocked_ioctl
= iio_ioctl
,
1859 .compat_ioctl
= compat_ptr_ioctl
,
1860 .open
= iio_chrdev_open
,
1861 .release
= iio_chrdev_release
,
1864 static int iio_check_unique_scan_index(struct iio_dev
*indio_dev
)
1867 const struct iio_chan_spec
*channels
= indio_dev
->channels
;
1869 if (!(indio_dev
->modes
& INDIO_ALL_BUFFER_MODES
))
1872 for (i
= 0; i
< indio_dev
->num_channels
- 1; i
++) {
1873 if (channels
[i
].scan_index
< 0)
1875 for (j
= i
+ 1; j
< indio_dev
->num_channels
; j
++)
1876 if (channels
[i
].scan_index
== channels
[j
].scan_index
) {
1877 dev_err(&indio_dev
->dev
,
1878 "Duplicate scan index %d\n",
1879 channels
[i
].scan_index
);
1887 static int iio_check_extended_name(const struct iio_dev
*indio_dev
)
1891 if (!indio_dev
->info
->read_label
)
1894 for (i
= 0; i
< indio_dev
->num_channels
; i
++) {
1895 if (indio_dev
->channels
[i
].extend_name
) {
1896 dev_err(&indio_dev
->dev
,
1897 "Cannot use labels and extend_name at the same time\n");
1905 static const struct iio_buffer_setup_ops noop_ring_setup_ops
;
1907 static void iio_sanity_check_avail_scan_masks(struct iio_dev
*indio_dev
)
1909 unsigned int num_masks
, masklength
, longs_per_mask
;
1910 const unsigned long *av_masks
;
1913 av_masks
= indio_dev
->available_scan_masks
;
1914 masklength
= iio_get_masklength(indio_dev
);
1915 longs_per_mask
= BITS_TO_LONGS(masklength
);
1918 * The code determining how many available_scan_masks is in the array
1919 * will be assuming the end of masks when first long with all bits
1920 * zeroed is encountered. This is incorrect for masks where mask
1921 * consists of more than one long, and where some of the available masks
1922 * has long worth of bits zeroed (but has subsequent bit(s) set). This
1923 * is a safety measure against bug where array of masks is terminated by
1924 * a single zero while mask width is greater than width of a long.
1926 if (longs_per_mask
> 1)
1927 dev_warn(indio_dev
->dev
.parent
,
1928 "multi long available scan masks not fully supported\n");
1930 if (bitmap_empty(av_masks
, masklength
))
1931 dev_warn(indio_dev
->dev
.parent
, "empty scan mask\n");
1933 for (num_masks
= 0; *av_masks
; num_masks
++)
1934 av_masks
+= longs_per_mask
;
1939 av_masks
= indio_dev
->available_scan_masks
;
1942 * Go through all the masks from first to one before the last, and see
1943 * that no mask found later from the available_scan_masks array is a
1944 * subset of mask found earlier. If this happens, then the mask found
1945 * later will never get used because scanning the array is stopped when
1946 * the first suitable mask is found. Drivers should order the array of
1947 * available masks in the order of preference (presumably the least
1948 * costy to access masks first).
1950 for (i
= 0; i
< num_masks
- 1; i
++) {
1951 const unsigned long *mask1
;
1954 mask1
= av_masks
+ i
* longs_per_mask
;
1955 for (j
= i
+ 1; j
< num_masks
; j
++) {
1956 const unsigned long *mask2
;
1958 mask2
= av_masks
+ j
* longs_per_mask
;
1959 if (bitmap_subset(mask2
, mask1
, masklength
))
1960 dev_warn(indio_dev
->dev
.parent
,
1961 "available_scan_mask %d subset of %d. Never used\n",
1968 * iio_active_scan_mask_index - Get index of the active scan mask inside the
1969 * available scan masks array
1970 * @indio_dev: the IIO device containing the active and available scan masks
1972 * Returns: the index or -EINVAL if active_scan_mask is not set
1974 int iio_active_scan_mask_index(struct iio_dev
*indio_dev
)
1977 const unsigned long *av_masks
;
1978 unsigned int masklength
= iio_get_masklength(indio_dev
);
1981 if (!indio_dev
->active_scan_mask
)
1985 * As in iio_scan_mask_match and iio_sanity_check_avail_scan_masks,
1986 * the condition here do not handle multi-long masks correctly.
1987 * It only checks the first long to be zero, and will use such mask
1988 * as a terminator even if there was bits set after the first long.
1990 * This should be fine since the available_scan_mask has already been
1991 * sanity tested using iio_sanity_check_avail_scan_masks.
1993 * See iio_scan_mask_match and iio_sanity_check_avail_scan_masks for
1996 av_masks
= indio_dev
->available_scan_masks
;
1998 if (indio_dev
->active_scan_mask
== av_masks
)
2000 av_masks
+= BITS_TO_LONGS(masklength
);
2004 dev_warn(indio_dev
->dev
.parent
,
2005 "active scan mask is not part of the available scan masks\n");
2008 EXPORT_SYMBOL_GPL(iio_active_scan_mask_index
);
2010 int __iio_device_register(struct iio_dev
*indio_dev
, struct module
*this_mod
)
2012 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
2013 struct fwnode_handle
*fwnode
= NULL
;
2016 if (!indio_dev
->info
)
2019 iio_dev_opaque
->driver_module
= this_mod
;
2021 /* If the calling driver did not initialize firmware node, do it here */
2022 if (dev_fwnode(&indio_dev
->dev
))
2023 fwnode
= dev_fwnode(&indio_dev
->dev
);
2024 /* The default dummy IIO device has no parent */
2025 else if (indio_dev
->dev
.parent
)
2026 fwnode
= dev_fwnode(indio_dev
->dev
.parent
);
2027 device_set_node(&indio_dev
->dev
, fwnode
);
2029 fwnode_property_read_string(fwnode
, "label", &indio_dev
->label
);
2031 ret
= iio_check_unique_scan_index(indio_dev
);
2035 ret
= iio_check_extended_name(indio_dev
);
2039 iio_device_register_debugfs(indio_dev
);
2041 ret
= iio_buffers_alloc_sysfs_and_mask(indio_dev
);
2043 dev_err(indio_dev
->dev
.parent
,
2044 "Failed to create buffer sysfs interfaces\n");
2045 goto error_unreg_debugfs
;
2048 if (indio_dev
->available_scan_masks
)
2049 iio_sanity_check_avail_scan_masks(indio_dev
);
2051 ret
= iio_device_register_sysfs(indio_dev
);
2053 dev_err(indio_dev
->dev
.parent
,
2054 "Failed to register sysfs interfaces\n");
2055 goto error_buffer_free_sysfs
;
2057 ret
= iio_device_register_eventset(indio_dev
);
2059 dev_err(indio_dev
->dev
.parent
,
2060 "Failed to register event set\n");
2061 goto error_free_sysfs
;
2063 if (indio_dev
->modes
& INDIO_ALL_TRIGGERED_MODES
)
2064 iio_device_register_trigger_consumer(indio_dev
);
2066 if ((indio_dev
->modes
& INDIO_ALL_BUFFER_MODES
) &&
2067 indio_dev
->setup_ops
== NULL
)
2068 indio_dev
->setup_ops
= &noop_ring_setup_ops
;
2070 if (iio_dev_opaque
->attached_buffers_cnt
)
2071 cdev_init(&iio_dev_opaque
->chrdev
, &iio_buffer_fileops
);
2072 else if (iio_dev_opaque
->event_interface
)
2073 cdev_init(&iio_dev_opaque
->chrdev
, &iio_event_fileops
);
2075 if (iio_dev_opaque
->attached_buffers_cnt
|| iio_dev_opaque
->event_interface
) {
2076 indio_dev
->dev
.devt
= MKDEV(MAJOR(iio_devt
), iio_dev_opaque
->id
);
2077 iio_dev_opaque
->chrdev
.owner
= this_mod
;
2080 /* assign device groups now; they should be all registered now */
2081 indio_dev
->dev
.groups
= iio_dev_opaque
->groups
;
2083 ret
= cdev_device_add(&iio_dev_opaque
->chrdev
, &indio_dev
->dev
);
2085 goto error_unreg_eventset
;
2089 error_unreg_eventset
:
2090 iio_device_unregister_eventset(indio_dev
);
2092 iio_device_unregister_sysfs(indio_dev
);
2093 error_buffer_free_sysfs
:
2094 iio_buffers_free_sysfs_and_mask(indio_dev
);
2095 error_unreg_debugfs
:
2096 iio_device_unregister_debugfs(indio_dev
);
2099 EXPORT_SYMBOL(__iio_device_register
);
2102 * iio_device_unregister() - unregister a device from the IIO subsystem
2103 * @indio_dev: Device structure representing the device.
2105 void iio_device_unregister(struct iio_dev
*indio_dev
)
2107 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
2109 cdev_device_del(&iio_dev_opaque
->chrdev
, &indio_dev
->dev
);
2111 scoped_guard(mutex
, &iio_dev_opaque
->info_exist_lock
) {
2112 iio_device_unregister_debugfs(indio_dev
);
2114 iio_disable_all_buffers(indio_dev
);
2116 indio_dev
->info
= NULL
;
2118 iio_device_wakeup_eventset(indio_dev
);
2119 iio_buffer_wakeup_poll(indio_dev
);
2122 iio_buffers_free_sysfs_and_mask(indio_dev
);
2124 EXPORT_SYMBOL(iio_device_unregister
);
2126 static void devm_iio_device_unreg(void *indio_dev
)
2128 iio_device_unregister(indio_dev
);
2131 int __devm_iio_device_register(struct device
*dev
, struct iio_dev
*indio_dev
,
2132 struct module
*this_mod
)
2136 ret
= __iio_device_register(indio_dev
, this_mod
);
2140 return devm_add_action_or_reset(dev
, devm_iio_device_unreg
, indio_dev
);
2142 EXPORT_SYMBOL_GPL(__devm_iio_device_register
);
2145 * iio_device_claim_direct_mode - Keep device in direct mode
2146 * @indio_dev: the iio_dev associated with the device
2148 * If the device is in direct mode it is guaranteed to stay
2149 * that way until iio_device_release_direct_mode() is called.
2151 * Use with iio_device_release_direct_mode()
2153 * Returns: 0 on success, -EBUSY on failure.
2155 int iio_device_claim_direct_mode(struct iio_dev
*indio_dev
)
2157 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
2159 mutex_lock(&iio_dev_opaque
->mlock
);
2161 if (iio_buffer_enabled(indio_dev
)) {
2162 mutex_unlock(&iio_dev_opaque
->mlock
);
2167 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode
);
2170 * iio_device_release_direct_mode - releases claim on direct mode
2171 * @indio_dev: the iio_dev associated with the device
2173 * Release the claim. Device is no longer guaranteed to stay
2176 * Use with iio_device_claim_direct_mode()
2178 void iio_device_release_direct_mode(struct iio_dev
*indio_dev
)
2180 mutex_unlock(&to_iio_dev_opaque(indio_dev
)->mlock
);
2182 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode
);
2185 * iio_device_claim_buffer_mode - Keep device in buffer mode
2186 * @indio_dev: the iio_dev associated with the device
2188 * If the device is in buffer mode it is guaranteed to stay
2189 * that way until iio_device_release_buffer_mode() is called.
2191 * Use with iio_device_release_buffer_mode().
2193 * Returns: 0 on success, -EBUSY on failure.
2195 int iio_device_claim_buffer_mode(struct iio_dev
*indio_dev
)
2197 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
2199 mutex_lock(&iio_dev_opaque
->mlock
);
2201 if (iio_buffer_enabled(indio_dev
))
2204 mutex_unlock(&iio_dev_opaque
->mlock
);
2207 EXPORT_SYMBOL_GPL(iio_device_claim_buffer_mode
);
2210 * iio_device_release_buffer_mode - releases claim on buffer mode
2211 * @indio_dev: the iio_dev associated with the device
2213 * Release the claim. Device is no longer guaranteed to stay
2216 * Use with iio_device_claim_buffer_mode().
2218 void iio_device_release_buffer_mode(struct iio_dev
*indio_dev
)
2220 mutex_unlock(&to_iio_dev_opaque(indio_dev
)->mlock
);
2222 EXPORT_SYMBOL_GPL(iio_device_release_buffer_mode
);
2225 * iio_device_get_current_mode() - helper function providing read-only access to
2226 * the opaque @currentmode variable
2227 * @indio_dev: IIO device structure for device
2229 int iio_device_get_current_mode(struct iio_dev
*indio_dev
)
2231 struct iio_dev_opaque
*iio_dev_opaque
= to_iio_dev_opaque(indio_dev
);
2233 return iio_dev_opaque
->currentmode
;
2235 EXPORT_SYMBOL_GPL(iio_device_get_current_mode
);
2237 subsys_initcall(iio_init
);
2238 module_exit(iio_exit
);
2240 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
2241 MODULE_DESCRIPTION("Industrial I/O core");
2242 MODULE_LICENSE("GPL");