i2c-core-base.c 63 KB

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