i2c-core-base.c 60 KB

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