i2c-core.c 63 KB

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