industrialio-core.c 58 KB

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