i2c-core-base.c 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Linux I2C core
  4. *
  5. * Copyright (C) 1995-99 Simon G. Vogl
  6. * With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>
  7. * Mux support by Rodolfo Giometti <giometti@enneenne.com> and
  8. * Michael Lawnick <michael.lawnick.ext@nsn.com>
  9. *
  10. * Copyright (C) 2013-2017 Wolfram Sang <wsa@kernel.org>
  11. */
  12. #define pr_fmt(fmt) "i2c-core: " fmt
  13. #include <dt-bindings/i2c/i2c.h>
  14. #include <linux/acpi.h>
  15. #include <linux/clk/clk-conf.h>
  16. #include <linux/completion.h>
  17. #include <linux/debugfs.h>
  18. #include <linux/delay.h>
  19. #include <linux/err.h>
  20. #include <linux/errno.h>
  21. #include <linux/gpio/consumer.h>
  22. #include <linux/i2c.h>
  23. #include <linux/i2c-smbus.h>
  24. #include <linux/idr.h>
  25. #include <linux/init.h>
  26. #include <linux/interrupt.h>
  27. #include <linux/irqflags.h>
  28. #include <linux/jump_label.h>
  29. #include <linux/kernel.h>
  30. #include <linux/module.h>
  31. #include <linux/mutex.h>
  32. #include <linux/of_device.h>
  33. #include <linux/of.h>
  34. #include <linux/of_irq.h>
  35. #include <linux/pinctrl/consumer.h>
  36. #include <linux/pinctrl/devinfo.h>
  37. #include <linux/pm_domain.h>
  38. #include <linux/pm_runtime.h>
  39. #include <linux/pm_wakeirq.h>
  40. #include <linux/property.h>
  41. #include <linux/rwsem.h>
  42. #include <linux/slab.h>
  43. #include "i2c-core.h"
  44. #define CREATE_TRACE_POINTS
  45. #include <trace/events/i2c.h>
  46. #define I2C_ADDR_OFFSET_TEN_BIT 0xa000
  47. #define I2C_ADDR_OFFSET_SLAVE 0x1000
  48. #define I2C_ADDR_7BITS_MAX 0x77
  49. #define I2C_ADDR_7BITS_COUNT (I2C_ADDR_7BITS_MAX + 1)
  50. #define I2C_ADDR_DEVICE_ID 0x7c
  51. /*
  52. * core_lock protects i2c_adapter_idr, and guarantees that device detection,
  53. * deletion of detected devices are serialized
  54. */
  55. static DEFINE_MUTEX(core_lock);
  56. static DEFINE_IDR(i2c_adapter_idr);
  57. static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
  58. static DEFINE_STATIC_KEY_FALSE(i2c_trace_msg_key);
  59. static bool is_registered;
  60. static struct dentry *i2c_debugfs_root;
  61. int i2c_transfer_trace_reg(void)
  62. {
  63. static_branch_inc(&i2c_trace_msg_key);
  64. return 0;
  65. }
  66. void i2c_transfer_trace_unreg(void)
  67. {
  68. static_branch_dec(&i2c_trace_msg_key);
  69. }
  70. const char *i2c_freq_mode_string(u32 bus_freq_hz)
  71. {
  72. switch (bus_freq_hz) {
  73. case I2C_MAX_STANDARD_MODE_FREQ:
  74. return "Standard Mode (100 kHz)";
  75. case I2C_MAX_FAST_MODE_FREQ:
  76. return "Fast Mode (400 kHz)";
  77. case I2C_MAX_FAST_MODE_PLUS_FREQ:
  78. return "Fast Mode Plus (1.0 MHz)";
  79. case I2C_MAX_TURBO_MODE_FREQ:
  80. return "Turbo Mode (1.4 MHz)";
  81. case I2C_MAX_HIGH_SPEED_MODE_FREQ:
  82. return "High Speed Mode (3.4 MHz)";
  83. case I2C_MAX_ULTRA_FAST_MODE_FREQ:
  84. return "Ultra Fast Mode (5.0 MHz)";
  85. default:
  86. return "Unknown Mode";
  87. }
  88. }
  89. EXPORT_SYMBOL_GPL(i2c_freq_mode_string);
  90. const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
  91. const struct i2c_client *client)
  92. {
  93. if (!(id && client))
  94. return NULL;
  95. while (id->name[0]) {
  96. if (strcmp(client->name, id->name) == 0)
  97. return id;
  98. id++;
  99. }
  100. return NULL;
  101. }
  102. EXPORT_SYMBOL_GPL(i2c_match_id);
  103. const void *i2c_get_match_data(const struct i2c_client *client)
  104. {
  105. struct i2c_driver *driver = to_i2c_driver(client->dev.driver);
  106. const struct i2c_device_id *match;
  107. const void *data;
  108. data = device_get_match_data(&client->dev);
  109. if (!data) {
  110. match = i2c_match_id(driver->id_table, client);
  111. if (!match)
  112. return NULL;
  113. data = (const void *)match->driver_data;
  114. }
  115. return data;
  116. }
  117. EXPORT_SYMBOL(i2c_get_match_data);
  118. static int i2c_device_match(struct device *dev, const struct device_driver *drv)
  119. {
  120. struct i2c_client *client = i2c_verify_client(dev);
  121. const struct i2c_driver *driver;
  122. /* Attempt an OF style match */
  123. if (i2c_of_match_device(drv->of_match_table, client))
  124. return 1;
  125. /* Then ACPI style match */
  126. if (acpi_driver_match_device(dev, drv))
  127. return 1;
  128. driver = to_i2c_driver(drv);
  129. /* Finally an I2C match */
  130. if (i2c_match_id(driver->id_table, client))
  131. return 1;
  132. return 0;
  133. }
  134. static int i2c_device_uevent(const struct device *dev, struct kobj_uevent_env *env)
  135. {
  136. const struct i2c_client *client = to_i2c_client(dev);
  137. int rc;
  138. rc = of_device_uevent_modalias(dev, env);
  139. if (rc != -ENODEV)
  140. return rc;
  141. rc = acpi_device_uevent_modalias(dev, env);
  142. if (rc != -ENODEV)
  143. return rc;
  144. return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
  145. }
  146. /* i2c bus recovery routines */
  147. static int get_scl_gpio_value(struct i2c_adapter *adap)
  148. {
  149. return gpiod_get_value_cansleep(adap->bus_recovery_info->scl_gpiod);
  150. }
  151. static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
  152. {
  153. gpiod_set_value_cansleep(adap->bus_recovery_info->scl_gpiod, val);
  154. }
  155. static int get_sda_gpio_value(struct i2c_adapter *adap)
  156. {
  157. return gpiod_get_value_cansleep(adap->bus_recovery_info->sda_gpiod);
  158. }
  159. static void set_sda_gpio_value(struct i2c_adapter *adap, int val)
  160. {
  161. gpiod_set_value_cansleep(adap->bus_recovery_info->sda_gpiod, val);
  162. }
  163. static int i2c_generic_bus_free(struct i2c_adapter *adap)
  164. {
  165. struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
  166. int ret = -EOPNOTSUPP;
  167. if (bri->get_bus_free)
  168. ret = bri->get_bus_free(adap);
  169. else if (bri->get_sda)
  170. ret = bri->get_sda(adap);
  171. if (ret < 0)
  172. return ret;
  173. return ret ? 0 : -EBUSY;
  174. }
  175. /*
  176. * We are generating clock pulses. ndelay() determines durating of clk pulses.
  177. * We will generate clock with rate 100 KHz and so duration of both clock levels
  178. * is: delay in ns = (10^6 / 100) / 2
  179. */
  180. #define RECOVERY_NDELAY 5000
  181. #define RECOVERY_CLK_CNT 9
  182. int i2c_generic_scl_recovery(struct i2c_adapter *adap)
  183. {
  184. struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
  185. int i = 0, scl = 1, ret = 0;
  186. if (bri->prepare_recovery)
  187. bri->prepare_recovery(adap);
  188. if (bri->pinctrl)
  189. pinctrl_select_state(bri->pinctrl, bri->pins_gpio);
  190. /*
  191. * If we can set SDA, we will always create a STOP to ensure additional
  192. * pulses will do no harm. This is achieved by letting SDA follow SCL
  193. * half a cycle later. Check the 'incomplete_write_byte' fault injector
  194. * for details. Note that we must honour tsu:sto, 4us, but lets use 5us
  195. * here for simplicity.
  196. */
  197. bri->set_scl(adap, scl);
  198. ndelay(RECOVERY_NDELAY);
  199. if (bri->set_sda)
  200. bri->set_sda(adap, scl);
  201. ndelay(RECOVERY_NDELAY / 2);
  202. /*
  203. * By this time SCL is high, as we need to give 9 falling-rising edges
  204. */
  205. while (i++ < RECOVERY_CLK_CNT * 2) {
  206. if (scl) {
  207. /* SCL shouldn't be low here */
  208. if (!bri->get_scl(adap)) {
  209. dev_err(&adap->dev,
  210. "SCL is stuck low, exit recovery\n");
  211. ret = -EBUSY;
  212. break;
  213. }
  214. }
  215. scl = !scl;
  216. bri->set_scl(adap, scl);
  217. /* Creating STOP again, see above */
  218. if (scl) {
  219. /* Honour minimum tsu:sto */
  220. ndelay(RECOVERY_NDELAY);
  221. } else {
  222. /* Honour minimum tf and thd:dat */
  223. ndelay(RECOVERY_NDELAY / 2);
  224. }
  225. if (bri->set_sda)
  226. bri->set_sda(adap, scl);
  227. ndelay(RECOVERY_NDELAY / 2);
  228. if (scl) {
  229. ret = i2c_generic_bus_free(adap);
  230. if (ret == 0)
  231. break;
  232. }
  233. }
  234. /* If we can't check bus status, assume recovery worked */
  235. if (ret == -EOPNOTSUPP)
  236. ret = 0;
  237. if (bri->unprepare_recovery)
  238. bri->unprepare_recovery(adap);
  239. if (bri->pinctrl)
  240. pinctrl_select_state(bri->pinctrl, bri->pins_default);
  241. return ret;
  242. }
  243. EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
  244. int i2c_recover_bus(struct i2c_adapter *adap)
  245. {
  246. if (!adap->bus_recovery_info)
  247. return -EBUSY;
  248. dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
  249. return adap->bus_recovery_info->recover_bus(adap);
  250. }
  251. EXPORT_SYMBOL_GPL(i2c_recover_bus);
  252. static void i2c_gpio_init_pinctrl_recovery(struct i2c_adapter *adap)
  253. {
  254. struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
  255. struct device *dev = &adap->dev;
  256. struct pinctrl *p = bri->pinctrl ?: dev_pinctrl(dev->parent);
  257. bri->pinctrl = p;
  258. /*
  259. * we can't change states without pinctrl, so remove the states if
  260. * populated
  261. */
  262. if (!p) {
  263. bri->pins_default = NULL;
  264. bri->pins_gpio = NULL;
  265. return;
  266. }
  267. if (!bri->pins_default) {
  268. bri->pins_default = pinctrl_lookup_state(p,
  269. PINCTRL_STATE_DEFAULT);
  270. if (IS_ERR(bri->pins_default)) {
  271. dev_dbg(dev, PINCTRL_STATE_DEFAULT " state not found for GPIO recovery\n");
  272. bri->pins_default = NULL;
  273. }
  274. }
  275. if (!bri->pins_gpio) {
  276. bri->pins_gpio = pinctrl_lookup_state(p, "gpio");
  277. if (IS_ERR(bri->pins_gpio))
  278. bri->pins_gpio = pinctrl_lookup_state(p, "recovery");
  279. if (IS_ERR(bri->pins_gpio)) {
  280. dev_dbg(dev, "no gpio or recovery state found for GPIO recovery\n");
  281. bri->pins_gpio = NULL;
  282. }
  283. }
  284. /* for pinctrl state changes, we need all the information */
  285. if (bri->pins_default && bri->pins_gpio) {
  286. dev_info(dev, "using pinctrl states for GPIO recovery");
  287. } else {
  288. bri->pinctrl = NULL;
  289. bri->pins_default = NULL;
  290. bri->pins_gpio = NULL;
  291. }
  292. }
  293. static int i2c_gpio_init_generic_recovery(struct i2c_adapter *adap)
  294. {
  295. struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
  296. struct device *dev = &adap->dev;
  297. struct gpio_desc *gpiod;
  298. int ret = 0;
  299. /*
  300. * don't touch the recovery information if the driver is not using
  301. * generic SCL recovery
  302. */
  303. if (bri->recover_bus && bri->recover_bus != i2c_generic_scl_recovery)
  304. return 0;
  305. /*
  306. * pins might be taken as GPIO, so we should inform pinctrl about
  307. * this and move the state to GPIO
  308. */
  309. if (bri->pinctrl)
  310. pinctrl_select_state(bri->pinctrl, bri->pins_gpio);
  311. /*
  312. * if there is incomplete or no recovery information, see if generic
  313. * GPIO recovery is available
  314. */
  315. if (!bri->scl_gpiod) {
  316. gpiod = devm_gpiod_get(dev, "scl", GPIOD_OUT_HIGH_OPEN_DRAIN);
  317. if (PTR_ERR(gpiod) == -EPROBE_DEFER) {
  318. ret = -EPROBE_DEFER;
  319. goto cleanup_pinctrl_state;
  320. }
  321. if (!IS_ERR(gpiod)) {
  322. bri->scl_gpiod = gpiod;
  323. bri->recover_bus = i2c_generic_scl_recovery;
  324. dev_info(dev, "using generic GPIOs for recovery\n");
  325. }
  326. }
  327. /* SDA GPIOD line is optional, so we care about DEFER only */
  328. if (!bri->sda_gpiod) {
  329. /*
  330. * We have SCL. Pull SCL low and wait a bit so that SDA glitches
  331. * have no effect.
  332. */
  333. gpiod_direction_output(bri->scl_gpiod, 0);
  334. udelay(10);
  335. gpiod = devm_gpiod_get(dev, "sda", GPIOD_IN);
  336. /* Wait a bit in case of a SDA glitch, and then release SCL. */
  337. udelay(10);
  338. gpiod_direction_output(bri->scl_gpiod, 1);
  339. if (PTR_ERR(gpiod) == -EPROBE_DEFER) {
  340. ret = -EPROBE_DEFER;
  341. goto cleanup_pinctrl_state;
  342. }
  343. if (!IS_ERR(gpiod))
  344. bri->sda_gpiod = gpiod;
  345. }
  346. cleanup_pinctrl_state:
  347. /* change the state of the pins back to their default state */
  348. if (bri->pinctrl)
  349. pinctrl_select_state(bri->pinctrl, bri->pins_default);
  350. return ret;
  351. }
  352. static int i2c_gpio_init_recovery(struct i2c_adapter *adap)
  353. {
  354. i2c_gpio_init_pinctrl_recovery(adap);
  355. return i2c_gpio_init_generic_recovery(adap);
  356. }
  357. static int i2c_init_recovery(struct i2c_adapter *adap)
  358. {
  359. struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
  360. bool is_error_level = true;
  361. char *err_str;
  362. if (!bri)
  363. return 0;
  364. if (i2c_gpio_init_recovery(adap) == -EPROBE_DEFER)
  365. return -EPROBE_DEFER;
  366. if (!bri->recover_bus) {
  367. err_str = "no suitable method provided";
  368. is_error_level = false;
  369. goto err;
  370. }
  371. if (bri->scl_gpiod && bri->recover_bus == i2c_generic_scl_recovery) {
  372. bri->get_scl = get_scl_gpio_value;
  373. bri->set_scl = set_scl_gpio_value;
  374. if (bri->sda_gpiod) {
  375. bri->get_sda = get_sda_gpio_value;
  376. /* FIXME: add proper flag instead of '0' once available */
  377. if (gpiod_get_direction(bri->sda_gpiod) == 0)
  378. bri->set_sda = set_sda_gpio_value;
  379. }
  380. } else if (bri->recover_bus == i2c_generic_scl_recovery) {
  381. /* Generic SCL recovery */
  382. if (!bri->set_scl || !bri->get_scl) {
  383. err_str = "no {get|set}_scl() found";
  384. goto err;
  385. }
  386. if (!bri->set_sda && !bri->get_sda) {
  387. err_str = "either get_sda() or set_sda() needed";
  388. goto err;
  389. }
  390. }
  391. return 0;
  392. err:
  393. if (is_error_level)
  394. dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
  395. else
  396. dev_dbg(&adap->dev, "Not using recovery: %s\n", err_str);
  397. adap->bus_recovery_info = NULL;
  398. return -EINVAL;
  399. }
  400. static int i2c_smbus_host_notify_to_irq(const struct i2c_client *client)
  401. {
  402. struct i2c_adapter *adap = client->adapter;
  403. unsigned int irq;
  404. if (!adap->host_notify_domain)
  405. return -ENXIO;
  406. if (client->flags & I2C_CLIENT_TEN)
  407. return -EINVAL;
  408. irq = irq_create_mapping(adap->host_notify_domain, client->addr);
  409. return irq > 0 ? irq : -ENXIO;
  410. }
  411. static int i2c_device_probe(struct device *dev)
  412. {
  413. struct i2c_client *client = i2c_verify_client(dev);
  414. struct i2c_driver *driver;
  415. bool do_power_on;
  416. int status;
  417. if (!client)
  418. return 0;
  419. client->irq = client->init_irq;
  420. if (!client->irq) {
  421. int irq = -ENOENT;
  422. if (client->flags & I2C_CLIENT_HOST_NOTIFY) {
  423. dev_dbg(dev, "Using Host Notify IRQ\n");
  424. /* Keep adapter active when Host Notify is required */
  425. pm_runtime_get_sync(&client->adapter->dev);
  426. irq = i2c_smbus_host_notify_to_irq(client);
  427. } else if (dev->of_node) {
  428. irq = of_irq_get_byname(dev->of_node, "irq");
  429. if (irq == -EINVAL || irq == -ENODATA)
  430. irq = of_irq_get(dev->of_node, 0);
  431. } else if (ACPI_COMPANION(dev)) {
  432. bool wake_capable;
  433. irq = i2c_acpi_get_irq(client, &wake_capable);
  434. if (irq > 0 && wake_capable)
  435. client->flags |= I2C_CLIENT_WAKE;
  436. }
  437. if (irq == -EPROBE_DEFER) {
  438. status = irq;
  439. goto put_sync_adapter;
  440. }
  441. if (irq < 0)
  442. irq = 0;
  443. client->irq = irq;
  444. }
  445. driver = to_i2c_driver(dev->driver);
  446. /*
  447. * An I2C ID table is not mandatory, if and only if, a suitable OF
  448. * or ACPI ID table is supplied for the probing device.
  449. */
  450. if (!driver->id_table &&
  451. !acpi_driver_match_device(dev, dev->driver) &&
  452. !i2c_of_match_device(dev->driver->of_match_table, client)) {
  453. status = -ENODEV;
  454. goto put_sync_adapter;
  455. }
  456. if (client->flags & I2C_CLIENT_WAKE) {
  457. int wakeirq;
  458. wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
  459. if (wakeirq == -EPROBE_DEFER) {
  460. status = wakeirq;
  461. goto put_sync_adapter;
  462. }
  463. device_init_wakeup(&client->dev, true);
  464. if (wakeirq > 0 && wakeirq != client->irq)
  465. status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
  466. else if (client->irq > 0)
  467. status = dev_pm_set_wake_irq(dev, client->irq);
  468. else
  469. status = 0;
  470. if (status)
  471. dev_warn(&client->dev, "failed to set up wakeup irq\n");
  472. }
  473. dev_dbg(dev, "probe\n");
  474. status = of_clk_set_defaults(dev->of_node, false);
  475. if (status < 0)
  476. goto err_clear_wakeup_irq;
  477. do_power_on = !i2c_acpi_waive_d0_probe(dev);
  478. status = dev_pm_domain_attach(&client->dev, do_power_on);
  479. if (status)
  480. goto err_clear_wakeup_irq;
  481. client->devres_group_id = devres_open_group(&client->dev, NULL,
  482. GFP_KERNEL);
  483. if (!client->devres_group_id) {
  484. status = -ENOMEM;
  485. goto err_detach_pm_domain;
  486. }
  487. if (driver->probe)
  488. status = driver->probe(client);
  489. else
  490. status = -EINVAL;
  491. /*
  492. * Note that we are not closing the devres group opened above so
  493. * even resources that were attached to the device after probe is
  494. * run are released when i2c_device_remove() is executed. This is
  495. * needed as some drivers would allocate additional resources,
  496. * for example when updating firmware.
  497. */
  498. if (status)
  499. goto err_release_driver_resources;
  500. return 0;
  501. err_release_driver_resources:
  502. devres_release_group(&client->dev, client->devres_group_id);
  503. err_detach_pm_domain:
  504. dev_pm_domain_detach(&client->dev, do_power_on);
  505. err_clear_wakeup_irq:
  506. dev_pm_clear_wake_irq(&client->dev);
  507. device_init_wakeup(&client->dev, false);
  508. put_sync_adapter:
  509. if (client->flags & I2C_CLIENT_HOST_NOTIFY)
  510. pm_runtime_put_sync(&client->adapter->dev);
  511. return status;
  512. }
  513. static void i2c_device_remove(struct device *dev)
  514. {
  515. struct i2c_client *client = to_i2c_client(dev);
  516. struct i2c_driver *driver;
  517. driver = to_i2c_driver(dev->driver);
  518. if (driver->remove) {
  519. dev_dbg(dev, "remove\n");
  520. driver->remove(client);
  521. }
  522. devres_release_group(&client->dev, client->devres_group_id);
  523. dev_pm_domain_detach(&client->dev, true);
  524. dev_pm_clear_wake_irq(&client->dev);
  525. device_init_wakeup(&client->dev, false);
  526. client->irq = 0;
  527. if (client->flags & I2C_CLIENT_HOST_NOTIFY)
  528. pm_runtime_put(&client->adapter->dev);
  529. }
  530. static void i2c_device_shutdown(struct device *dev)
  531. {
  532. struct i2c_client *client = i2c_verify_client(dev);
  533. struct i2c_driver *driver;
  534. if (!client || !dev->driver)
  535. return;
  536. driver = to_i2c_driver(dev->driver);
  537. if (driver->shutdown)
  538. driver->shutdown(client);
  539. else if (client->irq > 0)
  540. disable_irq(client->irq);
  541. }
  542. static void i2c_client_dev_release(struct device *dev)
  543. {
  544. kfree(to_i2c_client(dev));
  545. }
  546. static ssize_t
  547. name_show(struct device *dev, struct device_attribute *attr, char *buf)
  548. {
  549. return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
  550. to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
  551. }
  552. static DEVICE_ATTR_RO(name);
  553. static ssize_t
  554. modalias_show(struct device *dev, struct device_attribute *attr, char *buf)
  555. {
  556. struct i2c_client *client = to_i2c_client(dev);
  557. int len;
  558. len = of_device_modalias(dev, buf, PAGE_SIZE);
  559. if (len != -ENODEV)
  560. return len;
  561. len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
  562. if (len != -ENODEV)
  563. return len;
  564. return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
  565. }
  566. static DEVICE_ATTR_RO(modalias);
  567. static struct attribute *i2c_dev_attrs[] = {
  568. &dev_attr_name.attr,
  569. /* modalias helps coldplug: modprobe $(cat .../modalias) */
  570. &dev_attr_modalias.attr,
  571. NULL
  572. };
  573. ATTRIBUTE_GROUPS(i2c_dev);
  574. const struct bus_type i2c_bus_type = {
  575. .name = "i2c",
  576. .match = i2c_device_match,
  577. .probe = i2c_device_probe,
  578. .remove = i2c_device_remove,
  579. .shutdown = i2c_device_shutdown,
  580. };
  581. EXPORT_SYMBOL_GPL(i2c_bus_type);
  582. const struct device_type i2c_client_type = {
  583. .groups = i2c_dev_groups,
  584. .uevent = i2c_device_uevent,
  585. .release = i2c_client_dev_release,
  586. };
  587. EXPORT_SYMBOL_GPL(i2c_client_type);
  588. /**
  589. * i2c_verify_client - return parameter as i2c_client, or NULL
  590. * @dev: device, probably from some driver model iterator
  591. *
  592. * When traversing the driver model tree, perhaps using driver model
  593. * iterators like @device_for_each_child(), you can't assume very much
  594. * about the nodes you find. Use this function to avoid oopses caused
  595. * by wrongly treating some non-I2C device as an i2c_client.
  596. */
  597. struct i2c_client *i2c_verify_client(struct device *dev)
  598. {
  599. return (dev->type == &i2c_client_type)
  600. ? to_i2c_client(dev)
  601. : NULL;
  602. }
  603. EXPORT_SYMBOL(i2c_verify_client);
  604. /* Return a unique address which takes the flags of the client into account */
  605. static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
  606. {
  607. unsigned short addr = client->addr;
  608. /* For some client flags, add an arbitrary offset to avoid collisions */
  609. if (client->flags & I2C_CLIENT_TEN)
  610. addr |= I2C_ADDR_OFFSET_TEN_BIT;
  611. if (client->flags & I2C_CLIENT_SLAVE)
  612. addr |= I2C_ADDR_OFFSET_SLAVE;
  613. return addr;
  614. }
  615. /* This is a permissive address validity check, I2C address map constraints
  616. * are purposely not enforced, except for the general call address. */
  617. static int i2c_check_addr_validity(unsigned int addr, unsigned short flags)
  618. {
  619. if (flags & I2C_CLIENT_TEN) {
  620. /* 10-bit address, all values are valid */
  621. if (addr > 0x3ff)
  622. return -EINVAL;
  623. } else {
  624. /* 7-bit address, reject the general call address */
  625. if (addr == 0x00 || addr > 0x7f)
  626. return -EINVAL;
  627. }
  628. return 0;
  629. }
  630. /* And this is a strict address validity check, used when probing. If a
  631. * device uses a reserved address, then it shouldn't be probed. 7-bit
  632. * addressing is assumed, 10-bit address devices are rare and should be
  633. * explicitly enumerated. */
  634. int i2c_check_7bit_addr_validity_strict(unsigned short addr)
  635. {
  636. /*
  637. * Reserved addresses per I2C specification:
  638. * 0x00 General call address / START byte
  639. * 0x01 CBUS address
  640. * 0x02 Reserved for different bus format
  641. * 0x03 Reserved for future purposes
  642. * 0x04-0x07 Hs-mode master code
  643. * 0x78-0x7b 10-bit slave addressing
  644. * 0x7c-0x7f Reserved for future purposes
  645. */
  646. if (addr < 0x08 || addr > 0x77)
  647. return -EINVAL;
  648. return 0;
  649. }
  650. static int __i2c_check_addr_busy(struct device *dev, void *addrp)
  651. {
  652. struct i2c_client *client = i2c_verify_client(dev);
  653. int addr = *(int *)addrp;
  654. if (client && i2c_encode_flags_to_addr(client) == addr)
  655. return -EBUSY;
  656. return 0;
  657. }
  658. /* walk up mux tree */
  659. static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
  660. {
  661. struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
  662. int result;
  663. result = device_for_each_child(&adapter->dev, &addr,
  664. __i2c_check_addr_busy);
  665. if (!result && parent)
  666. result = i2c_check_mux_parents(parent, addr);
  667. return result;
  668. }
  669. /* recurse down mux tree */
  670. static int i2c_check_mux_children(struct device *dev, void *addrp)
  671. {
  672. int result;
  673. if (dev->type == &i2c_adapter_type)
  674. result = device_for_each_child(dev, addrp,
  675. i2c_check_mux_children);
  676. else
  677. result = __i2c_check_addr_busy(dev, addrp);
  678. return result;
  679. }
  680. static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
  681. {
  682. struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
  683. int result = 0;
  684. if (parent)
  685. result = i2c_check_mux_parents(parent, addr);
  686. if (!result)
  687. result = device_for_each_child(&adapter->dev, &addr,
  688. i2c_check_mux_children);
  689. return result;
  690. }
  691. /**
  692. * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
  693. * @adapter: Target I2C bus segment
  694. * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
  695. * locks only this branch in the adapter tree
  696. */
  697. static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
  698. unsigned int flags)
  699. {
  700. rt_mutex_lock_nested(&adapter->bus_lock, i2c_adapter_depth(adapter));
  701. }
  702. /**
  703. * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
  704. * @adapter: Target I2C bus segment
  705. * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
  706. * trylocks only this branch in the adapter tree
  707. */
  708. static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
  709. unsigned int flags)
  710. {
  711. return rt_mutex_trylock(&adapter->bus_lock);
  712. }
  713. /**
  714. * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
  715. * @adapter: Target I2C bus segment
  716. * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
  717. * unlocks only this branch in the adapter tree
  718. */
  719. static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
  720. unsigned int flags)
  721. {
  722. rt_mutex_unlock(&adapter->bus_lock);
  723. }
  724. static void i2c_dev_set_name(struct i2c_adapter *adap,
  725. struct i2c_client *client,
  726. struct i2c_board_info const *info)
  727. {
  728. struct acpi_device *adev = ACPI_COMPANION(&client->dev);
  729. if (info && info->dev_name) {
  730. dev_set_name(&client->dev, "i2c-%s", info->dev_name);
  731. return;
  732. }
  733. if (adev) {
  734. dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
  735. return;
  736. }
  737. dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
  738. i2c_encode_flags_to_addr(client));
  739. }
  740. int i2c_dev_irq_from_resources(const struct resource *resources,
  741. unsigned int num_resources)
  742. {
  743. struct irq_data *irqd;
  744. int i;
  745. for (i = 0; i < num_resources; i++) {
  746. const struct resource *r = &resources[i];
  747. if (resource_type(r) != IORESOURCE_IRQ)
  748. continue;
  749. if (r->flags & IORESOURCE_BITS) {
  750. irqd = irq_get_irq_data(r->start);
  751. if (!irqd)
  752. break;
  753. irqd_set_trigger_type(irqd, r->flags & IORESOURCE_BITS);
  754. }
  755. return r->start;
  756. }
  757. return 0;
  758. }
  759. /*
  760. * Serialize device instantiation in case it can be instantiated explicitly
  761. * and by auto-detection
  762. */
  763. static int i2c_lock_addr(struct i2c_adapter *adap, unsigned short addr,
  764. unsigned short flags)
  765. {
  766. if (!(flags & I2C_CLIENT_TEN) &&
  767. test_and_set_bit(addr, adap->addrs_in_instantiation))
  768. return -EBUSY;
  769. return 0;
  770. }
  771. static void i2c_unlock_addr(struct i2c_adapter *adap, unsigned short addr,
  772. unsigned short flags)
  773. {
  774. if (!(flags & I2C_CLIENT_TEN))
  775. clear_bit(addr, adap->addrs_in_instantiation);
  776. }
  777. /**
  778. * i2c_new_client_device - instantiate an i2c device
  779. * @adap: the adapter managing the device
  780. * @info: describes one I2C device; bus_num is ignored
  781. * Context: can sleep
  782. *
  783. * Create an i2c device. Binding is handled through driver model
  784. * probe()/remove() methods. A driver may be bound to this device when we
  785. * return from this function, or any later moment (e.g. maybe hotplugging will
  786. * load the driver module). This call is not appropriate for use by mainboard
  787. * initialization logic, which usually runs during an arch_initcall() long
  788. * before any i2c_adapter could exist.
  789. *
  790. * This returns the new i2c client, which may be saved for later use with
  791. * i2c_unregister_device(); or an ERR_PTR to describe the error.
  792. */
  793. struct i2c_client *
  794. i2c_new_client_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
  795. {
  796. struct i2c_client *client;
  797. bool need_put = false;
  798. int status;
  799. client = kzalloc(sizeof *client, GFP_KERNEL);
  800. if (!client)
  801. return ERR_PTR(-ENOMEM);
  802. client->adapter = adap;
  803. client->dev.platform_data = info->platform_data;
  804. client->flags = info->flags;
  805. client->addr = info->addr;
  806. client->init_irq = info->irq;
  807. if (!client->init_irq)
  808. client->init_irq = i2c_dev_irq_from_resources(info->resources,
  809. info->num_resources);
  810. strscpy(client->name, info->type, sizeof(client->name));
  811. status = i2c_check_addr_validity(client->addr, client->flags);
  812. if (status) {
  813. dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
  814. client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
  815. goto out_err_silent;
  816. }
  817. status = i2c_lock_addr(adap, client->addr, client->flags);
  818. if (status)
  819. goto out_err_silent;
  820. /* Check for address business */
  821. status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
  822. if (status)
  823. goto out_err;
  824. client->dev.parent = &client->adapter->dev;
  825. client->dev.bus = &i2c_bus_type;
  826. client->dev.type = &i2c_client_type;
  827. client->dev.of_node = of_node_get(info->of_node);
  828. client->dev.fwnode = info->fwnode;
  829. device_enable_async_suspend(&client->dev);
  830. if (info->swnode) {
  831. status = device_add_software_node(&client->dev, info->swnode);
  832. if (status) {
  833. dev_err(&adap->dev,
  834. "Failed to add software node to client %s: %d\n",
  835. client->name, status);
  836. goto out_err_put_of_node;
  837. }
  838. }
  839. i2c_dev_set_name(adap, client, info);
  840. status = device_register(&client->dev);
  841. if (status)
  842. goto out_remove_swnode;
  843. dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
  844. client->name, dev_name(&client->dev));
  845. i2c_unlock_addr(adap, client->addr, client->flags);
  846. return client;
  847. out_remove_swnode:
  848. device_remove_software_node(&client->dev);
  849. need_put = true;
  850. out_err_put_of_node:
  851. of_node_put(info->of_node);
  852. out_err:
  853. dev_err(&adap->dev,
  854. "Failed to register i2c client %s at 0x%02x (%d)\n",
  855. client->name, client->addr, status);
  856. i2c_unlock_addr(adap, client->addr, client->flags);
  857. out_err_silent:
  858. if (need_put)
  859. put_device(&client->dev);
  860. else
  861. kfree(client);
  862. return ERR_PTR(status);
  863. }
  864. EXPORT_SYMBOL_GPL(i2c_new_client_device);
  865. /**
  866. * i2c_unregister_device - reverse effect of i2c_new_*_device()
  867. * @client: value returned from i2c_new_*_device()
  868. * Context: can sleep
  869. */
  870. void i2c_unregister_device(struct i2c_client *client)
  871. {
  872. if (IS_ERR_OR_NULL(client))
  873. return;
  874. if (client->dev.of_node) {
  875. of_node_clear_flag(client->dev.of_node, OF_POPULATED);
  876. of_node_put(client->dev.of_node);
  877. }
  878. if (ACPI_COMPANION(&client->dev))
  879. acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
  880. device_remove_software_node(&client->dev);
  881. device_unregister(&client->dev);
  882. }
  883. EXPORT_SYMBOL_GPL(i2c_unregister_device);
  884. /**
  885. * i2c_find_device_by_fwnode() - find an i2c_client for the fwnode
  886. * @fwnode: &struct fwnode_handle corresponding to the &struct i2c_client
  887. *
  888. * Look up and return the &struct i2c_client corresponding to the @fwnode.
  889. * If no client can be found, or @fwnode is NULL, this returns NULL.
  890. *
  891. * The user must call put_device(&client->dev) once done with the i2c client.
  892. */
  893. struct i2c_client *i2c_find_device_by_fwnode(struct fwnode_handle *fwnode)
  894. {
  895. struct i2c_client *client;
  896. struct device *dev;
  897. if (!fwnode)
  898. return NULL;
  899. dev = bus_find_device_by_fwnode(&i2c_bus_type, fwnode);
  900. if (!dev)
  901. return NULL;
  902. client = i2c_verify_client(dev);
  903. if (!client)
  904. put_device(dev);
  905. return client;
  906. }
  907. EXPORT_SYMBOL(i2c_find_device_by_fwnode);
  908. static const struct i2c_device_id dummy_id[] = {
  909. { "dummy", },
  910. { "smbus_host_notify", },
  911. { }
  912. };
  913. static int dummy_probe(struct i2c_client *client)
  914. {
  915. return 0;
  916. }
  917. static struct i2c_driver dummy_driver = {
  918. .driver.name = "dummy",
  919. .probe = dummy_probe,
  920. .id_table = dummy_id,
  921. };
  922. /**
  923. * i2c_new_dummy_device - return a new i2c device bound to a dummy driver
  924. * @adapter: the adapter managing the device
  925. * @address: seven bit address to be used
  926. * Context: can sleep
  927. *
  928. * This returns an I2C client bound to the "dummy" driver, intended for use
  929. * with devices that consume multiple addresses. Examples of such chips
  930. * include various EEPROMS (like 24c04 and 24c08 models).
  931. *
  932. * These dummy devices have two main uses. First, most I2C and SMBus calls
  933. * except i2c_transfer() need a client handle; the dummy will be that handle.
  934. * And second, this prevents the specified address from being bound to a
  935. * different driver.
  936. *
  937. * This returns the new i2c client, which should be saved for later use with
  938. * i2c_unregister_device(); or an ERR_PTR to describe the error.
  939. */
  940. struct i2c_client *i2c_new_dummy_device(struct i2c_adapter *adapter, u16 address)
  941. {
  942. struct i2c_board_info info = {
  943. I2C_BOARD_INFO("dummy", address),
  944. };
  945. return i2c_new_client_device(adapter, &info);
  946. }
  947. EXPORT_SYMBOL_GPL(i2c_new_dummy_device);
  948. static void devm_i2c_release_dummy(void *client)
  949. {
  950. i2c_unregister_device(client);
  951. }
  952. /**
  953. * devm_i2c_new_dummy_device - return a new i2c device bound to a dummy driver
  954. * @dev: device the managed resource is bound to
  955. * @adapter: the adapter managing the device
  956. * @address: seven bit address to be used
  957. * Context: can sleep
  958. *
  959. * This is the device-managed version of @i2c_new_dummy_device. It returns the
  960. * new i2c client or an ERR_PTR in case of an error.
  961. */
  962. struct i2c_client *devm_i2c_new_dummy_device(struct device *dev,
  963. struct i2c_adapter *adapter,
  964. u16 address)
  965. {
  966. struct i2c_client *client;
  967. int ret;
  968. client = i2c_new_dummy_device(adapter, address);
  969. if (IS_ERR(client))
  970. return client;
  971. ret = devm_add_action_or_reset(dev, devm_i2c_release_dummy, client);
  972. if (ret)
  973. return ERR_PTR(ret);
  974. return client;
  975. }
  976. EXPORT_SYMBOL_GPL(devm_i2c_new_dummy_device);
  977. /**
  978. * i2c_new_ancillary_device - Helper to get the instantiated secondary address
  979. * and create the associated device
  980. * @client: Handle to the primary client
  981. * @name: Handle to specify which secondary address to get
  982. * @default_addr: Used as a fallback if no secondary address was specified
  983. * Context: can sleep
  984. *
  985. * I2C clients can be composed of multiple I2C slaves bound together in a single
  986. * component. The I2C client driver then binds to the master I2C slave and needs
  987. * to create I2C dummy clients to communicate with all the other slaves.
  988. *
  989. * This function creates and returns an I2C dummy client whose I2C address is
  990. * retrieved from the platform firmware based on the given slave name. If no
  991. * address is specified by the firmware default_addr is used.
  992. *
  993. * On DT-based platforms the address is retrieved from the "reg" property entry
  994. * cell whose "reg-names" value matches the slave name.
  995. *
  996. * This returns the new i2c client, which should be saved for later use with
  997. * i2c_unregister_device(); or an ERR_PTR to describe the error.
  998. */
  999. struct i2c_client *i2c_new_ancillary_device(struct i2c_client *client,
  1000. const char *name,
  1001. u16 default_addr)
  1002. {
  1003. struct device_node *np = client->dev.of_node;
  1004. u32 addr = default_addr;
  1005. int i;
  1006. if (np) {
  1007. i = of_property_match_string(np, "reg-names", name);
  1008. if (i >= 0)
  1009. of_property_read_u32_index(np, "reg", i, &addr);
  1010. }
  1011. dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
  1012. return i2c_new_dummy_device(client->adapter, addr);
  1013. }
  1014. EXPORT_SYMBOL_GPL(i2c_new_ancillary_device);
  1015. /* ------------------------------------------------------------------------- */
  1016. /* I2C bus adapters -- one roots each I2C or SMBUS segment */
  1017. static void i2c_adapter_dev_release(struct device *dev)
  1018. {
  1019. struct i2c_adapter *adap = to_i2c_adapter(dev);
  1020. complete(&adap->dev_released);
  1021. }
  1022. unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
  1023. {
  1024. unsigned int depth = 0;
  1025. struct device *parent;
  1026. for (parent = adapter->dev.parent; parent; parent = parent->parent)
  1027. if (parent->type == &i2c_adapter_type)
  1028. depth++;
  1029. WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
  1030. "adapter depth exceeds lockdep subclass limit\n");
  1031. return depth;
  1032. }
  1033. EXPORT_SYMBOL_GPL(i2c_adapter_depth);
  1034. /*
  1035. * Let users instantiate I2C devices through sysfs. This can be used when
  1036. * platform initialization code doesn't contain the proper data for
  1037. * whatever reason. Also useful for drivers that do device detection and
  1038. * detection fails, either because the device uses an unexpected address,
  1039. * or this is a compatible device with different ID register values.
  1040. *
  1041. * Parameter checking may look overzealous, but we really don't want
  1042. * the user to provide incorrect parameters.
  1043. */
  1044. static ssize_t
  1045. new_device_store(struct device *dev, struct device_attribute *attr,
  1046. const char *buf, size_t count)
  1047. {
  1048. struct i2c_adapter *adap = to_i2c_adapter(dev);
  1049. struct i2c_board_info info;
  1050. struct i2c_client *client;
  1051. char *blank, end;
  1052. int res;
  1053. memset(&info, 0, sizeof(struct i2c_board_info));
  1054. blank = strchr(buf, ' ');
  1055. if (!blank) {
  1056. dev_err(dev, "%s: Missing parameters\n", "new_device");
  1057. return -EINVAL;
  1058. }
  1059. if (blank - buf > I2C_NAME_SIZE - 1) {
  1060. dev_err(dev, "%s: Invalid device name\n", "new_device");
  1061. return -EINVAL;
  1062. }
  1063. memcpy(info.type, buf, blank - buf);
  1064. /* Parse remaining parameters, reject extra parameters */
  1065. res = sscanf(++blank, "%hi%c", &info.addr, &end);
  1066. if (res < 1) {
  1067. dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
  1068. return -EINVAL;
  1069. }
  1070. if (res > 1 && end != '\n') {
  1071. dev_err(dev, "%s: Extra parameters\n", "new_device");
  1072. return -EINVAL;
  1073. }
  1074. if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
  1075. info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
  1076. info.flags |= I2C_CLIENT_TEN;
  1077. }
  1078. if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
  1079. info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
  1080. info.flags |= I2C_CLIENT_SLAVE;
  1081. }
  1082. client = i2c_new_client_device(adap, &info);
  1083. if (IS_ERR(client))
  1084. return PTR_ERR(client);
  1085. /* Keep track of the added device */
  1086. mutex_lock(&adap->userspace_clients_lock);
  1087. list_add_tail(&client->detected, &adap->userspace_clients);
  1088. mutex_unlock(&adap->userspace_clients_lock);
  1089. dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
  1090. info.type, info.addr);
  1091. return count;
  1092. }
  1093. static DEVICE_ATTR_WO(new_device);
  1094. /*
  1095. * And of course let the users delete the devices they instantiated, if
  1096. * they got it wrong. This interface can only be used to delete devices
  1097. * instantiated by i2c_sysfs_new_device above. This guarantees that we
  1098. * don't delete devices to which some kernel code still has references.
  1099. *
  1100. * Parameter checking may look overzealous, but we really don't want
  1101. * the user to delete the wrong device.
  1102. */
  1103. static ssize_t
  1104. delete_device_store(struct device *dev, struct device_attribute *attr,
  1105. const char *buf, size_t count)
  1106. {
  1107. struct i2c_adapter *adap = to_i2c_adapter(dev);
  1108. struct i2c_client *client, *next;
  1109. unsigned short addr;
  1110. char end;
  1111. int res;
  1112. /* Parse parameters, reject extra parameters */
  1113. res = sscanf(buf, "%hi%c", &addr, &end);
  1114. if (res < 1) {
  1115. dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
  1116. return -EINVAL;
  1117. }
  1118. if (res > 1 && end != '\n') {
  1119. dev_err(dev, "%s: Extra parameters\n", "delete_device");
  1120. return -EINVAL;
  1121. }
  1122. /* Make sure the device was added through sysfs */
  1123. res = -ENOENT;
  1124. mutex_lock_nested(&adap->userspace_clients_lock,
  1125. i2c_adapter_depth(adap));
  1126. list_for_each_entry_safe(client, next, &adap->userspace_clients,
  1127. detected) {
  1128. if (i2c_encode_flags_to_addr(client) == addr) {
  1129. dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
  1130. "delete_device", client->name, client->addr);
  1131. list_del(&client->detected);
  1132. i2c_unregister_device(client);
  1133. res = count;
  1134. break;
  1135. }
  1136. }
  1137. mutex_unlock(&adap->userspace_clients_lock);
  1138. if (res < 0)
  1139. dev_err(dev, "%s: Can't find device in list\n",
  1140. "delete_device");
  1141. return res;
  1142. }
  1143. static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
  1144. delete_device_store);
  1145. static struct attribute *i2c_adapter_attrs[] = {
  1146. &dev_attr_name.attr,
  1147. &dev_attr_new_device.attr,
  1148. &dev_attr_delete_device.attr,
  1149. NULL
  1150. };
  1151. ATTRIBUTE_GROUPS(i2c_adapter);
  1152. const struct device_type i2c_adapter_type = {
  1153. .groups = i2c_adapter_groups,
  1154. .release = i2c_adapter_dev_release,
  1155. };
  1156. EXPORT_SYMBOL_GPL(i2c_adapter_type);
  1157. /**
  1158. * i2c_verify_adapter - return parameter as i2c_adapter or NULL
  1159. * @dev: device, probably from some driver model iterator
  1160. *
  1161. * When traversing the driver model tree, perhaps using driver model
  1162. * iterators like @device_for_each_child(), you can't assume very much
  1163. * about the nodes you find. Use this function to avoid oopses caused
  1164. * by wrongly treating some non-I2C device as an i2c_adapter.
  1165. */
  1166. struct i2c_adapter *i2c_verify_adapter(struct device *dev)
  1167. {
  1168. return (dev->type == &i2c_adapter_type)
  1169. ? to_i2c_adapter(dev)
  1170. : NULL;
  1171. }
  1172. EXPORT_SYMBOL(i2c_verify_adapter);
  1173. static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
  1174. {
  1175. struct i2c_devinfo *devinfo;
  1176. down_read(&__i2c_board_lock);
  1177. list_for_each_entry(devinfo, &__i2c_board_list, list) {
  1178. if (devinfo->busnum == adapter->nr &&
  1179. IS_ERR(i2c_new_client_device(adapter, &devinfo->board_info)))
  1180. dev_err(&adapter->dev,
  1181. "Can't create device at 0x%02x\n",
  1182. devinfo->board_info.addr);
  1183. }
  1184. up_read(&__i2c_board_lock);
  1185. }
  1186. static int i2c_do_add_adapter(struct i2c_driver *driver,
  1187. struct i2c_adapter *adap)
  1188. {
  1189. /* Detect supported devices on that bus, and instantiate them */
  1190. i2c_detect(adap, driver);
  1191. return 0;
  1192. }
  1193. static int __process_new_adapter(struct device_driver *d, void *data)
  1194. {
  1195. return i2c_do_add_adapter(to_i2c_driver(d), data);
  1196. }
  1197. static const struct i2c_lock_operations i2c_adapter_lock_ops = {
  1198. .lock_bus = i2c_adapter_lock_bus,
  1199. .trylock_bus = i2c_adapter_trylock_bus,
  1200. .unlock_bus = i2c_adapter_unlock_bus,
  1201. };
  1202. static void i2c_host_notify_irq_teardown(struct i2c_adapter *adap)
  1203. {
  1204. struct irq_domain *domain = adap->host_notify_domain;
  1205. irq_hw_number_t hwirq;
  1206. if (!domain)
  1207. return;
  1208. for (hwirq = 0 ; hwirq < I2C_ADDR_7BITS_COUNT ; hwirq++)
  1209. irq_dispose_mapping(irq_find_mapping(domain, hwirq));
  1210. irq_domain_remove(domain);
  1211. adap->host_notify_domain = NULL;
  1212. }
  1213. static int i2c_host_notify_irq_map(struct irq_domain *h,
  1214. unsigned int virq,
  1215. irq_hw_number_t hw_irq_num)
  1216. {
  1217. irq_set_chip_and_handler(virq, &dummy_irq_chip, handle_simple_irq);
  1218. return 0;
  1219. }
  1220. static const struct irq_domain_ops i2c_host_notify_irq_ops = {
  1221. .map = i2c_host_notify_irq_map,
  1222. };
  1223. static int i2c_setup_host_notify_irq_domain(struct i2c_adapter *adap)
  1224. {
  1225. struct irq_domain *domain;
  1226. if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_HOST_NOTIFY))
  1227. return 0;
  1228. domain = irq_domain_create_linear(adap->dev.parent->fwnode,
  1229. I2C_ADDR_7BITS_COUNT,
  1230. &i2c_host_notify_irq_ops, adap);
  1231. if (!domain)
  1232. return -ENOMEM;
  1233. adap->host_notify_domain = domain;
  1234. return 0;
  1235. }
  1236. /**
  1237. * i2c_handle_smbus_host_notify - Forward a Host Notify event to the correct
  1238. * I2C client.
  1239. * @adap: the adapter
  1240. * @addr: the I2C address of the notifying device
  1241. * Context: can't sleep
  1242. *
  1243. * Helper function to be called from an I2C bus driver's interrupt
  1244. * handler. It will schedule the Host Notify IRQ.
  1245. */
  1246. int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
  1247. {
  1248. int irq;
  1249. if (!adap)
  1250. return -EINVAL;
  1251. dev_dbg(&adap->dev, "Detected HostNotify from address 0x%02x", addr);
  1252. irq = irq_find_mapping(adap->host_notify_domain, addr);
  1253. if (irq <= 0)
  1254. return -ENXIO;
  1255. generic_handle_irq_safe(irq);
  1256. return 0;
  1257. }
  1258. EXPORT_SYMBOL_GPL(i2c_handle_smbus_host_notify);
  1259. static int i2c_register_adapter(struct i2c_adapter *adap)
  1260. {
  1261. int res = -EINVAL;
  1262. /* Can't register until after driver model init */
  1263. if (WARN_ON(!is_registered)) {
  1264. res = -EAGAIN;
  1265. goto out_list;
  1266. }
  1267. /* Sanity checks */
  1268. if (WARN(!adap->name[0], "i2c adapter has no name"))
  1269. goto out_list;
  1270. if (!adap->algo) {
  1271. pr_err("adapter '%s': no algo supplied!\n", adap->name);
  1272. goto out_list;
  1273. }
  1274. if (!adap->lock_ops)
  1275. adap->lock_ops = &i2c_adapter_lock_ops;
  1276. adap->locked_flags = 0;
  1277. rt_mutex_init(&adap->bus_lock);
  1278. rt_mutex_init(&adap->mux_lock);
  1279. mutex_init(&adap->userspace_clients_lock);
  1280. INIT_LIST_HEAD(&adap->userspace_clients);
  1281. /* Set default timeout to 1 second if not already set */
  1282. if (adap->timeout == 0)
  1283. adap->timeout = HZ;
  1284. /* register soft irqs for Host Notify */
  1285. res = i2c_setup_host_notify_irq_domain(adap);
  1286. if (res) {
  1287. pr_err("adapter '%s': can't create Host Notify IRQs (%d)\n",
  1288. adap->name, res);
  1289. goto out_list;
  1290. }
  1291. dev_set_name(&adap->dev, "i2c-%d", adap->nr);
  1292. adap->dev.bus = &i2c_bus_type;
  1293. adap->dev.type = &i2c_adapter_type;
  1294. device_initialize(&adap->dev);
  1295. /*
  1296. * This adapter can be used as a parent immediately after device_add(),
  1297. * setup runtime-pm (especially ignore-children) before hand.
  1298. */
  1299. device_enable_async_suspend(&adap->dev);
  1300. pm_runtime_no_callbacks(&adap->dev);
  1301. pm_suspend_ignore_children(&adap->dev, true);
  1302. pm_runtime_enable(&adap->dev);
  1303. res = device_add(&adap->dev);
  1304. if (res) {
  1305. pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
  1306. put_device(&adap->dev);
  1307. goto out_list;
  1308. }
  1309. adap->debugfs = debugfs_create_dir(dev_name(&adap->dev), i2c_debugfs_root);
  1310. res = i2c_setup_smbus_alert(adap);
  1311. if (res)
  1312. goto out_reg;
  1313. res = i2c_init_recovery(adap);
  1314. if (res == -EPROBE_DEFER)
  1315. goto out_reg;
  1316. dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
  1317. /* create pre-declared device nodes */
  1318. of_i2c_register_devices(adap);
  1319. i2c_acpi_install_space_handler(adap);
  1320. i2c_acpi_register_devices(adap);
  1321. if (adap->nr < __i2c_first_dynamic_bus_num)
  1322. i2c_scan_static_board_info(adap);
  1323. /* Notify drivers */
  1324. mutex_lock(&core_lock);
  1325. bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
  1326. mutex_unlock(&core_lock);
  1327. return 0;
  1328. out_reg:
  1329. debugfs_remove_recursive(adap->debugfs);
  1330. init_completion(&adap->dev_released);
  1331. device_unregister(&adap->dev);
  1332. wait_for_completion(&adap->dev_released);
  1333. out_list:
  1334. mutex_lock(&core_lock);
  1335. idr_remove(&i2c_adapter_idr, adap->nr);
  1336. mutex_unlock(&core_lock);
  1337. return res;
  1338. }
  1339. /**
  1340. * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
  1341. * @adap: the adapter to register (with adap->nr initialized)
  1342. * Context: can sleep
  1343. *
  1344. * See i2c_add_numbered_adapter() for details.
  1345. */
  1346. static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
  1347. {
  1348. int id;
  1349. mutex_lock(&core_lock);
  1350. id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
  1351. mutex_unlock(&core_lock);
  1352. if (WARN(id < 0, "couldn't get idr"))
  1353. return id == -ENOSPC ? -EBUSY : id;
  1354. return i2c_register_adapter(adap);
  1355. }
  1356. /**
  1357. * i2c_add_adapter - declare i2c adapter, use dynamic bus number
  1358. * @adapter: the adapter to add
  1359. * Context: can sleep
  1360. *
  1361. * This routine is used to declare an I2C adapter when its bus number
  1362. * doesn't matter or when its bus number is specified by an dt alias.
  1363. * Examples of bases when the bus number doesn't matter: I2C adapters
  1364. * dynamically added by USB links or PCI plugin cards.
  1365. *
  1366. * When this returns zero, a new bus number was allocated and stored
  1367. * in adap->nr, and the specified adapter became available for clients.
  1368. * Otherwise, a negative errno value is returned.
  1369. */
  1370. int i2c_add_adapter(struct i2c_adapter *adapter)
  1371. {
  1372. struct device *dev = &adapter->dev;
  1373. int id;
  1374. if (dev->of_node) {
  1375. id = of_alias_get_id(dev->of_node, "i2c");
  1376. if (id >= 0) {
  1377. adapter->nr = id;
  1378. return __i2c_add_numbered_adapter(adapter);
  1379. }
  1380. }
  1381. mutex_lock(&core_lock);
  1382. id = idr_alloc(&i2c_adapter_idr, adapter,
  1383. __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
  1384. mutex_unlock(&core_lock);
  1385. if (WARN(id < 0, "couldn't get idr"))
  1386. return id;
  1387. adapter->nr = id;
  1388. return i2c_register_adapter(adapter);
  1389. }
  1390. EXPORT_SYMBOL(i2c_add_adapter);
  1391. /**
  1392. * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
  1393. * @adap: the adapter to register (with adap->nr initialized)
  1394. * Context: can sleep
  1395. *
  1396. * This routine is used to declare an I2C adapter when its bus number
  1397. * matters. For example, use it for I2C adapters from system-on-chip CPUs,
  1398. * or otherwise built in to the system's mainboard, and where i2c_board_info
  1399. * is used to properly configure I2C devices.
  1400. *
  1401. * If the requested bus number is set to -1, then this function will behave
  1402. * identically to i2c_add_adapter, and will dynamically assign a bus number.
  1403. *
  1404. * If no devices have pre-been declared for this bus, then be sure to
  1405. * register the adapter before any dynamically allocated ones. Otherwise
  1406. * the required bus ID may not be available.
  1407. *
  1408. * When this returns zero, the specified adapter became available for
  1409. * clients using the bus number provided in adap->nr. Also, the table
  1410. * of I2C devices pre-declared using i2c_register_board_info() is scanned,
  1411. * and the appropriate driver model device nodes are created. Otherwise, a
  1412. * negative errno value is returned.
  1413. */
  1414. int i2c_add_numbered_adapter(struct i2c_adapter *adap)
  1415. {
  1416. if (adap->nr == -1) /* -1 means dynamically assign bus id */
  1417. return i2c_add_adapter(adap);
  1418. return __i2c_add_numbered_adapter(adap);
  1419. }
  1420. EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
  1421. static void i2c_do_del_adapter(struct i2c_driver *driver,
  1422. struct i2c_adapter *adapter)
  1423. {
  1424. struct i2c_client *client, *_n;
  1425. /* Remove the devices we created ourselves as the result of hardware
  1426. * probing (using a driver's detect method) */
  1427. list_for_each_entry_safe(client, _n, &driver->clients, detected) {
  1428. if (client->adapter == adapter) {
  1429. dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
  1430. client->name, client->addr);
  1431. list_del(&client->detected);
  1432. i2c_unregister_device(client);
  1433. }
  1434. }
  1435. }
  1436. static int __unregister_client(struct device *dev, void *dummy)
  1437. {
  1438. struct i2c_client *client = i2c_verify_client(dev);
  1439. if (client && strcmp(client->name, "dummy"))
  1440. i2c_unregister_device(client);
  1441. return 0;
  1442. }
  1443. static int __unregister_dummy(struct device *dev, void *dummy)
  1444. {
  1445. struct i2c_client *client = i2c_verify_client(dev);
  1446. i2c_unregister_device(client);
  1447. return 0;
  1448. }
  1449. static int __process_removed_adapter(struct device_driver *d, void *data)
  1450. {
  1451. i2c_do_del_adapter(to_i2c_driver(d), data);
  1452. return 0;
  1453. }
  1454. /**
  1455. * i2c_del_adapter - unregister I2C adapter
  1456. * @adap: the adapter being unregistered
  1457. * Context: can sleep
  1458. *
  1459. * This unregisters an I2C adapter which was previously registered
  1460. * by @i2c_add_adapter or @i2c_add_numbered_adapter.
  1461. */
  1462. void i2c_del_adapter(struct i2c_adapter *adap)
  1463. {
  1464. struct i2c_adapter *found;
  1465. struct i2c_client *client, *next;
  1466. /* First make sure that this adapter was ever added */
  1467. mutex_lock(&core_lock);
  1468. found = idr_find(&i2c_adapter_idr, adap->nr);
  1469. mutex_unlock(&core_lock);
  1470. if (found != adap) {
  1471. pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
  1472. return;
  1473. }
  1474. i2c_acpi_remove_space_handler(adap);
  1475. /* Tell drivers about this removal */
  1476. mutex_lock(&core_lock);
  1477. bus_for_each_drv(&i2c_bus_type, NULL, adap,
  1478. __process_removed_adapter);
  1479. mutex_unlock(&core_lock);
  1480. /* Remove devices instantiated from sysfs */
  1481. mutex_lock_nested(&adap->userspace_clients_lock,
  1482. i2c_adapter_depth(adap));
  1483. list_for_each_entry_safe(client, next, &adap->userspace_clients,
  1484. detected) {
  1485. dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
  1486. client->addr);
  1487. list_del(&client->detected);
  1488. i2c_unregister_device(client);
  1489. }
  1490. mutex_unlock(&adap->userspace_clients_lock);
  1491. /* Detach any active clients. This can't fail, thus we do not
  1492. * check the returned value. This is a two-pass process, because
  1493. * we can't remove the dummy devices during the first pass: they
  1494. * could have been instantiated by real devices wishing to clean
  1495. * them up properly, so we give them a chance to do that first. */
  1496. device_for_each_child(&adap->dev, NULL, __unregister_client);
  1497. device_for_each_child(&adap->dev, NULL, __unregister_dummy);
  1498. /* device name is gone after device_unregister */
  1499. dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
  1500. pm_runtime_disable(&adap->dev);
  1501. i2c_host_notify_irq_teardown(adap);
  1502. debugfs_remove_recursive(adap->debugfs);
  1503. /* wait until all references to the device are gone
  1504. *
  1505. * FIXME: This is old code and should ideally be replaced by an
  1506. * alternative which results in decoupling the lifetime of the struct
  1507. * device from the i2c_adapter, like spi or netdev do. Any solution
  1508. * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
  1509. */
  1510. init_completion(&adap->dev_released);
  1511. device_unregister(&adap->dev);
  1512. wait_for_completion(&adap->dev_released);
  1513. /* free bus id */
  1514. mutex_lock(&core_lock);
  1515. idr_remove(&i2c_adapter_idr, adap->nr);
  1516. mutex_unlock(&core_lock);
  1517. /* Clear the device structure in case this adapter is ever going to be
  1518. added again */
  1519. memset(&adap->dev, 0, sizeof(adap->dev));
  1520. }
  1521. EXPORT_SYMBOL(i2c_del_adapter);
  1522. static void devm_i2c_del_adapter(void *adapter)
  1523. {
  1524. i2c_del_adapter(adapter);
  1525. }
  1526. /**
  1527. * devm_i2c_add_adapter - device-managed variant of i2c_add_adapter()
  1528. * @dev: managing device for adding this I2C adapter
  1529. * @adapter: the adapter to add
  1530. * Context: can sleep
  1531. *
  1532. * Add adapter with dynamic bus number, same with i2c_add_adapter()
  1533. * but the adapter will be auto deleted on driver detach.
  1534. */
  1535. int devm_i2c_add_adapter(struct device *dev, struct i2c_adapter *adapter)
  1536. {
  1537. int ret;
  1538. ret = i2c_add_adapter(adapter);
  1539. if (ret)
  1540. return ret;
  1541. return devm_add_action_or_reset(dev, devm_i2c_del_adapter, adapter);
  1542. }
  1543. EXPORT_SYMBOL_GPL(devm_i2c_add_adapter);
  1544. static int i2c_dev_or_parent_fwnode_match(struct device *dev, const void *data)
  1545. {
  1546. if (dev_fwnode(dev) == data)
  1547. return 1;
  1548. if (dev->parent && dev_fwnode(dev->parent) == data)
  1549. return 1;
  1550. return 0;
  1551. }
  1552. /**
  1553. * i2c_find_adapter_by_fwnode() - find an i2c_adapter for the fwnode
  1554. * @fwnode: &struct fwnode_handle corresponding to the &struct i2c_adapter
  1555. *
  1556. * Look up and return the &struct i2c_adapter corresponding to the @fwnode.
  1557. * If no adapter can be found, or @fwnode is NULL, this returns NULL.
  1558. *
  1559. * The user must call put_device(&adapter->dev) once done with the i2c adapter.
  1560. */
  1561. struct i2c_adapter *i2c_find_adapter_by_fwnode(struct fwnode_handle *fwnode)
  1562. {
  1563. struct i2c_adapter *adapter;
  1564. struct device *dev;
  1565. if (!fwnode)
  1566. return NULL;
  1567. dev = bus_find_device(&i2c_bus_type, NULL, fwnode,
  1568. i2c_dev_or_parent_fwnode_match);
  1569. if (!dev)
  1570. return NULL;
  1571. adapter = i2c_verify_adapter(dev);
  1572. if (!adapter)
  1573. put_device(dev);
  1574. return adapter;
  1575. }
  1576. EXPORT_SYMBOL(i2c_find_adapter_by_fwnode);
  1577. /**
  1578. * i2c_get_adapter_by_fwnode() - find an i2c_adapter for the fwnode
  1579. * @fwnode: &struct fwnode_handle corresponding to the &struct i2c_adapter
  1580. *
  1581. * Look up and return the &struct i2c_adapter corresponding to the @fwnode,
  1582. * and increment the adapter module's use count. If no adapter can be found,
  1583. * or @fwnode is NULL, this returns NULL.
  1584. *
  1585. * The user must call i2c_put_adapter(adapter) once done with the i2c adapter.
  1586. * Note that this is different from i2c_find_adapter_by_node().
  1587. */
  1588. struct i2c_adapter *i2c_get_adapter_by_fwnode(struct fwnode_handle *fwnode)
  1589. {
  1590. struct i2c_adapter *adapter;
  1591. adapter = i2c_find_adapter_by_fwnode(fwnode);
  1592. if (!adapter)
  1593. return NULL;
  1594. if (!try_module_get(adapter->owner)) {
  1595. put_device(&adapter->dev);
  1596. adapter = NULL;
  1597. }
  1598. return adapter;
  1599. }
  1600. EXPORT_SYMBOL(i2c_get_adapter_by_fwnode);
  1601. static void i2c_parse_timing(struct device *dev, char *prop_name, u32 *cur_val_p,
  1602. u32 def_val, bool use_def)
  1603. {
  1604. int ret;
  1605. ret = device_property_read_u32(dev, prop_name, cur_val_p);
  1606. if (ret && use_def)
  1607. *cur_val_p = def_val;
  1608. dev_dbg(dev, "%s: %u\n", prop_name, *cur_val_p);
  1609. }
  1610. /**
  1611. * i2c_parse_fw_timings - get I2C related timing parameters from firmware
  1612. * @dev: The device to scan for I2C timing properties
  1613. * @t: the i2c_timings struct to be filled with values
  1614. * @use_defaults: bool to use sane defaults derived from the I2C specification
  1615. * when properties are not found, otherwise don't update
  1616. *
  1617. * Scan the device for the generic I2C properties describing timing parameters
  1618. * for the signal and fill the given struct with the results. If a property was
  1619. * not found and use_defaults was true, then maximum timings are assumed which
  1620. * are derived from the I2C specification. If use_defaults is not used, the
  1621. * results will be as before, so drivers can apply their own defaults before
  1622. * calling this helper. The latter is mainly intended for avoiding regressions
  1623. * of existing drivers which want to switch to this function. New drivers
  1624. * almost always should use the defaults.
  1625. */
  1626. void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
  1627. {
  1628. bool u = use_defaults;
  1629. u32 d;
  1630. i2c_parse_timing(dev, "clock-frequency", &t->bus_freq_hz,
  1631. I2C_MAX_STANDARD_MODE_FREQ, u);
  1632. d = t->bus_freq_hz <= I2C_MAX_STANDARD_MODE_FREQ ? 1000 :
  1633. t->bus_freq_hz <= I2C_MAX_FAST_MODE_FREQ ? 300 : 120;
  1634. i2c_parse_timing(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns, d, u);
  1635. d = t->bus_freq_hz <= I2C_MAX_FAST_MODE_FREQ ? 300 : 120;
  1636. i2c_parse_timing(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns, d, u);
  1637. i2c_parse_timing(dev, "i2c-scl-internal-delay-ns",
  1638. &t->scl_int_delay_ns, 0, u);
  1639. i2c_parse_timing(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns,
  1640. t->scl_fall_ns, u);
  1641. i2c_parse_timing(dev, "i2c-sda-hold-time-ns", &t->sda_hold_ns, 0, u);
  1642. i2c_parse_timing(dev, "i2c-digital-filter-width-ns",
  1643. &t->digital_filter_width_ns, 0, u);
  1644. i2c_parse_timing(dev, "i2c-analog-filter-cutoff-frequency",
  1645. &t->analog_filter_cutoff_freq_hz, 0, u);
  1646. }
  1647. EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
  1648. /* ------------------------------------------------------------------------- */
  1649. int i2c_for_each_dev(void *data, int (*fn)(struct device *dev, void *data))
  1650. {
  1651. int res;
  1652. mutex_lock(&core_lock);
  1653. res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
  1654. mutex_unlock(&core_lock);
  1655. return res;
  1656. }
  1657. EXPORT_SYMBOL_GPL(i2c_for_each_dev);
  1658. static int __process_new_driver(struct device *dev, void *data)
  1659. {
  1660. if (dev->type != &i2c_adapter_type)
  1661. return 0;
  1662. return i2c_do_add_adapter(data, to_i2c_adapter(dev));
  1663. }
  1664. /*
  1665. * An i2c_driver is used with one or more i2c_client (device) nodes to access
  1666. * i2c slave chips, on a bus instance associated with some i2c_adapter.
  1667. */
  1668. int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
  1669. {
  1670. int res;
  1671. /* Can't register until after driver model init */
  1672. if (WARN_ON(!is_registered))
  1673. return -EAGAIN;
  1674. /* add the driver to the list of i2c drivers in the driver core */
  1675. driver->driver.owner = owner;
  1676. driver->driver.bus = &i2c_bus_type;
  1677. INIT_LIST_HEAD(&driver->clients);
  1678. /* When registration returns, the driver core
  1679. * will have called probe() for all matching-but-unbound devices.
  1680. */
  1681. res = driver_register(&driver->driver);
  1682. if (res)
  1683. return res;
  1684. pr_debug("driver [%s] registered\n", driver->driver.name);
  1685. /* Walk the adapters that are already present */
  1686. i2c_for_each_dev(driver, __process_new_driver);
  1687. return 0;
  1688. }
  1689. EXPORT_SYMBOL(i2c_register_driver);
  1690. static int __process_removed_driver(struct device *dev, void *data)
  1691. {
  1692. if (dev->type == &i2c_adapter_type)
  1693. i2c_do_del_adapter(data, to_i2c_adapter(dev));
  1694. return 0;
  1695. }
  1696. /**
  1697. * i2c_del_driver - unregister I2C driver
  1698. * @driver: the driver being unregistered
  1699. * Context: can sleep
  1700. */
  1701. void i2c_del_driver(struct i2c_driver *driver)
  1702. {
  1703. i2c_for_each_dev(driver, __process_removed_driver);
  1704. driver_unregister(&driver->driver);
  1705. pr_debug("driver [%s] unregistered\n", driver->driver.name);
  1706. }
  1707. EXPORT_SYMBOL(i2c_del_driver);
  1708. /* ------------------------------------------------------------------------- */
  1709. struct i2c_cmd_arg {
  1710. unsigned cmd;
  1711. void *arg;
  1712. };
  1713. static int i2c_cmd(struct device *dev, void *_arg)
  1714. {
  1715. struct i2c_client *client = i2c_verify_client(dev);
  1716. struct i2c_cmd_arg *arg = _arg;
  1717. struct i2c_driver *driver;
  1718. if (!client || !client->dev.driver)
  1719. return 0;
  1720. driver = to_i2c_driver(client->dev.driver);
  1721. if (driver->command)
  1722. driver->command(client, arg->cmd, arg->arg);
  1723. return 0;
  1724. }
  1725. void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
  1726. {
  1727. struct i2c_cmd_arg cmd_arg;
  1728. cmd_arg.cmd = cmd;
  1729. cmd_arg.arg = arg;
  1730. device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
  1731. }
  1732. EXPORT_SYMBOL(i2c_clients_command);
  1733. static int __init i2c_init(void)
  1734. {
  1735. int retval;
  1736. retval = of_alias_get_highest_id("i2c");
  1737. down_write(&__i2c_board_lock);
  1738. if (retval >= __i2c_first_dynamic_bus_num)
  1739. __i2c_first_dynamic_bus_num = retval + 1;
  1740. up_write(&__i2c_board_lock);
  1741. retval = bus_register(&i2c_bus_type);
  1742. if (retval)
  1743. return retval;
  1744. is_registered = true;
  1745. i2c_debugfs_root = debugfs_create_dir("i2c", NULL);
  1746. retval = i2c_add_driver(&dummy_driver);
  1747. if (retval)
  1748. goto class_err;
  1749. if (IS_ENABLED(CONFIG_OF_DYNAMIC))
  1750. WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
  1751. if (IS_ENABLED(CONFIG_ACPI))
  1752. WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
  1753. return 0;
  1754. class_err:
  1755. is_registered = false;
  1756. bus_unregister(&i2c_bus_type);
  1757. return retval;
  1758. }
  1759. static void __exit i2c_exit(void)
  1760. {
  1761. if (IS_ENABLED(CONFIG_ACPI))
  1762. WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
  1763. if (IS_ENABLED(CONFIG_OF_DYNAMIC))
  1764. WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
  1765. i2c_del_driver(&dummy_driver);
  1766. debugfs_remove_recursive(i2c_debugfs_root);
  1767. bus_unregister(&i2c_bus_type);
  1768. tracepoint_synchronize_unregister();
  1769. }
  1770. /* We must initialize early, because some subsystems register i2c drivers
  1771. * in subsys_initcall() code, but are linked (and initialized) before i2c.
  1772. */
  1773. postcore_initcall(i2c_init);
  1774. module_exit(i2c_exit);
  1775. /* ----------------------------------------------------
  1776. * the functional interface to the i2c busses.
  1777. * ----------------------------------------------------
  1778. */
  1779. /* Check if val is exceeding the quirk IFF quirk is non 0 */
  1780. #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
  1781. static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
  1782. {
  1783. dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
  1784. err_msg, msg->addr, msg->len,
  1785. msg->flags & I2C_M_RD ? "read" : "write");
  1786. return -EOPNOTSUPP;
  1787. }
  1788. static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
  1789. {
  1790. const struct i2c_adapter_quirks *q = adap->quirks;
  1791. int max_num = q->max_num_msgs, i;
  1792. bool do_len_check = true;
  1793. if (q->flags & I2C_AQ_COMB) {
  1794. max_num = 2;
  1795. /* special checks for combined messages */
  1796. if (num == 2) {
  1797. if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
  1798. return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
  1799. if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
  1800. return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
  1801. if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
  1802. return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
  1803. if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
  1804. return i2c_quirk_error(adap, &msgs[0], "msg too long");
  1805. if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
  1806. return i2c_quirk_error(adap, &msgs[1], "msg too long");
  1807. do_len_check = false;
  1808. }
  1809. }
  1810. if (i2c_quirk_exceeded(num, max_num))
  1811. return i2c_quirk_error(adap, &msgs[0], "too many messages");
  1812. for (i = 0; i < num; i++) {
  1813. u16 len = msgs[i].len;
  1814. if (msgs[i].flags & I2C_M_RD) {
  1815. if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
  1816. return i2c_quirk_error(adap, &msgs[i], "msg too long");
  1817. if (q->flags & I2C_AQ_NO_ZERO_LEN_READ && len == 0)
  1818. return i2c_quirk_error(adap, &msgs[i], "no zero length");
  1819. } else {
  1820. if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
  1821. return i2c_quirk_error(adap, &msgs[i], "msg too long");
  1822. if (q->flags & I2C_AQ_NO_ZERO_LEN_WRITE && len == 0)
  1823. return i2c_quirk_error(adap, &msgs[i], "no zero length");
  1824. }
  1825. }
  1826. return 0;
  1827. }
  1828. /**
  1829. * __i2c_transfer - unlocked flavor of i2c_transfer
  1830. * @adap: Handle to I2C bus
  1831. * @msgs: One or more messages to execute before STOP is issued to
  1832. * terminate the operation; each message begins with a START.
  1833. * @num: Number of messages to be executed.
  1834. *
  1835. * Returns negative errno, else the number of messages executed.
  1836. *
  1837. * Adapter lock must be held when calling this function. No debug logging
  1838. * takes place.
  1839. */
  1840. int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
  1841. {
  1842. unsigned long orig_jiffies;
  1843. int ret, try;
  1844. if (!adap->algo->master_xfer) {
  1845. dev_dbg(&adap->dev, "I2C level transfers not supported\n");
  1846. return -EOPNOTSUPP;
  1847. }
  1848. if (WARN_ON(!msgs || num < 1))
  1849. return -EINVAL;
  1850. ret = __i2c_check_suspended(adap);
  1851. if (ret)
  1852. return ret;
  1853. if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
  1854. return -EOPNOTSUPP;
  1855. /*
  1856. * i2c_trace_msg_key gets enabled when tracepoint i2c_transfer gets
  1857. * enabled. This is an efficient way of keeping the for-loop from
  1858. * being executed when not needed.
  1859. */
  1860. if (static_branch_unlikely(&i2c_trace_msg_key)) {
  1861. int i;
  1862. for (i = 0; i < num; i++)
  1863. if (msgs[i].flags & I2C_M_RD)
  1864. trace_i2c_read(adap, &msgs[i], i);
  1865. else
  1866. trace_i2c_write(adap, &msgs[i], i);
  1867. }
  1868. /* Retry automatically on arbitration loss */
  1869. orig_jiffies = jiffies;
  1870. for (ret = 0, try = 0; try <= adap->retries; try++) {
  1871. if (i2c_in_atomic_xfer_mode() && adap->algo->master_xfer_atomic)
  1872. ret = adap->algo->master_xfer_atomic(adap, msgs, num);
  1873. else
  1874. ret = adap->algo->master_xfer(adap, msgs, num);
  1875. if (ret != -EAGAIN)
  1876. break;
  1877. if (time_after(jiffies, orig_jiffies + adap->timeout))
  1878. break;
  1879. }
  1880. if (static_branch_unlikely(&i2c_trace_msg_key)) {
  1881. int i;
  1882. for (i = 0; i < ret; i++)
  1883. if (msgs[i].flags & I2C_M_RD)
  1884. trace_i2c_reply(adap, &msgs[i], i);
  1885. trace_i2c_result(adap, num, ret);
  1886. }
  1887. return ret;
  1888. }
  1889. EXPORT_SYMBOL(__i2c_transfer);
  1890. /**
  1891. * i2c_transfer - execute a single or combined I2C message
  1892. * @adap: Handle to I2C bus
  1893. * @msgs: One or more messages to execute before STOP is issued to
  1894. * terminate the operation; each message begins with a START.
  1895. * @num: Number of messages to be executed.
  1896. *
  1897. * Returns negative errno, else the number of messages executed.
  1898. *
  1899. * Note that there is no requirement that each message be sent to
  1900. * the same slave address, although that is the most common model.
  1901. */
  1902. int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
  1903. {
  1904. int ret;
  1905. /* REVISIT the fault reporting model here is weak:
  1906. *
  1907. * - When we get an error after receiving N bytes from a slave,
  1908. * there is no way to report "N".
  1909. *
  1910. * - When we get a NAK after transmitting N bytes to a slave,
  1911. * there is no way to report "N" ... or to let the master
  1912. * continue executing the rest of this combined message, if
  1913. * that's the appropriate response.
  1914. *
  1915. * - When for example "num" is two and we successfully complete
  1916. * the first message but get an error part way through the
  1917. * second, it's unclear whether that should be reported as
  1918. * one (discarding status on the second message) or errno
  1919. * (discarding status on the first one).
  1920. */
  1921. ret = __i2c_lock_bus_helper(adap);
  1922. if (ret)
  1923. return ret;
  1924. ret = __i2c_transfer(adap, msgs, num);
  1925. i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
  1926. return ret;
  1927. }
  1928. EXPORT_SYMBOL(i2c_transfer);
  1929. /**
  1930. * i2c_transfer_buffer_flags - issue a single I2C message transferring data
  1931. * to/from a buffer
  1932. * @client: Handle to slave device
  1933. * @buf: Where the data is stored
  1934. * @count: How many bytes to transfer, must be less than 64k since msg.len is u16
  1935. * @flags: The flags to be used for the message, e.g. I2C_M_RD for reads
  1936. *
  1937. * Returns negative errno, or else the number of bytes transferred.
  1938. */
  1939. int i2c_transfer_buffer_flags(const struct i2c_client *client, char *buf,
  1940. int count, u16 flags)
  1941. {
  1942. int ret;
  1943. struct i2c_msg msg = {
  1944. .addr = client->addr,
  1945. .flags = flags | (client->flags & I2C_M_TEN),
  1946. .len = count,
  1947. .buf = buf,
  1948. };
  1949. ret = i2c_transfer(client->adapter, &msg, 1);
  1950. /*
  1951. * If everything went ok (i.e. 1 msg transferred), return #bytes
  1952. * transferred, else error code.
  1953. */
  1954. return (ret == 1) ? count : ret;
  1955. }
  1956. EXPORT_SYMBOL(i2c_transfer_buffer_flags);
  1957. /**
  1958. * i2c_get_device_id - get manufacturer, part id and die revision of a device
  1959. * @client: The device to query
  1960. * @id: The queried information
  1961. *
  1962. * Returns negative errno on error, zero on success.
  1963. */
  1964. int i2c_get_device_id(const struct i2c_client *client,
  1965. struct i2c_device_identity *id)
  1966. {
  1967. struct i2c_adapter *adap = client->adapter;
  1968. union i2c_smbus_data raw_id;
  1969. int ret;
  1970. if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
  1971. return -EOPNOTSUPP;
  1972. raw_id.block[0] = 3;
  1973. ret = i2c_smbus_xfer(adap, I2C_ADDR_DEVICE_ID, 0,
  1974. I2C_SMBUS_READ, client->addr << 1,
  1975. I2C_SMBUS_I2C_BLOCK_DATA, &raw_id);
  1976. if (ret)
  1977. return ret;
  1978. id->manufacturer_id = (raw_id.block[1] << 4) | (raw_id.block[2] >> 4);
  1979. id->part_id = ((raw_id.block[2] & 0xf) << 5) | (raw_id.block[3] >> 3);
  1980. id->die_revision = raw_id.block[3] & 0x7;
  1981. return 0;
  1982. }
  1983. EXPORT_SYMBOL_GPL(i2c_get_device_id);
  1984. /**
  1985. * i2c_client_get_device_id - get the driver match table entry of a device
  1986. * @client: the device to query. The device must be bound to a driver
  1987. *
  1988. * Returns a pointer to the matching entry if found, NULL otherwise.
  1989. */
  1990. const struct i2c_device_id *i2c_client_get_device_id(const struct i2c_client *client)
  1991. {
  1992. const struct i2c_driver *drv = to_i2c_driver(client->dev.driver);
  1993. return i2c_match_id(drv->id_table, client);
  1994. }
  1995. EXPORT_SYMBOL_GPL(i2c_client_get_device_id);
  1996. /* ----------------------------------------------------
  1997. * the i2c address scanning function
  1998. * Will not work for 10-bit addresses!
  1999. * ----------------------------------------------------
  2000. */
  2001. /*
  2002. * Legacy default probe function, mostly relevant for SMBus. The default
  2003. * probe method is a quick write, but it is known to corrupt the 24RF08
  2004. * EEPROMs due to a state machine bug, and could also irreversibly
  2005. * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
  2006. * we use a short byte read instead. Also, some bus drivers don't implement
  2007. * quick write, so we fallback to a byte read in that case too.
  2008. * On x86, there is another special case for FSC hardware monitoring chips,
  2009. * which want regular byte reads (address 0x73.) Fortunately, these are the
  2010. * only known chips using this I2C address on PC hardware.
  2011. * Returns 1 if probe succeeded, 0 if not.
  2012. */
  2013. static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
  2014. {
  2015. int err;
  2016. union i2c_smbus_data dummy;
  2017. #ifdef CONFIG_X86
  2018. if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
  2019. && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
  2020. err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
  2021. I2C_SMBUS_BYTE_DATA, &dummy);
  2022. else
  2023. #endif
  2024. if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
  2025. && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
  2026. err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
  2027. I2C_SMBUS_QUICK, NULL);
  2028. else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
  2029. err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
  2030. I2C_SMBUS_BYTE, &dummy);
  2031. else {
  2032. dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
  2033. addr);
  2034. err = -EOPNOTSUPP;
  2035. }
  2036. return err >= 0;
  2037. }
  2038. static int i2c_detect_address(struct i2c_client *temp_client,
  2039. struct i2c_driver *driver)
  2040. {
  2041. struct i2c_board_info info;
  2042. struct i2c_adapter *adapter = temp_client->adapter;
  2043. int addr = temp_client->addr;
  2044. int err;
  2045. /* Make sure the address is valid */
  2046. err = i2c_check_7bit_addr_validity_strict(addr);
  2047. if (err) {
  2048. dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
  2049. addr);
  2050. return err;
  2051. }
  2052. /* Skip if already in use (7 bit, no need to encode flags) */
  2053. if (i2c_check_addr_busy(adapter, addr))
  2054. return 0;
  2055. /* Make sure there is something at this address */
  2056. if (!i2c_default_probe(adapter, addr))
  2057. return 0;
  2058. /* Finally call the custom detection function */
  2059. memset(&info, 0, sizeof(struct i2c_board_info));
  2060. info.addr = addr;
  2061. err = driver->detect(temp_client, &info);
  2062. if (err) {
  2063. /* -ENODEV is returned if the detection fails. We catch it
  2064. here as this isn't an error. */
  2065. return err == -ENODEV ? 0 : err;
  2066. }
  2067. /* Consistency check */
  2068. if (info.type[0] == '\0') {
  2069. dev_err(&adapter->dev,
  2070. "%s detection function provided no name for 0x%x\n",
  2071. driver->driver.name, addr);
  2072. } else {
  2073. struct i2c_client *client;
  2074. /* Detection succeeded, instantiate the device */
  2075. if (adapter->class & I2C_CLASS_DEPRECATED)
  2076. dev_warn(&adapter->dev,
  2077. "This adapter will soon drop class based instantiation of devices. "
  2078. "Please make sure client 0x%02x gets instantiated by other means. "
  2079. "Check 'Documentation/i2c/instantiating-devices.rst' for details.\n",
  2080. info.addr);
  2081. dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
  2082. info.type, info.addr);
  2083. client = i2c_new_client_device(adapter, &info);
  2084. if (!IS_ERR(client))
  2085. list_add_tail(&client->detected, &driver->clients);
  2086. else
  2087. dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
  2088. info.type, info.addr);
  2089. }
  2090. return 0;
  2091. }
  2092. static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
  2093. {
  2094. const unsigned short *address_list;
  2095. struct i2c_client *temp_client;
  2096. int i, err = 0;
  2097. address_list = driver->address_list;
  2098. if (!driver->detect || !address_list)
  2099. return 0;
  2100. /* Warn that the adapter lost class based instantiation */
  2101. if (adapter->class == I2C_CLASS_DEPRECATED) {
  2102. dev_dbg(&adapter->dev,
  2103. "This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
  2104. "If you need it, check 'Documentation/i2c/instantiating-devices.rst' for alternatives.\n",
  2105. driver->driver.name);
  2106. return 0;
  2107. }
  2108. /* Stop here if the classes do not match */
  2109. if (!(adapter->class & driver->class))
  2110. return 0;
  2111. /* Set up a temporary client to help detect callback */
  2112. temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
  2113. if (!temp_client)
  2114. return -ENOMEM;
  2115. temp_client->adapter = adapter;
  2116. for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
  2117. dev_dbg(&adapter->dev,
  2118. "found normal entry for adapter %d, addr 0x%02x\n",
  2119. i2c_adapter_id(adapter), address_list[i]);
  2120. temp_client->addr = address_list[i];
  2121. err = i2c_detect_address(temp_client, driver);
  2122. if (unlikely(err))
  2123. break;
  2124. }
  2125. kfree(temp_client);
  2126. return err;
  2127. }
  2128. int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
  2129. {
  2130. return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
  2131. I2C_SMBUS_QUICK, NULL) >= 0;
  2132. }
  2133. EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
  2134. struct i2c_client *
  2135. i2c_new_scanned_device(struct i2c_adapter *adap,
  2136. struct i2c_board_info *info,
  2137. unsigned short const *addr_list,
  2138. int (*probe)(struct i2c_adapter *adap, unsigned short addr))
  2139. {
  2140. int i;
  2141. if (!probe)
  2142. probe = i2c_default_probe;
  2143. for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
  2144. /* Check address validity */
  2145. if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
  2146. dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
  2147. addr_list[i]);
  2148. continue;
  2149. }
  2150. /* Check address availability (7 bit, no need to encode flags) */
  2151. if (i2c_check_addr_busy(adap, addr_list[i])) {
  2152. dev_dbg(&adap->dev,
  2153. "Address 0x%02x already in use, not probing\n",
  2154. addr_list[i]);
  2155. continue;
  2156. }
  2157. /* Test address responsiveness */
  2158. if (probe(adap, addr_list[i]))
  2159. break;
  2160. }
  2161. if (addr_list[i] == I2C_CLIENT_END) {
  2162. dev_dbg(&adap->dev, "Probing failed, no device found\n");
  2163. return ERR_PTR(-ENODEV);
  2164. }
  2165. info->addr = addr_list[i];
  2166. return i2c_new_client_device(adap, info);
  2167. }
  2168. EXPORT_SYMBOL_GPL(i2c_new_scanned_device);
  2169. struct i2c_adapter *i2c_get_adapter(int nr)
  2170. {
  2171. struct i2c_adapter *adapter;
  2172. mutex_lock(&core_lock);
  2173. adapter = idr_find(&i2c_adapter_idr, nr);
  2174. if (!adapter)
  2175. goto exit;
  2176. if (try_module_get(adapter->owner))
  2177. get_device(&adapter->dev);
  2178. else
  2179. adapter = NULL;
  2180. exit:
  2181. mutex_unlock(&core_lock);
  2182. return adapter;
  2183. }
  2184. EXPORT_SYMBOL(i2c_get_adapter);
  2185. void i2c_put_adapter(struct i2c_adapter *adap)
  2186. {
  2187. if (!adap)
  2188. return;
  2189. module_put(adap->owner);
  2190. /* Should be last, otherwise we risk use-after-free with 'adap' */
  2191. put_device(&adap->dev);
  2192. }
  2193. EXPORT_SYMBOL(i2c_put_adapter);
  2194. /**
  2195. * i2c_get_dma_safe_msg_buf() - get a DMA safe buffer for the given i2c_msg
  2196. * @msg: the message to be checked
  2197. * @threshold: the minimum number of bytes for which using DMA makes sense.
  2198. * Should at least be 1.
  2199. *
  2200. * Return: NULL if a DMA safe buffer was not obtained. Use msg->buf with PIO.
  2201. * Or a valid pointer to be used with DMA. After use, release it by
  2202. * calling i2c_put_dma_safe_msg_buf().
  2203. *
  2204. * This function must only be called from process context!
  2205. */
  2206. u8 *i2c_get_dma_safe_msg_buf(struct i2c_msg *msg, unsigned int threshold)
  2207. {
  2208. /* also skip 0-length msgs for bogus thresholds of 0 */
  2209. if (!threshold)
  2210. pr_debug("DMA buffer for addr=0x%02x with length 0 is bogus\n",
  2211. msg->addr);
  2212. if (msg->len < threshold || msg->len == 0)
  2213. return NULL;
  2214. if (msg->flags & I2C_M_DMA_SAFE)
  2215. return msg->buf;
  2216. pr_debug("using bounce buffer for addr=0x%02x, len=%d\n",
  2217. msg->addr, msg->len);
  2218. if (msg->flags & I2C_M_RD)
  2219. return kzalloc(msg->len, GFP_KERNEL);
  2220. else
  2221. return kmemdup(msg->buf, msg->len, GFP_KERNEL);
  2222. }
  2223. EXPORT_SYMBOL_GPL(i2c_get_dma_safe_msg_buf);
  2224. /**
  2225. * i2c_put_dma_safe_msg_buf - release DMA safe buffer and sync with i2c_msg
  2226. * @buf: the buffer obtained from i2c_get_dma_safe_msg_buf(). May be NULL.
  2227. * @msg: the message which the buffer corresponds to
  2228. * @xferred: bool saying if the message was transferred
  2229. */
  2230. void i2c_put_dma_safe_msg_buf(u8 *buf, struct i2c_msg *msg, bool xferred)
  2231. {
  2232. if (!buf || buf == msg->buf)
  2233. return;
  2234. if (xferred && msg->flags & I2C_M_RD)
  2235. memcpy(msg->buf, buf, msg->len);
  2236. kfree(buf);
  2237. }
  2238. EXPORT_SYMBOL_GPL(i2c_put_dma_safe_msg_buf);
  2239. MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
  2240. MODULE_DESCRIPTION("I2C-Bus main module");
  2241. MODULE_LICENSE("GPL");