PageRenderTime 32ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/drivers/iio/industrialio-core.c

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