spi.c 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407
  1. /*
  2. * SPI init/core code
  3. *
  4. * Copyright (C) 2005 David Brownell
  5. * Copyright (C) 2008 Secret Lab Technologies Ltd.
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. */
  17. #include <linux/kernel.h>
  18. #include <linux/device.h>
  19. #include <linux/init.h>
  20. #include <linux/cache.h>
  21. #include <linux/dma-mapping.h>
  22. #include <linux/dmaengine.h>
  23. #include <linux/mutex.h>
  24. #include <linux/of_device.h>
  25. #include <linux/of_irq.h>
  26. #include <linux/clk/clk-conf.h>
  27. #include <linux/slab.h>
  28. #include <linux/mod_devicetable.h>
  29. #include <linux/spi/spi.h>
  30. #include <linux/of_gpio.h>
  31. #include <linux/pm_runtime.h>
  32. #include <linux/pm_domain.h>
  33. #include <linux/export.h>
  34. #include <linux/sched/rt.h>
  35. #include <linux/delay.h>
  36. #include <linux/kthread.h>
  37. #include <linux/ioport.h>
  38. #include <linux/acpi.h>
  39. #define CREATE_TRACE_POINTS
  40. #include <trace/events/spi.h>
  41. static void spidev_release(struct device *dev)
  42. {
  43. struct spi_device *spi = to_spi_device(dev);
  44. /* spi masters may cleanup for released devices */
  45. if (spi->master->cleanup)
  46. spi->master->cleanup(spi);
  47. spi_master_put(spi->master);
  48. kfree(spi);
  49. }
  50. static ssize_t
  51. modalias_show(struct device *dev, struct device_attribute *a, char *buf)
  52. {
  53. const struct spi_device *spi = to_spi_device(dev);
  54. int len;
  55. len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
  56. if (len != -ENODEV)
  57. return len;
  58. return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
  59. }
  60. static DEVICE_ATTR_RO(modalias);
  61. static struct attribute *spi_dev_attrs[] = {
  62. &dev_attr_modalias.attr,
  63. NULL,
  64. };
  65. ATTRIBUTE_GROUPS(spi_dev);
  66. /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
  67. * and the sysfs version makes coldplug work too.
  68. */
  69. static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
  70. const struct spi_device *sdev)
  71. {
  72. while (id->name[0]) {
  73. if (!strcmp(sdev->modalias, id->name))
  74. return id;
  75. id++;
  76. }
  77. return NULL;
  78. }
  79. const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
  80. {
  81. const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
  82. return spi_match_id(sdrv->id_table, sdev);
  83. }
  84. EXPORT_SYMBOL_GPL(spi_get_device_id);
  85. static int spi_match_device(struct device *dev, struct device_driver *drv)
  86. {
  87. const struct spi_device *spi = to_spi_device(dev);
  88. const struct spi_driver *sdrv = to_spi_driver(drv);
  89. /* Attempt an OF style match */
  90. if (of_driver_match_device(dev, drv))
  91. return 1;
  92. /* Then try ACPI */
  93. if (acpi_driver_match_device(dev, drv))
  94. return 1;
  95. if (sdrv->id_table)
  96. return !!spi_match_id(sdrv->id_table, spi);
  97. return strcmp(spi->modalias, drv->name) == 0;
  98. }
  99. static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
  100. {
  101. const struct spi_device *spi = to_spi_device(dev);
  102. int rc;
  103. rc = acpi_device_uevent_modalias(dev, env);
  104. if (rc != -ENODEV)
  105. return rc;
  106. add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
  107. return 0;
  108. }
  109. struct bus_type spi_bus_type = {
  110. .name = "spi",
  111. .dev_groups = spi_dev_groups,
  112. .match = spi_match_device,
  113. .uevent = spi_uevent,
  114. };
  115. EXPORT_SYMBOL_GPL(spi_bus_type);
  116. static int spi_drv_probe(struct device *dev)
  117. {
  118. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  119. int ret;
  120. ret = of_clk_set_defaults(dev->of_node, false);
  121. if (ret)
  122. return ret;
  123. ret = dev_pm_domain_attach(dev, true);
  124. if (ret != -EPROBE_DEFER) {
  125. ret = sdrv->probe(to_spi_device(dev));
  126. if (ret)
  127. dev_pm_domain_detach(dev, true);
  128. }
  129. return ret;
  130. }
  131. static int spi_drv_remove(struct device *dev)
  132. {
  133. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  134. int ret;
  135. ret = sdrv->remove(to_spi_device(dev));
  136. dev_pm_domain_detach(dev, true);
  137. return ret;
  138. }
  139. static void spi_drv_shutdown(struct device *dev)
  140. {
  141. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  142. sdrv->shutdown(to_spi_device(dev));
  143. }
  144. /**
  145. * spi_register_driver - register a SPI driver
  146. * @sdrv: the driver to register
  147. * Context: can sleep
  148. */
  149. int spi_register_driver(struct spi_driver *sdrv)
  150. {
  151. sdrv->driver.bus = &spi_bus_type;
  152. if (sdrv->probe)
  153. sdrv->driver.probe = spi_drv_probe;
  154. if (sdrv->remove)
  155. sdrv->driver.remove = spi_drv_remove;
  156. if (sdrv->shutdown)
  157. sdrv->driver.shutdown = spi_drv_shutdown;
  158. return driver_register(&sdrv->driver);
  159. }
  160. EXPORT_SYMBOL_GPL(spi_register_driver);
  161. /*-------------------------------------------------------------------------*/
  162. /* SPI devices should normally not be created by SPI device drivers; that
  163. * would make them board-specific. Similarly with SPI master drivers.
  164. * Device registration normally goes into like arch/.../mach.../board-YYY.c
  165. * with other readonly (flashable) information about mainboard devices.
  166. */
  167. struct boardinfo {
  168. struct list_head list;
  169. struct spi_board_info board_info;
  170. };
  171. static LIST_HEAD(board_list);
  172. static LIST_HEAD(spi_master_list);
  173. /*
  174. * Used to protect add/del opertion for board_info list and
  175. * spi_master list, and their matching process
  176. */
  177. static DEFINE_MUTEX(board_lock);
  178. /**
  179. * spi_alloc_device - Allocate a new SPI device
  180. * @master: Controller to which device is connected
  181. * Context: can sleep
  182. *
  183. * Allows a driver to allocate and initialize a spi_device without
  184. * registering it immediately. This allows a driver to directly
  185. * fill the spi_device with device parameters before calling
  186. * spi_add_device() on it.
  187. *
  188. * Caller is responsible to call spi_add_device() on the returned
  189. * spi_device structure to add it to the SPI master. If the caller
  190. * needs to discard the spi_device without adding it, then it should
  191. * call spi_dev_put() on it.
  192. *
  193. * Returns a pointer to the new device, or NULL.
  194. */
  195. struct spi_device *spi_alloc_device(struct spi_master *master)
  196. {
  197. struct spi_device *spi;
  198. if (!spi_master_get(master))
  199. return NULL;
  200. spi = kzalloc(sizeof(*spi), GFP_KERNEL);
  201. if (!spi) {
  202. spi_master_put(master);
  203. return NULL;
  204. }
  205. spi->master = master;
  206. spi->dev.parent = &master->dev;
  207. spi->dev.bus = &spi_bus_type;
  208. spi->dev.release = spidev_release;
  209. spi->cs_gpio = -ENOENT;
  210. device_initialize(&spi->dev);
  211. return spi;
  212. }
  213. EXPORT_SYMBOL_GPL(spi_alloc_device);
  214. static void spi_dev_set_name(struct spi_device *spi)
  215. {
  216. struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
  217. if (adev) {
  218. dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
  219. return;
  220. }
  221. dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->master->dev),
  222. spi->chip_select);
  223. }
  224. static int spi_dev_check(struct device *dev, void *data)
  225. {
  226. struct spi_device *spi = to_spi_device(dev);
  227. struct spi_device *new_spi = data;
  228. if (spi->master == new_spi->master &&
  229. spi->chip_select == new_spi->chip_select)
  230. return -EBUSY;
  231. return 0;
  232. }
  233. /**
  234. * spi_add_device - Add spi_device allocated with spi_alloc_device
  235. * @spi: spi_device to register
  236. *
  237. * Companion function to spi_alloc_device. Devices allocated with
  238. * spi_alloc_device can be added onto the spi bus with this function.
  239. *
  240. * Returns 0 on success; negative errno on failure
  241. */
  242. int spi_add_device(struct spi_device *spi)
  243. {
  244. static DEFINE_MUTEX(spi_add_lock);
  245. struct spi_master *master = spi->master;
  246. struct device *dev = master->dev.parent;
  247. int status;
  248. /* Chipselects are numbered 0..max; validate. */
  249. if (spi->chip_select >= master->num_chipselect) {
  250. dev_err(dev, "cs%d >= max %d\n",
  251. spi->chip_select,
  252. master->num_chipselect);
  253. return -EINVAL;
  254. }
  255. /* Set the bus ID string */
  256. spi_dev_set_name(spi);
  257. /* We need to make sure there's no other device with this
  258. * chipselect **BEFORE** we call setup(), else we'll trash
  259. * its configuration. Lock against concurrent add() calls.
  260. */
  261. mutex_lock(&spi_add_lock);
  262. status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
  263. if (status) {
  264. dev_err(dev, "chipselect %d already in use\n",
  265. spi->chip_select);
  266. goto done;
  267. }
  268. if (master->cs_gpios)
  269. spi->cs_gpio = master->cs_gpios[spi->chip_select];
  270. /* Drivers may modify this initial i/o setup, but will
  271. * normally rely on the device being setup. Devices
  272. * using SPI_CS_HIGH can't coexist well otherwise...
  273. */
  274. status = spi_setup(spi);
  275. if (status < 0) {
  276. dev_err(dev, "can't setup %s, status %d\n",
  277. dev_name(&spi->dev), status);
  278. goto done;
  279. }
  280. /* Device may be bound to an active driver when this returns */
  281. status = device_add(&spi->dev);
  282. if (status < 0)
  283. dev_err(dev, "can't add %s, status %d\n",
  284. dev_name(&spi->dev), status);
  285. else
  286. dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
  287. done:
  288. mutex_unlock(&spi_add_lock);
  289. return status;
  290. }
  291. EXPORT_SYMBOL_GPL(spi_add_device);
  292. /**
  293. * spi_new_device - instantiate one new SPI device
  294. * @master: Controller to which device is connected
  295. * @chip: Describes the SPI device
  296. * Context: can sleep
  297. *
  298. * On typical mainboards, this is purely internal; and it's not needed
  299. * after board init creates the hard-wired devices. Some development
  300. * platforms may not be able to use spi_register_board_info though, and
  301. * this is exported so that for example a USB or parport based adapter
  302. * driver could add devices (which it would learn about out-of-band).
  303. *
  304. * Returns the new device, or NULL.
  305. */
  306. struct spi_device *spi_new_device(struct spi_master *master,
  307. struct spi_board_info *chip)
  308. {
  309. struct spi_device *proxy;
  310. int status;
  311. /* NOTE: caller did any chip->bus_num checks necessary.
  312. *
  313. * Also, unless we change the return value convention to use
  314. * error-or-pointer (not NULL-or-pointer), troubleshootability
  315. * suggests syslogged diagnostics are best here (ugh).
  316. */
  317. proxy = spi_alloc_device(master);
  318. if (!proxy)
  319. return NULL;
  320. WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
  321. proxy->chip_select = chip->chip_select;
  322. proxy->max_speed_hz = chip->max_speed_hz;
  323. proxy->mode = chip->mode;
  324. proxy->irq = chip->irq;
  325. strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
  326. proxy->dev.platform_data = (void *) chip->platform_data;
  327. proxy->controller_data = chip->controller_data;
  328. proxy->controller_state = NULL;
  329. status = spi_add_device(proxy);
  330. if (status < 0) {
  331. spi_dev_put(proxy);
  332. return NULL;
  333. }
  334. return proxy;
  335. }
  336. EXPORT_SYMBOL_GPL(spi_new_device);
  337. static void spi_match_master_to_boardinfo(struct spi_master *master,
  338. struct spi_board_info *bi)
  339. {
  340. struct spi_device *dev;
  341. if (master->bus_num != bi->bus_num)
  342. return;
  343. dev = spi_new_device(master, bi);
  344. if (!dev)
  345. dev_err(master->dev.parent, "can't create new device for %s\n",
  346. bi->modalias);
  347. }
  348. /**
  349. * spi_register_board_info - register SPI devices for a given board
  350. * @info: array of chip descriptors
  351. * @n: how many descriptors are provided
  352. * Context: can sleep
  353. *
  354. * Board-specific early init code calls this (probably during arch_initcall)
  355. * with segments of the SPI device table. Any device nodes are created later,
  356. * after the relevant parent SPI controller (bus_num) is defined. We keep
  357. * this table of devices forever, so that reloading a controller driver will
  358. * not make Linux forget about these hard-wired devices.
  359. *
  360. * Other code can also call this, e.g. a particular add-on board might provide
  361. * SPI devices through its expansion connector, so code initializing that board
  362. * would naturally declare its SPI devices.
  363. *
  364. * The board info passed can safely be __initdata ... but be careful of
  365. * any embedded pointers (platform_data, etc), they're copied as-is.
  366. */
  367. int spi_register_board_info(struct spi_board_info const *info, unsigned n)
  368. {
  369. struct boardinfo *bi;
  370. int i;
  371. if (!n)
  372. return -EINVAL;
  373. bi = kzalloc(n * sizeof(*bi), GFP_KERNEL);
  374. if (!bi)
  375. return -ENOMEM;
  376. for (i = 0; i < n; i++, bi++, info++) {
  377. struct spi_master *master;
  378. memcpy(&bi->board_info, info, sizeof(*info));
  379. mutex_lock(&board_lock);
  380. list_add_tail(&bi->list, &board_list);
  381. list_for_each_entry(master, &spi_master_list, list)
  382. spi_match_master_to_boardinfo(master, &bi->board_info);
  383. mutex_unlock(&board_lock);
  384. }
  385. return 0;
  386. }
  387. /*-------------------------------------------------------------------------*/
  388. static void spi_set_cs(struct spi_device *spi, bool enable)
  389. {
  390. if (spi->mode & SPI_CS_HIGH)
  391. enable = !enable;
  392. if (spi->cs_gpio >= 0)
  393. gpio_set_value(spi->cs_gpio, !enable);
  394. else if (spi->master->set_cs)
  395. spi->master->set_cs(spi, !enable);
  396. }
  397. #ifdef CONFIG_HAS_DMA
  398. static int spi_map_buf(struct spi_master *master, struct device *dev,
  399. struct sg_table *sgt, void *buf, size_t len,
  400. enum dma_data_direction dir)
  401. {
  402. const bool vmalloced_buf = is_vmalloc_addr(buf);
  403. const int desc_len = vmalloced_buf ? PAGE_SIZE : master->max_dma_len;
  404. const int sgs = DIV_ROUND_UP(len, desc_len);
  405. struct page *vm_page;
  406. void *sg_buf;
  407. size_t min;
  408. int i, ret;
  409. ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
  410. if (ret != 0)
  411. return ret;
  412. for (i = 0; i < sgs; i++) {
  413. min = min_t(size_t, len, desc_len);
  414. if (vmalloced_buf) {
  415. vm_page = vmalloc_to_page(buf);
  416. if (!vm_page) {
  417. sg_free_table(sgt);
  418. return -ENOMEM;
  419. }
  420. sg_set_page(&sgt->sgl[i], vm_page,
  421. min, offset_in_page(buf));
  422. } else {
  423. sg_buf = buf;
  424. sg_set_buf(&sgt->sgl[i], sg_buf, min);
  425. }
  426. buf += min;
  427. len -= min;
  428. }
  429. ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
  430. if (!ret)
  431. ret = -ENOMEM;
  432. if (ret < 0) {
  433. sg_free_table(sgt);
  434. return ret;
  435. }
  436. sgt->nents = ret;
  437. return 0;
  438. }
  439. static void spi_unmap_buf(struct spi_master *master, struct device *dev,
  440. struct sg_table *sgt, enum dma_data_direction dir)
  441. {
  442. if (sgt->orig_nents) {
  443. dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
  444. sg_free_table(sgt);
  445. }
  446. }
  447. static int __spi_map_msg(struct spi_master *master, struct spi_message *msg)
  448. {
  449. struct device *tx_dev, *rx_dev;
  450. struct spi_transfer *xfer;
  451. int ret;
  452. if (!master->can_dma)
  453. return 0;
  454. tx_dev = master->dma_tx->device->dev;
  455. rx_dev = master->dma_rx->device->dev;
  456. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  457. if (!master->can_dma(master, msg->spi, xfer))
  458. continue;
  459. if (xfer->tx_buf != NULL) {
  460. ret = spi_map_buf(master, tx_dev, &xfer->tx_sg,
  461. (void *)xfer->tx_buf, xfer->len,
  462. DMA_TO_DEVICE);
  463. if (ret != 0)
  464. return ret;
  465. }
  466. if (xfer->rx_buf != NULL) {
  467. ret = spi_map_buf(master, rx_dev, &xfer->rx_sg,
  468. xfer->rx_buf, xfer->len,
  469. DMA_FROM_DEVICE);
  470. if (ret != 0) {
  471. spi_unmap_buf(master, tx_dev, &xfer->tx_sg,
  472. DMA_TO_DEVICE);
  473. return ret;
  474. }
  475. }
  476. }
  477. master->cur_msg_mapped = true;
  478. return 0;
  479. }
  480. static int spi_unmap_msg(struct spi_master *master, struct spi_message *msg)
  481. {
  482. struct spi_transfer *xfer;
  483. struct device *tx_dev, *rx_dev;
  484. if (!master->cur_msg_mapped || !master->can_dma)
  485. return 0;
  486. tx_dev = master->dma_tx->device->dev;
  487. rx_dev = master->dma_rx->device->dev;
  488. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  489. /*
  490. * Restore the original value of tx_buf or rx_buf if they are
  491. * NULL.
  492. */
  493. if (xfer->tx_buf == master->dummy_tx)
  494. xfer->tx_buf = NULL;
  495. if (xfer->rx_buf == master->dummy_rx)
  496. xfer->rx_buf = NULL;
  497. if (!master->can_dma(master, msg->spi, xfer))
  498. continue;
  499. spi_unmap_buf(master, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
  500. spi_unmap_buf(master, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
  501. }
  502. return 0;
  503. }
  504. #else /* !CONFIG_HAS_DMA */
  505. static inline int __spi_map_msg(struct spi_master *master,
  506. struct spi_message *msg)
  507. {
  508. return 0;
  509. }
  510. static inline int spi_unmap_msg(struct spi_master *master,
  511. struct spi_message *msg)
  512. {
  513. return 0;
  514. }
  515. #endif /* !CONFIG_HAS_DMA */
  516. static int spi_map_msg(struct spi_master *master, struct spi_message *msg)
  517. {
  518. struct spi_transfer *xfer;
  519. void *tmp;
  520. unsigned int max_tx, max_rx;
  521. if (master->flags & (SPI_MASTER_MUST_RX | SPI_MASTER_MUST_TX)) {
  522. max_tx = 0;
  523. max_rx = 0;
  524. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  525. if ((master->flags & SPI_MASTER_MUST_TX) &&
  526. !xfer->tx_buf)
  527. max_tx = max(xfer->len, max_tx);
  528. if ((master->flags & SPI_MASTER_MUST_RX) &&
  529. !xfer->rx_buf)
  530. max_rx = max(xfer->len, max_rx);
  531. }
  532. if (max_tx) {
  533. tmp = krealloc(master->dummy_tx, max_tx,
  534. GFP_KERNEL | GFP_DMA);
  535. if (!tmp)
  536. return -ENOMEM;
  537. master->dummy_tx = tmp;
  538. memset(tmp, 0, max_tx);
  539. }
  540. if (max_rx) {
  541. tmp = krealloc(master->dummy_rx, max_rx,
  542. GFP_KERNEL | GFP_DMA);
  543. if (!tmp)
  544. return -ENOMEM;
  545. master->dummy_rx = tmp;
  546. }
  547. if (max_tx || max_rx) {
  548. list_for_each_entry(xfer, &msg->transfers,
  549. transfer_list) {
  550. if (!xfer->tx_buf)
  551. xfer->tx_buf = master->dummy_tx;
  552. if (!xfer->rx_buf)
  553. xfer->rx_buf = master->dummy_rx;
  554. }
  555. }
  556. }
  557. return __spi_map_msg(master, msg);
  558. }
  559. /*
  560. * spi_transfer_one_message - Default implementation of transfer_one_message()
  561. *
  562. * This is a standard implementation of transfer_one_message() for
  563. * drivers which impelment a transfer_one() operation. It provides
  564. * standard handling of delays and chip select management.
  565. */
  566. static int spi_transfer_one_message(struct spi_master *master,
  567. struct spi_message *msg)
  568. {
  569. struct spi_transfer *xfer;
  570. bool keep_cs = false;
  571. int ret = 0;
  572. unsigned long ms = 1;
  573. spi_set_cs(msg->spi, true);
  574. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  575. trace_spi_transfer_start(msg, xfer);
  576. if (xfer->tx_buf || xfer->rx_buf) {
  577. reinit_completion(&master->xfer_completion);
  578. ret = master->transfer_one(master, msg->spi, xfer);
  579. if (ret < 0) {
  580. dev_err(&msg->spi->dev,
  581. "SPI transfer failed: %d\n", ret);
  582. goto out;
  583. }
  584. if (ret > 0) {
  585. ret = 0;
  586. ms = xfer->len * 8 * 1000 / xfer->speed_hz;
  587. ms += ms + 100; /* some tolerance */
  588. ms = wait_for_completion_timeout(&master->xfer_completion,
  589. msecs_to_jiffies(ms));
  590. }
  591. if (ms == 0) {
  592. dev_err(&msg->spi->dev,
  593. "SPI transfer timed out\n");
  594. msg->status = -ETIMEDOUT;
  595. }
  596. } else {
  597. if (xfer->len)
  598. dev_err(&msg->spi->dev,
  599. "Bufferless transfer has length %u\n",
  600. xfer->len);
  601. }
  602. trace_spi_transfer_stop(msg, xfer);
  603. if (msg->status != -EINPROGRESS)
  604. goto out;
  605. if (xfer->delay_usecs)
  606. udelay(xfer->delay_usecs);
  607. if (xfer->cs_change) {
  608. if (list_is_last(&xfer->transfer_list,
  609. &msg->transfers)) {
  610. keep_cs = true;
  611. } else {
  612. spi_set_cs(msg->spi, false);
  613. udelay(10);
  614. spi_set_cs(msg->spi, true);
  615. }
  616. }
  617. msg->actual_length += xfer->len;
  618. }
  619. out:
  620. if (ret != 0 || !keep_cs)
  621. spi_set_cs(msg->spi, false);
  622. if (msg->status == -EINPROGRESS)
  623. msg->status = ret;
  624. if (msg->status && master->handle_err)
  625. master->handle_err(master, msg);
  626. spi_finalize_current_message(master);
  627. return ret;
  628. }
  629. /**
  630. * spi_finalize_current_transfer - report completion of a transfer
  631. * @master: the master reporting completion
  632. *
  633. * Called by SPI drivers using the core transfer_one_message()
  634. * implementation to notify it that the current interrupt driven
  635. * transfer has finished and the next one may be scheduled.
  636. */
  637. void spi_finalize_current_transfer(struct spi_master *master)
  638. {
  639. complete(&master->xfer_completion);
  640. }
  641. EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
  642. /**
  643. * __spi_pump_messages - function which processes spi message queue
  644. * @master: master to process queue for
  645. * @in_kthread: true if we are in the context of the message pump thread
  646. *
  647. * This function checks if there is any spi message in the queue that
  648. * needs processing and if so call out to the driver to initialize hardware
  649. * and transfer each message.
  650. *
  651. * Note that it is called both from the kthread itself and also from
  652. * inside spi_sync(); the queue extraction handling at the top of the
  653. * function should deal with this safely.
  654. */
  655. static void __spi_pump_messages(struct spi_master *master, bool in_kthread)
  656. {
  657. unsigned long flags;
  658. bool was_busy = false;
  659. int ret;
  660. /* Lock queue */
  661. spin_lock_irqsave(&master->queue_lock, flags);
  662. /* Make sure we are not already running a message */
  663. if (master->cur_msg) {
  664. spin_unlock_irqrestore(&master->queue_lock, flags);
  665. return;
  666. }
  667. /* If another context is idling the device then defer */
  668. if (master->idling) {
  669. queue_kthread_work(&master->kworker, &master->pump_messages);
  670. spin_unlock_irqrestore(&master->queue_lock, flags);
  671. return;
  672. }
  673. /* Check if the queue is idle */
  674. if (list_empty(&master->queue) || !master->running) {
  675. if (!master->busy) {
  676. spin_unlock_irqrestore(&master->queue_lock, flags);
  677. return;
  678. }
  679. /* Only do teardown in the thread */
  680. if (!in_kthread) {
  681. queue_kthread_work(&master->kworker,
  682. &master->pump_messages);
  683. spin_unlock_irqrestore(&master->queue_lock, flags);
  684. return;
  685. }
  686. master->busy = false;
  687. master->idling = true;
  688. spin_unlock_irqrestore(&master->queue_lock, flags);
  689. kfree(master->dummy_rx);
  690. master->dummy_rx = NULL;
  691. kfree(master->dummy_tx);
  692. master->dummy_tx = NULL;
  693. if (master->unprepare_transfer_hardware &&
  694. master->unprepare_transfer_hardware(master))
  695. dev_err(&master->dev,
  696. "failed to unprepare transfer hardware\n");
  697. if (master->auto_runtime_pm) {
  698. pm_runtime_mark_last_busy(master->dev.parent);
  699. pm_runtime_put_autosuspend(master->dev.parent);
  700. }
  701. trace_spi_master_idle(master);
  702. spin_lock_irqsave(&master->queue_lock, flags);
  703. master->idling = false;
  704. spin_unlock_irqrestore(&master->queue_lock, flags);
  705. return;
  706. }
  707. /* Extract head of queue */
  708. master->cur_msg =
  709. list_first_entry(&master->queue, struct spi_message, queue);
  710. list_del_init(&master->cur_msg->queue);
  711. if (master->busy)
  712. was_busy = true;
  713. else
  714. master->busy = true;
  715. spin_unlock_irqrestore(&master->queue_lock, flags);
  716. if (!was_busy && master->auto_runtime_pm) {
  717. ret = pm_runtime_get_sync(master->dev.parent);
  718. if (ret < 0) {
  719. dev_err(&master->dev, "Failed to power device: %d\n",
  720. ret);
  721. return;
  722. }
  723. }
  724. if (!was_busy)
  725. trace_spi_master_busy(master);
  726. if (!was_busy && master->prepare_transfer_hardware) {
  727. ret = master->prepare_transfer_hardware(master);
  728. if (ret) {
  729. dev_err(&master->dev,
  730. "failed to prepare transfer hardware\n");
  731. if (master->auto_runtime_pm)
  732. pm_runtime_put(master->dev.parent);
  733. return;
  734. }
  735. }
  736. trace_spi_message_start(master->cur_msg);
  737. if (master->prepare_message) {
  738. ret = master->prepare_message(master, master->cur_msg);
  739. if (ret) {
  740. dev_err(&master->dev,
  741. "failed to prepare message: %d\n", ret);
  742. master->cur_msg->status = ret;
  743. spi_finalize_current_message(master);
  744. return;
  745. }
  746. master->cur_msg_prepared = true;
  747. }
  748. ret = spi_map_msg(master, master->cur_msg);
  749. if (ret) {
  750. master->cur_msg->status = ret;
  751. spi_finalize_current_message(master);
  752. return;
  753. }
  754. ret = master->transfer_one_message(master, master->cur_msg);
  755. if (ret) {
  756. dev_err(&master->dev,
  757. "failed to transfer one message from queue\n");
  758. return;
  759. }
  760. }
  761. /**
  762. * spi_pump_messages - kthread work function which processes spi message queue
  763. * @work: pointer to kthread work struct contained in the master struct
  764. */
  765. static void spi_pump_messages(struct kthread_work *work)
  766. {
  767. struct spi_master *master =
  768. container_of(work, struct spi_master, pump_messages);
  769. __spi_pump_messages(master, true);
  770. }
  771. static int spi_init_queue(struct spi_master *master)
  772. {
  773. struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
  774. master->running = false;
  775. master->busy = false;
  776. init_kthread_worker(&master->kworker);
  777. master->kworker_task = kthread_run(kthread_worker_fn,
  778. &master->kworker, "%s",
  779. dev_name(&master->dev));
  780. if (IS_ERR(master->kworker_task)) {
  781. dev_err(&master->dev, "failed to create message pump task\n");
  782. return PTR_ERR(master->kworker_task);
  783. }
  784. init_kthread_work(&master->pump_messages, spi_pump_messages);
  785. /*
  786. * Master config will indicate if this controller should run the
  787. * message pump with high (realtime) priority to reduce the transfer
  788. * latency on the bus by minimising the delay between a transfer
  789. * request and the scheduling of the message pump thread. Without this
  790. * setting the message pump thread will remain at default priority.
  791. */
  792. if (master->rt) {
  793. dev_info(&master->dev,
  794. "will run message pump with realtime priority\n");
  795. sched_setscheduler(master->kworker_task, SCHED_FIFO, &param);
  796. }
  797. return 0;
  798. }
  799. /**
  800. * spi_get_next_queued_message() - called by driver to check for queued
  801. * messages
  802. * @master: the master to check for queued messages
  803. *
  804. * If there are more messages in the queue, the next message is returned from
  805. * this call.
  806. */
  807. struct spi_message *spi_get_next_queued_message(struct spi_master *master)
  808. {
  809. struct spi_message *next;
  810. unsigned long flags;
  811. /* get a pointer to the next message, if any */
  812. spin_lock_irqsave(&master->queue_lock, flags);
  813. next = list_first_entry_or_null(&master->queue, struct spi_message,
  814. queue);
  815. spin_unlock_irqrestore(&master->queue_lock, flags);
  816. return next;
  817. }
  818. EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
  819. /**
  820. * spi_finalize_current_message() - the current message is complete
  821. * @master: the master to return the message to
  822. *
  823. * Called by the driver to notify the core that the message in the front of the
  824. * queue is complete and can be removed from the queue.
  825. */
  826. void spi_finalize_current_message(struct spi_master *master)
  827. {
  828. struct spi_message *mesg;
  829. unsigned long flags;
  830. int ret;
  831. spin_lock_irqsave(&master->queue_lock, flags);
  832. mesg = master->cur_msg;
  833. master->cur_msg = NULL;
  834. queue_kthread_work(&master->kworker, &master->pump_messages);
  835. spin_unlock_irqrestore(&master->queue_lock, flags);
  836. spi_unmap_msg(master, mesg);
  837. if (master->cur_msg_prepared && master->unprepare_message) {
  838. ret = master->unprepare_message(master, mesg);
  839. if (ret) {
  840. dev_err(&master->dev,
  841. "failed to unprepare message: %d\n", ret);
  842. }
  843. }
  844. trace_spi_message_done(mesg);
  845. master->cur_msg_prepared = false;
  846. mesg->state = NULL;
  847. if (mesg->complete)
  848. mesg->complete(mesg->context);
  849. }
  850. EXPORT_SYMBOL_GPL(spi_finalize_current_message);
  851. static int spi_start_queue(struct spi_master *master)
  852. {
  853. unsigned long flags;
  854. spin_lock_irqsave(&master->queue_lock, flags);
  855. if (master->running || master->busy) {
  856. spin_unlock_irqrestore(&master->queue_lock, flags);
  857. return -EBUSY;
  858. }
  859. master->running = true;
  860. master->cur_msg = NULL;
  861. spin_unlock_irqrestore(&master->queue_lock, flags);
  862. queue_kthread_work(&master->kworker, &master->pump_messages);
  863. return 0;
  864. }
  865. static int spi_stop_queue(struct spi_master *master)
  866. {
  867. unsigned long flags;
  868. unsigned limit = 500;
  869. int ret = 0;
  870. spin_lock_irqsave(&master->queue_lock, flags);
  871. /*
  872. * This is a bit lame, but is optimized for the common execution path.
  873. * A wait_queue on the master->busy could be used, but then the common
  874. * execution path (pump_messages) would be required to call wake_up or
  875. * friends on every SPI message. Do this instead.
  876. */
  877. while ((!list_empty(&master->queue) || master->busy) && limit--) {
  878. spin_unlock_irqrestore(&master->queue_lock, flags);
  879. usleep_range(10000, 11000);
  880. spin_lock_irqsave(&master->queue_lock, flags);
  881. }
  882. if (!list_empty(&master->queue) || master->busy)
  883. ret = -EBUSY;
  884. else
  885. master->running = false;
  886. spin_unlock_irqrestore(&master->queue_lock, flags);
  887. if (ret) {
  888. dev_warn(&master->dev,
  889. "could not stop message queue\n");
  890. return ret;
  891. }
  892. return ret;
  893. }
  894. static int spi_destroy_queue(struct spi_master *master)
  895. {
  896. int ret;
  897. ret = spi_stop_queue(master);
  898. /*
  899. * flush_kthread_worker will block until all work is done.
  900. * If the reason that stop_queue timed out is that the work will never
  901. * finish, then it does no good to call flush/stop thread, so
  902. * return anyway.
  903. */
  904. if (ret) {
  905. dev_err(&master->dev, "problem destroying queue\n");
  906. return ret;
  907. }
  908. flush_kthread_worker(&master->kworker);
  909. kthread_stop(master->kworker_task);
  910. return 0;
  911. }
  912. static int __spi_queued_transfer(struct spi_device *spi,
  913. struct spi_message *msg,
  914. bool need_pump)
  915. {
  916. struct spi_master *master = spi->master;
  917. unsigned long flags;
  918. spin_lock_irqsave(&master->queue_lock, flags);
  919. if (!master->running) {
  920. spin_unlock_irqrestore(&master->queue_lock, flags);
  921. return -ESHUTDOWN;
  922. }
  923. msg->actual_length = 0;
  924. msg->status = -EINPROGRESS;
  925. list_add_tail(&msg->queue, &master->queue);
  926. if (!master->busy && need_pump)
  927. queue_kthread_work(&master->kworker, &master->pump_messages);
  928. spin_unlock_irqrestore(&master->queue_lock, flags);
  929. return 0;
  930. }
  931. /**
  932. * spi_queued_transfer - transfer function for queued transfers
  933. * @spi: spi device which is requesting transfer
  934. * @msg: spi message which is to handled is queued to driver queue
  935. */
  936. static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
  937. {
  938. return __spi_queued_transfer(spi, msg, true);
  939. }
  940. static int spi_master_initialize_queue(struct spi_master *master)
  941. {
  942. int ret;
  943. master->transfer = spi_queued_transfer;
  944. if (!master->transfer_one_message)
  945. master->transfer_one_message = spi_transfer_one_message;
  946. /* Initialize and start queue */
  947. ret = spi_init_queue(master);
  948. if (ret) {
  949. dev_err(&master->dev, "problem initializing queue\n");
  950. goto err_init_queue;
  951. }
  952. master->queued = true;
  953. ret = spi_start_queue(master);
  954. if (ret) {
  955. dev_err(&master->dev, "problem starting queue\n");
  956. goto err_start_queue;
  957. }
  958. return 0;
  959. err_start_queue:
  960. spi_destroy_queue(master);
  961. err_init_queue:
  962. return ret;
  963. }
  964. /*-------------------------------------------------------------------------*/
  965. #if defined(CONFIG_OF)
  966. static struct spi_device *
  967. of_register_spi_device(struct spi_master *master, struct device_node *nc)
  968. {
  969. struct spi_device *spi;
  970. int rc;
  971. u32 value;
  972. /* Alloc an spi_device */
  973. spi = spi_alloc_device(master);
  974. if (!spi) {
  975. dev_err(&master->dev, "spi_device alloc error for %s\n",
  976. nc->full_name);
  977. rc = -ENOMEM;
  978. goto err_out;
  979. }
  980. /* Select device driver */
  981. rc = of_modalias_node(nc, spi->modalias,
  982. sizeof(spi->modalias));
  983. if (rc < 0) {
  984. dev_err(&master->dev, "cannot find modalias for %s\n",
  985. nc->full_name);
  986. goto err_out;
  987. }
  988. /* Device address */
  989. rc = of_property_read_u32(nc, "reg", &value);
  990. if (rc) {
  991. dev_err(&master->dev, "%s has no valid 'reg' property (%d)\n",
  992. nc->full_name, rc);
  993. goto err_out;
  994. }
  995. spi->chip_select = value;
  996. /* Mode (clock phase/polarity/etc.) */
  997. if (of_find_property(nc, "spi-cpha", NULL))
  998. spi->mode |= SPI_CPHA;
  999. if (of_find_property(nc, "spi-cpol", NULL))
  1000. spi->mode |= SPI_CPOL;
  1001. if (of_find_property(nc, "spi-cs-high", NULL))
  1002. spi->mode |= SPI_CS_HIGH;
  1003. if (of_find_property(nc, "spi-3wire", NULL))
  1004. spi->mode |= SPI_3WIRE;
  1005. if (of_find_property(nc, "spi-lsb-first", NULL))
  1006. spi->mode |= SPI_LSB_FIRST;
  1007. /* Device DUAL/QUAD mode */
  1008. if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
  1009. switch (value) {
  1010. case 1:
  1011. break;
  1012. case 2:
  1013. spi->mode |= SPI_TX_DUAL;
  1014. break;
  1015. case 4:
  1016. spi->mode |= SPI_TX_QUAD;
  1017. break;
  1018. default:
  1019. dev_warn(&master->dev,
  1020. "spi-tx-bus-width %d not supported\n",
  1021. value);
  1022. break;
  1023. }
  1024. }
  1025. if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
  1026. switch (value) {
  1027. case 1:
  1028. break;
  1029. case 2:
  1030. spi->mode |= SPI_RX_DUAL;
  1031. break;
  1032. case 4:
  1033. spi->mode |= SPI_RX_QUAD;
  1034. break;
  1035. default:
  1036. dev_warn(&master->dev,
  1037. "spi-rx-bus-width %d not supported\n",
  1038. value);
  1039. break;
  1040. }
  1041. }
  1042. /* Device speed */
  1043. rc = of_property_read_u32(nc, "spi-max-frequency", &value);
  1044. if (rc) {
  1045. dev_err(&master->dev, "%s has no valid 'spi-max-frequency' property (%d)\n",
  1046. nc->full_name, rc);
  1047. goto err_out;
  1048. }
  1049. spi->max_speed_hz = value;
  1050. /* IRQ */
  1051. spi->irq = irq_of_parse_and_map(nc, 0);
  1052. /* Store a pointer to the node in the device structure */
  1053. of_node_get(nc);
  1054. spi->dev.of_node = nc;
  1055. /* Register the new device */
  1056. rc = spi_add_device(spi);
  1057. if (rc) {
  1058. dev_err(&master->dev, "spi_device register error %s\n",
  1059. nc->full_name);
  1060. goto err_out;
  1061. }
  1062. return spi;
  1063. err_out:
  1064. spi_dev_put(spi);
  1065. return ERR_PTR(rc);
  1066. }
  1067. /**
  1068. * of_register_spi_devices() - Register child devices onto the SPI bus
  1069. * @master: Pointer to spi_master device
  1070. *
  1071. * Registers an spi_device for each child node of master node which has a 'reg'
  1072. * property.
  1073. */
  1074. static void of_register_spi_devices(struct spi_master *master)
  1075. {
  1076. struct spi_device *spi;
  1077. struct device_node *nc;
  1078. if (!master->dev.of_node)
  1079. return;
  1080. for_each_available_child_of_node(master->dev.of_node, nc) {
  1081. spi = of_register_spi_device(master, nc);
  1082. if (IS_ERR(spi))
  1083. dev_warn(&master->dev, "Failed to create SPI device for %s\n",
  1084. nc->full_name);
  1085. }
  1086. }
  1087. #else
  1088. static void of_register_spi_devices(struct spi_master *master) { }
  1089. #endif
  1090. #ifdef CONFIG_ACPI
  1091. static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
  1092. {
  1093. struct spi_device *spi = data;
  1094. if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
  1095. struct acpi_resource_spi_serialbus *sb;
  1096. sb = &ares->data.spi_serial_bus;
  1097. if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
  1098. spi->chip_select = sb->device_selection;
  1099. spi->max_speed_hz = sb->connection_speed;
  1100. if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
  1101. spi->mode |= SPI_CPHA;
  1102. if (sb->clock_polarity == ACPI_SPI_START_HIGH)
  1103. spi->mode |= SPI_CPOL;
  1104. if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
  1105. spi->mode |= SPI_CS_HIGH;
  1106. }
  1107. } else if (spi->irq < 0) {
  1108. struct resource r;
  1109. if (acpi_dev_resource_interrupt(ares, 0, &r))
  1110. spi->irq = r.start;
  1111. }
  1112. /* Always tell the ACPI core to skip this resource */
  1113. return 1;
  1114. }
  1115. static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
  1116. void *data, void **return_value)
  1117. {
  1118. struct spi_master *master = data;
  1119. struct list_head resource_list;
  1120. struct acpi_device *adev;
  1121. struct spi_device *spi;
  1122. int ret;
  1123. if (acpi_bus_get_device(handle, &adev))
  1124. return AE_OK;
  1125. if (acpi_bus_get_status(adev) || !adev->status.present)
  1126. return AE_OK;
  1127. spi = spi_alloc_device(master);
  1128. if (!spi) {
  1129. dev_err(&master->dev, "failed to allocate SPI device for %s\n",
  1130. dev_name(&adev->dev));
  1131. return AE_NO_MEMORY;
  1132. }
  1133. ACPI_COMPANION_SET(&spi->dev, adev);
  1134. spi->irq = -1;
  1135. INIT_LIST_HEAD(&resource_list);
  1136. ret = acpi_dev_get_resources(adev, &resource_list,
  1137. acpi_spi_add_resource, spi);
  1138. acpi_dev_free_resource_list(&resource_list);
  1139. if (ret < 0 || !spi->max_speed_hz) {
  1140. spi_dev_put(spi);
  1141. return AE_OK;
  1142. }
  1143. adev->power.flags.ignore_parent = true;
  1144. strlcpy(spi->modalias, acpi_device_hid(adev), sizeof(spi->modalias));
  1145. if (spi_add_device(spi)) {
  1146. adev->power.flags.ignore_parent = false;
  1147. dev_err(&master->dev, "failed to add SPI device %s from ACPI\n",
  1148. dev_name(&adev->dev));
  1149. spi_dev_put(spi);
  1150. }
  1151. return AE_OK;
  1152. }
  1153. static void acpi_register_spi_devices(struct spi_master *master)
  1154. {
  1155. acpi_status status;
  1156. acpi_handle handle;
  1157. handle = ACPI_HANDLE(master->dev.parent);
  1158. if (!handle)
  1159. return;
  1160. status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
  1161. acpi_spi_add_device, NULL,
  1162. master, NULL);
  1163. if (ACPI_FAILURE(status))
  1164. dev_warn(&master->dev, "failed to enumerate SPI slaves\n");
  1165. }
  1166. #else
  1167. static inline void acpi_register_spi_devices(struct spi_master *master) {}
  1168. #endif /* CONFIG_ACPI */
  1169. static void spi_master_release(struct device *dev)
  1170. {
  1171. struct spi_master *master;
  1172. master = container_of(dev, struct spi_master, dev);
  1173. kfree(master);
  1174. }
  1175. static struct class spi_master_class = {
  1176. .name = "spi_master",
  1177. .owner = THIS_MODULE,
  1178. .dev_release = spi_master_release,
  1179. };
  1180. /**
  1181. * spi_alloc_master - allocate SPI master controller
  1182. * @dev: the controller, possibly using the platform_bus
  1183. * @size: how much zeroed driver-private data to allocate; the pointer to this
  1184. * memory is in the driver_data field of the returned device,
  1185. * accessible with spi_master_get_devdata().
  1186. * Context: can sleep
  1187. *
  1188. * This call is used only by SPI master controller drivers, which are the
  1189. * only ones directly touching chip registers. It's how they allocate
  1190. * an spi_master structure, prior to calling spi_register_master().
  1191. *
  1192. * This must be called from context that can sleep. It returns the SPI
  1193. * master structure on success, else NULL.
  1194. *
  1195. * The caller is responsible for assigning the bus number and initializing
  1196. * the master's methods before calling spi_register_master(); and (after errors
  1197. * adding the device) calling spi_master_put() and kfree() to prevent a memory
  1198. * leak.
  1199. */
  1200. struct spi_master *spi_alloc_master(struct device *dev, unsigned size)
  1201. {
  1202. struct spi_master *master;
  1203. if (!dev)
  1204. return NULL;
  1205. master = kzalloc(size + sizeof(*master), GFP_KERNEL);
  1206. if (!master)
  1207. return NULL;
  1208. device_initialize(&master->dev);
  1209. master->bus_num = -1;
  1210. master->num_chipselect = 1;
  1211. master->dev.class = &spi_master_class;
  1212. master->dev.parent = get_device(dev);
  1213. spi_master_set_devdata(master, &master[1]);
  1214. return master;
  1215. }
  1216. EXPORT_SYMBOL_GPL(spi_alloc_master);
  1217. #ifdef CONFIG_OF
  1218. static int of_spi_register_master(struct spi_master *master)
  1219. {
  1220. int nb, i, *cs;
  1221. struct device_node *np = master->dev.of_node;
  1222. if (!np)
  1223. return 0;
  1224. nb = of_gpio_named_count(np, "cs-gpios");
  1225. master->num_chipselect = max_t(int, nb, master->num_chipselect);
  1226. /* Return error only for an incorrectly formed cs-gpios property */
  1227. if (nb == 0 || nb == -ENOENT)
  1228. return 0;
  1229. else if (nb < 0)
  1230. return nb;
  1231. cs = devm_kzalloc(&master->dev,
  1232. sizeof(int) * master->num_chipselect,
  1233. GFP_KERNEL);
  1234. master->cs_gpios = cs;
  1235. if (!master->cs_gpios)
  1236. return -ENOMEM;
  1237. for (i = 0; i < master->num_chipselect; i++)
  1238. cs[i] = -ENOENT;
  1239. for (i = 0; i < nb; i++)
  1240. cs[i] = of_get_named_gpio(np, "cs-gpios", i);
  1241. return 0;
  1242. }
  1243. #else
  1244. static int of_spi_register_master(struct spi_master *master)
  1245. {
  1246. return 0;
  1247. }
  1248. #endif
  1249. /**
  1250. * spi_register_master - register SPI master controller
  1251. * @master: initialized master, originally from spi_alloc_master()
  1252. * Context: can sleep
  1253. *
  1254. * SPI master controllers connect to their drivers using some non-SPI bus,
  1255. * such as the platform bus. The final stage of probe() in that code
  1256. * includes calling spi_register_master() to hook up to this SPI bus glue.
  1257. *
  1258. * SPI controllers use board specific (often SOC specific) bus numbers,
  1259. * and board-specific addressing for SPI devices combines those numbers
  1260. * with chip select numbers. Since SPI does not directly support dynamic
  1261. * device identification, boards need configuration tables telling which
  1262. * chip is at which address.
  1263. *
  1264. * This must be called from context that can sleep. It returns zero on
  1265. * success, else a negative error code (dropping the master's refcount).
  1266. * After a successful return, the caller is responsible for calling
  1267. * spi_unregister_master().
  1268. */
  1269. int spi_register_master(struct spi_master *master)
  1270. {
  1271. static atomic_t dyn_bus_id = ATOMIC_INIT((1<<15) - 1);
  1272. struct device *dev = master->dev.parent;
  1273. struct boardinfo *bi;
  1274. int status = -ENODEV;
  1275. int dynamic = 0;
  1276. if (!dev)
  1277. return -ENODEV;
  1278. status = of_spi_register_master(master);
  1279. if (status)
  1280. return status;
  1281. /* even if it's just one always-selected device, there must
  1282. * be at least one chipselect
  1283. */
  1284. if (master->num_chipselect == 0)
  1285. return -EINVAL;
  1286. if ((master->bus_num < 0) && master->dev.of_node)
  1287. master->bus_num = of_alias_get_id(master->dev.of_node, "spi");
  1288. /* convention: dynamically assigned bus IDs count down from the max */
  1289. if (master->bus_num < 0) {
  1290. /* FIXME switch to an IDR based scheme, something like
  1291. * I2C now uses, so we can't run out of "dynamic" IDs
  1292. */
  1293. master->bus_num = atomic_dec_return(&dyn_bus_id);
  1294. dynamic = 1;
  1295. }
  1296. INIT_LIST_HEAD(&master->queue);
  1297. spin_lock_init(&master->queue_lock);
  1298. spin_lock_init(&master->bus_lock_spinlock);
  1299. mutex_init(&master->bus_lock_mutex);
  1300. master->bus_lock_flag = 0;
  1301. init_completion(&master->xfer_completion);
  1302. if (!master->max_dma_len)
  1303. master->max_dma_len = INT_MAX;
  1304. /* register the device, then userspace will see it.
  1305. * registration fails if the bus ID is in use.
  1306. */
  1307. dev_set_name(&master->dev, "spi%u", master->bus_num);
  1308. status = device_add(&master->dev);
  1309. if (status < 0)
  1310. goto done;
  1311. dev_dbg(dev, "registered master %s%s\n", dev_name(&master->dev),
  1312. dynamic ? " (dynamic)" : "");
  1313. /* If we're using a queued driver, start the queue */
  1314. if (master->transfer)
  1315. dev_info(dev, "master is unqueued, this is deprecated\n");
  1316. else {
  1317. status = spi_master_initialize_queue(master);
  1318. if (status) {
  1319. device_del(&master->dev);
  1320. goto done;
  1321. }
  1322. }
  1323. mutex_lock(&board_lock);
  1324. list_add_tail(&master->list, &spi_master_list);
  1325. list_for_each_entry(bi, &board_list, list)
  1326. spi_match_master_to_boardinfo(master, &bi->board_info);
  1327. mutex_unlock(&board_lock);
  1328. /* Register devices from the device tree and ACPI */
  1329. of_register_spi_devices(master);
  1330. acpi_register_spi_devices(master);
  1331. done:
  1332. return status;
  1333. }
  1334. EXPORT_SYMBOL_GPL(spi_register_master);
  1335. static void devm_spi_unregister(struct device *dev, void *res)
  1336. {
  1337. spi_unregister_master(*(struct spi_master **)res);
  1338. }
  1339. /**
  1340. * dev_spi_register_master - register managed SPI master controller
  1341. * @dev: device managing SPI master
  1342. * @master: initialized master, originally from spi_alloc_master()
  1343. * Context: can sleep
  1344. *
  1345. * Register a SPI device as with spi_register_master() which will
  1346. * automatically be unregister
  1347. */
  1348. int devm_spi_register_master(struct device *dev, struct spi_master *master)
  1349. {
  1350. struct spi_master **ptr;
  1351. int ret;
  1352. ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
  1353. if (!ptr)
  1354. return -ENOMEM;
  1355. ret = spi_register_master(master);
  1356. if (!ret) {
  1357. *ptr = master;
  1358. devres_add(dev, ptr);
  1359. } else {
  1360. devres_free(ptr);
  1361. }
  1362. return ret;
  1363. }
  1364. EXPORT_SYMBOL_GPL(devm_spi_register_master);
  1365. static int __unregister(struct device *dev, void *null)
  1366. {
  1367. spi_unregister_device(to_spi_device(dev));
  1368. return 0;
  1369. }
  1370. /**
  1371. * spi_unregister_master - unregister SPI master controller
  1372. * @master: the master being unregistered
  1373. * Context: can sleep
  1374. *
  1375. * This call is used only by SPI master controller drivers, which are the
  1376. * only ones directly touching chip registers.
  1377. *
  1378. * This must be called from context that can sleep.
  1379. */
  1380. void spi_unregister_master(struct spi_master *master)
  1381. {
  1382. int dummy;
  1383. if (master->queued) {
  1384. if (spi_destroy_queue(master))
  1385. dev_err(&master->dev, "queue remove failed\n");
  1386. }
  1387. mutex_lock(&board_lock);
  1388. list_del(&master->list);
  1389. mutex_unlock(&board_lock);
  1390. dummy = device_for_each_child(&master->dev, NULL, __unregister);
  1391. device_unregister(&master->dev);
  1392. }
  1393. EXPORT_SYMBOL_GPL(spi_unregister_master);
  1394. int spi_master_suspend(struct spi_master *master)
  1395. {
  1396. int ret;
  1397. /* Basically no-ops for non-queued masters */
  1398. if (!master->queued)
  1399. return 0;
  1400. ret = spi_stop_queue(master);
  1401. if (ret)
  1402. dev_err(&master->dev, "queue stop failed\n");
  1403. return ret;
  1404. }
  1405. EXPORT_SYMBOL_GPL(spi_master_suspend);
  1406. int spi_master_resume(struct spi_master *master)
  1407. {
  1408. int ret;
  1409. if (!master->queued)
  1410. return 0;
  1411. ret = spi_start_queue(master);
  1412. if (ret)
  1413. dev_err(&master->dev, "queue restart failed\n");
  1414. return ret;
  1415. }
  1416. EXPORT_SYMBOL_GPL(spi_master_resume);
  1417. static int __spi_master_match(struct device *dev, const void *data)
  1418. {
  1419. struct spi_master *m;
  1420. const u16 *bus_num = data;
  1421. m = container_of(dev, struct spi_master, dev);
  1422. return m->bus_num == *bus_num;
  1423. }
  1424. /**
  1425. * spi_busnum_to_master - look up master associated with bus_num
  1426. * @bus_num: the master's bus number
  1427. * Context: can sleep
  1428. *
  1429. * This call may be used with devices that are registered after
  1430. * arch init time. It returns a refcounted pointer to the relevant
  1431. * spi_master (which the caller must release), or NULL if there is
  1432. * no such master registered.
  1433. */
  1434. struct spi_master *spi_busnum_to_master(u16 bus_num)
  1435. {
  1436. struct device *dev;
  1437. struct spi_master *master = NULL;
  1438. dev = class_find_device(&spi_master_class, NULL, &bus_num,
  1439. __spi_master_match);
  1440. if (dev)
  1441. master = container_of(dev, struct spi_master, dev);
  1442. /* reference got in class_find_device */
  1443. return master;
  1444. }
  1445. EXPORT_SYMBOL_GPL(spi_busnum_to_master);
  1446. /*-------------------------------------------------------------------------*/
  1447. /* Core methods for SPI master protocol drivers. Some of the
  1448. * other core methods are currently defined as inline functions.
  1449. */
  1450. /**
  1451. * spi_setup - setup SPI mode and clock rate
  1452. * @spi: the device whose settings are being modified
  1453. * Context: can sleep, and no requests are queued to the device
  1454. *
  1455. * SPI protocol drivers may need to update the transfer mode if the
  1456. * device doesn't work with its default. They may likewise need
  1457. * to update clock rates or word sizes from initial values. This function
  1458. * changes those settings, and must be called from a context that can sleep.
  1459. * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
  1460. * effect the next time the device is selected and data is transferred to
  1461. * or from it. When this function returns, the spi device is deselected.
  1462. *
  1463. * Note that this call will fail if the protocol driver specifies an option
  1464. * that the underlying controller or its driver does not support. For
  1465. * example, not all hardware supports wire transfers using nine bit words,
  1466. * LSB-first wire encoding, or active-high chipselects.
  1467. */
  1468. int spi_setup(struct spi_device *spi)
  1469. {
  1470. unsigned bad_bits, ugly_bits;
  1471. int status = 0;
  1472. /* check mode to prevent that DUAL and QUAD set at the same time
  1473. */
  1474. if (((spi->mode & SPI_TX_DUAL) && (spi->mode & SPI_TX_QUAD)) ||
  1475. ((spi->mode & SPI_RX_DUAL) && (spi->mode & SPI_RX_QUAD))) {
  1476. dev_err(&spi->dev,
  1477. "setup: can not select dual and quad at the same time\n");
  1478. return -EINVAL;
  1479. }
  1480. /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
  1481. */
  1482. if ((spi->mode & SPI_3WIRE) && (spi->mode &
  1483. (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD)))
  1484. return -EINVAL;
  1485. /* help drivers fail *cleanly* when they need options
  1486. * that aren't supported with their current master
  1487. */
  1488. bad_bits = spi->mode & ~spi->master->mode_bits;
  1489. ugly_bits = bad_bits &
  1490. (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD);
  1491. if (ugly_bits) {
  1492. dev_warn(&spi->dev,
  1493. "setup: ignoring unsupported mode bits %x\n",
  1494. ugly_bits);
  1495. spi->mode &= ~ugly_bits;
  1496. bad_bits &= ~ugly_bits;
  1497. }
  1498. if (bad_bits) {
  1499. dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
  1500. bad_bits);
  1501. return -EINVAL;
  1502. }
  1503. if (!spi->bits_per_word)
  1504. spi->bits_per_word = 8;
  1505. if (!spi->max_speed_hz)
  1506. spi->max_speed_hz = spi->master->max_speed_hz;
  1507. spi_set_cs(spi, false);
  1508. if (spi->master->setup)
  1509. status = spi->master->setup(spi);
  1510. dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
  1511. (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
  1512. (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
  1513. (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
  1514. (spi->mode & SPI_3WIRE) ? "3wire, " : "",
  1515. (spi->mode & SPI_LOOP) ? "loopback, " : "",
  1516. spi->bits_per_word, spi->max_speed_hz,
  1517. status);
  1518. return status;
  1519. }
  1520. EXPORT_SYMBOL_GPL(spi_setup);
  1521. static int __spi_validate(struct spi_device *spi, struct spi_message *message)
  1522. {
  1523. struct spi_master *master = spi->master;
  1524. struct spi_transfer *xfer;
  1525. int w_size;
  1526. if (list_empty(&message->transfers))
  1527. return -EINVAL;
  1528. /* Half-duplex links include original MicroWire, and ones with
  1529. * only one data pin like SPI_3WIRE (switches direction) or where
  1530. * either MOSI or MISO is missing. They can also be caused by
  1531. * software limitations.
  1532. */
  1533. if ((master->flags & SPI_MASTER_HALF_DUPLEX)
  1534. || (spi->mode & SPI_3WIRE)) {
  1535. unsigned flags = master->flags;
  1536. list_for_each_entry(xfer, &message->transfers, transfer_list) {
  1537. if (xfer->rx_buf && xfer->tx_buf)
  1538. return -EINVAL;
  1539. if ((flags & SPI_MASTER_NO_TX) && xfer->tx_buf)
  1540. return -EINVAL;
  1541. if ((flags & SPI_MASTER_NO_RX) && xfer->rx_buf)
  1542. return -EINVAL;
  1543. }
  1544. }
  1545. /**
  1546. * Set transfer bits_per_word and max speed as spi device default if
  1547. * it is not set for this transfer.
  1548. * Set transfer tx_nbits and rx_nbits as single transfer default
  1549. * (SPI_NBITS_SINGLE) if it is not set for this transfer.
  1550. */
  1551. list_for_each_entry(xfer, &message->transfers, transfer_list) {
  1552. message->frame_length += xfer->len;
  1553. if (!xfer->bits_per_word)
  1554. xfer->bits_per_word = spi->bits_per_word;
  1555. if (!xfer->speed_hz)
  1556. xfer->speed_hz = spi->max_speed_hz;
  1557. if (master->max_speed_hz &&
  1558. xfer->speed_hz > master->max_speed_hz)
  1559. xfer->speed_hz = master->max_speed_hz;
  1560. if (master->bits_per_word_mask) {
  1561. /* Only 32 bits fit in the mask */
  1562. if (xfer->bits_per_word > 32)
  1563. return -EINVAL;
  1564. if (!(master->bits_per_word_mask &
  1565. BIT(xfer->bits_per_word - 1)))
  1566. return -EINVAL;
  1567. }
  1568. /*
  1569. * SPI transfer length should be multiple of SPI word size
  1570. * where SPI word size should be power-of-two multiple
  1571. */
  1572. if (xfer->bits_per_word <= 8)
  1573. w_size = 1;
  1574. else if (xfer->bits_per_word <= 16)
  1575. w_size = 2;
  1576. else
  1577. w_size = 4;
  1578. /* No partial transfers accepted */
  1579. if (xfer->len % w_size)
  1580. return -EINVAL;
  1581. if (xfer->speed_hz && master->min_speed_hz &&
  1582. xfer->speed_hz < master->min_speed_hz)
  1583. return -EINVAL;
  1584. if (xfer->tx_buf && !xfer->tx_nbits)
  1585. xfer->tx_nbits = SPI_NBITS_SINGLE;
  1586. if (xfer->rx_buf && !xfer->rx_nbits)
  1587. xfer->rx_nbits = SPI_NBITS_SINGLE;
  1588. /* check transfer tx/rx_nbits:
  1589. * 1. check the value matches one of single, dual and quad
  1590. * 2. check tx/rx_nbits match the mode in spi_device
  1591. */
  1592. if (xfer->tx_buf) {
  1593. if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
  1594. xfer->tx_nbits != SPI_NBITS_DUAL &&
  1595. xfer->tx_nbits != SPI_NBITS_QUAD)
  1596. return -EINVAL;
  1597. if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
  1598. !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
  1599. return -EINVAL;
  1600. if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
  1601. !(spi->mode & SPI_TX_QUAD))
  1602. return -EINVAL;
  1603. }
  1604. /* check transfer rx_nbits */
  1605. if (xfer->rx_buf) {
  1606. if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
  1607. xfer->rx_nbits != SPI_NBITS_DUAL &&
  1608. xfer->rx_nbits != SPI_NBITS_QUAD)
  1609. return -EINVAL;
  1610. if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
  1611. !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
  1612. return -EINVAL;
  1613. if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
  1614. !(spi->mode & SPI_RX_QUAD))
  1615. return -EINVAL;
  1616. }
  1617. }
  1618. message->status = -EINPROGRESS;
  1619. return 0;
  1620. }
  1621. static int __spi_async(struct spi_device *spi, struct spi_message *message)
  1622. {
  1623. struct spi_master *master = spi->master;
  1624. message->spi = spi;
  1625. trace_spi_message_submit(message);
  1626. return master->transfer(spi, message);
  1627. }
  1628. /**
  1629. * spi_async - asynchronous SPI transfer
  1630. * @spi: device with which data will be exchanged
  1631. * @message: describes the data transfers, including completion callback
  1632. * Context: any (irqs may be blocked, etc)
  1633. *
  1634. * This call may be used in_irq and other contexts which can't sleep,
  1635. * as well as from task contexts which can sleep.
  1636. *
  1637. * The completion callback is invoked in a context which can't sleep.
  1638. * Before that invocation, the value of message->status is undefined.
  1639. * When the callback is issued, message->status holds either zero (to
  1640. * indicate complete success) or a negative error code. After that
  1641. * callback returns, the driver which issued the transfer request may
  1642. * deallocate the associated memory; it's no longer in use by any SPI
  1643. * core or controller driver code.
  1644. *
  1645. * Note that although all messages to a spi_device are handled in
  1646. * FIFO order, messages may go to different devices in other orders.
  1647. * Some device might be higher priority, or have various "hard" access
  1648. * time requirements, for example.
  1649. *
  1650. * On detection of any fault during the transfer, processing of
  1651. * the entire message is aborted, and the device is deselected.
  1652. * Until returning from the associated message completion callback,
  1653. * no other spi_message queued to that device will be processed.
  1654. * (This rule applies equally to all the synchronous transfer calls,
  1655. * which are wrappers around this core asynchronous primitive.)
  1656. */
  1657. int spi_async(struct spi_device *spi, struct spi_message *message)
  1658. {
  1659. struct spi_master *master = spi->master;
  1660. int ret;
  1661. unsigned long flags;
  1662. ret = __spi_validate(spi, message);
  1663. if (ret != 0)
  1664. return ret;
  1665. spin_lock_irqsave(&master->bus_lock_spinlock, flags);
  1666. if (master->bus_lock_flag)
  1667. ret = -EBUSY;
  1668. else
  1669. ret = __spi_async(spi, message);
  1670. spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
  1671. return ret;
  1672. }
  1673. EXPORT_SYMBOL_GPL(spi_async);
  1674. /**
  1675. * spi_async_locked - version of spi_async with exclusive bus usage
  1676. * @spi: device with which data will be exchanged
  1677. * @message: describes the data transfers, including completion callback
  1678. * Context: any (irqs may be blocked, etc)
  1679. *
  1680. * This call may be used in_irq and other contexts which can't sleep,
  1681. * as well as from task contexts which can sleep.
  1682. *
  1683. * The completion callback is invoked in a context which can't sleep.
  1684. * Before that invocation, the value of message->status is undefined.
  1685. * When the callback is issued, message->status holds either zero (to
  1686. * indicate complete success) or a negative error code. After that
  1687. * callback returns, the driver which issued the transfer request may
  1688. * deallocate the associated memory; it's no longer in use by any SPI
  1689. * core or controller driver code.
  1690. *
  1691. * Note that although all messages to a spi_device are handled in
  1692. * FIFO order, messages may go to different devices in other orders.
  1693. * Some device might be higher priority, or have various "hard" access
  1694. * time requirements, for example.
  1695. *
  1696. * On detection of any fault during the transfer, processing of
  1697. * the entire message is aborted, and the device is deselected.
  1698. * Until returning from the associated message completion callback,
  1699. * no other spi_message queued to that device will be processed.
  1700. * (This rule applies equally to all the synchronous transfer calls,
  1701. * which are wrappers around this core asynchronous primitive.)
  1702. */
  1703. int spi_async_locked(struct spi_device *spi, struct spi_message *message)
  1704. {
  1705. struct spi_master *master = spi->master;
  1706. int ret;
  1707. unsigned long flags;
  1708. ret = __spi_validate(spi, message);
  1709. if (ret != 0)
  1710. return ret;
  1711. spin_lock_irqsave(&master->bus_lock_spinlock, flags);
  1712. ret = __spi_async(spi, message);
  1713. spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
  1714. return ret;
  1715. }
  1716. EXPORT_SYMBOL_GPL(spi_async_locked);
  1717. /*-------------------------------------------------------------------------*/
  1718. /* Utility methods for SPI master protocol drivers, layered on
  1719. * top of the core. Some other utility methods are defined as
  1720. * inline functions.
  1721. */
  1722. static void spi_complete(void *arg)
  1723. {
  1724. complete(arg);
  1725. }
  1726. static int __spi_sync(struct spi_device *spi, struct spi_message *message,
  1727. int bus_locked)
  1728. {
  1729. DECLARE_COMPLETION_ONSTACK(done);
  1730. int status;
  1731. struct spi_master *master = spi->master;
  1732. unsigned long flags;
  1733. status = __spi_validate(spi, message);
  1734. if (status != 0)
  1735. return status;
  1736. message->complete = spi_complete;
  1737. message->context = &done;
  1738. message->spi = spi;
  1739. if (!bus_locked)
  1740. mutex_lock(&master->bus_lock_mutex);
  1741. /* If we're not using the legacy transfer method then we will
  1742. * try to transfer in the calling context so special case.
  1743. * This code would be less tricky if we could remove the
  1744. * support for driver implemented message queues.
  1745. */
  1746. if (master->transfer == spi_queued_transfer) {
  1747. spin_lock_irqsave(&master->bus_lock_spinlock, flags);
  1748. trace_spi_message_submit(message);
  1749. status = __spi_queued_transfer(spi, message, false);
  1750. spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
  1751. } else {
  1752. status = spi_async_locked(spi, message);
  1753. }
  1754. if (!bus_locked)
  1755. mutex_unlock(&master->bus_lock_mutex);
  1756. if (status == 0) {
  1757. /* Push out the messages in the calling context if we
  1758. * can.
  1759. */
  1760. if (master->transfer == spi_queued_transfer)
  1761. __spi_pump_messages(master, false);
  1762. wait_for_completion(&done);
  1763. status = message->status;
  1764. }
  1765. message->context = NULL;
  1766. return status;
  1767. }
  1768. /**
  1769. * spi_sync - blocking/synchronous SPI data transfers
  1770. * @spi: device with which data will be exchanged
  1771. * @message: describes the data transfers
  1772. * Context: can sleep
  1773. *
  1774. * This call may only be used from a context that may sleep. The sleep
  1775. * is non-interruptible, and has no timeout. Low-overhead controller
  1776. * drivers may DMA directly into and out of the message buffers.
  1777. *
  1778. * Note that the SPI device's chip select is active during the message,
  1779. * and then is normally disabled between messages. Drivers for some
  1780. * frequently-used devices may want to minimize costs of selecting a chip,
  1781. * by leaving it selected in anticipation that the next message will go
  1782. * to the same chip. (That may increase power usage.)
  1783. *
  1784. * Also, the caller is guaranteeing that the memory associated with the
  1785. * message will not be freed before this call returns.
  1786. *
  1787. * It returns zero on success, else a negative error code.
  1788. */
  1789. int spi_sync(struct spi_device *spi, struct spi_message *message)
  1790. {
  1791. return __spi_sync(spi, message, 0);
  1792. }
  1793. EXPORT_SYMBOL_GPL(spi_sync);
  1794. /**
  1795. * spi_sync_locked - version of spi_sync with exclusive bus usage
  1796. * @spi: device with which data will be exchanged
  1797. * @message: describes the data transfers
  1798. * Context: can sleep
  1799. *
  1800. * This call may only be used from a context that may sleep. The sleep
  1801. * is non-interruptible, and has no timeout. Low-overhead controller
  1802. * drivers may DMA directly into and out of the message buffers.
  1803. *
  1804. * This call should be used by drivers that require exclusive access to the
  1805. * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
  1806. * be released by a spi_bus_unlock call when the exclusive access is over.
  1807. *
  1808. * It returns zero on success, else a negative error code.
  1809. */
  1810. int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
  1811. {
  1812. return __spi_sync(spi, message, 1);
  1813. }
  1814. EXPORT_SYMBOL_GPL(spi_sync_locked);
  1815. /**
  1816. * spi_bus_lock - obtain a lock for exclusive SPI bus usage
  1817. * @master: SPI bus master that should be locked for exclusive bus access
  1818. * Context: can sleep
  1819. *
  1820. * This call may only be used from a context that may sleep. The sleep
  1821. * is non-interruptible, and has no timeout.
  1822. *
  1823. * This call should be used by drivers that require exclusive access to the
  1824. * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
  1825. * exclusive access is over. Data transfer must be done by spi_sync_locked
  1826. * and spi_async_locked calls when the SPI bus lock is held.
  1827. *
  1828. * It returns zero on success, else a negative error code.
  1829. */
  1830. int spi_bus_lock(struct spi_master *master)
  1831. {
  1832. unsigned long flags;
  1833. mutex_lock(&master->bus_lock_mutex);
  1834. spin_lock_irqsave(&master->bus_lock_spinlock, flags);
  1835. master->bus_lock_flag = 1;
  1836. spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
  1837. /* mutex remains locked until spi_bus_unlock is called */
  1838. return 0;
  1839. }
  1840. EXPORT_SYMBOL_GPL(spi_bus_lock);
  1841. /**
  1842. * spi_bus_unlock - release the lock for exclusive SPI bus usage
  1843. * @master: SPI bus master that was locked for exclusive bus access
  1844. * Context: can sleep
  1845. *
  1846. * This call may only be used from a context that may sleep. The sleep
  1847. * is non-interruptible, and has no timeout.
  1848. *
  1849. * This call releases an SPI bus lock previously obtained by an spi_bus_lock
  1850. * call.
  1851. *
  1852. * It returns zero on success, else a negative error code.
  1853. */
  1854. int spi_bus_unlock(struct spi_master *master)
  1855. {
  1856. master->bus_lock_flag = 0;
  1857. mutex_unlock(&master->bus_lock_mutex);
  1858. return 0;
  1859. }
  1860. EXPORT_SYMBOL_GPL(spi_bus_unlock);
  1861. /* portable code must never pass more than 32 bytes */
  1862. #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
  1863. static u8 *buf;
  1864. /**
  1865. * spi_write_then_read - SPI synchronous write followed by read
  1866. * @spi: device with which data will be exchanged
  1867. * @txbuf: data to be written (need not be dma-safe)
  1868. * @n_tx: size of txbuf, in bytes
  1869. * @rxbuf: buffer into which data will be read (need not be dma-safe)
  1870. * @n_rx: size of rxbuf, in bytes
  1871. * Context: can sleep
  1872. *
  1873. * This performs a half duplex MicroWire style transaction with the
  1874. * device, sending txbuf and then reading rxbuf. The return value
  1875. * is zero for success, else a negative errno status code.
  1876. * This call may only be used from a context that may sleep.
  1877. *
  1878. * Parameters to this routine are always copied using a small buffer;
  1879. * portable code should never use this for more than 32 bytes.
  1880. * Performance-sensitive or bulk transfer code should instead use
  1881. * spi_{async,sync}() calls with dma-safe buffers.
  1882. */
  1883. int spi_write_then_read(struct spi_device *spi,
  1884. const void *txbuf, unsigned n_tx,
  1885. void *rxbuf, unsigned n_rx)
  1886. {
  1887. static DEFINE_MUTEX(lock);
  1888. int status;
  1889. struct spi_message message;
  1890. struct spi_transfer x[2];
  1891. u8 *local_buf;
  1892. /* Use preallocated DMA-safe buffer if we can. We can't avoid
  1893. * copying here, (as a pure convenience thing), but we can
  1894. * keep heap costs out of the hot path unless someone else is
  1895. * using the pre-allocated buffer or the transfer is too large.
  1896. */
  1897. if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
  1898. local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
  1899. GFP_KERNEL | GFP_DMA);
  1900. if (!local_buf)
  1901. return -ENOMEM;
  1902. } else {
  1903. local_buf = buf;
  1904. }
  1905. spi_message_init(&message);
  1906. memset(x, 0, sizeof(x));
  1907. if (n_tx) {
  1908. x[0].len = n_tx;
  1909. spi_message_add_tail(&x[0], &message);
  1910. }
  1911. if (n_rx) {
  1912. x[1].len = n_rx;
  1913. spi_message_add_tail(&x[1], &message);
  1914. }
  1915. memcpy(local_buf, txbuf, n_tx);
  1916. x[0].tx_buf = local_buf;
  1917. x[1].rx_buf = local_buf + n_tx;
  1918. /* do the i/o */
  1919. status = spi_sync(spi, &message);
  1920. if (status == 0)
  1921. memcpy(rxbuf, x[1].rx_buf, n_rx);
  1922. if (x[0].tx_buf == buf)
  1923. mutex_unlock(&lock);
  1924. else
  1925. kfree(local_buf);
  1926. return status;
  1927. }
  1928. EXPORT_SYMBOL_GPL(spi_write_then_read);
  1929. /*-------------------------------------------------------------------------*/
  1930. #if IS_ENABLED(CONFIG_OF_DYNAMIC)
  1931. static int __spi_of_device_match(struct device *dev, void *data)
  1932. {
  1933. return dev->of_node == data;
  1934. }
  1935. /* must call put_device() when done with returned spi_device device */
  1936. static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
  1937. {
  1938. struct device *dev = bus_find_device(&spi_bus_type, NULL, node,
  1939. __spi_of_device_match);
  1940. return dev ? to_spi_device(dev) : NULL;
  1941. }
  1942. static int __spi_of_master_match(struct device *dev, const void *data)
  1943. {
  1944. return dev->of_node == data;
  1945. }
  1946. /* the spi masters are not using spi_bus, so we find it with another way */
  1947. static struct spi_master *of_find_spi_master_by_node(struct device_node *node)
  1948. {
  1949. struct device *dev;
  1950. dev = class_find_device(&spi_master_class, NULL, node,
  1951. __spi_of_master_match);
  1952. if (!dev)
  1953. return NULL;
  1954. /* reference got in class_find_device */
  1955. return container_of(dev, struct spi_master, dev);
  1956. }
  1957. static int of_spi_notify(struct notifier_block *nb, unsigned long action,
  1958. void *arg)
  1959. {
  1960. struct of_reconfig_data *rd = arg;
  1961. struct spi_master *master;
  1962. struct spi_device *spi;
  1963. switch (of_reconfig_get_state_change(action, arg)) {
  1964. case OF_RECONFIG_CHANGE_ADD:
  1965. master = of_find_spi_master_by_node(rd->dn->parent);
  1966. if (master == NULL)
  1967. return NOTIFY_OK; /* not for us */
  1968. spi = of_register_spi_device(master, rd->dn);
  1969. put_device(&master->dev);
  1970. if (IS_ERR(spi)) {
  1971. pr_err("%s: failed to create for '%s'\n",
  1972. __func__, rd->dn->full_name);
  1973. return notifier_from_errno(PTR_ERR(spi));
  1974. }
  1975. break;
  1976. case OF_RECONFIG_CHANGE_REMOVE:
  1977. /* find our device by node */
  1978. spi = of_find_spi_device_by_node(rd->dn);
  1979. if (spi == NULL)
  1980. return NOTIFY_OK; /* no? not meant for us */
  1981. /* unregister takes one ref away */
  1982. spi_unregister_device(spi);
  1983. /* and put the reference of the find */
  1984. put_device(&spi->dev);
  1985. break;
  1986. }
  1987. return NOTIFY_OK;
  1988. }
  1989. static struct notifier_block spi_of_notifier = {
  1990. .notifier_call = of_spi_notify,
  1991. };
  1992. #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
  1993. extern struct notifier_block spi_of_notifier;
  1994. #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
  1995. static int __init spi_init(void)
  1996. {
  1997. int status;
  1998. buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
  1999. if (!buf) {
  2000. status = -ENOMEM;
  2001. goto err0;
  2002. }
  2003. status = bus_register(&spi_bus_type);
  2004. if (status < 0)
  2005. goto err1;
  2006. status = class_register(&spi_master_class);
  2007. if (status < 0)
  2008. goto err2;
  2009. if (IS_ENABLED(CONFIG_OF_DYNAMIC))
  2010. WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
  2011. return 0;
  2012. err2:
  2013. bus_unregister(&spi_bus_type);
  2014. err1:
  2015. kfree(buf);
  2016. buf = NULL;
  2017. err0:
  2018. return status;
  2019. }
  2020. /* board_info is normally registered in arch_initcall(),
  2021. * but even essential drivers wait till later
  2022. *
  2023. * REVISIT only boardinfo really needs static linking. the rest (device and
  2024. * driver registration) _could_ be dynamically linked (modular) ... costs
  2025. * include needing to have boardinfo data structures be much more public.
  2026. */
  2027. postcore_initcall(spi_init);