i2c-core-base.c 61 KB

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