i2c-core-base.c 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Linux I2C core
  4. *
  5. * Copyright (C) 1995-99 Simon G. Vogl
  6. * With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>
  7. * Mux support by Rodolfo Giometti <giometti@enneenne.com> and
  8. * Michael Lawnick <michael.lawnick.ext@nsn.com>
  9. *
  10. * Copyright (C) 2013-2017 Wolfram Sang <wsa@kernel.org>
  11. */
  12. #define pr_fmt(fmt) "i2c-core: " fmt
  13. #include <dt-bindings/i2c/i2c.h>
  14. #include <linux/acpi.h>
  15. #include <linux/clk/clk-conf.h>
  16. #include <linux/completion.h>
  17. #include <linux/debugfs.h>
  18. #include <linux/delay.h>
  19. #include <linux/err.h>
  20. #include <linux/errno.h>
  21. #include <linux/gpio/consumer.h>
  22. #include <linux/i2c.h>
  23. #include <linux/i2c-smbus.h>
  24. #include <linux/idr.h>
  25. #include <linux/init.h>
  26. #include <linux/interrupt.h>
  27. #include <linux/irq.h>
  28. #include <linux/jump_label.h>
  29. #include <linux/kernel.h>
  30. #include <linux/module.h>
  31. #include <linux/mutex.h>
  32. #include <linux/of_device.h>
  33. #include <linux/of.h>
  34. #include <linux/pinctrl/consumer.h>
  35. #include <linux/pinctrl/devinfo.h>
  36. #include <linux/pm_domain.h>
  37. #include <linux/pm_runtime.h>
  38. #include <linux/pm_wakeirq.h>
  39. #include <linux/property.h>
  40. #include <linux/rwsem.h>
  41. #include <linux/slab.h>
  42. #include <linux/string_choices.h>
  43. #include "i2c-core.h"
  44. #define CREATE_TRACE_POINTS
  45. #include <trace/events/i2c.h>
  46. #define I2C_ADDR_OFFSET_TEN_BIT 0xa000
  47. #define I2C_ADDR_OFFSET_SLAVE 0x1000
  48. #define I2C_ADDR_7BITS_MAX 0x77
  49. #define I2C_ADDR_7BITS_COUNT (I2C_ADDR_7BITS_MAX + 1)
  50. #define I2C_ADDR_DEVICE_ID 0x7c
  51. /*
  52. * core_lock protects i2c_adapter_idr, and guarantees that device detection,
  53. * deletion of detected devices are serialized
  54. */
  55. static DEFINE_MUTEX(core_lock);
  56. static DEFINE_IDR(i2c_adapter_idr);
  57. static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
  58. static DEFINE_STATIC_KEY_FALSE(i2c_trace_msg_key);
  59. static bool is_registered;
  60. static struct dentry *i2c_debugfs_root;
  61. int i2c_transfer_trace_reg(void)
  62. {
  63. static_branch_inc(&i2c_trace_msg_key);
  64. return 0;
  65. }
  66. void i2c_transfer_trace_unreg(void)
  67. {
  68. static_branch_dec(&i2c_trace_msg_key);
  69. }
  70. const char *i2c_freq_mode_string(u32 bus_freq_hz)
  71. {
  72. switch (bus_freq_hz) {
  73. case I2C_MAX_STANDARD_MODE_FREQ:
  74. return "Standard Mode (100 kHz)";
  75. case I2C_MAX_FAST_MODE_FREQ:
  76. return "Fast Mode (400 kHz)";
  77. case I2C_MAX_FAST_MODE_PLUS_FREQ:
  78. return "Fast Mode Plus (1.0 MHz)";
  79. case I2C_MAX_TURBO_MODE_FREQ:
  80. return "Turbo Mode (1.4 MHz)";
  81. case I2C_MAX_HIGH_SPEED_MODE_FREQ:
  82. return "High Speed Mode (3.4 MHz)";
  83. case I2C_MAX_ULTRA_FAST_MODE_FREQ:
  84. return "Ultra Fast Mode (5.0 MHz)";
  85. default:
  86. return "Unknown Mode";
  87. }
  88. }
  89. EXPORT_SYMBOL_GPL(i2c_freq_mode_string);
  90. const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
  91. const struct i2c_client *client)
  92. {
  93. if (!(id && client))
  94. return NULL;
  95. while (id->name[0]) {
  96. if (strcmp(client->name, id->name) == 0)
  97. return id;
  98. id++;
  99. }
  100. return NULL;
  101. }
  102. EXPORT_SYMBOL_GPL(i2c_match_id);
  103. const void *i2c_get_match_data(const struct i2c_client *client)
  104. {
  105. struct i2c_driver *driver = to_i2c_driver(client->dev.driver);
  106. const struct i2c_device_id *match;
  107. const void *data;
  108. data = device_get_match_data(&client->dev);
  109. if (!data) {
  110. match = i2c_match_id(driver->id_table, client);
  111. if (!match)
  112. return NULL;
  113. data = (const void *)match->driver_data;
  114. }
  115. return data;
  116. }
  117. EXPORT_SYMBOL(i2c_get_match_data);
  118. static int i2c_device_match(struct device *dev, const struct device_driver *drv)
  119. {
  120. struct i2c_client *client = i2c_verify_client(dev);
  121. const struct i2c_driver *driver;
  122. /* Attempt an OF style match */
  123. if (i2c_of_match_device(drv->of_match_table, client))
  124. return 1;
  125. /* Then ACPI style match */
  126. if (acpi_driver_match_device(dev, drv))
  127. return 1;
  128. driver = to_i2c_driver(drv);
  129. /* Finally an I2C match */
  130. if (i2c_match_id(driver->id_table, client))
  131. return 1;
  132. return 0;
  133. }
  134. static int i2c_device_uevent(const struct device *dev, struct kobj_uevent_env *env)
  135. {
  136. const struct i2c_client *client = to_i2c_client(dev);
  137. int rc;
  138. rc = of_device_uevent_modalias(dev, env);
  139. if (rc != -ENODEV)
  140. return rc;
  141. rc = acpi_device_uevent_modalias(dev, env);
  142. if (rc != -ENODEV)
  143. return rc;
  144. return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
  145. }
  146. /* i2c bus recovery routines */
  147. static int get_scl_gpio_value(struct i2c_adapter *adap)
  148. {
  149. return gpiod_get_value_cansleep(adap->bus_recovery_info->scl_gpiod);
  150. }
  151. static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
  152. {
  153. gpiod_set_value_cansleep(adap->bus_recovery_info->scl_gpiod, val);
  154. }
  155. static int get_sda_gpio_value(struct i2c_adapter *adap)
  156. {
  157. return gpiod_get_value_cansleep(adap->bus_recovery_info->sda_gpiod);
  158. }
  159. static void set_sda_gpio_value(struct i2c_adapter *adap, int val)
  160. {
  161. gpiod_set_value_cansleep(adap->bus_recovery_info->sda_gpiod, val);
  162. }
  163. static int i2c_generic_bus_free(struct i2c_adapter *adap)
  164. {
  165. struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
  166. int ret = -EOPNOTSUPP;
  167. if (bri->get_bus_free)
  168. ret = bri->get_bus_free(adap);
  169. else if (bri->get_sda)
  170. ret = bri->get_sda(adap);
  171. if (ret < 0)
  172. return ret;
  173. return ret ? 0 : -EBUSY;
  174. }
  175. /*
  176. * We are generating clock pulses. ndelay() determines durating of clk pulses.
  177. * We will generate clock with rate 100 KHz and so duration of both clock levels
  178. * is: delay in ns = (10^6 / 100) / 2
  179. */
  180. #define RECOVERY_NDELAY 5000
  181. #define RECOVERY_CLK_CNT 9
  182. int i2c_generic_scl_recovery(struct i2c_adapter *adap)
  183. {
  184. struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
  185. int i = 0, scl = 1, ret = 0;
  186. if (bri->prepare_recovery)
  187. bri->prepare_recovery(adap);
  188. if (bri->pinctrl)
  189. pinctrl_select_state(bri->pinctrl, bri->pins_gpio);
  190. /*
  191. * If we can set SDA, we will always create a STOP to ensure additional
  192. * pulses will do no harm. This is achieved by letting SDA follow SCL
  193. * half a cycle later. Check the 'incomplete_write_byte' fault injector
  194. * for details. Note that we must honour tsu:sto, 4us, but lets use 5us
  195. * here for simplicity.
  196. */
  197. bri->set_scl(adap, scl);
  198. ndelay(RECOVERY_NDELAY);
  199. if (bri->set_sda)
  200. bri->set_sda(adap, scl);
  201. ndelay(RECOVERY_NDELAY / 2);
  202. /*
  203. * By this time SCL is high, as we need to give 9 falling-rising edges
  204. */
  205. while (i++ < RECOVERY_CLK_CNT * 2) {
  206. if (scl) {
  207. /* SCL shouldn't be low here */
  208. if (!bri->get_scl(adap)) {
  209. dev_err(&adap->dev,
  210. "SCL is stuck low, exit recovery\n");
  211. ret = -EBUSY;
  212. break;
  213. }
  214. }
  215. scl = !scl;
  216. bri->set_scl(adap, scl);
  217. /* Creating STOP again, see above */
  218. if (scl) {
  219. /* Honour minimum tsu:sto */
  220. ndelay(RECOVERY_NDELAY);
  221. } else {
  222. /* Honour minimum tf and thd:dat */
  223. ndelay(RECOVERY_NDELAY / 2);
  224. }
  225. if (bri->set_sda)
  226. bri->set_sda(adap, scl);
  227. ndelay(RECOVERY_NDELAY / 2);
  228. if (scl) {
  229. ret = i2c_generic_bus_free(adap);
  230. if (ret == 0)
  231. break;
  232. }
  233. }
  234. /* If we can't check bus status, assume recovery worked */
  235. if (ret == -EOPNOTSUPP)
  236. ret = 0;
  237. if (bri->unprepare_recovery)
  238. bri->unprepare_recovery(adap);
  239. if (bri->pinctrl)
  240. pinctrl_select_state(bri->pinctrl, bri->pins_default);
  241. return ret;
  242. }
  243. EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
  244. int i2c_recover_bus(struct i2c_adapter *adap)
  245. {
  246. if (!adap->bus_recovery_info)
  247. return -EBUSY;
  248. dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
  249. return adap->bus_recovery_info->recover_bus(adap);
  250. }
  251. EXPORT_SYMBOL_GPL(i2c_recover_bus);
  252. static void i2c_gpio_init_pinctrl_recovery(struct i2c_adapter *adap)
  253. {
  254. struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
  255. struct device *dev = &adap->dev;
  256. struct pinctrl *p = bri->pinctrl ?: dev_pinctrl(dev->parent);
  257. bri->pinctrl = p;
  258. /*
  259. * we can't change states without pinctrl, so remove the states if
  260. * populated
  261. */
  262. if (!p) {
  263. bri->pins_default = NULL;
  264. bri->pins_gpio = NULL;
  265. return;
  266. }
  267. if (!bri->pins_default) {
  268. bri->pins_default = pinctrl_lookup_state(p,
  269. PINCTRL_STATE_DEFAULT);
  270. if (IS_ERR(bri->pins_default)) {
  271. dev_dbg(dev, PINCTRL_STATE_DEFAULT " state not found for GPIO recovery\n");
  272. bri->pins_default = NULL;
  273. }
  274. }
  275. if (!bri->pins_gpio) {
  276. bri->pins_gpio = pinctrl_lookup_state(p, "gpio");
  277. if (IS_ERR(bri->pins_gpio))
  278. bri->pins_gpio = pinctrl_lookup_state(p, "recovery");
  279. if (IS_ERR(bri->pins_gpio)) {
  280. dev_dbg(dev, "no gpio or recovery state found for GPIO recovery\n");
  281. bri->pins_gpio = NULL;
  282. }
  283. }
  284. /* for pinctrl state changes, we need all the information */
  285. if (bri->pins_default && bri->pins_gpio) {
  286. dev_info(dev, "using pinctrl states for GPIO recovery");
  287. } else {
  288. bri->pinctrl = NULL;
  289. bri->pins_default = NULL;
  290. bri->pins_gpio = NULL;
  291. }
  292. }
  293. static int i2c_gpio_init_generic_recovery(struct i2c_adapter *adap)
  294. {
  295. struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
  296. struct device *dev = &adap->dev;
  297. struct gpio_desc *gpiod;
  298. int ret = 0;
  299. /*
  300. * don't touch the recovery information if the driver is not using
  301. * generic SCL recovery
  302. */
  303. if (bri->recover_bus && bri->recover_bus != i2c_generic_scl_recovery)
  304. return 0;
  305. /*
  306. * pins might be taken as GPIO, so we should inform pinctrl about
  307. * this and move the state to GPIO
  308. */
  309. if (bri->pinctrl)
  310. pinctrl_select_state(bri->pinctrl, bri->pins_gpio);
  311. /*
  312. * if there is incomplete or no recovery information, see if generic
  313. * GPIO recovery is available
  314. */
  315. if (!bri->scl_gpiod) {
  316. gpiod = devm_gpiod_get(dev, "scl", GPIOD_OUT_HIGH_OPEN_DRAIN);
  317. if (PTR_ERR(gpiod) == -EPROBE_DEFER) {
  318. ret = -EPROBE_DEFER;
  319. goto cleanup_pinctrl_state;
  320. }
  321. if (!IS_ERR(gpiod)) {
  322. bri->scl_gpiod = gpiod;
  323. bri->recover_bus = i2c_generic_scl_recovery;
  324. dev_info(dev, "using generic GPIOs for recovery\n");
  325. }
  326. }
  327. /* SDA GPIOD line is optional, so we care about DEFER only */
  328. if (!bri->sda_gpiod) {
  329. /*
  330. * We have SCL. Pull SCL low and wait a bit so that SDA glitches
  331. * have no effect.
  332. */
  333. gpiod_direction_output(bri->scl_gpiod, 0);
  334. udelay(10);
  335. gpiod = devm_gpiod_get(dev, "sda", GPIOD_IN);
  336. /* Wait a bit in case of a SDA glitch, and then release SCL. */
  337. udelay(10);
  338. gpiod_direction_output(bri->scl_gpiod, 1);
  339. if (PTR_ERR(gpiod) == -EPROBE_DEFER) {
  340. ret = -EPROBE_DEFER;
  341. goto cleanup_pinctrl_state;
  342. }
  343. if (!IS_ERR(gpiod))
  344. bri->sda_gpiod = gpiod;
  345. }
  346. cleanup_pinctrl_state:
  347. /* change the state of the pins back to their default state */
  348. if (bri->pinctrl)
  349. pinctrl_select_state(bri->pinctrl, bri->pins_default);
  350. return ret;
  351. }
  352. static int i2c_gpio_init_recovery(struct i2c_adapter *adap)
  353. {
  354. i2c_gpio_init_pinctrl_recovery(adap);
  355. return i2c_gpio_init_generic_recovery(adap);
  356. }
  357. static int i2c_init_recovery(struct i2c_adapter *adap)
  358. {
  359. struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
  360. bool is_error_level = true;
  361. char *err_str;
  362. if (!bri)
  363. return 0;
  364. if (i2c_gpio_init_recovery(adap) == -EPROBE_DEFER)
  365. return -EPROBE_DEFER;
  366. if (!bri->recover_bus) {
  367. err_str = "no suitable method provided";
  368. is_error_level = false;
  369. goto err;
  370. }
  371. if (bri->scl_gpiod && bri->recover_bus == i2c_generic_scl_recovery) {
  372. bri->get_scl = get_scl_gpio_value;
  373. bri->set_scl = set_scl_gpio_value;
  374. if (bri->sda_gpiod) {
  375. bri->get_sda = get_sda_gpio_value;
  376. /* FIXME: add proper flag instead of '0' once available */
  377. if (gpiod_get_direction(bri->sda_gpiod) == 0)
  378. bri->set_sda = set_sda_gpio_value;
  379. }
  380. } else if (bri->recover_bus == i2c_generic_scl_recovery) {
  381. /* Generic SCL recovery */
  382. if (!bri->set_scl || !bri->get_scl) {
  383. err_str = "no {get|set}_scl() found";
  384. goto err;
  385. }
  386. if (!bri->set_sda && !bri->get_sda) {
  387. err_str = "either get_sda() or set_sda() needed";
  388. goto err;
  389. }
  390. }
  391. return 0;
  392. err:
  393. if (is_error_level)
  394. dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
  395. else
  396. dev_dbg(&adap->dev, "Not using recovery: %s\n", err_str);
  397. adap->bus_recovery_info = NULL;
  398. return -EINVAL;
  399. }
  400. static int i2c_smbus_host_notify_to_irq(const struct i2c_client *client)
  401. {
  402. struct i2c_adapter *adap = client->adapter;
  403. unsigned int irq;
  404. if (!adap->host_notify_domain)
  405. return -ENXIO;
  406. if (client->flags & I2C_CLIENT_TEN)
  407. return -EINVAL;
  408. irq = irq_create_mapping(adap->host_notify_domain, client->addr);
  409. return irq > 0 ? irq : -ENXIO;
  410. }
  411. static int i2c_device_probe(struct device *dev)
  412. {
  413. struct fwnode_handle *fwnode = dev_fwnode(dev);
  414. struct i2c_client *client = i2c_verify_client(dev);
  415. struct i2c_driver *driver;
  416. bool do_power_on;
  417. int status;
  418. if (!client)
  419. return 0;
  420. client->irq = client->init_irq;
  421. if (!client->irq) {
  422. int irq = -ENOENT;
  423. if (client->flags & I2C_CLIENT_HOST_NOTIFY) {
  424. dev_dbg(dev, "Using Host Notify IRQ\n");
  425. /* Keep adapter active when Host Notify is required */
  426. pm_runtime_get_sync(&client->adapter->dev);
  427. irq = i2c_smbus_host_notify_to_irq(client);
  428. } else if (is_of_node(fwnode)) {
  429. irq = fwnode_irq_get_byname(fwnode, "irq");
  430. if (irq == -EINVAL || irq == -ENODATA)
  431. irq = fwnode_irq_get(fwnode, 0);
  432. } else if (is_acpi_device_node(fwnode)) {
  433. bool wake_capable;
  434. irq = i2c_acpi_get_irq(client, &wake_capable);
  435. if (irq > 0 && wake_capable)
  436. client->flags |= I2C_CLIENT_WAKE;
  437. }
  438. if (irq == -EPROBE_DEFER) {
  439. status = dev_err_probe(dev, irq, "can't get irq\n");
  440. goto put_sync_adapter;
  441. }
  442. if (irq < 0)
  443. irq = 0;
  444. client->irq = irq;
  445. }
  446. driver = to_i2c_driver(dev->driver);
  447. /*
  448. * An I2C ID table is not mandatory, if and only if, a suitable OF
  449. * or ACPI ID table is supplied for the probing device.
  450. */
  451. if (!driver->id_table &&
  452. !acpi_driver_match_device(dev, dev->driver) &&
  453. !i2c_of_match_device(dev->driver->of_match_table, client)) {
  454. status = -ENODEV;
  455. goto put_sync_adapter;
  456. }
  457. if (client->flags & I2C_CLIENT_WAKE) {
  458. int wakeirq;
  459. wakeirq = fwnode_irq_get_byname(fwnode, "wakeup");
  460. if (wakeirq == -EPROBE_DEFER) {
  461. status = dev_err_probe(dev, wakeirq, "can't get wakeirq\n");
  462. goto put_sync_adapter;
  463. }
  464. device_init_wakeup(&client->dev, true);
  465. if (wakeirq > 0 && wakeirq != client->irq)
  466. status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
  467. else if (client->irq > 0)
  468. status = dev_pm_set_wake_irq(dev, client->irq);
  469. else
  470. status = 0;
  471. if (status)
  472. dev_warn(&client->dev, "failed to set up wakeup irq\n");
  473. }
  474. dev_dbg(dev, "probe\n");
  475. status = of_clk_set_defaults(to_of_node(fwnode), false);
  476. if (status < 0)
  477. goto err_clear_wakeup_irq;
  478. do_power_on = !i2c_acpi_waive_d0_probe(dev);
  479. status = dev_pm_domain_attach(&client->dev, PD_FLAG_DETACH_POWER_OFF |
  480. (do_power_on ? PD_FLAG_ATTACH_POWER_ON : 0));
  481. if (status)
  482. goto err_clear_wakeup_irq;
  483. client->devres_group_id = devres_open_group(&client->dev, NULL,
  484. GFP_KERNEL);
  485. if (!client->devres_group_id) {
  486. status = -ENOMEM;
  487. goto err_clear_wakeup_irq;
  488. }
  489. client->debugfs = debugfs_create_dir(dev_name(&client->dev),
  490. client->adapter->debugfs);
  491. if (driver->probe)
  492. status = driver->probe(client);
  493. else
  494. status = -EINVAL;
  495. /*
  496. * Note that we are not closing the devres group opened above so
  497. * even resources that were attached to the device after probe is
  498. * run are released when i2c_device_remove() is executed. This is
  499. * needed as some drivers would allocate additional resources,
  500. * for example when updating firmware.
  501. */
  502. if (status)
  503. goto err_release_driver_resources;
  504. return 0;
  505. err_release_driver_resources:
  506. debugfs_remove_recursive(client->debugfs);
  507. devres_release_group(&client->dev, client->devres_group_id);
  508. err_clear_wakeup_irq:
  509. dev_pm_clear_wake_irq(&client->dev);
  510. device_init_wakeup(&client->dev, false);
  511. put_sync_adapter:
  512. if (client->flags & I2C_CLIENT_HOST_NOTIFY)
  513. pm_runtime_put_sync(&client->adapter->dev);
  514. return status;
  515. }
  516. static void i2c_device_remove(struct device *dev)
  517. {
  518. struct i2c_client *client = to_i2c_client(dev);
  519. struct i2c_driver *driver;
  520. driver = to_i2c_driver(dev->driver);
  521. if (driver->remove) {
  522. dev_dbg(dev, "remove\n");
  523. driver->remove(client);
  524. }
  525. debugfs_remove_recursive(client->debugfs);
  526. devres_release_group(&client->dev, client->devres_group_id);
  527. dev_pm_clear_wake_irq(&client->dev);
  528. device_init_wakeup(&client->dev, false);
  529. client->irq = 0;
  530. if (client->flags & I2C_CLIENT_HOST_NOTIFY)
  531. pm_runtime_put(&client->adapter->dev);
  532. }
  533. static void i2c_device_shutdown(struct device *dev)
  534. {
  535. struct i2c_client *client = i2c_verify_client(dev);
  536. struct i2c_driver *driver;
  537. if (!client || !dev->driver)
  538. return;
  539. driver = to_i2c_driver(dev->driver);
  540. if (driver->shutdown)
  541. driver->shutdown(client);
  542. else if (client->irq > 0)
  543. disable_irq(client->irq);
  544. }
  545. static void i2c_client_dev_release(struct device *dev)
  546. {
  547. kfree(to_i2c_client(dev));
  548. }
  549. static ssize_t
  550. name_show(struct device *dev, struct device_attribute *attr, char *buf)
  551. {
  552. return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
  553. to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
  554. }
  555. static DEVICE_ATTR_RO(name);
  556. static ssize_t
  557. modalias_show(struct device *dev, struct device_attribute *attr, char *buf)
  558. {
  559. struct i2c_client *client = to_i2c_client(dev);
  560. int len;
  561. len = of_device_modalias(dev, buf, PAGE_SIZE);
  562. if (len != -ENODEV)
  563. return len;
  564. len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
  565. if (len != -ENODEV)
  566. return len;
  567. return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
  568. }
  569. static DEVICE_ATTR_RO(modalias);
  570. static struct attribute *i2c_dev_attrs[] = {
  571. &dev_attr_name.attr,
  572. /* modalias helps coldplug: modprobe $(cat .../modalias) */
  573. &dev_attr_modalias.attr,
  574. NULL
  575. };
  576. ATTRIBUTE_GROUPS(i2c_dev);
  577. const struct bus_type i2c_bus_type = {
  578. .name = "i2c",
  579. .match = i2c_device_match,
  580. .probe = i2c_device_probe,
  581. .remove = i2c_device_remove,
  582. .shutdown = i2c_device_shutdown,
  583. };
  584. EXPORT_SYMBOL_GPL(i2c_bus_type);
  585. const struct device_type i2c_client_type = {
  586. .groups = i2c_dev_groups,
  587. .uevent = i2c_device_uevent,
  588. .release = i2c_client_dev_release,
  589. };
  590. EXPORT_SYMBOL_GPL(i2c_client_type);
  591. /**
  592. * i2c_verify_client - return parameter as i2c_client, or NULL
  593. * @dev: device, probably from some driver model iterator
  594. *
  595. * When traversing the driver model tree, perhaps using driver model
  596. * iterators like @device_for_each_child(), you can't assume very much
  597. * about the nodes you find. Use this function to avoid oopses caused
  598. * by wrongly treating some non-I2C device as an i2c_client.
  599. */
  600. struct i2c_client *i2c_verify_client(struct device *dev)
  601. {
  602. return (dev->type == &i2c_client_type)
  603. ? to_i2c_client(dev)
  604. : NULL;
  605. }
  606. EXPORT_SYMBOL(i2c_verify_client);
  607. /* Return a unique address which takes the flags of the client into account */
  608. static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
  609. {
  610. unsigned short addr = client->addr;
  611. /* For some client flags, add an arbitrary offset to avoid collisions */
  612. if (client->flags & I2C_CLIENT_TEN)
  613. addr |= I2C_ADDR_OFFSET_TEN_BIT;
  614. if (client->flags & I2C_CLIENT_SLAVE)
  615. addr |= I2C_ADDR_OFFSET_SLAVE;
  616. return addr;
  617. }
  618. /* This is a permissive address validity check, I2C address map constraints
  619. * are purposely not enforced, except for the general call address. */
  620. static int i2c_check_addr_validity(unsigned int addr, unsigned short flags)
  621. {
  622. if (flags & I2C_CLIENT_TEN) {
  623. /* 10-bit address, all values are valid */
  624. if (addr > 0x3ff)
  625. return -EINVAL;
  626. } else {
  627. /* 7-bit address, reject the general call address */
  628. if (addr == 0x00 || addr > 0x7f)
  629. return -EINVAL;
  630. }
  631. return 0;
  632. }
  633. /* And this is a strict address validity check, used when probing. If a
  634. * device uses a reserved address, then it shouldn't be probed. 7-bit
  635. * addressing is assumed, 10-bit address devices are rare and should be
  636. * explicitly enumerated. */
  637. int i2c_check_7bit_addr_validity_strict(unsigned short addr)
  638. {
  639. /*
  640. * Reserved addresses per I2C specification:
  641. * 0x00 General call address / START byte
  642. * 0x01 CBUS address
  643. * 0x02 Reserved for different bus format
  644. * 0x03 Reserved for future purposes
  645. * 0x04-0x07 Hs-mode master code
  646. * 0x78-0x7b 10-bit slave addressing
  647. * 0x7c-0x7f Reserved for future purposes
  648. */
  649. if (addr < 0x08 || addr > 0x77)
  650. return -EINVAL;
  651. return 0;
  652. }
  653. static int __i2c_check_addr_busy(struct device *dev, void *addrp)
  654. {
  655. struct i2c_client *client = i2c_verify_client(dev);
  656. int addr = *(int *)addrp;
  657. if (client && i2c_encode_flags_to_addr(client) == addr)
  658. return -EBUSY;
  659. return 0;
  660. }
  661. /* walk up mux tree */
  662. static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
  663. {
  664. struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
  665. int result;
  666. result = device_for_each_child(&adapter->dev, &addr,
  667. __i2c_check_addr_busy);
  668. if (!result && parent)
  669. result = i2c_check_mux_parents(parent, addr);
  670. return result;
  671. }
  672. /* recurse down mux tree */
  673. static int i2c_check_mux_children(struct device *dev, void *addrp)
  674. {
  675. int result;
  676. if (dev->type == &i2c_adapter_type)
  677. result = device_for_each_child(dev, addrp,
  678. i2c_check_mux_children);
  679. else
  680. result = __i2c_check_addr_busy(dev, addrp);
  681. return result;
  682. }
  683. static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
  684. {
  685. struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
  686. int result = 0;
  687. if (parent)
  688. result = i2c_check_mux_parents(parent, addr);
  689. if (!result)
  690. result = device_for_each_child(&adapter->dev, &addr,
  691. i2c_check_mux_children);
  692. return result;
  693. }
  694. /**
  695. * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
  696. * @adapter: Target I2C bus segment
  697. * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
  698. * locks only this branch in the adapter tree
  699. */
  700. static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
  701. unsigned int flags)
  702. {
  703. rt_mutex_lock_nested(&adapter->bus_lock, i2c_adapter_depth(adapter));
  704. }
  705. /**
  706. * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
  707. * @adapter: Target I2C bus segment
  708. * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
  709. * trylocks only this branch in the adapter tree
  710. */
  711. static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
  712. unsigned int flags)
  713. {
  714. return rt_mutex_trylock(&adapter->bus_lock);
  715. }
  716. /**
  717. * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
  718. * @adapter: Target I2C bus segment
  719. * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
  720. * unlocks only this branch in the adapter tree
  721. */
  722. static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
  723. unsigned int flags)
  724. {
  725. rt_mutex_unlock(&adapter->bus_lock);
  726. }
  727. static void i2c_dev_set_name(struct i2c_adapter *adap,
  728. struct i2c_client *client,
  729. struct i2c_board_info const *info)
  730. {
  731. struct acpi_device *adev = ACPI_COMPANION(&client->dev);
  732. if (info && info->dev_name) {
  733. dev_set_name(&client->dev, "i2c-%s", info->dev_name);
  734. return;
  735. }
  736. if (adev) {
  737. dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
  738. return;
  739. }
  740. dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
  741. i2c_encode_flags_to_addr(client));
  742. }
  743. int i2c_dev_irq_from_resources(const struct resource *resources,
  744. unsigned int num_resources)
  745. {
  746. struct irq_data *irqd;
  747. int i;
  748. for (i = 0; i < num_resources; i++) {
  749. const struct resource *r = &resources[i];
  750. if (resource_type(r) != IORESOURCE_IRQ)
  751. continue;
  752. if (r->flags & IORESOURCE_BITS) {
  753. irqd = irq_get_irq_data(r->start);
  754. if (!irqd)
  755. break;
  756. irqd_set_trigger_type(irqd, r->flags & IORESOURCE_BITS);
  757. }
  758. return r->start;
  759. }
  760. return 0;
  761. }
  762. /*
  763. * Serialize device instantiation in case it can be instantiated explicitly
  764. * and by auto-detection
  765. */
  766. static int i2c_lock_addr(struct i2c_adapter *adap, unsigned short addr,
  767. unsigned short flags)
  768. {
  769. if (!(flags & I2C_CLIENT_TEN) &&
  770. test_and_set_bit(addr, adap->addrs_in_instantiation))
  771. return -EBUSY;
  772. return 0;
  773. }
  774. static void i2c_unlock_addr(struct i2c_adapter *adap, unsigned short addr,
  775. unsigned short flags)
  776. {
  777. if (!(flags & I2C_CLIENT_TEN))
  778. clear_bit(addr, adap->addrs_in_instantiation);
  779. }
  780. /**
  781. * i2c_new_client_device - instantiate an i2c device
  782. * @adap: the adapter managing the device
  783. * @info: describes one I2C device; bus_num is ignored
  784. * Context: can sleep
  785. *
  786. * Create an i2c device. Binding is handled through driver model
  787. * probe()/remove() methods. A driver may be bound to this device when we
  788. * return from this function, or any later moment (e.g. maybe hotplugging will
  789. * load the driver module). This call is not appropriate for use by mainboard
  790. * initialization logic, which usually runs during an arch_initcall() long
  791. * before any i2c_adapter could exist.
  792. *
  793. * This returns the new i2c client, which may be saved for later use with
  794. * i2c_unregister_device(); or an ERR_PTR to describe the error.
  795. */
  796. struct i2c_client *
  797. i2c_new_client_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
  798. {
  799. struct fwnode_handle *fwnode = info->fwnode;
  800. struct i2c_client *client;
  801. bool need_put = false;
  802. int status;
  803. client = kzalloc_obj(*client);
  804. if (!client)
  805. return ERR_PTR(-ENOMEM);
  806. client->adapter = adap;
  807. client->dev.platform_data = info->platform_data;
  808. client->flags = info->flags;
  809. client->addr = info->addr;
  810. client->init_irq = info->irq;
  811. if (!client->init_irq)
  812. client->init_irq = i2c_dev_irq_from_resources(info->resources,
  813. info->num_resources);
  814. strscpy(client->name, info->type, sizeof(client->name));
  815. status = i2c_check_addr_validity(client->addr, client->flags);
  816. if (status) {
  817. dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
  818. client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
  819. goto out_err_silent;
  820. }
  821. status = i2c_lock_addr(adap, client->addr, client->flags);
  822. if (status)
  823. goto out_err_silent;
  824. /* Check for address business */
  825. status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
  826. if (status)
  827. goto out_err;
  828. client->dev.parent = &client->adapter->dev;
  829. client->dev.bus = &i2c_bus_type;
  830. client->dev.type = &i2c_client_type;
  831. device_enable_async_suspend(&client->dev);
  832. device_set_node(&client->dev, fwnode_handle_get(fwnode));
  833. if (info->swnode) {
  834. status = device_add_software_node(&client->dev, info->swnode);
  835. if (status) {
  836. dev_err(&adap->dev,
  837. "Failed to add software node to client %s: %d\n",
  838. client->name, status);
  839. goto out_err_put_fwnode;
  840. }
  841. }
  842. i2c_dev_set_name(adap, client, info);
  843. status = device_register(&client->dev);
  844. if (status)
  845. goto out_remove_swnode;
  846. dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
  847. client->name, dev_name(&client->dev));
  848. i2c_unlock_addr(adap, client->addr, client->flags);
  849. return client;
  850. out_remove_swnode:
  851. device_remove_software_node(&client->dev);
  852. need_put = true;
  853. out_err_put_fwnode:
  854. fwnode_handle_put(fwnode);
  855. out_err:
  856. dev_err(&adap->dev,
  857. "Failed to register i2c client %s at 0x%02x (%d)\n",
  858. client->name, client->addr, status);
  859. i2c_unlock_addr(adap, client->addr, client->flags);
  860. out_err_silent:
  861. if (need_put)
  862. put_device(&client->dev);
  863. else
  864. kfree(client);
  865. return ERR_PTR(status);
  866. }
  867. EXPORT_SYMBOL_GPL(i2c_new_client_device);
  868. /**
  869. * i2c_unregister_device - reverse effect of i2c_new_*_device()
  870. * @client: value returned from i2c_new_*_device()
  871. * Context: can sleep
  872. */
  873. void i2c_unregister_device(struct i2c_client *client)
  874. {
  875. struct fwnode_handle *fwnode;
  876. if (IS_ERR_OR_NULL(client))
  877. return;
  878. fwnode = dev_fwnode(&client->dev);
  879. if (is_of_node(fwnode))
  880. of_node_clear_flag(to_of_node(fwnode), OF_POPULATED);
  881. else if (is_acpi_device_node(fwnode))
  882. acpi_device_clear_enumerated(to_acpi_device_node(fwnode));
  883. /*
  884. * If the primary fwnode is a software node it is free-ed by
  885. * device_remove_software_node() below, avoid double-free.
  886. */
  887. if (!is_software_node(fwnode))
  888. fwnode_handle_put(fwnode);
  889. device_remove_software_node(&client->dev);
  890. device_unregister(&client->dev);
  891. }
  892. EXPORT_SYMBOL_GPL(i2c_unregister_device);
  893. /**
  894. * i2c_find_device_by_fwnode() - find an i2c_client for the fwnode
  895. * @fwnode: &struct fwnode_handle corresponding to the &struct i2c_client
  896. *
  897. * Look up and return the &struct i2c_client corresponding to the @fwnode.
  898. * If no client can be found, or @fwnode is NULL, this returns NULL.
  899. *
  900. * The user must call put_device(&client->dev) once done with the i2c client.
  901. */
  902. struct i2c_client *i2c_find_device_by_fwnode(struct fwnode_handle *fwnode)
  903. {
  904. struct i2c_client *client;
  905. struct device *dev;
  906. if (IS_ERR_OR_NULL(fwnode))
  907. return NULL;
  908. dev = bus_find_device_by_fwnode(&i2c_bus_type, fwnode);
  909. if (!dev)
  910. return NULL;
  911. client = i2c_verify_client(dev);
  912. if (!client)
  913. put_device(dev);
  914. return client;
  915. }
  916. EXPORT_SYMBOL(i2c_find_device_by_fwnode);
  917. static const struct i2c_device_id dummy_id[] = {
  918. { "dummy", },
  919. { "smbus_host_notify", },
  920. { }
  921. };
  922. static int dummy_probe(struct i2c_client *client)
  923. {
  924. return 0;
  925. }
  926. static struct i2c_driver dummy_driver = {
  927. .driver.name = "dummy",
  928. .probe = dummy_probe,
  929. .id_table = dummy_id,
  930. };
  931. /**
  932. * i2c_new_dummy_device - return a new i2c device bound to a dummy driver
  933. * @adapter: the adapter managing the device
  934. * @address: seven bit address to be used
  935. * Context: can sleep
  936. *
  937. * This returns an I2C client bound to the "dummy" driver, intended for use
  938. * with devices that consume multiple addresses. Examples of such chips
  939. * include various EEPROMS (like 24c04 and 24c08 models).
  940. *
  941. * These dummy devices have two main uses. First, most I2C and SMBus calls
  942. * except i2c_transfer() need a client handle; the dummy will be that handle.
  943. * And second, this prevents the specified address from being bound to a
  944. * different driver.
  945. *
  946. * This returns the new i2c client, which should be saved for later use with
  947. * i2c_unregister_device(); or an ERR_PTR to describe the error.
  948. */
  949. struct i2c_client *i2c_new_dummy_device(struct i2c_adapter *adapter, u16 address)
  950. {
  951. struct i2c_board_info info = {
  952. I2C_BOARD_INFO("dummy", address),
  953. };
  954. return i2c_new_client_device(adapter, &info);
  955. }
  956. EXPORT_SYMBOL_GPL(i2c_new_dummy_device);
  957. static void devm_i2c_release_dummy(void *client)
  958. {
  959. i2c_unregister_device(client);
  960. }
  961. /**
  962. * devm_i2c_new_dummy_device - return a new i2c device bound to a dummy driver
  963. * @dev: device the managed resource is bound to
  964. * @adapter: the adapter managing the device
  965. * @address: seven bit address to be used
  966. * Context: can sleep
  967. *
  968. * This is the device-managed version of @i2c_new_dummy_device. It returns the
  969. * new i2c client or an ERR_PTR in case of an error.
  970. */
  971. struct i2c_client *devm_i2c_new_dummy_device(struct device *dev,
  972. struct i2c_adapter *adapter,
  973. u16 address)
  974. {
  975. struct i2c_client *client;
  976. int ret;
  977. client = i2c_new_dummy_device(adapter, address);
  978. if (IS_ERR(client))
  979. return client;
  980. ret = devm_add_action_or_reset(dev, devm_i2c_release_dummy, client);
  981. if (ret)
  982. return ERR_PTR(ret);
  983. return client;
  984. }
  985. EXPORT_SYMBOL_GPL(devm_i2c_new_dummy_device);
  986. /**
  987. * i2c_new_ancillary_device - Helper to get the instantiated secondary address
  988. * and create the associated device
  989. * @client: Handle to the primary client
  990. * @name: Handle to specify which secondary address to get
  991. * @default_addr: Used as a fallback if no secondary address was specified
  992. * Context: can sleep
  993. *
  994. * I2C clients can be composed of multiple I2C slaves bound together in a single
  995. * component. The I2C client driver then binds to the master I2C slave and needs
  996. * to create I2C dummy clients to communicate with all the other slaves.
  997. *
  998. * This function creates and returns an I2C dummy client whose I2C address is
  999. * retrieved from the platform firmware based on the given slave name. If no
  1000. * address is specified by the firmware default_addr is used.
  1001. *
  1002. * On DT-based platforms the address is retrieved from the "reg" property entry
  1003. * cell whose "reg-names" value matches the slave name.
  1004. *
  1005. * This returns the new i2c client, which should be saved for later use with
  1006. * i2c_unregister_device(); or an ERR_PTR to describe the error.
  1007. */
  1008. struct i2c_client *i2c_new_ancillary_device(struct i2c_client *client,
  1009. const char *name,
  1010. u16 default_addr)
  1011. {
  1012. struct device_node *np = client->dev.of_node;
  1013. u32 addr = default_addr;
  1014. int i;
  1015. i = of_property_match_string(np, "reg-names", name);
  1016. if (i >= 0)
  1017. of_property_read_u32_index(np, "reg", i, &addr);
  1018. dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
  1019. return i2c_new_dummy_device(client->adapter, addr);
  1020. }
  1021. EXPORT_SYMBOL_GPL(i2c_new_ancillary_device);
  1022. /* ------------------------------------------------------------------------- */
  1023. /* I2C bus adapters -- one roots each I2C or SMBUS segment */
  1024. static void i2c_adapter_dev_release(struct device *dev)
  1025. {
  1026. struct i2c_adapter *adap = to_i2c_adapter(dev);
  1027. complete(&adap->dev_released);
  1028. }
  1029. unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
  1030. {
  1031. unsigned int depth = 0;
  1032. struct device *parent;
  1033. for (parent = adapter->dev.parent; parent; parent = parent->parent)
  1034. if (parent->type == &i2c_adapter_type)
  1035. depth++;
  1036. WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
  1037. "adapter depth exceeds lockdep subclass limit\n");
  1038. return depth;
  1039. }
  1040. EXPORT_SYMBOL_GPL(i2c_adapter_depth);
  1041. /*
  1042. * Let users instantiate I2C devices through sysfs. This can be used when
  1043. * platform initialization code doesn't contain the proper data for
  1044. * whatever reason. Also useful for drivers that do device detection and
  1045. * detection fails, either because the device uses an unexpected address,
  1046. * or this is a compatible device with different ID register values.
  1047. *
  1048. * Parameter checking may look overzealous, but we really don't want
  1049. * the user to provide incorrect parameters.
  1050. */
  1051. static ssize_t
  1052. new_device_store(struct device *dev, struct device_attribute *attr,
  1053. const char *buf, size_t count)
  1054. {
  1055. struct i2c_adapter *adap = to_i2c_adapter(dev);
  1056. struct i2c_board_info info;
  1057. struct i2c_client *client;
  1058. char *blank, end;
  1059. int res;
  1060. memset(&info, 0, sizeof(struct i2c_board_info));
  1061. blank = strchr(buf, ' ');
  1062. if (!blank) {
  1063. dev_err(dev, "%s: Missing parameters\n", "new_device");
  1064. return -EINVAL;
  1065. }
  1066. if (blank - buf > I2C_NAME_SIZE - 1) {
  1067. dev_err(dev, "%s: Invalid device name\n", "new_device");
  1068. return -EINVAL;
  1069. }
  1070. memcpy(info.type, buf, blank - buf);
  1071. /* Parse remaining parameters, reject extra parameters */
  1072. res = sscanf(++blank, "%hi%c", &info.addr, &end);
  1073. if (res < 1) {
  1074. dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
  1075. return -EINVAL;
  1076. }
  1077. if (res > 1 && end != '\n') {
  1078. dev_err(dev, "%s: Extra parameters\n", "new_device");
  1079. return -EINVAL;
  1080. }
  1081. if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
  1082. info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
  1083. info.flags |= I2C_CLIENT_TEN;
  1084. }
  1085. if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
  1086. info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
  1087. info.flags |= I2C_CLIENT_SLAVE;
  1088. }
  1089. client = i2c_new_client_device(adap, &info);
  1090. if (IS_ERR(client))
  1091. return PTR_ERR(client);
  1092. /* Keep track of the added device */
  1093. mutex_lock(&adap->userspace_clients_lock);
  1094. list_add_tail(&client->detected, &adap->userspace_clients);
  1095. mutex_unlock(&adap->userspace_clients_lock);
  1096. dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
  1097. info.type, info.addr);
  1098. return count;
  1099. }
  1100. static DEVICE_ATTR_WO(new_device);
  1101. /*
  1102. * And of course let the users delete the devices they instantiated, if
  1103. * they got it wrong. This interface can only be used to delete devices
  1104. * instantiated by i2c_sysfs_new_device above. This guarantees that we
  1105. * don't delete devices to which some kernel code still has references.
  1106. *
  1107. * Parameter checking may look overzealous, but we really don't want
  1108. * the user to delete the wrong device.
  1109. */
  1110. static ssize_t
  1111. delete_device_store(struct device *dev, struct device_attribute *attr,
  1112. const char *buf, size_t count)
  1113. {
  1114. struct i2c_adapter *adap = to_i2c_adapter(dev);
  1115. struct i2c_client *client, *next;
  1116. unsigned short addr;
  1117. char end;
  1118. int res;
  1119. /* Parse parameters, reject extra parameters */
  1120. res = sscanf(buf, "%hi%c", &addr, &end);
  1121. if (res < 1) {
  1122. dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
  1123. return -EINVAL;
  1124. }
  1125. if (res > 1 && end != '\n') {
  1126. dev_err(dev, "%s: Extra parameters\n", "delete_device");
  1127. return -EINVAL;
  1128. }
  1129. /* Make sure the device was added through sysfs */
  1130. res = -ENOENT;
  1131. mutex_lock_nested(&adap->userspace_clients_lock,
  1132. i2c_adapter_depth(adap));
  1133. list_for_each_entry_safe(client, next, &adap->userspace_clients,
  1134. detected) {
  1135. if (i2c_encode_flags_to_addr(client) == addr) {
  1136. dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
  1137. "delete_device", client->name, client->addr);
  1138. list_del(&client->detected);
  1139. i2c_unregister_device(client);
  1140. res = count;
  1141. break;
  1142. }
  1143. }
  1144. mutex_unlock(&adap->userspace_clients_lock);
  1145. if (res < 0)
  1146. dev_err(dev, "%s: Can't find device in list\n",
  1147. "delete_device");
  1148. return res;
  1149. }
  1150. static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
  1151. delete_device_store);
  1152. static struct attribute *i2c_adapter_attrs[] = {
  1153. &dev_attr_name.attr,
  1154. &dev_attr_new_device.attr,
  1155. &dev_attr_delete_device.attr,
  1156. NULL
  1157. };
  1158. ATTRIBUTE_GROUPS(i2c_adapter);
  1159. const struct device_type i2c_adapter_type = {
  1160. .groups = i2c_adapter_groups,
  1161. .release = i2c_adapter_dev_release,
  1162. };
  1163. EXPORT_SYMBOL_GPL(i2c_adapter_type);
  1164. /**
  1165. * i2c_verify_adapter - return parameter as i2c_adapter or NULL
  1166. * @dev: device, probably from some driver model iterator
  1167. *
  1168. * When traversing the driver model tree, perhaps using driver model
  1169. * iterators like @device_for_each_child(), you can't assume very much
  1170. * about the nodes you find. Use this function to avoid oopses caused
  1171. * by wrongly treating some non-I2C device as an i2c_adapter.
  1172. */
  1173. struct i2c_adapter *i2c_verify_adapter(struct device *dev)
  1174. {
  1175. return (dev->type == &i2c_adapter_type)
  1176. ? to_i2c_adapter(dev)
  1177. : NULL;
  1178. }
  1179. EXPORT_SYMBOL(i2c_verify_adapter);
  1180. static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
  1181. {
  1182. struct i2c_devinfo *devinfo;
  1183. down_read(&__i2c_board_lock);
  1184. list_for_each_entry(devinfo, &__i2c_board_list, list) {
  1185. if (devinfo->busnum == adapter->nr &&
  1186. IS_ERR(i2c_new_client_device(adapter, &devinfo->board_info)))
  1187. dev_err(&adapter->dev,
  1188. "Can't create device at 0x%02x\n",
  1189. devinfo->board_info.addr);
  1190. }
  1191. up_read(&__i2c_board_lock);
  1192. }
  1193. static int i2c_do_add_adapter(struct i2c_driver *driver,
  1194. struct i2c_adapter *adap)
  1195. {
  1196. /* Detect supported devices on that bus, and instantiate them */
  1197. i2c_detect(adap, driver);
  1198. return 0;
  1199. }
  1200. static int __process_new_adapter(struct device_driver *d, void *data)
  1201. {
  1202. return i2c_do_add_adapter(to_i2c_driver(d), data);
  1203. }
  1204. static const struct i2c_lock_operations i2c_adapter_lock_ops = {
  1205. .lock_bus = i2c_adapter_lock_bus,
  1206. .trylock_bus = i2c_adapter_trylock_bus,
  1207. .unlock_bus = i2c_adapter_unlock_bus,
  1208. };
  1209. static void i2c_host_notify_irq_teardown(struct i2c_adapter *adap)
  1210. {
  1211. struct irq_domain *domain = adap->host_notify_domain;
  1212. irq_hw_number_t hwirq;
  1213. if (!domain)
  1214. return;
  1215. for (hwirq = 0 ; hwirq < I2C_ADDR_7BITS_COUNT ; hwirq++)
  1216. irq_dispose_mapping(irq_find_mapping(domain, hwirq));
  1217. irq_domain_remove(domain);
  1218. adap->host_notify_domain = NULL;
  1219. }
  1220. static int i2c_host_notify_irq_map(struct irq_domain *h,
  1221. unsigned int virq,
  1222. irq_hw_number_t hw_irq_num)
  1223. {
  1224. irq_set_chip_and_handler(virq, &dummy_irq_chip, handle_simple_irq);
  1225. return 0;
  1226. }
  1227. static const struct irq_domain_ops i2c_host_notify_irq_ops = {
  1228. .map = i2c_host_notify_irq_map,
  1229. };
  1230. static int i2c_setup_host_notify_irq_domain(struct i2c_adapter *adap)
  1231. {
  1232. struct irq_domain *domain;
  1233. if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_HOST_NOTIFY))
  1234. return 0;
  1235. domain = irq_domain_create_linear(dev_fwnode(adap->dev.parent),
  1236. I2C_ADDR_7BITS_COUNT,
  1237. &i2c_host_notify_irq_ops, adap);
  1238. if (!domain)
  1239. return -ENOMEM;
  1240. adap->host_notify_domain = domain;
  1241. return 0;
  1242. }
  1243. /**
  1244. * i2c_handle_smbus_host_notify - Forward a Host Notify event to the correct
  1245. * I2C client.
  1246. * @adap: the adapter
  1247. * @addr: the I2C address of the notifying device
  1248. * Context: can't sleep
  1249. *
  1250. * Helper function to be called from an I2C bus driver's interrupt
  1251. * handler. It will schedule the Host Notify IRQ.
  1252. */
  1253. int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
  1254. {
  1255. int irq;
  1256. if (!adap)
  1257. return -EINVAL;
  1258. dev_dbg(&adap->dev, "Detected HostNotify from address 0x%02x", addr);
  1259. irq = irq_find_mapping(adap->host_notify_domain, addr);
  1260. if (irq <= 0)
  1261. return -ENXIO;
  1262. generic_handle_irq_safe(irq);
  1263. return 0;
  1264. }
  1265. EXPORT_SYMBOL_GPL(i2c_handle_smbus_host_notify);
  1266. static int i2c_register_adapter(struct i2c_adapter *adap)
  1267. {
  1268. int res = -EINVAL;
  1269. /* Can't register until after driver model init */
  1270. if (WARN_ON(!is_registered)) {
  1271. res = -EAGAIN;
  1272. goto out_list;
  1273. }
  1274. /* Sanity checks */
  1275. if (WARN(!adap->name[0], "i2c adapter has no name"))
  1276. goto out_list;
  1277. if (!adap->algo) {
  1278. pr_err("adapter '%s': no algo supplied!\n", adap->name);
  1279. goto out_list;
  1280. }
  1281. if (!adap->lock_ops)
  1282. adap->lock_ops = &i2c_adapter_lock_ops;
  1283. adap->locked_flags = 0;
  1284. rt_mutex_init(&adap->bus_lock);
  1285. rt_mutex_init(&adap->mux_lock);
  1286. mutex_init(&adap->userspace_clients_lock);
  1287. INIT_LIST_HEAD(&adap->userspace_clients);
  1288. /* Set default timeout to 1 second if not already set */
  1289. if (adap->timeout == 0)
  1290. adap->timeout = HZ;
  1291. /* register soft irqs for Host Notify */
  1292. res = i2c_setup_host_notify_irq_domain(adap);
  1293. if (res) {
  1294. pr_err("adapter '%s': can't create Host Notify IRQs (%d)\n",
  1295. adap->name, res);
  1296. goto out_list;
  1297. }
  1298. dev_set_name(&adap->dev, "i2c-%d", adap->nr);
  1299. adap->dev.bus = &i2c_bus_type;
  1300. adap->dev.type = &i2c_adapter_type;
  1301. device_initialize(&adap->dev);
  1302. /*
  1303. * This adapter can be used as a parent immediately after device_add(),
  1304. * setup runtime-pm (especially ignore-children) before hand.
  1305. */
  1306. device_enable_async_suspend(&adap->dev);
  1307. pm_runtime_no_callbacks(&adap->dev);
  1308. pm_suspend_ignore_children(&adap->dev, true);
  1309. pm_runtime_enable(&adap->dev);
  1310. res = device_add(&adap->dev);
  1311. if (res) {
  1312. pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
  1313. put_device(&adap->dev);
  1314. goto out_list;
  1315. }
  1316. adap->debugfs = debugfs_create_dir(dev_name(&adap->dev), i2c_debugfs_root);
  1317. res = i2c_setup_smbus_alert(adap);
  1318. if (res)
  1319. goto out_reg;
  1320. res = i2c_init_recovery(adap);
  1321. if (res == -EPROBE_DEFER)
  1322. goto out_reg;
  1323. dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
  1324. /* create pre-declared device nodes */
  1325. of_i2c_register_devices(adap);
  1326. i2c_acpi_install_space_handler(adap);
  1327. i2c_acpi_register_devices(adap);
  1328. if (adap->nr < __i2c_first_dynamic_bus_num)
  1329. i2c_scan_static_board_info(adap);
  1330. /* Notify drivers */
  1331. mutex_lock(&core_lock);
  1332. bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
  1333. mutex_unlock(&core_lock);
  1334. return 0;
  1335. out_reg:
  1336. debugfs_remove_recursive(adap->debugfs);
  1337. init_completion(&adap->dev_released);
  1338. device_unregister(&adap->dev);
  1339. wait_for_completion(&adap->dev_released);
  1340. out_list:
  1341. mutex_lock(&core_lock);
  1342. idr_remove(&i2c_adapter_idr, adap->nr);
  1343. mutex_unlock(&core_lock);
  1344. return res;
  1345. }
  1346. /**
  1347. * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
  1348. * @adap: the adapter to register (with adap->nr initialized)
  1349. * Context: can sleep
  1350. *
  1351. * See i2c_add_numbered_adapter() for details.
  1352. */
  1353. static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
  1354. {
  1355. int id;
  1356. mutex_lock(&core_lock);
  1357. id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
  1358. mutex_unlock(&core_lock);
  1359. if (WARN(id < 0, "couldn't get idr"))
  1360. return id == -ENOSPC ? -EBUSY : id;
  1361. return i2c_register_adapter(adap);
  1362. }
  1363. /**
  1364. * i2c_add_adapter - declare i2c adapter, use dynamic bus number
  1365. * @adapter: the adapter to add
  1366. * Context: can sleep
  1367. *
  1368. * This routine is used to declare an I2C adapter when its bus number
  1369. * doesn't matter or when its bus number is specified by an dt alias.
  1370. * Examples of bases when the bus number doesn't matter: I2C adapters
  1371. * dynamically added by USB links or PCI plugin cards.
  1372. *
  1373. * When this returns zero, a new bus number was allocated and stored
  1374. * in adap->nr, and the specified adapter became available for clients.
  1375. * Otherwise, a negative errno value is returned.
  1376. */
  1377. int i2c_add_adapter(struct i2c_adapter *adapter)
  1378. {
  1379. struct device *dev = &adapter->dev;
  1380. int id;
  1381. id = of_alias_get_id(dev->of_node, "i2c");
  1382. if (id >= 0) {
  1383. adapter->nr = id;
  1384. return __i2c_add_numbered_adapter(adapter);
  1385. }
  1386. mutex_lock(&core_lock);
  1387. id = idr_alloc(&i2c_adapter_idr, adapter,
  1388. __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
  1389. mutex_unlock(&core_lock);
  1390. if (WARN(id < 0, "couldn't get idr"))
  1391. return id;
  1392. adapter->nr = id;
  1393. return i2c_register_adapter(adapter);
  1394. }
  1395. EXPORT_SYMBOL(i2c_add_adapter);
  1396. /**
  1397. * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
  1398. * @adap: the adapter to register (with adap->nr initialized)
  1399. * Context: can sleep
  1400. *
  1401. * This routine is used to declare an I2C adapter when its bus number
  1402. * matters. For example, use it for I2C adapters from system-on-chip CPUs,
  1403. * or otherwise built in to the system's mainboard, and where i2c_board_info
  1404. * is used to properly configure I2C devices.
  1405. *
  1406. * If the requested bus number is set to -1, then this function will behave
  1407. * identically to i2c_add_adapter, and will dynamically assign a bus number.
  1408. *
  1409. * If no devices have pre-been declared for this bus, then be sure to
  1410. * register the adapter before any dynamically allocated ones. Otherwise
  1411. * the required bus ID may not be available.
  1412. *
  1413. * When this returns zero, the specified adapter became available for
  1414. * clients using the bus number provided in adap->nr. Also, the table
  1415. * of I2C devices pre-declared using i2c_register_board_info() is scanned,
  1416. * and the appropriate driver model device nodes are created. Otherwise, a
  1417. * negative errno value is returned.
  1418. */
  1419. int i2c_add_numbered_adapter(struct i2c_adapter *adap)
  1420. {
  1421. if (adap->nr == -1) /* -1 means dynamically assign bus id */
  1422. return i2c_add_adapter(adap);
  1423. return __i2c_add_numbered_adapter(adap);
  1424. }
  1425. EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
  1426. static void i2c_do_del_adapter(struct i2c_driver *driver,
  1427. struct i2c_adapter *adapter)
  1428. {
  1429. struct i2c_client *client, *_n;
  1430. /* Remove the devices we created ourselves as the result of hardware
  1431. * probing (using a driver's detect method) */
  1432. list_for_each_entry_safe(client, _n, &driver->clients, detected) {
  1433. if (client->adapter == adapter) {
  1434. dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
  1435. client->name, client->addr);
  1436. list_del(&client->detected);
  1437. i2c_unregister_device(client);
  1438. }
  1439. }
  1440. }
  1441. static int __unregister_client(struct device *dev, void *dummy)
  1442. {
  1443. struct i2c_client *client = i2c_verify_client(dev);
  1444. if (client && strcmp(client->name, "dummy"))
  1445. i2c_unregister_device(client);
  1446. return 0;
  1447. }
  1448. static int __unregister_dummy(struct device *dev, void *dummy)
  1449. {
  1450. struct i2c_client *client = i2c_verify_client(dev);
  1451. i2c_unregister_device(client);
  1452. return 0;
  1453. }
  1454. static int __process_removed_adapter(struct device_driver *d, void *data)
  1455. {
  1456. i2c_do_del_adapter(to_i2c_driver(d), data);
  1457. return 0;
  1458. }
  1459. /**
  1460. * i2c_del_adapter - unregister I2C adapter
  1461. * @adap: the adapter being unregistered
  1462. * Context: can sleep
  1463. *
  1464. * This unregisters an I2C adapter which was previously registered
  1465. * by @i2c_add_adapter or @i2c_add_numbered_adapter.
  1466. */
  1467. void i2c_del_adapter(struct i2c_adapter *adap)
  1468. {
  1469. struct i2c_adapter *found;
  1470. struct i2c_client *client, *next;
  1471. /* First make sure that this adapter was ever added */
  1472. mutex_lock(&core_lock);
  1473. found = idr_find(&i2c_adapter_idr, adap->nr);
  1474. mutex_unlock(&core_lock);
  1475. if (found != adap) {
  1476. pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
  1477. return;
  1478. }
  1479. i2c_acpi_remove_space_handler(adap);
  1480. /* Tell drivers about this removal */
  1481. mutex_lock(&core_lock);
  1482. bus_for_each_drv(&i2c_bus_type, NULL, adap,
  1483. __process_removed_adapter);
  1484. mutex_unlock(&core_lock);
  1485. /* Remove devices instantiated from sysfs */
  1486. mutex_lock_nested(&adap->userspace_clients_lock,
  1487. i2c_adapter_depth(adap));
  1488. list_for_each_entry_safe(client, next, &adap->userspace_clients,
  1489. detected) {
  1490. dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
  1491. client->addr);
  1492. list_del(&client->detected);
  1493. i2c_unregister_device(client);
  1494. }
  1495. mutex_unlock(&adap->userspace_clients_lock);
  1496. /* Detach any active clients. This can't fail, thus we do not
  1497. * check the returned value. This is a two-pass process, because
  1498. * we can't remove the dummy devices during the first pass: they
  1499. * could have been instantiated by real devices wishing to clean
  1500. * them up properly, so we give them a chance to do that first. */
  1501. device_for_each_child(&adap->dev, NULL, __unregister_client);
  1502. device_for_each_child(&adap->dev, NULL, __unregister_dummy);
  1503. /* device name is gone after device_unregister */
  1504. dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
  1505. pm_runtime_disable(&adap->dev);
  1506. i2c_host_notify_irq_teardown(adap);
  1507. debugfs_remove_recursive(adap->debugfs);
  1508. /* wait until all references to the device are gone
  1509. *
  1510. * FIXME: This is old code and should ideally be replaced by an
  1511. * alternative which results in decoupling the lifetime of the struct
  1512. * device from the i2c_adapter, like spi or netdev do. Any solution
  1513. * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
  1514. */
  1515. init_completion(&adap->dev_released);
  1516. device_unregister(&adap->dev);
  1517. wait_for_completion(&adap->dev_released);
  1518. /* free bus id */
  1519. mutex_lock(&core_lock);
  1520. idr_remove(&i2c_adapter_idr, adap->nr);
  1521. mutex_unlock(&core_lock);
  1522. /* Clear the device structure in case this adapter is ever going to be
  1523. added again */
  1524. memset(&adap->dev, 0, sizeof(adap->dev));
  1525. }
  1526. EXPORT_SYMBOL(i2c_del_adapter);
  1527. static void devm_i2c_del_adapter(void *adapter)
  1528. {
  1529. i2c_del_adapter(adapter);
  1530. }
  1531. /**
  1532. * devm_i2c_add_adapter - device-managed variant of i2c_add_adapter()
  1533. * @dev: managing device for adding this I2C adapter
  1534. * @adapter: the adapter to add
  1535. * Context: can sleep
  1536. *
  1537. * Add adapter with dynamic bus number, same with i2c_add_adapter()
  1538. * but the adapter will be auto deleted on driver detach.
  1539. */
  1540. int devm_i2c_add_adapter(struct device *dev, struct i2c_adapter *adapter)
  1541. {
  1542. int ret;
  1543. ret = i2c_add_adapter(adapter);
  1544. if (ret)
  1545. return ret;
  1546. return devm_add_action_or_reset(dev, devm_i2c_del_adapter, adapter);
  1547. }
  1548. EXPORT_SYMBOL_GPL(devm_i2c_add_adapter);
  1549. static int i2c_dev_or_parent_fwnode_match(struct device *dev, const void *data)
  1550. {
  1551. if (device_match_fwnode(dev, data))
  1552. return 1;
  1553. if (dev->parent && device_match_fwnode(dev->parent, data))
  1554. return 1;
  1555. return 0;
  1556. }
  1557. /**
  1558. * i2c_find_adapter_by_fwnode() - find an i2c_adapter for the fwnode
  1559. * @fwnode: &struct fwnode_handle corresponding to the &struct i2c_adapter
  1560. *
  1561. * Look up and return the &struct i2c_adapter corresponding to the @fwnode.
  1562. * If no adapter can be found, or @fwnode is NULL, this returns NULL.
  1563. *
  1564. * The user must call put_device(&adapter->dev) once done with the i2c adapter.
  1565. */
  1566. struct i2c_adapter *i2c_find_adapter_by_fwnode(struct fwnode_handle *fwnode)
  1567. {
  1568. struct i2c_adapter *adapter;
  1569. struct device *dev;
  1570. if (IS_ERR_OR_NULL(fwnode))
  1571. return NULL;
  1572. dev = bus_find_device(&i2c_bus_type, NULL, fwnode,
  1573. i2c_dev_or_parent_fwnode_match);
  1574. if (!dev)
  1575. return NULL;
  1576. adapter = i2c_verify_adapter(dev);
  1577. if (!adapter)
  1578. put_device(dev);
  1579. return adapter;
  1580. }
  1581. EXPORT_SYMBOL(i2c_find_adapter_by_fwnode);
  1582. /**
  1583. * i2c_get_adapter_by_fwnode() - find an i2c_adapter for the fwnode
  1584. * @fwnode: &struct fwnode_handle corresponding to the &struct i2c_adapter
  1585. *
  1586. * Look up and return the &struct i2c_adapter corresponding to the @fwnode,
  1587. * and increment the adapter module's use count. If no adapter can be found,
  1588. * or @fwnode is NULL, this returns NULL.
  1589. *
  1590. * The user must call i2c_put_adapter(adapter) once done with the i2c adapter.
  1591. * Note that this is different from i2c_find_adapter_by_node().
  1592. */
  1593. struct i2c_adapter *i2c_get_adapter_by_fwnode(struct fwnode_handle *fwnode)
  1594. {
  1595. struct i2c_adapter *adapter;
  1596. adapter = i2c_find_adapter_by_fwnode(fwnode);
  1597. if (!adapter)
  1598. return NULL;
  1599. if (!try_module_get(adapter->owner)) {
  1600. put_device(&adapter->dev);
  1601. adapter = NULL;
  1602. }
  1603. return adapter;
  1604. }
  1605. EXPORT_SYMBOL(i2c_get_adapter_by_fwnode);
  1606. static void i2c_parse_timing(struct device *dev, char *prop_name, u32 *cur_val_p,
  1607. u32 def_val, bool use_def)
  1608. {
  1609. int ret;
  1610. ret = device_property_read_u32(dev, prop_name, cur_val_p);
  1611. if (ret && use_def)
  1612. *cur_val_p = def_val;
  1613. dev_dbg(dev, "%s: %u\n", prop_name, *cur_val_p);
  1614. }
  1615. /**
  1616. * i2c_parse_fw_timings - get I2C related timing parameters from firmware
  1617. * @dev: The device to scan for I2C timing properties
  1618. * @t: the i2c_timings struct to be filled with values
  1619. * @use_defaults: bool to use sane defaults derived from the I2C specification
  1620. * when properties are not found, otherwise don't update
  1621. *
  1622. * Scan the device for the generic I2C properties describing timing parameters
  1623. * for the signal and fill the given struct with the results. If a property was
  1624. * not found and use_defaults was true, then maximum timings are assumed which
  1625. * are derived from the I2C specification. If use_defaults is not used, the
  1626. * results will be as before, so drivers can apply their own defaults before
  1627. * calling this helper. The latter is mainly intended for avoiding regressions
  1628. * of existing drivers which want to switch to this function. New drivers
  1629. * almost always should use the defaults.
  1630. */
  1631. void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
  1632. {
  1633. bool u = use_defaults;
  1634. u32 d;
  1635. i2c_parse_timing(dev, "clock-frequency", &t->bus_freq_hz,
  1636. I2C_MAX_STANDARD_MODE_FREQ, u);
  1637. d = t->bus_freq_hz <= I2C_MAX_STANDARD_MODE_FREQ ? 1000 :
  1638. t->bus_freq_hz <= I2C_MAX_FAST_MODE_FREQ ? 300 : 120;
  1639. i2c_parse_timing(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns, d, u);
  1640. d = t->bus_freq_hz <= I2C_MAX_FAST_MODE_FREQ ? 300 : 120;
  1641. i2c_parse_timing(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns, d, u);
  1642. i2c_parse_timing(dev, "i2c-scl-internal-delay-ns",
  1643. &t->scl_int_delay_ns, 0, u);
  1644. i2c_parse_timing(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns,
  1645. t->scl_fall_ns, u);
  1646. i2c_parse_timing(dev, "i2c-sda-hold-time-ns", &t->sda_hold_ns, 0, u);
  1647. i2c_parse_timing(dev, "i2c-digital-filter-width-ns",
  1648. &t->digital_filter_width_ns, 0, u);
  1649. i2c_parse_timing(dev, "i2c-analog-filter-cutoff-frequency",
  1650. &t->analog_filter_cutoff_freq_hz, 0, u);
  1651. }
  1652. EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
  1653. /* ------------------------------------------------------------------------- */
  1654. int i2c_for_each_dev(void *data, int (*fn)(struct device *dev, void *data))
  1655. {
  1656. int res;
  1657. mutex_lock(&core_lock);
  1658. res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
  1659. mutex_unlock(&core_lock);
  1660. return res;
  1661. }
  1662. EXPORT_SYMBOL_GPL(i2c_for_each_dev);
  1663. static int __process_new_driver(struct device *dev, void *data)
  1664. {
  1665. if (dev->type != &i2c_adapter_type)
  1666. return 0;
  1667. return i2c_do_add_adapter(data, to_i2c_adapter(dev));
  1668. }
  1669. /*
  1670. * An i2c_driver is used with one or more i2c_client (device) nodes to access
  1671. * i2c slave chips, on a bus instance associated with some i2c_adapter.
  1672. */
  1673. int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
  1674. {
  1675. int res;
  1676. /* Can't register until after driver model init */
  1677. if (WARN_ON(!is_registered))
  1678. return -EAGAIN;
  1679. /* add the driver to the list of i2c drivers in the driver core */
  1680. driver->driver.owner = owner;
  1681. driver->driver.bus = &i2c_bus_type;
  1682. INIT_LIST_HEAD(&driver->clients);
  1683. /* When registration returns, the driver core
  1684. * will have called probe() for all matching-but-unbound devices.
  1685. */
  1686. res = driver_register(&driver->driver);
  1687. if (res)
  1688. return res;
  1689. pr_debug("driver [%s] registered\n", driver->driver.name);
  1690. /* Walk the adapters that are already present */
  1691. i2c_for_each_dev(driver, __process_new_driver);
  1692. return 0;
  1693. }
  1694. EXPORT_SYMBOL(i2c_register_driver);
  1695. static int __process_removed_driver(struct device *dev, void *data)
  1696. {
  1697. if (dev->type == &i2c_adapter_type)
  1698. i2c_do_del_adapter(data, to_i2c_adapter(dev));
  1699. return 0;
  1700. }
  1701. /**
  1702. * i2c_del_driver - unregister I2C driver
  1703. * @driver: the driver being unregistered
  1704. * Context: can sleep
  1705. */
  1706. void i2c_del_driver(struct i2c_driver *driver)
  1707. {
  1708. i2c_for_each_dev(driver, __process_removed_driver);
  1709. driver_unregister(&driver->driver);
  1710. pr_debug("driver [%s] unregistered\n", driver->driver.name);
  1711. }
  1712. EXPORT_SYMBOL(i2c_del_driver);
  1713. /* ------------------------------------------------------------------------- */
  1714. struct i2c_cmd_arg {
  1715. unsigned cmd;
  1716. void *arg;
  1717. };
  1718. static int i2c_cmd(struct device *dev, void *_arg)
  1719. {
  1720. struct i2c_client *client = i2c_verify_client(dev);
  1721. struct i2c_cmd_arg *arg = _arg;
  1722. struct i2c_driver *driver;
  1723. if (!client || !client->dev.driver)
  1724. return 0;
  1725. driver = to_i2c_driver(client->dev.driver);
  1726. if (driver->command)
  1727. driver->command(client, arg->cmd, arg->arg);
  1728. return 0;
  1729. }
  1730. void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
  1731. {
  1732. struct i2c_cmd_arg cmd_arg;
  1733. cmd_arg.cmd = cmd;
  1734. cmd_arg.arg = arg;
  1735. device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
  1736. }
  1737. EXPORT_SYMBOL(i2c_clients_command);
  1738. static int __init i2c_init(void)
  1739. {
  1740. int retval;
  1741. retval = of_alias_get_highest_id("i2c");
  1742. down_write(&__i2c_board_lock);
  1743. if (retval >= __i2c_first_dynamic_bus_num)
  1744. __i2c_first_dynamic_bus_num = retval + 1;
  1745. up_write(&__i2c_board_lock);
  1746. retval = bus_register(&i2c_bus_type);
  1747. if (retval)
  1748. return retval;
  1749. is_registered = true;
  1750. i2c_debugfs_root = debugfs_create_dir("i2c", NULL);
  1751. retval = i2c_add_driver(&dummy_driver);
  1752. if (retval)
  1753. goto class_err;
  1754. if (IS_ENABLED(CONFIG_OF_DYNAMIC))
  1755. WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
  1756. if (IS_ENABLED(CONFIG_ACPI))
  1757. WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
  1758. return 0;
  1759. class_err:
  1760. is_registered = false;
  1761. bus_unregister(&i2c_bus_type);
  1762. return retval;
  1763. }
  1764. static void __exit i2c_exit(void)
  1765. {
  1766. if (IS_ENABLED(CONFIG_ACPI))
  1767. WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
  1768. if (IS_ENABLED(CONFIG_OF_DYNAMIC))
  1769. WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
  1770. i2c_del_driver(&dummy_driver);
  1771. debugfs_remove_recursive(i2c_debugfs_root);
  1772. bus_unregister(&i2c_bus_type);
  1773. tracepoint_synchronize_unregister();
  1774. }
  1775. /* We must initialize early, because some subsystems register i2c drivers
  1776. * in subsys_initcall() code, but are linked (and initialized) before i2c.
  1777. */
  1778. postcore_initcall(i2c_init);
  1779. module_exit(i2c_exit);
  1780. /* ----------------------------------------------------
  1781. * the functional interface to the i2c busses.
  1782. * ----------------------------------------------------
  1783. */
  1784. /* Check if val is exceeding the quirk IFF quirk is non 0 */
  1785. #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
  1786. static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
  1787. {
  1788. dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
  1789. err_msg, msg->addr, msg->len,
  1790. str_read_write(msg->flags & I2C_M_RD));
  1791. return -EOPNOTSUPP;
  1792. }
  1793. static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
  1794. {
  1795. const struct i2c_adapter_quirks *q = adap->quirks;
  1796. int max_num = q->max_num_msgs, i;
  1797. bool do_len_check = true;
  1798. if (q->flags & I2C_AQ_COMB) {
  1799. max_num = 2;
  1800. /* special checks for combined messages */
  1801. if (num == 2) {
  1802. if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
  1803. return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
  1804. if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
  1805. return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
  1806. if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
  1807. return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
  1808. if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
  1809. return i2c_quirk_error(adap, &msgs[0], "msg too long");
  1810. if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
  1811. return i2c_quirk_error(adap, &msgs[1], "msg too long");
  1812. do_len_check = false;
  1813. }
  1814. }
  1815. if (i2c_quirk_exceeded(num, max_num))
  1816. return i2c_quirk_error(adap, &msgs[0], "too many messages");
  1817. for (i = 0; i < num; i++) {
  1818. u16 len = msgs[i].len;
  1819. if (msgs[i].flags & I2C_M_RD) {
  1820. if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
  1821. return i2c_quirk_error(adap, &msgs[i], "msg too long");
  1822. if (q->flags & I2C_AQ_NO_ZERO_LEN_READ && len == 0)
  1823. return i2c_quirk_error(adap, &msgs[i], "no zero length");
  1824. } else {
  1825. if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
  1826. return i2c_quirk_error(adap, &msgs[i], "msg too long");
  1827. if (q->flags & I2C_AQ_NO_ZERO_LEN_WRITE && len == 0)
  1828. return i2c_quirk_error(adap, &msgs[i], "no zero length");
  1829. }
  1830. }
  1831. return 0;
  1832. }
  1833. /**
  1834. * __i2c_transfer - unlocked flavor of i2c_transfer
  1835. * @adap: Handle to I2C bus
  1836. * @msgs: One or more messages to execute before STOP is issued to
  1837. * terminate the operation; each message begins with a START.
  1838. * @num: Number of messages to be executed.
  1839. *
  1840. * Returns negative errno, else the number of messages executed.
  1841. *
  1842. * Adapter lock must be held when calling this function. No debug logging
  1843. * takes place.
  1844. */
  1845. int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
  1846. {
  1847. unsigned long orig_jiffies;
  1848. int ret, try;
  1849. if (!adap->algo->master_xfer) {
  1850. dev_dbg(&adap->dev, "I2C level transfers not supported\n");
  1851. return -EOPNOTSUPP;
  1852. }
  1853. if (WARN_ON(!msgs || num < 1))
  1854. return -EINVAL;
  1855. ret = __i2c_check_suspended(adap);
  1856. if (ret)
  1857. return ret;
  1858. if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
  1859. return -EOPNOTSUPP;
  1860. /*
  1861. * i2c_trace_msg_key gets enabled when tracepoint i2c_transfer gets
  1862. * enabled. This is an efficient way of keeping the for-loop from
  1863. * being executed when not needed.
  1864. */
  1865. if (static_branch_unlikely(&i2c_trace_msg_key)) {
  1866. int i;
  1867. for (i = 0; i < num; i++)
  1868. if (msgs[i].flags & I2C_M_RD)
  1869. trace_i2c_read(adap, &msgs[i], i);
  1870. else
  1871. trace_i2c_write(adap, &msgs[i], i);
  1872. }
  1873. /* Retry automatically on arbitration loss */
  1874. orig_jiffies = jiffies;
  1875. for (ret = 0, try = 0; try <= adap->retries; try++) {
  1876. if (i2c_in_atomic_xfer_mode() && adap->algo->master_xfer_atomic)
  1877. ret = adap->algo->master_xfer_atomic(adap, msgs, num);
  1878. else
  1879. ret = adap->algo->master_xfer(adap, msgs, num);
  1880. if (ret != -EAGAIN)
  1881. break;
  1882. if (time_after(jiffies, orig_jiffies + adap->timeout))
  1883. break;
  1884. }
  1885. if (static_branch_unlikely(&i2c_trace_msg_key)) {
  1886. int i;
  1887. for (i = 0; i < ret; i++)
  1888. if (msgs[i].flags & I2C_M_RD)
  1889. trace_i2c_reply(adap, &msgs[i], i);
  1890. trace_i2c_result(adap, num, ret);
  1891. }
  1892. return ret;
  1893. }
  1894. EXPORT_SYMBOL(__i2c_transfer);
  1895. /**
  1896. * i2c_transfer - execute a single or combined I2C message
  1897. * @adap: Handle to I2C bus
  1898. * @msgs: One or more messages to execute before STOP is issued to
  1899. * terminate the operation; each message begins with a START.
  1900. * @num: Number of messages to be executed.
  1901. *
  1902. * Returns negative errno, else the number of messages executed.
  1903. *
  1904. * Note that there is no requirement that each message be sent to
  1905. * the same slave address, although that is the most common model.
  1906. */
  1907. int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
  1908. {
  1909. int ret;
  1910. /* REVISIT the fault reporting model here is weak:
  1911. *
  1912. * - When we get an error after receiving N bytes from a slave,
  1913. * there is no way to report "N".
  1914. *
  1915. * - When we get a NAK after transmitting N bytes to a slave,
  1916. * there is no way to report "N" ... or to let the master
  1917. * continue executing the rest of this combined message, if
  1918. * that's the appropriate response.
  1919. *
  1920. * - When for example "num" is two and we successfully complete
  1921. * the first message but get an error part way through the
  1922. * second, it's unclear whether that should be reported as
  1923. * one (discarding status on the second message) or errno
  1924. * (discarding status on the first one).
  1925. */
  1926. ret = __i2c_lock_bus_helper(adap);
  1927. if (ret)
  1928. return ret;
  1929. ret = __i2c_transfer(adap, msgs, num);
  1930. i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
  1931. return ret;
  1932. }
  1933. EXPORT_SYMBOL(i2c_transfer);
  1934. /**
  1935. * i2c_transfer_buffer_flags - issue a single I2C message transferring data
  1936. * to/from a buffer
  1937. * @client: Handle to slave device
  1938. * @buf: Where the data is stored
  1939. * @count: How many bytes to transfer, must be less than 64k since msg.len is u16
  1940. * @flags: The flags to be used for the message, e.g. I2C_M_RD for reads
  1941. *
  1942. * Returns negative errno, or else the number of bytes transferred.
  1943. */
  1944. int i2c_transfer_buffer_flags(const struct i2c_client *client, char *buf,
  1945. int count, u16 flags)
  1946. {
  1947. int ret;
  1948. struct i2c_msg msg = {
  1949. .addr = client->addr,
  1950. .flags = flags | (client->flags & I2C_M_TEN),
  1951. .len = count,
  1952. .buf = buf,
  1953. };
  1954. ret = i2c_transfer(client->adapter, &msg, 1);
  1955. /*
  1956. * If everything went ok (i.e. 1 msg transferred), return #bytes
  1957. * transferred, else error code.
  1958. */
  1959. return (ret == 1) ? count : ret;
  1960. }
  1961. EXPORT_SYMBOL(i2c_transfer_buffer_flags);
  1962. /**
  1963. * i2c_get_device_id - get manufacturer, part id and die revision of a device
  1964. * @client: The device to query
  1965. * @id: The queried information
  1966. *
  1967. * Returns negative errno on error, zero on success.
  1968. */
  1969. int i2c_get_device_id(const struct i2c_client *client,
  1970. struct i2c_device_identity *id)
  1971. {
  1972. struct i2c_adapter *adap = client->adapter;
  1973. union i2c_smbus_data raw_id;
  1974. int ret;
  1975. if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
  1976. return -EOPNOTSUPP;
  1977. raw_id.block[0] = 3;
  1978. ret = i2c_smbus_xfer(adap, I2C_ADDR_DEVICE_ID, 0,
  1979. I2C_SMBUS_READ, client->addr << 1,
  1980. I2C_SMBUS_I2C_BLOCK_DATA, &raw_id);
  1981. if (ret)
  1982. return ret;
  1983. id->manufacturer_id = (raw_id.block[1] << 4) | (raw_id.block[2] >> 4);
  1984. id->part_id = ((raw_id.block[2] & 0xf) << 5) | (raw_id.block[3] >> 3);
  1985. id->die_revision = raw_id.block[3] & 0x7;
  1986. return 0;
  1987. }
  1988. EXPORT_SYMBOL_GPL(i2c_get_device_id);
  1989. /**
  1990. * i2c_client_get_device_id - get the driver match table entry of a device
  1991. * @client: the device to query. The device must be bound to a driver
  1992. *
  1993. * Returns a pointer to the matching entry if found, NULL otherwise.
  1994. */
  1995. const struct i2c_device_id *i2c_client_get_device_id(const struct i2c_client *client)
  1996. {
  1997. const struct i2c_driver *drv = to_i2c_driver(client->dev.driver);
  1998. return i2c_match_id(drv->id_table, client);
  1999. }
  2000. EXPORT_SYMBOL_GPL(i2c_client_get_device_id);
  2001. /* ----------------------------------------------------
  2002. * the i2c address scanning function
  2003. * Will not work for 10-bit addresses!
  2004. * ----------------------------------------------------
  2005. */
  2006. /*
  2007. * Legacy default probe function, mostly relevant for SMBus. The default
  2008. * probe method is a quick write, but it is known to corrupt the 24RF08
  2009. * EEPROMs due to a state machine bug, and could also irreversibly
  2010. * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
  2011. * we use a short byte read instead. Also, some bus drivers don't implement
  2012. * quick write, so we fallback to a byte read in that case too.
  2013. * On x86, there is another special case for FSC hardware monitoring chips,
  2014. * which want regular byte reads (address 0x73.) Fortunately, these are the
  2015. * only known chips using this I2C address on PC hardware.
  2016. * Returns 1 if probe succeeded, 0 if not.
  2017. */
  2018. static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
  2019. {
  2020. int err;
  2021. union i2c_smbus_data dummy;
  2022. #ifdef CONFIG_X86
  2023. if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
  2024. && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
  2025. err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
  2026. I2C_SMBUS_BYTE_DATA, &dummy);
  2027. else
  2028. #endif
  2029. if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
  2030. && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
  2031. err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
  2032. I2C_SMBUS_QUICK, NULL);
  2033. else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
  2034. err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
  2035. I2C_SMBUS_BYTE, &dummy);
  2036. else {
  2037. dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
  2038. addr);
  2039. err = -EOPNOTSUPP;
  2040. }
  2041. return err >= 0;
  2042. }
  2043. static int i2c_detect_address(struct i2c_client *temp_client,
  2044. struct i2c_driver *driver)
  2045. {
  2046. struct i2c_board_info info;
  2047. struct i2c_adapter *adapter = temp_client->adapter;
  2048. int addr = temp_client->addr;
  2049. int err;
  2050. /* Make sure the address is valid */
  2051. err = i2c_check_7bit_addr_validity_strict(addr);
  2052. if (err) {
  2053. dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
  2054. addr);
  2055. return err;
  2056. }
  2057. /* Skip if already in use (7 bit, no need to encode flags) */
  2058. if (i2c_check_addr_busy(adapter, addr))
  2059. return 0;
  2060. /* Make sure there is something at this address */
  2061. if (!i2c_default_probe(adapter, addr))
  2062. return 0;
  2063. /* Finally call the custom detection function */
  2064. memset(&info, 0, sizeof(struct i2c_board_info));
  2065. info.addr = addr;
  2066. err = driver->detect(temp_client, &info);
  2067. if (err) {
  2068. /* -ENODEV is returned if the detection fails. We catch it
  2069. here as this isn't an error. */
  2070. return err == -ENODEV ? 0 : err;
  2071. }
  2072. /* Consistency check */
  2073. if (info.type[0] == '\0') {
  2074. dev_err(&adapter->dev,
  2075. "%s detection function provided no name for 0x%x\n",
  2076. driver->driver.name, addr);
  2077. } else {
  2078. struct i2c_client *client;
  2079. /* Detection succeeded, instantiate the device */
  2080. if (adapter->class & I2C_CLASS_DEPRECATED)
  2081. dev_warn(&adapter->dev,
  2082. "This adapter will soon drop class based instantiation of devices. "
  2083. "Please make sure client 0x%02x gets instantiated by other means. "
  2084. "Check 'Documentation/i2c/instantiating-devices.rst' for details.\n",
  2085. info.addr);
  2086. dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
  2087. info.type, info.addr);
  2088. client = i2c_new_client_device(adapter, &info);
  2089. if (!IS_ERR(client))
  2090. list_add_tail(&client->detected, &driver->clients);
  2091. else
  2092. dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
  2093. info.type, info.addr);
  2094. }
  2095. return 0;
  2096. }
  2097. static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
  2098. {
  2099. const unsigned short *address_list;
  2100. struct i2c_client *temp_client;
  2101. int i, err = 0;
  2102. address_list = driver->address_list;
  2103. if (!driver->detect || !address_list)
  2104. return 0;
  2105. /* Warn that the adapter lost class based instantiation */
  2106. if (adapter->class == I2C_CLASS_DEPRECATED) {
  2107. dev_dbg(&adapter->dev,
  2108. "This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
  2109. "If you need it, check 'Documentation/i2c/instantiating-devices.rst' for alternatives.\n",
  2110. driver->driver.name);
  2111. return 0;
  2112. }
  2113. /* Stop here if the classes do not match */
  2114. if (!(adapter->class & driver->class))
  2115. return 0;
  2116. /* Set up a temporary client to help detect callback */
  2117. temp_client = kzalloc_obj(*temp_client);
  2118. if (!temp_client)
  2119. return -ENOMEM;
  2120. temp_client->adapter = adapter;
  2121. for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
  2122. dev_dbg(&adapter->dev,
  2123. "found normal entry for adapter %d, addr 0x%02x\n",
  2124. i2c_adapter_id(adapter), address_list[i]);
  2125. temp_client->addr = address_list[i];
  2126. err = i2c_detect_address(temp_client, driver);
  2127. if (unlikely(err))
  2128. break;
  2129. }
  2130. kfree(temp_client);
  2131. return err;
  2132. }
  2133. int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
  2134. {
  2135. return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
  2136. I2C_SMBUS_QUICK, NULL) >= 0;
  2137. }
  2138. EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
  2139. struct i2c_client *
  2140. i2c_new_scanned_device(struct i2c_adapter *adap,
  2141. struct i2c_board_info *info,
  2142. unsigned short const *addr_list,
  2143. int (*probe)(struct i2c_adapter *adap, unsigned short addr))
  2144. {
  2145. int i;
  2146. if (!probe)
  2147. probe = i2c_default_probe;
  2148. for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
  2149. /* Check address validity */
  2150. if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
  2151. dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
  2152. addr_list[i]);
  2153. continue;
  2154. }
  2155. /* Check address availability (7 bit, no need to encode flags) */
  2156. if (i2c_check_addr_busy(adap, addr_list[i])) {
  2157. dev_dbg(&adap->dev,
  2158. "Address 0x%02x already in use, not probing\n",
  2159. addr_list[i]);
  2160. continue;
  2161. }
  2162. /* Test address responsiveness */
  2163. if (probe(adap, addr_list[i]))
  2164. break;
  2165. }
  2166. if (addr_list[i] == I2C_CLIENT_END) {
  2167. dev_dbg(&adap->dev, "Probing failed, no device found\n");
  2168. return ERR_PTR(-ENODEV);
  2169. }
  2170. info->addr = addr_list[i];
  2171. return i2c_new_client_device(adap, info);
  2172. }
  2173. EXPORT_SYMBOL_GPL(i2c_new_scanned_device);
  2174. struct i2c_adapter *i2c_get_adapter(int nr)
  2175. {
  2176. struct i2c_adapter *adapter;
  2177. mutex_lock(&core_lock);
  2178. adapter = idr_find(&i2c_adapter_idr, nr);
  2179. if (!adapter)
  2180. goto exit;
  2181. if (try_module_get(adapter->owner))
  2182. get_device(&adapter->dev);
  2183. else
  2184. adapter = NULL;
  2185. exit:
  2186. mutex_unlock(&core_lock);
  2187. return adapter;
  2188. }
  2189. EXPORT_SYMBOL(i2c_get_adapter);
  2190. void i2c_put_adapter(struct i2c_adapter *adap)
  2191. {
  2192. if (!adap)
  2193. return;
  2194. module_put(adap->owner);
  2195. /* Should be last, otherwise we risk use-after-free with 'adap' */
  2196. put_device(&adap->dev);
  2197. }
  2198. EXPORT_SYMBOL(i2c_put_adapter);
  2199. /**
  2200. * i2c_get_dma_safe_msg_buf() - get a DMA safe buffer for the given i2c_msg
  2201. * @msg: the message to be checked
  2202. * @threshold: the minimum number of bytes for which using DMA makes sense.
  2203. * Should at least be 1.
  2204. *
  2205. * Return: NULL if a DMA safe buffer was not obtained. Use msg->buf with PIO.
  2206. * Or a valid pointer to be used with DMA. After use, release it by
  2207. * calling i2c_put_dma_safe_msg_buf().
  2208. *
  2209. * This function must only be called from process context!
  2210. */
  2211. u8 *i2c_get_dma_safe_msg_buf(struct i2c_msg *msg, unsigned int threshold)
  2212. {
  2213. /* also skip 0-length msgs for bogus thresholds of 0 */
  2214. if (!threshold)
  2215. pr_debug("DMA buffer for addr=0x%02x with length 0 is bogus\n",
  2216. msg->addr);
  2217. if (msg->len < threshold || msg->len == 0)
  2218. return NULL;
  2219. if (msg->flags & I2C_M_DMA_SAFE)
  2220. return msg->buf;
  2221. pr_debug("using bounce buffer for addr=0x%02x, len=%d\n",
  2222. msg->addr, msg->len);
  2223. if (msg->flags & I2C_M_RD)
  2224. return kzalloc(msg->len, GFP_KERNEL);
  2225. else
  2226. return kmemdup(msg->buf, msg->len, GFP_KERNEL);
  2227. }
  2228. EXPORT_SYMBOL_GPL(i2c_get_dma_safe_msg_buf);
  2229. /**
  2230. * i2c_put_dma_safe_msg_buf - release DMA safe buffer and sync with i2c_msg
  2231. * @buf: the buffer obtained from i2c_get_dma_safe_msg_buf(). May be NULL.
  2232. * @msg: the message which the buffer corresponds to
  2233. * @xferred: bool saying if the message was transferred
  2234. */
  2235. void i2c_put_dma_safe_msg_buf(u8 *buf, struct i2c_msg *msg, bool xferred)
  2236. {
  2237. if (!buf || buf == msg->buf)
  2238. return;
  2239. if (xferred && msg->flags & I2C_M_RD)
  2240. memcpy(msg->buf, buf, msg->len);
  2241. kfree(buf);
  2242. }
  2243. EXPORT_SYMBOL_GPL(i2c_put_dma_safe_msg_buf);
  2244. MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
  2245. MODULE_DESCRIPTION("I2C-Bus main module");
  2246. MODULE_LICENSE("GPL");