i2c-core-base.c 62 KB

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