i2c-core-base.c 60 KB

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