i2c-core.c 63 KB

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