i2c-core-base.c 62 KB

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