i2c-core-base.c 62 KB

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