spi.c 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398
  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. if (!master->can_dma(master, msg->spi, xfer))
  490. continue;
  491. spi_unmap_buf(master, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
  492. spi_unmap_buf(master, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
  493. }
  494. return 0;
  495. }
  496. #else /* !CONFIG_HAS_DMA */
  497. static inline int __spi_map_msg(struct spi_master *master,
  498. struct spi_message *msg)
  499. {
  500. return 0;
  501. }
  502. static inline int spi_unmap_msg(struct spi_master *master,
  503. struct spi_message *msg)
  504. {
  505. return 0;
  506. }
  507. #endif /* !CONFIG_HAS_DMA */
  508. static int spi_map_msg(struct spi_master *master, struct spi_message *msg)
  509. {
  510. struct spi_transfer *xfer;
  511. void *tmp;
  512. unsigned int max_tx, max_rx;
  513. if (master->flags & (SPI_MASTER_MUST_RX | SPI_MASTER_MUST_TX)) {
  514. max_tx = 0;
  515. max_rx = 0;
  516. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  517. if ((master->flags & SPI_MASTER_MUST_TX) &&
  518. !xfer->tx_buf)
  519. max_tx = max(xfer->len, max_tx);
  520. if ((master->flags & SPI_MASTER_MUST_RX) &&
  521. !xfer->rx_buf)
  522. max_rx = max(xfer->len, max_rx);
  523. }
  524. if (max_tx) {
  525. tmp = krealloc(master->dummy_tx, max_tx,
  526. GFP_KERNEL | GFP_DMA);
  527. if (!tmp)
  528. return -ENOMEM;
  529. master->dummy_tx = tmp;
  530. memset(tmp, 0, max_tx);
  531. }
  532. if (max_rx) {
  533. tmp = krealloc(master->dummy_rx, max_rx,
  534. GFP_KERNEL | GFP_DMA);
  535. if (!tmp)
  536. return -ENOMEM;
  537. master->dummy_rx = tmp;
  538. }
  539. if (max_tx || max_rx) {
  540. list_for_each_entry(xfer, &msg->transfers,
  541. transfer_list) {
  542. if (!xfer->tx_buf)
  543. xfer->tx_buf = master->dummy_tx;
  544. if (!xfer->rx_buf)
  545. xfer->rx_buf = master->dummy_rx;
  546. }
  547. }
  548. }
  549. return __spi_map_msg(master, msg);
  550. }
  551. /*
  552. * spi_transfer_one_message - Default implementation of transfer_one_message()
  553. *
  554. * This is a standard implementation of transfer_one_message() for
  555. * drivers which impelment a transfer_one() operation. It provides
  556. * standard handling of delays and chip select management.
  557. */
  558. static int spi_transfer_one_message(struct spi_master *master,
  559. struct spi_message *msg)
  560. {
  561. struct spi_transfer *xfer;
  562. bool keep_cs = false;
  563. int ret = 0;
  564. unsigned long ms = 1;
  565. spi_set_cs(msg->spi, true);
  566. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  567. trace_spi_transfer_start(msg, xfer);
  568. if (xfer->tx_buf || xfer->rx_buf) {
  569. reinit_completion(&master->xfer_completion);
  570. ret = master->transfer_one(master, msg->spi, xfer);
  571. if (ret < 0) {
  572. dev_err(&msg->spi->dev,
  573. "SPI transfer failed: %d\n", ret);
  574. goto out;
  575. }
  576. if (ret > 0) {
  577. ret = 0;
  578. ms = xfer->len * 8 * 1000 / xfer->speed_hz;
  579. ms += ms + 100; /* some tolerance */
  580. ms = wait_for_completion_timeout(&master->xfer_completion,
  581. msecs_to_jiffies(ms));
  582. }
  583. if (ms == 0) {
  584. dev_err(&msg->spi->dev,
  585. "SPI transfer timed out\n");
  586. msg->status = -ETIMEDOUT;
  587. }
  588. } else {
  589. if (xfer->len)
  590. dev_err(&msg->spi->dev,
  591. "Bufferless transfer has length %u\n",
  592. xfer->len);
  593. }
  594. trace_spi_transfer_stop(msg, xfer);
  595. if (msg->status != -EINPROGRESS)
  596. goto out;
  597. if (xfer->delay_usecs)
  598. udelay(xfer->delay_usecs);
  599. if (xfer->cs_change) {
  600. if (list_is_last(&xfer->transfer_list,
  601. &msg->transfers)) {
  602. keep_cs = true;
  603. } else {
  604. spi_set_cs(msg->spi, false);
  605. udelay(10);
  606. spi_set_cs(msg->spi, true);
  607. }
  608. }
  609. msg->actual_length += xfer->len;
  610. }
  611. out:
  612. if (ret != 0 || !keep_cs)
  613. spi_set_cs(msg->spi, false);
  614. if (msg->status == -EINPROGRESS)
  615. msg->status = ret;
  616. if (msg->status && master->handle_err)
  617. master->handle_err(master, msg);
  618. spi_finalize_current_message(master);
  619. return ret;
  620. }
  621. /**
  622. * spi_finalize_current_transfer - report completion of a transfer
  623. * @master: the master reporting completion
  624. *
  625. * Called by SPI drivers using the core transfer_one_message()
  626. * implementation to notify it that the current interrupt driven
  627. * transfer has finished and the next one may be scheduled.
  628. */
  629. void spi_finalize_current_transfer(struct spi_master *master)
  630. {
  631. complete(&master->xfer_completion);
  632. }
  633. EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
  634. /**
  635. * __spi_pump_messages - function which processes spi message queue
  636. * @master: master to process queue for
  637. * @in_kthread: true if we are in the context of the message pump thread
  638. *
  639. * This function checks if there is any spi message in the queue that
  640. * needs processing and if so call out to the driver to initialize hardware
  641. * and transfer each message.
  642. *
  643. * Note that it is called both from the kthread itself and also from
  644. * inside spi_sync(); the queue extraction handling at the top of the
  645. * function should deal with this safely.
  646. */
  647. static void __spi_pump_messages(struct spi_master *master, bool in_kthread)
  648. {
  649. unsigned long flags;
  650. bool was_busy = false;
  651. int ret;
  652. /* Lock queue */
  653. spin_lock_irqsave(&master->queue_lock, flags);
  654. /* Make sure we are not already running a message */
  655. if (master->cur_msg) {
  656. spin_unlock_irqrestore(&master->queue_lock, flags);
  657. return;
  658. }
  659. /* If another context is idling the device then defer */
  660. if (master->idling) {
  661. queue_kthread_work(&master->kworker, &master->pump_messages);
  662. spin_unlock_irqrestore(&master->queue_lock, flags);
  663. return;
  664. }
  665. /* Check if the queue is idle */
  666. if (list_empty(&master->queue) || !master->running) {
  667. if (!master->busy) {
  668. spin_unlock_irqrestore(&master->queue_lock, flags);
  669. return;
  670. }
  671. /* Only do teardown in the thread */
  672. if (!in_kthread) {
  673. queue_kthread_work(&master->kworker,
  674. &master->pump_messages);
  675. spin_unlock_irqrestore(&master->queue_lock, flags);
  676. return;
  677. }
  678. master->busy = false;
  679. master->idling = true;
  680. spin_unlock_irqrestore(&master->queue_lock, flags);
  681. kfree(master->dummy_rx);
  682. master->dummy_rx = NULL;
  683. kfree(master->dummy_tx);
  684. master->dummy_tx = NULL;
  685. if (master->unprepare_transfer_hardware &&
  686. master->unprepare_transfer_hardware(master))
  687. dev_err(&master->dev,
  688. "failed to unprepare transfer hardware\n");
  689. if (master->auto_runtime_pm) {
  690. pm_runtime_mark_last_busy(master->dev.parent);
  691. pm_runtime_put_autosuspend(master->dev.parent);
  692. }
  693. trace_spi_master_idle(master);
  694. spin_lock_irqsave(&master->queue_lock, flags);
  695. master->idling = false;
  696. spin_unlock_irqrestore(&master->queue_lock, flags);
  697. return;
  698. }
  699. /* Extract head of queue */
  700. master->cur_msg =
  701. list_first_entry(&master->queue, struct spi_message, queue);
  702. list_del_init(&master->cur_msg->queue);
  703. if (master->busy)
  704. was_busy = true;
  705. else
  706. master->busy = true;
  707. spin_unlock_irqrestore(&master->queue_lock, flags);
  708. if (!was_busy && master->auto_runtime_pm) {
  709. ret = pm_runtime_get_sync(master->dev.parent);
  710. if (ret < 0) {
  711. dev_err(&master->dev, "Failed to power device: %d\n",
  712. ret);
  713. return;
  714. }
  715. }
  716. if (!was_busy)
  717. trace_spi_master_busy(master);
  718. if (!was_busy && master->prepare_transfer_hardware) {
  719. ret = master->prepare_transfer_hardware(master);
  720. if (ret) {
  721. dev_err(&master->dev,
  722. "failed to prepare transfer hardware\n");
  723. if (master->auto_runtime_pm)
  724. pm_runtime_put(master->dev.parent);
  725. return;
  726. }
  727. }
  728. trace_spi_message_start(master->cur_msg);
  729. if (master->prepare_message) {
  730. ret = master->prepare_message(master, master->cur_msg);
  731. if (ret) {
  732. dev_err(&master->dev,
  733. "failed to prepare message: %d\n", ret);
  734. master->cur_msg->status = ret;
  735. spi_finalize_current_message(master);
  736. return;
  737. }
  738. master->cur_msg_prepared = true;
  739. }
  740. ret = spi_map_msg(master, master->cur_msg);
  741. if (ret) {
  742. master->cur_msg->status = ret;
  743. spi_finalize_current_message(master);
  744. return;
  745. }
  746. ret = master->transfer_one_message(master, master->cur_msg);
  747. if (ret) {
  748. dev_err(&master->dev,
  749. "failed to transfer one message from queue\n");
  750. return;
  751. }
  752. }
  753. /**
  754. * spi_pump_messages - kthread work function which processes spi message queue
  755. * @work: pointer to kthread work struct contained in the master struct
  756. */
  757. static void spi_pump_messages(struct kthread_work *work)
  758. {
  759. struct spi_master *master =
  760. container_of(work, struct spi_master, pump_messages);
  761. __spi_pump_messages(master, true);
  762. }
  763. static int spi_init_queue(struct spi_master *master)
  764. {
  765. struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
  766. master->running = false;
  767. master->busy = false;
  768. init_kthread_worker(&master->kworker);
  769. master->kworker_task = kthread_run(kthread_worker_fn,
  770. &master->kworker, "%s",
  771. dev_name(&master->dev));
  772. if (IS_ERR(master->kworker_task)) {
  773. dev_err(&master->dev, "failed to create message pump task\n");
  774. return PTR_ERR(master->kworker_task);
  775. }
  776. init_kthread_work(&master->pump_messages, spi_pump_messages);
  777. /*
  778. * Master config will indicate if this controller should run the
  779. * message pump with high (realtime) priority to reduce the transfer
  780. * latency on the bus by minimising the delay between a transfer
  781. * request and the scheduling of the message pump thread. Without this
  782. * setting the message pump thread will remain at default priority.
  783. */
  784. if (master->rt) {
  785. dev_info(&master->dev,
  786. "will run message pump with realtime priority\n");
  787. sched_setscheduler(master->kworker_task, SCHED_FIFO, &param);
  788. }
  789. return 0;
  790. }
  791. /**
  792. * spi_get_next_queued_message() - called by driver to check for queued
  793. * messages
  794. * @master: the master to check for queued messages
  795. *
  796. * If there are more messages in the queue, the next message is returned from
  797. * this call.
  798. */
  799. struct spi_message *spi_get_next_queued_message(struct spi_master *master)
  800. {
  801. struct spi_message *next;
  802. unsigned long flags;
  803. /* get a pointer to the next message, if any */
  804. spin_lock_irqsave(&master->queue_lock, flags);
  805. next = list_first_entry_or_null(&master->queue, struct spi_message,
  806. queue);
  807. spin_unlock_irqrestore(&master->queue_lock, flags);
  808. return next;
  809. }
  810. EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
  811. /**
  812. * spi_finalize_current_message() - the current message is complete
  813. * @master: the master to return the message to
  814. *
  815. * Called by the driver to notify the core that the message in the front of the
  816. * queue is complete and can be removed from the queue.
  817. */
  818. void spi_finalize_current_message(struct spi_master *master)
  819. {
  820. struct spi_message *mesg;
  821. unsigned long flags;
  822. int ret;
  823. spin_lock_irqsave(&master->queue_lock, flags);
  824. mesg = master->cur_msg;
  825. master->cur_msg = NULL;
  826. queue_kthread_work(&master->kworker, &master->pump_messages);
  827. spin_unlock_irqrestore(&master->queue_lock, flags);
  828. spi_unmap_msg(master, mesg);
  829. if (master->cur_msg_prepared && master->unprepare_message) {
  830. ret = master->unprepare_message(master, mesg);
  831. if (ret) {
  832. dev_err(&master->dev,
  833. "failed to unprepare message: %d\n", ret);
  834. }
  835. }
  836. trace_spi_message_done(mesg);
  837. master->cur_msg_prepared = false;
  838. mesg->state = NULL;
  839. if (mesg->complete)
  840. mesg->complete(mesg->context);
  841. }
  842. EXPORT_SYMBOL_GPL(spi_finalize_current_message);
  843. static int spi_start_queue(struct spi_master *master)
  844. {
  845. unsigned long flags;
  846. spin_lock_irqsave(&master->queue_lock, flags);
  847. if (master->running || master->busy) {
  848. spin_unlock_irqrestore(&master->queue_lock, flags);
  849. return -EBUSY;
  850. }
  851. master->running = true;
  852. master->cur_msg = NULL;
  853. spin_unlock_irqrestore(&master->queue_lock, flags);
  854. queue_kthread_work(&master->kworker, &master->pump_messages);
  855. return 0;
  856. }
  857. static int spi_stop_queue(struct spi_master *master)
  858. {
  859. unsigned long flags;
  860. unsigned limit = 500;
  861. int ret = 0;
  862. spin_lock_irqsave(&master->queue_lock, flags);
  863. /*
  864. * This is a bit lame, but is optimized for the common execution path.
  865. * A wait_queue on the master->busy could be used, but then the common
  866. * execution path (pump_messages) would be required to call wake_up or
  867. * friends on every SPI message. Do this instead.
  868. */
  869. while ((!list_empty(&master->queue) || master->busy) && limit--) {
  870. spin_unlock_irqrestore(&master->queue_lock, flags);
  871. usleep_range(10000, 11000);
  872. spin_lock_irqsave(&master->queue_lock, flags);
  873. }
  874. if (!list_empty(&master->queue) || master->busy)
  875. ret = -EBUSY;
  876. else
  877. master->running = false;
  878. spin_unlock_irqrestore(&master->queue_lock, flags);
  879. if (ret) {
  880. dev_warn(&master->dev,
  881. "could not stop message queue\n");
  882. return ret;
  883. }
  884. return ret;
  885. }
  886. static int spi_destroy_queue(struct spi_master *master)
  887. {
  888. int ret;
  889. ret = spi_stop_queue(master);
  890. /*
  891. * flush_kthread_worker will block until all work is done.
  892. * If the reason that stop_queue timed out is that the work will never
  893. * finish, then it does no good to call flush/stop thread, so
  894. * return anyway.
  895. */
  896. if (ret) {
  897. dev_err(&master->dev, "problem destroying queue\n");
  898. return ret;
  899. }
  900. flush_kthread_worker(&master->kworker);
  901. kthread_stop(master->kworker_task);
  902. return 0;
  903. }
  904. static int __spi_queued_transfer(struct spi_device *spi,
  905. struct spi_message *msg,
  906. bool need_pump)
  907. {
  908. struct spi_master *master = spi->master;
  909. unsigned long flags;
  910. spin_lock_irqsave(&master->queue_lock, flags);
  911. if (!master->running) {
  912. spin_unlock_irqrestore(&master->queue_lock, flags);
  913. return -ESHUTDOWN;
  914. }
  915. msg->actual_length = 0;
  916. msg->status = -EINPROGRESS;
  917. list_add_tail(&msg->queue, &master->queue);
  918. if (!master->busy && need_pump)
  919. queue_kthread_work(&master->kworker, &master->pump_messages);
  920. spin_unlock_irqrestore(&master->queue_lock, flags);
  921. return 0;
  922. }
  923. /**
  924. * spi_queued_transfer - transfer function for queued transfers
  925. * @spi: spi device which is requesting transfer
  926. * @msg: spi message which is to handled is queued to driver queue
  927. */
  928. static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
  929. {
  930. return __spi_queued_transfer(spi, msg, true);
  931. }
  932. static int spi_master_initialize_queue(struct spi_master *master)
  933. {
  934. int ret;
  935. master->transfer = spi_queued_transfer;
  936. if (!master->transfer_one_message)
  937. master->transfer_one_message = spi_transfer_one_message;
  938. /* Initialize and start queue */
  939. ret = spi_init_queue(master);
  940. if (ret) {
  941. dev_err(&master->dev, "problem initializing queue\n");
  942. goto err_init_queue;
  943. }
  944. master->queued = true;
  945. ret = spi_start_queue(master);
  946. if (ret) {
  947. dev_err(&master->dev, "problem starting queue\n");
  948. goto err_start_queue;
  949. }
  950. return 0;
  951. err_start_queue:
  952. spi_destroy_queue(master);
  953. err_init_queue:
  954. return ret;
  955. }
  956. /*-------------------------------------------------------------------------*/
  957. #if defined(CONFIG_OF)
  958. static struct spi_device *
  959. of_register_spi_device(struct spi_master *master, struct device_node *nc)
  960. {
  961. struct spi_device *spi;
  962. int rc;
  963. u32 value;
  964. /* Alloc an spi_device */
  965. spi = spi_alloc_device(master);
  966. if (!spi) {
  967. dev_err(&master->dev, "spi_device alloc error for %s\n",
  968. nc->full_name);
  969. rc = -ENOMEM;
  970. goto err_out;
  971. }
  972. /* Select device driver */
  973. rc = of_modalias_node(nc, spi->modalias,
  974. sizeof(spi->modalias));
  975. if (rc < 0) {
  976. dev_err(&master->dev, "cannot find modalias for %s\n",
  977. nc->full_name);
  978. goto err_out;
  979. }
  980. /* Device address */
  981. rc = of_property_read_u32(nc, "reg", &value);
  982. if (rc) {
  983. dev_err(&master->dev, "%s has no valid 'reg' property (%d)\n",
  984. nc->full_name, rc);
  985. goto err_out;
  986. }
  987. spi->chip_select = value;
  988. /* Mode (clock phase/polarity/etc.) */
  989. if (of_find_property(nc, "spi-cpha", NULL))
  990. spi->mode |= SPI_CPHA;
  991. if (of_find_property(nc, "spi-cpol", NULL))
  992. spi->mode |= SPI_CPOL;
  993. if (of_find_property(nc, "spi-cs-high", NULL))
  994. spi->mode |= SPI_CS_HIGH;
  995. if (of_find_property(nc, "spi-3wire", NULL))
  996. spi->mode |= SPI_3WIRE;
  997. if (of_find_property(nc, "spi-lsb-first", NULL))
  998. spi->mode |= SPI_LSB_FIRST;
  999. /* Device DUAL/QUAD mode */
  1000. if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
  1001. switch (value) {
  1002. case 1:
  1003. break;
  1004. case 2:
  1005. spi->mode |= SPI_TX_DUAL;
  1006. break;
  1007. case 4:
  1008. spi->mode |= SPI_TX_QUAD;
  1009. break;
  1010. default:
  1011. dev_warn(&master->dev,
  1012. "spi-tx-bus-width %d not supported\n",
  1013. value);
  1014. break;
  1015. }
  1016. }
  1017. if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
  1018. switch (value) {
  1019. case 1:
  1020. break;
  1021. case 2:
  1022. spi->mode |= SPI_RX_DUAL;
  1023. break;
  1024. case 4:
  1025. spi->mode |= SPI_RX_QUAD;
  1026. break;
  1027. default:
  1028. dev_warn(&master->dev,
  1029. "spi-rx-bus-width %d not supported\n",
  1030. value);
  1031. break;
  1032. }
  1033. }
  1034. /* Device speed */
  1035. rc = of_property_read_u32(nc, "spi-max-frequency", &value);
  1036. if (rc) {
  1037. dev_err(&master->dev, "%s has no valid 'spi-max-frequency' property (%d)\n",
  1038. nc->full_name, rc);
  1039. goto err_out;
  1040. }
  1041. spi->max_speed_hz = value;
  1042. /* IRQ */
  1043. spi->irq = irq_of_parse_and_map(nc, 0);
  1044. /* Store a pointer to the node in the device structure */
  1045. of_node_get(nc);
  1046. spi->dev.of_node = nc;
  1047. /* Register the new device */
  1048. rc = spi_add_device(spi);
  1049. if (rc) {
  1050. dev_err(&master->dev, "spi_device register error %s\n",
  1051. nc->full_name);
  1052. goto err_out;
  1053. }
  1054. return spi;
  1055. err_out:
  1056. spi_dev_put(spi);
  1057. return ERR_PTR(rc);
  1058. }
  1059. /**
  1060. * of_register_spi_devices() - Register child devices onto the SPI bus
  1061. * @master: Pointer to spi_master device
  1062. *
  1063. * Registers an spi_device for each child node of master node which has a 'reg'
  1064. * property.
  1065. */
  1066. static void of_register_spi_devices(struct spi_master *master)
  1067. {
  1068. struct spi_device *spi;
  1069. struct device_node *nc;
  1070. if (!master->dev.of_node)
  1071. return;
  1072. for_each_available_child_of_node(master->dev.of_node, nc) {
  1073. spi = of_register_spi_device(master, nc);
  1074. if (IS_ERR(spi))
  1075. dev_warn(&master->dev, "Failed to create SPI device for %s\n",
  1076. nc->full_name);
  1077. }
  1078. }
  1079. #else
  1080. static void of_register_spi_devices(struct spi_master *master) { }
  1081. #endif
  1082. #ifdef CONFIG_ACPI
  1083. static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
  1084. {
  1085. struct spi_device *spi = data;
  1086. if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
  1087. struct acpi_resource_spi_serialbus *sb;
  1088. sb = &ares->data.spi_serial_bus;
  1089. if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
  1090. spi->chip_select = sb->device_selection;
  1091. spi->max_speed_hz = sb->connection_speed;
  1092. if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
  1093. spi->mode |= SPI_CPHA;
  1094. if (sb->clock_polarity == ACPI_SPI_START_HIGH)
  1095. spi->mode |= SPI_CPOL;
  1096. if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
  1097. spi->mode |= SPI_CS_HIGH;
  1098. }
  1099. } else if (spi->irq < 0) {
  1100. struct resource r;
  1101. if (acpi_dev_resource_interrupt(ares, 0, &r))
  1102. spi->irq = r.start;
  1103. }
  1104. /* Always tell the ACPI core to skip this resource */
  1105. return 1;
  1106. }
  1107. static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
  1108. void *data, void **return_value)
  1109. {
  1110. struct spi_master *master = data;
  1111. struct list_head resource_list;
  1112. struct acpi_device *adev;
  1113. struct spi_device *spi;
  1114. int ret;
  1115. if (acpi_bus_get_device(handle, &adev))
  1116. return AE_OK;
  1117. if (acpi_bus_get_status(adev) || !adev->status.present)
  1118. return AE_OK;
  1119. spi = spi_alloc_device(master);
  1120. if (!spi) {
  1121. dev_err(&master->dev, "failed to allocate SPI device for %s\n",
  1122. dev_name(&adev->dev));
  1123. return AE_NO_MEMORY;
  1124. }
  1125. ACPI_COMPANION_SET(&spi->dev, adev);
  1126. spi->irq = -1;
  1127. INIT_LIST_HEAD(&resource_list);
  1128. ret = acpi_dev_get_resources(adev, &resource_list,
  1129. acpi_spi_add_resource, spi);
  1130. acpi_dev_free_resource_list(&resource_list);
  1131. if (ret < 0 || !spi->max_speed_hz) {
  1132. spi_dev_put(spi);
  1133. return AE_OK;
  1134. }
  1135. adev->power.flags.ignore_parent = true;
  1136. strlcpy(spi->modalias, acpi_device_hid(adev), sizeof(spi->modalias));
  1137. if (spi_add_device(spi)) {
  1138. adev->power.flags.ignore_parent = false;
  1139. dev_err(&master->dev, "failed to add SPI device %s from ACPI\n",
  1140. dev_name(&adev->dev));
  1141. spi_dev_put(spi);
  1142. }
  1143. return AE_OK;
  1144. }
  1145. static void acpi_register_spi_devices(struct spi_master *master)
  1146. {
  1147. acpi_status status;
  1148. acpi_handle handle;
  1149. handle = ACPI_HANDLE(master->dev.parent);
  1150. if (!handle)
  1151. return;
  1152. status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
  1153. acpi_spi_add_device, NULL,
  1154. master, NULL);
  1155. if (ACPI_FAILURE(status))
  1156. dev_warn(&master->dev, "failed to enumerate SPI slaves\n");
  1157. }
  1158. #else
  1159. static inline void acpi_register_spi_devices(struct spi_master *master) {}
  1160. #endif /* CONFIG_ACPI */
  1161. static void spi_master_release(struct device *dev)
  1162. {
  1163. struct spi_master *master;
  1164. master = container_of(dev, struct spi_master, dev);
  1165. kfree(master);
  1166. }
  1167. static struct class spi_master_class = {
  1168. .name = "spi_master",
  1169. .owner = THIS_MODULE,
  1170. .dev_release = spi_master_release,
  1171. };
  1172. /**
  1173. * spi_alloc_master - allocate SPI master controller
  1174. * @dev: the controller, possibly using the platform_bus
  1175. * @size: how much zeroed driver-private data to allocate; the pointer to this
  1176. * memory is in the driver_data field of the returned device,
  1177. * accessible with spi_master_get_devdata().
  1178. * Context: can sleep
  1179. *
  1180. * This call is used only by SPI master controller drivers, which are the
  1181. * only ones directly touching chip registers. It's how they allocate
  1182. * an spi_master structure, prior to calling spi_register_master().
  1183. *
  1184. * This must be called from context that can sleep. It returns the SPI
  1185. * master structure on success, else NULL.
  1186. *
  1187. * The caller is responsible for assigning the bus number and initializing
  1188. * the master's methods before calling spi_register_master(); and (after errors
  1189. * adding the device) calling spi_master_put() and kfree() to prevent a memory
  1190. * leak.
  1191. */
  1192. struct spi_master *spi_alloc_master(struct device *dev, unsigned size)
  1193. {
  1194. struct spi_master *master;
  1195. if (!dev)
  1196. return NULL;
  1197. master = kzalloc(size + sizeof(*master), GFP_KERNEL);
  1198. if (!master)
  1199. return NULL;
  1200. device_initialize(&master->dev);
  1201. master->bus_num = -1;
  1202. master->num_chipselect = 1;
  1203. master->dev.class = &spi_master_class;
  1204. master->dev.parent = get_device(dev);
  1205. spi_master_set_devdata(master, &master[1]);
  1206. return master;
  1207. }
  1208. EXPORT_SYMBOL_GPL(spi_alloc_master);
  1209. #ifdef CONFIG_OF
  1210. static int of_spi_register_master(struct spi_master *master)
  1211. {
  1212. int nb, i, *cs;
  1213. struct device_node *np = master->dev.of_node;
  1214. if (!np)
  1215. return 0;
  1216. nb = of_gpio_named_count(np, "cs-gpios");
  1217. master->num_chipselect = max_t(int, nb, master->num_chipselect);
  1218. /* Return error only for an incorrectly formed cs-gpios property */
  1219. if (nb == 0 || nb == -ENOENT)
  1220. return 0;
  1221. else if (nb < 0)
  1222. return nb;
  1223. cs = devm_kzalloc(&master->dev,
  1224. sizeof(int) * master->num_chipselect,
  1225. GFP_KERNEL);
  1226. master->cs_gpios = cs;
  1227. if (!master->cs_gpios)
  1228. return -ENOMEM;
  1229. for (i = 0; i < master->num_chipselect; i++)
  1230. cs[i] = -ENOENT;
  1231. for (i = 0; i < nb; i++)
  1232. cs[i] = of_get_named_gpio(np, "cs-gpios", i);
  1233. return 0;
  1234. }
  1235. #else
  1236. static int of_spi_register_master(struct spi_master *master)
  1237. {
  1238. return 0;
  1239. }
  1240. #endif
  1241. /**
  1242. * spi_register_master - register SPI master controller
  1243. * @master: initialized master, originally from spi_alloc_master()
  1244. * Context: can sleep
  1245. *
  1246. * SPI master controllers connect to their drivers using some non-SPI bus,
  1247. * such as the platform bus. The final stage of probe() in that code
  1248. * includes calling spi_register_master() to hook up to this SPI bus glue.
  1249. *
  1250. * SPI controllers use board specific (often SOC specific) bus numbers,
  1251. * and board-specific addressing for SPI devices combines those numbers
  1252. * with chip select numbers. Since SPI does not directly support dynamic
  1253. * device identification, boards need configuration tables telling which
  1254. * chip is at which address.
  1255. *
  1256. * This must be called from context that can sleep. It returns zero on
  1257. * success, else a negative error code (dropping the master's refcount).
  1258. * After a successful return, the caller is responsible for calling
  1259. * spi_unregister_master().
  1260. */
  1261. int spi_register_master(struct spi_master *master)
  1262. {
  1263. static atomic_t dyn_bus_id = ATOMIC_INIT((1<<15) - 1);
  1264. struct device *dev = master->dev.parent;
  1265. struct boardinfo *bi;
  1266. int status = -ENODEV;
  1267. int dynamic = 0;
  1268. if (!dev)
  1269. return -ENODEV;
  1270. status = of_spi_register_master(master);
  1271. if (status)
  1272. return status;
  1273. /* even if it's just one always-selected device, there must
  1274. * be at least one chipselect
  1275. */
  1276. if (master->num_chipselect == 0)
  1277. return -EINVAL;
  1278. if ((master->bus_num < 0) && master->dev.of_node)
  1279. master->bus_num = of_alias_get_id(master->dev.of_node, "spi");
  1280. /* convention: dynamically assigned bus IDs count down from the max */
  1281. if (master->bus_num < 0) {
  1282. /* FIXME switch to an IDR based scheme, something like
  1283. * I2C now uses, so we can't run out of "dynamic" IDs
  1284. */
  1285. master->bus_num = atomic_dec_return(&dyn_bus_id);
  1286. dynamic = 1;
  1287. }
  1288. INIT_LIST_HEAD(&master->queue);
  1289. spin_lock_init(&master->queue_lock);
  1290. spin_lock_init(&master->bus_lock_spinlock);
  1291. mutex_init(&master->bus_lock_mutex);
  1292. master->bus_lock_flag = 0;
  1293. init_completion(&master->xfer_completion);
  1294. if (!master->max_dma_len)
  1295. master->max_dma_len = INT_MAX;
  1296. /* register the device, then userspace will see it.
  1297. * registration fails if the bus ID is in use.
  1298. */
  1299. dev_set_name(&master->dev, "spi%u", master->bus_num);
  1300. status = device_add(&master->dev);
  1301. if (status < 0)
  1302. goto done;
  1303. dev_dbg(dev, "registered master %s%s\n", dev_name(&master->dev),
  1304. dynamic ? " (dynamic)" : "");
  1305. /* If we're using a queued driver, start the queue */
  1306. if (master->transfer)
  1307. dev_info(dev, "master is unqueued, this is deprecated\n");
  1308. else {
  1309. status = spi_master_initialize_queue(master);
  1310. if (status) {
  1311. device_del(&master->dev);
  1312. goto done;
  1313. }
  1314. }
  1315. mutex_lock(&board_lock);
  1316. list_add_tail(&master->list, &spi_master_list);
  1317. list_for_each_entry(bi, &board_list, list)
  1318. spi_match_master_to_boardinfo(master, &bi->board_info);
  1319. mutex_unlock(&board_lock);
  1320. /* Register devices from the device tree and ACPI */
  1321. of_register_spi_devices(master);
  1322. acpi_register_spi_devices(master);
  1323. done:
  1324. return status;
  1325. }
  1326. EXPORT_SYMBOL_GPL(spi_register_master);
  1327. static void devm_spi_unregister(struct device *dev, void *res)
  1328. {
  1329. spi_unregister_master(*(struct spi_master **)res);
  1330. }
  1331. /**
  1332. * dev_spi_register_master - register managed SPI master controller
  1333. * @dev: device managing SPI master
  1334. * @master: initialized master, originally from spi_alloc_master()
  1335. * Context: can sleep
  1336. *
  1337. * Register a SPI device as with spi_register_master() which will
  1338. * automatically be unregister
  1339. */
  1340. int devm_spi_register_master(struct device *dev, struct spi_master *master)
  1341. {
  1342. struct spi_master **ptr;
  1343. int ret;
  1344. ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
  1345. if (!ptr)
  1346. return -ENOMEM;
  1347. ret = spi_register_master(master);
  1348. if (!ret) {
  1349. *ptr = master;
  1350. devres_add(dev, ptr);
  1351. } else {
  1352. devres_free(ptr);
  1353. }
  1354. return ret;
  1355. }
  1356. EXPORT_SYMBOL_GPL(devm_spi_register_master);
  1357. static int __unregister(struct device *dev, void *null)
  1358. {
  1359. spi_unregister_device(to_spi_device(dev));
  1360. return 0;
  1361. }
  1362. /**
  1363. * spi_unregister_master - unregister SPI master controller
  1364. * @master: the master being unregistered
  1365. * Context: can sleep
  1366. *
  1367. * This call is used only by SPI master controller drivers, which are the
  1368. * only ones directly touching chip registers.
  1369. *
  1370. * This must be called from context that can sleep.
  1371. */
  1372. void spi_unregister_master(struct spi_master *master)
  1373. {
  1374. int dummy;
  1375. if (master->queued) {
  1376. if (spi_destroy_queue(master))
  1377. dev_err(&master->dev, "queue remove failed\n");
  1378. }
  1379. mutex_lock(&board_lock);
  1380. list_del(&master->list);
  1381. mutex_unlock(&board_lock);
  1382. dummy = device_for_each_child(&master->dev, NULL, __unregister);
  1383. device_unregister(&master->dev);
  1384. }
  1385. EXPORT_SYMBOL_GPL(spi_unregister_master);
  1386. int spi_master_suspend(struct spi_master *master)
  1387. {
  1388. int ret;
  1389. /* Basically no-ops for non-queued masters */
  1390. if (!master->queued)
  1391. return 0;
  1392. ret = spi_stop_queue(master);
  1393. if (ret)
  1394. dev_err(&master->dev, "queue stop failed\n");
  1395. return ret;
  1396. }
  1397. EXPORT_SYMBOL_GPL(spi_master_suspend);
  1398. int spi_master_resume(struct spi_master *master)
  1399. {
  1400. int ret;
  1401. if (!master->queued)
  1402. return 0;
  1403. ret = spi_start_queue(master);
  1404. if (ret)
  1405. dev_err(&master->dev, "queue restart failed\n");
  1406. return ret;
  1407. }
  1408. EXPORT_SYMBOL_GPL(spi_master_resume);
  1409. static int __spi_master_match(struct device *dev, const void *data)
  1410. {
  1411. struct spi_master *m;
  1412. const u16 *bus_num = data;
  1413. m = container_of(dev, struct spi_master, dev);
  1414. return m->bus_num == *bus_num;
  1415. }
  1416. /**
  1417. * spi_busnum_to_master - look up master associated with bus_num
  1418. * @bus_num: the master's bus number
  1419. * Context: can sleep
  1420. *
  1421. * This call may be used with devices that are registered after
  1422. * arch init time. It returns a refcounted pointer to the relevant
  1423. * spi_master (which the caller must release), or NULL if there is
  1424. * no such master registered.
  1425. */
  1426. struct spi_master *spi_busnum_to_master(u16 bus_num)
  1427. {
  1428. struct device *dev;
  1429. struct spi_master *master = NULL;
  1430. dev = class_find_device(&spi_master_class, NULL, &bus_num,
  1431. __spi_master_match);
  1432. if (dev)
  1433. master = container_of(dev, struct spi_master, dev);
  1434. /* reference got in class_find_device */
  1435. return master;
  1436. }
  1437. EXPORT_SYMBOL_GPL(spi_busnum_to_master);
  1438. /*-------------------------------------------------------------------------*/
  1439. /* Core methods for SPI master protocol drivers. Some of the
  1440. * other core methods are currently defined as inline functions.
  1441. */
  1442. /**
  1443. * spi_setup - setup SPI mode and clock rate
  1444. * @spi: the device whose settings are being modified
  1445. * Context: can sleep, and no requests are queued to the device
  1446. *
  1447. * SPI protocol drivers may need to update the transfer mode if the
  1448. * device doesn't work with its default. They may likewise need
  1449. * to update clock rates or word sizes from initial values. This function
  1450. * changes those settings, and must be called from a context that can sleep.
  1451. * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
  1452. * effect the next time the device is selected and data is transferred to
  1453. * or from it. When this function returns, the spi device is deselected.
  1454. *
  1455. * Note that this call will fail if the protocol driver specifies an option
  1456. * that the underlying controller or its driver does not support. For
  1457. * example, not all hardware supports wire transfers using nine bit words,
  1458. * LSB-first wire encoding, or active-high chipselects.
  1459. */
  1460. int spi_setup(struct spi_device *spi)
  1461. {
  1462. unsigned bad_bits, ugly_bits;
  1463. int status = 0;
  1464. /* check mode to prevent that DUAL and QUAD set at the same time
  1465. */
  1466. if (((spi->mode & SPI_TX_DUAL) && (spi->mode & SPI_TX_QUAD)) ||
  1467. ((spi->mode & SPI_RX_DUAL) && (spi->mode & SPI_RX_QUAD))) {
  1468. dev_err(&spi->dev,
  1469. "setup: can not select dual and quad at the same time\n");
  1470. return -EINVAL;
  1471. }
  1472. /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
  1473. */
  1474. if ((spi->mode & SPI_3WIRE) && (spi->mode &
  1475. (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD)))
  1476. return -EINVAL;
  1477. /* help drivers fail *cleanly* when they need options
  1478. * that aren't supported with their current master
  1479. */
  1480. bad_bits = spi->mode & ~spi->master->mode_bits;
  1481. ugly_bits = bad_bits &
  1482. (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD);
  1483. if (ugly_bits) {
  1484. dev_warn(&spi->dev,
  1485. "setup: ignoring unsupported mode bits %x\n",
  1486. ugly_bits);
  1487. spi->mode &= ~ugly_bits;
  1488. bad_bits &= ~ugly_bits;
  1489. }
  1490. if (bad_bits) {
  1491. dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
  1492. bad_bits);
  1493. return -EINVAL;
  1494. }
  1495. if (!spi->bits_per_word)
  1496. spi->bits_per_word = 8;
  1497. if (!spi->max_speed_hz)
  1498. spi->max_speed_hz = spi->master->max_speed_hz;
  1499. spi_set_cs(spi, false);
  1500. if (spi->master->setup)
  1501. status = spi->master->setup(spi);
  1502. dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
  1503. (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
  1504. (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
  1505. (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
  1506. (spi->mode & SPI_3WIRE) ? "3wire, " : "",
  1507. (spi->mode & SPI_LOOP) ? "loopback, " : "",
  1508. spi->bits_per_word, spi->max_speed_hz,
  1509. status);
  1510. return status;
  1511. }
  1512. EXPORT_SYMBOL_GPL(spi_setup);
  1513. static int __spi_validate(struct spi_device *spi, struct spi_message *message)
  1514. {
  1515. struct spi_master *master = spi->master;
  1516. struct spi_transfer *xfer;
  1517. int w_size;
  1518. if (list_empty(&message->transfers))
  1519. return -EINVAL;
  1520. /* Half-duplex links include original MicroWire, and ones with
  1521. * only one data pin like SPI_3WIRE (switches direction) or where
  1522. * either MOSI or MISO is missing. They can also be caused by
  1523. * software limitations.
  1524. */
  1525. if ((master->flags & SPI_MASTER_HALF_DUPLEX)
  1526. || (spi->mode & SPI_3WIRE)) {
  1527. unsigned flags = master->flags;
  1528. list_for_each_entry(xfer, &message->transfers, transfer_list) {
  1529. if (xfer->rx_buf && xfer->tx_buf)
  1530. return -EINVAL;
  1531. if ((flags & SPI_MASTER_NO_TX) && xfer->tx_buf)
  1532. return -EINVAL;
  1533. if ((flags & SPI_MASTER_NO_RX) && xfer->rx_buf)
  1534. return -EINVAL;
  1535. }
  1536. }
  1537. /**
  1538. * Set transfer bits_per_word and max speed as spi device default if
  1539. * it is not set for this transfer.
  1540. * Set transfer tx_nbits and rx_nbits as single transfer default
  1541. * (SPI_NBITS_SINGLE) if it is not set for this transfer.
  1542. */
  1543. list_for_each_entry(xfer, &message->transfers, transfer_list) {
  1544. message->frame_length += xfer->len;
  1545. if (!xfer->bits_per_word)
  1546. xfer->bits_per_word = spi->bits_per_word;
  1547. if (!xfer->speed_hz)
  1548. xfer->speed_hz = spi->max_speed_hz;
  1549. if (master->max_speed_hz &&
  1550. xfer->speed_hz > master->max_speed_hz)
  1551. xfer->speed_hz = master->max_speed_hz;
  1552. if (master->bits_per_word_mask) {
  1553. /* Only 32 bits fit in the mask */
  1554. if (xfer->bits_per_word > 32)
  1555. return -EINVAL;
  1556. if (!(master->bits_per_word_mask &
  1557. BIT(xfer->bits_per_word - 1)))
  1558. return -EINVAL;
  1559. }
  1560. /*
  1561. * SPI transfer length should be multiple of SPI word size
  1562. * where SPI word size should be power-of-two multiple
  1563. */
  1564. if (xfer->bits_per_word <= 8)
  1565. w_size = 1;
  1566. else if (xfer->bits_per_word <= 16)
  1567. w_size = 2;
  1568. else
  1569. w_size = 4;
  1570. /* No partial transfers accepted */
  1571. if (xfer->len % w_size)
  1572. return -EINVAL;
  1573. if (xfer->speed_hz && master->min_speed_hz &&
  1574. xfer->speed_hz < master->min_speed_hz)
  1575. return -EINVAL;
  1576. if (xfer->tx_buf && !xfer->tx_nbits)
  1577. xfer->tx_nbits = SPI_NBITS_SINGLE;
  1578. if (xfer->rx_buf && !xfer->rx_nbits)
  1579. xfer->rx_nbits = SPI_NBITS_SINGLE;
  1580. /* check transfer tx/rx_nbits:
  1581. * 1. check the value matches one of single, dual and quad
  1582. * 2. check tx/rx_nbits match the mode in spi_device
  1583. */
  1584. if (xfer->tx_buf) {
  1585. if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
  1586. xfer->tx_nbits != SPI_NBITS_DUAL &&
  1587. xfer->tx_nbits != SPI_NBITS_QUAD)
  1588. return -EINVAL;
  1589. if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
  1590. !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
  1591. return -EINVAL;
  1592. if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
  1593. !(spi->mode & SPI_TX_QUAD))
  1594. return -EINVAL;
  1595. }
  1596. /* check transfer rx_nbits */
  1597. if (xfer->rx_buf) {
  1598. if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
  1599. xfer->rx_nbits != SPI_NBITS_DUAL &&
  1600. xfer->rx_nbits != SPI_NBITS_QUAD)
  1601. return -EINVAL;
  1602. if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
  1603. !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
  1604. return -EINVAL;
  1605. if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
  1606. !(spi->mode & SPI_RX_QUAD))
  1607. return -EINVAL;
  1608. }
  1609. }
  1610. message->status = -EINPROGRESS;
  1611. return 0;
  1612. }
  1613. static int __spi_async(struct spi_device *spi, struct spi_message *message)
  1614. {
  1615. struct spi_master *master = spi->master;
  1616. message->spi = spi;
  1617. trace_spi_message_submit(message);
  1618. return master->transfer(spi, message);
  1619. }
  1620. /**
  1621. * spi_async - asynchronous SPI transfer
  1622. * @spi: device with which data will be exchanged
  1623. * @message: describes the data transfers, including completion callback
  1624. * Context: any (irqs may be blocked, etc)
  1625. *
  1626. * This call may be used in_irq and other contexts which can't sleep,
  1627. * as well as from task contexts which can sleep.
  1628. *
  1629. * The completion callback is invoked in a context which can't sleep.
  1630. * Before that invocation, the value of message->status is undefined.
  1631. * When the callback is issued, message->status holds either zero (to
  1632. * indicate complete success) or a negative error code. After that
  1633. * callback returns, the driver which issued the transfer request may
  1634. * deallocate the associated memory; it's no longer in use by any SPI
  1635. * core or controller driver code.
  1636. *
  1637. * Note that although all messages to a spi_device are handled in
  1638. * FIFO order, messages may go to different devices in other orders.
  1639. * Some device might be higher priority, or have various "hard" access
  1640. * time requirements, for example.
  1641. *
  1642. * On detection of any fault during the transfer, processing of
  1643. * the entire message is aborted, and the device is deselected.
  1644. * Until returning from the associated message completion callback,
  1645. * no other spi_message queued to that device will be processed.
  1646. * (This rule applies equally to all the synchronous transfer calls,
  1647. * which are wrappers around this core asynchronous primitive.)
  1648. */
  1649. int spi_async(struct spi_device *spi, struct spi_message *message)
  1650. {
  1651. struct spi_master *master = spi->master;
  1652. int ret;
  1653. unsigned long flags;
  1654. ret = __spi_validate(spi, message);
  1655. if (ret != 0)
  1656. return ret;
  1657. spin_lock_irqsave(&master->bus_lock_spinlock, flags);
  1658. if (master->bus_lock_flag)
  1659. ret = -EBUSY;
  1660. else
  1661. ret = __spi_async(spi, message);
  1662. spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
  1663. return ret;
  1664. }
  1665. EXPORT_SYMBOL_GPL(spi_async);
  1666. /**
  1667. * spi_async_locked - version of spi_async with exclusive bus usage
  1668. * @spi: device with which data will be exchanged
  1669. * @message: describes the data transfers, including completion callback
  1670. * Context: any (irqs may be blocked, etc)
  1671. *
  1672. * This call may be used in_irq and other contexts which can't sleep,
  1673. * as well as from task contexts which can sleep.
  1674. *
  1675. * The completion callback is invoked in a context which can't sleep.
  1676. * Before that invocation, the value of message->status is undefined.
  1677. * When the callback is issued, message->status holds either zero (to
  1678. * indicate complete success) or a negative error code. After that
  1679. * callback returns, the driver which issued the transfer request may
  1680. * deallocate the associated memory; it's no longer in use by any SPI
  1681. * core or controller driver code.
  1682. *
  1683. * Note that although all messages to a spi_device are handled in
  1684. * FIFO order, messages may go to different devices in other orders.
  1685. * Some device might be higher priority, or have various "hard" access
  1686. * time requirements, for example.
  1687. *
  1688. * On detection of any fault during the transfer, processing of
  1689. * the entire message is aborted, and the device is deselected.
  1690. * Until returning from the associated message completion callback,
  1691. * no other spi_message queued to that device will be processed.
  1692. * (This rule applies equally to all the synchronous transfer calls,
  1693. * which are wrappers around this core asynchronous primitive.)
  1694. */
  1695. int spi_async_locked(struct spi_device *spi, struct spi_message *message)
  1696. {
  1697. struct spi_master *master = spi->master;
  1698. int ret;
  1699. unsigned long flags;
  1700. ret = __spi_validate(spi, message);
  1701. if (ret != 0)
  1702. return ret;
  1703. spin_lock_irqsave(&master->bus_lock_spinlock, flags);
  1704. ret = __spi_async(spi, message);
  1705. spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
  1706. return ret;
  1707. }
  1708. EXPORT_SYMBOL_GPL(spi_async_locked);
  1709. /*-------------------------------------------------------------------------*/
  1710. /* Utility methods for SPI master protocol drivers, layered on
  1711. * top of the core. Some other utility methods are defined as
  1712. * inline functions.
  1713. */
  1714. static void spi_complete(void *arg)
  1715. {
  1716. complete(arg);
  1717. }
  1718. static int __spi_sync(struct spi_device *spi, struct spi_message *message,
  1719. int bus_locked)
  1720. {
  1721. DECLARE_COMPLETION_ONSTACK(done);
  1722. int status;
  1723. struct spi_master *master = spi->master;
  1724. unsigned long flags;
  1725. status = __spi_validate(spi, message);
  1726. if (status != 0)
  1727. return status;
  1728. message->complete = spi_complete;
  1729. message->context = &done;
  1730. message->spi = spi;
  1731. if (!bus_locked)
  1732. mutex_lock(&master->bus_lock_mutex);
  1733. /* If we're not using the legacy transfer method then we will
  1734. * try to transfer in the calling context so special case.
  1735. * This code would be less tricky if we could remove the
  1736. * support for driver implemented message queues.
  1737. */
  1738. if (master->transfer == spi_queued_transfer) {
  1739. spin_lock_irqsave(&master->bus_lock_spinlock, flags);
  1740. trace_spi_message_submit(message);
  1741. status = __spi_queued_transfer(spi, message, false);
  1742. spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
  1743. } else {
  1744. status = spi_async_locked(spi, message);
  1745. }
  1746. if (!bus_locked)
  1747. mutex_unlock(&master->bus_lock_mutex);
  1748. if (status == 0) {
  1749. /* Push out the messages in the calling context if we
  1750. * can.
  1751. */
  1752. if (master->transfer == spi_queued_transfer)
  1753. __spi_pump_messages(master, false);
  1754. wait_for_completion(&done);
  1755. status = message->status;
  1756. }
  1757. message->context = NULL;
  1758. return status;
  1759. }
  1760. /**
  1761. * spi_sync - blocking/synchronous SPI data transfers
  1762. * @spi: device with which data will be exchanged
  1763. * @message: describes the data transfers
  1764. * Context: can sleep
  1765. *
  1766. * This call may only be used from a context that may sleep. The sleep
  1767. * is non-interruptible, and has no timeout. Low-overhead controller
  1768. * drivers may DMA directly into and out of the message buffers.
  1769. *
  1770. * Note that the SPI device's chip select is active during the message,
  1771. * and then is normally disabled between messages. Drivers for some
  1772. * frequently-used devices may want to minimize costs of selecting a chip,
  1773. * by leaving it selected in anticipation that the next message will go
  1774. * to the same chip. (That may increase power usage.)
  1775. *
  1776. * Also, the caller is guaranteeing that the memory associated with the
  1777. * message will not be freed before this call returns.
  1778. *
  1779. * It returns zero on success, else a negative error code.
  1780. */
  1781. int spi_sync(struct spi_device *spi, struct spi_message *message)
  1782. {
  1783. return __spi_sync(spi, message, 0);
  1784. }
  1785. EXPORT_SYMBOL_GPL(spi_sync);
  1786. /**
  1787. * spi_sync_locked - version of spi_sync with exclusive bus usage
  1788. * @spi: device with which data will be exchanged
  1789. * @message: describes the data transfers
  1790. * Context: can sleep
  1791. *
  1792. * This call may only be used from a context that may sleep. The sleep
  1793. * is non-interruptible, and has no timeout. Low-overhead controller
  1794. * drivers may DMA directly into and out of the message buffers.
  1795. *
  1796. * This call should be used by drivers that require exclusive access to the
  1797. * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
  1798. * be released by a spi_bus_unlock call when the exclusive access is over.
  1799. *
  1800. * It returns zero on success, else a negative error code.
  1801. */
  1802. int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
  1803. {
  1804. return __spi_sync(spi, message, 1);
  1805. }
  1806. EXPORT_SYMBOL_GPL(spi_sync_locked);
  1807. /**
  1808. * spi_bus_lock - obtain a lock for exclusive SPI bus usage
  1809. * @master: SPI bus master that should be locked for exclusive bus access
  1810. * Context: can sleep
  1811. *
  1812. * This call may only be used from a context that may sleep. The sleep
  1813. * is non-interruptible, and has no timeout.
  1814. *
  1815. * This call should be used by drivers that require exclusive access to the
  1816. * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
  1817. * exclusive access is over. Data transfer must be done by spi_sync_locked
  1818. * and spi_async_locked calls when the SPI bus lock is held.
  1819. *
  1820. * It returns zero on success, else a negative error code.
  1821. */
  1822. int spi_bus_lock(struct spi_master *master)
  1823. {
  1824. unsigned long flags;
  1825. mutex_lock(&master->bus_lock_mutex);
  1826. spin_lock_irqsave(&master->bus_lock_spinlock, flags);
  1827. master->bus_lock_flag = 1;
  1828. spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
  1829. /* mutex remains locked until spi_bus_unlock is called */
  1830. return 0;
  1831. }
  1832. EXPORT_SYMBOL_GPL(spi_bus_lock);
  1833. /**
  1834. * spi_bus_unlock - release the lock for exclusive SPI bus usage
  1835. * @master: SPI bus master that was locked for exclusive bus access
  1836. * Context: can sleep
  1837. *
  1838. * This call may only be used from a context that may sleep. The sleep
  1839. * is non-interruptible, and has no timeout.
  1840. *
  1841. * This call releases an SPI bus lock previously obtained by an spi_bus_lock
  1842. * call.
  1843. *
  1844. * It returns zero on success, else a negative error code.
  1845. */
  1846. int spi_bus_unlock(struct spi_master *master)
  1847. {
  1848. master->bus_lock_flag = 0;
  1849. mutex_unlock(&master->bus_lock_mutex);
  1850. return 0;
  1851. }
  1852. EXPORT_SYMBOL_GPL(spi_bus_unlock);
  1853. /* portable code must never pass more than 32 bytes */
  1854. #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
  1855. static u8 *buf;
  1856. /**
  1857. * spi_write_then_read - SPI synchronous write followed by read
  1858. * @spi: device with which data will be exchanged
  1859. * @txbuf: data to be written (need not be dma-safe)
  1860. * @n_tx: size of txbuf, in bytes
  1861. * @rxbuf: buffer into which data will be read (need not be dma-safe)
  1862. * @n_rx: size of rxbuf, in bytes
  1863. * Context: can sleep
  1864. *
  1865. * This performs a half duplex MicroWire style transaction with the
  1866. * device, sending txbuf and then reading rxbuf. The return value
  1867. * is zero for success, else a negative errno status code.
  1868. * This call may only be used from a context that may sleep.
  1869. *
  1870. * Parameters to this routine are always copied using a small buffer;
  1871. * portable code should never use this for more than 32 bytes.
  1872. * Performance-sensitive or bulk transfer code should instead use
  1873. * spi_{async,sync}() calls with dma-safe buffers.
  1874. */
  1875. int spi_write_then_read(struct spi_device *spi,
  1876. const void *txbuf, unsigned n_tx,
  1877. void *rxbuf, unsigned n_rx)
  1878. {
  1879. static DEFINE_MUTEX(lock);
  1880. int status;
  1881. struct spi_message message;
  1882. struct spi_transfer x[2];
  1883. u8 *local_buf;
  1884. /* Use preallocated DMA-safe buffer if we can. We can't avoid
  1885. * copying here, (as a pure convenience thing), but we can
  1886. * keep heap costs out of the hot path unless someone else is
  1887. * using the pre-allocated buffer or the transfer is too large.
  1888. */
  1889. if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
  1890. local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
  1891. GFP_KERNEL | GFP_DMA);
  1892. if (!local_buf)
  1893. return -ENOMEM;
  1894. } else {
  1895. local_buf = buf;
  1896. }
  1897. spi_message_init(&message);
  1898. memset(x, 0, sizeof(x));
  1899. if (n_tx) {
  1900. x[0].len = n_tx;
  1901. spi_message_add_tail(&x[0], &message);
  1902. }
  1903. if (n_rx) {
  1904. x[1].len = n_rx;
  1905. spi_message_add_tail(&x[1], &message);
  1906. }
  1907. memcpy(local_buf, txbuf, n_tx);
  1908. x[0].tx_buf = local_buf;
  1909. x[1].rx_buf = local_buf + n_tx;
  1910. /* do the i/o */
  1911. status = spi_sync(spi, &message);
  1912. if (status == 0)
  1913. memcpy(rxbuf, x[1].rx_buf, n_rx);
  1914. if (x[0].tx_buf == buf)
  1915. mutex_unlock(&lock);
  1916. else
  1917. kfree(local_buf);
  1918. return status;
  1919. }
  1920. EXPORT_SYMBOL_GPL(spi_write_then_read);
  1921. /*-------------------------------------------------------------------------*/
  1922. #if IS_ENABLED(CONFIG_OF_DYNAMIC)
  1923. static int __spi_of_device_match(struct device *dev, void *data)
  1924. {
  1925. return dev->of_node == data;
  1926. }
  1927. /* must call put_device() when done with returned spi_device device */
  1928. static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
  1929. {
  1930. struct device *dev = bus_find_device(&spi_bus_type, NULL, node,
  1931. __spi_of_device_match);
  1932. return dev ? to_spi_device(dev) : NULL;
  1933. }
  1934. static int __spi_of_master_match(struct device *dev, const void *data)
  1935. {
  1936. return dev->of_node == data;
  1937. }
  1938. /* the spi masters are not using spi_bus, so we find it with another way */
  1939. static struct spi_master *of_find_spi_master_by_node(struct device_node *node)
  1940. {
  1941. struct device *dev;
  1942. dev = class_find_device(&spi_master_class, NULL, node,
  1943. __spi_of_master_match);
  1944. if (!dev)
  1945. return NULL;
  1946. /* reference got in class_find_device */
  1947. return container_of(dev, struct spi_master, dev);
  1948. }
  1949. static int of_spi_notify(struct notifier_block *nb, unsigned long action,
  1950. void *arg)
  1951. {
  1952. struct of_reconfig_data *rd = arg;
  1953. struct spi_master *master;
  1954. struct spi_device *spi;
  1955. switch (of_reconfig_get_state_change(action, arg)) {
  1956. case OF_RECONFIG_CHANGE_ADD:
  1957. master = of_find_spi_master_by_node(rd->dn->parent);
  1958. if (master == NULL)
  1959. return NOTIFY_OK; /* not for us */
  1960. spi = of_register_spi_device(master, rd->dn);
  1961. put_device(&master->dev);
  1962. if (IS_ERR(spi)) {
  1963. pr_err("%s: failed to create for '%s'\n",
  1964. __func__, rd->dn->full_name);
  1965. return notifier_from_errno(PTR_ERR(spi));
  1966. }
  1967. break;
  1968. case OF_RECONFIG_CHANGE_REMOVE:
  1969. /* find our device by node */
  1970. spi = of_find_spi_device_by_node(rd->dn);
  1971. if (spi == NULL)
  1972. return NOTIFY_OK; /* no? not meant for us */
  1973. /* unregister takes one ref away */
  1974. spi_unregister_device(spi);
  1975. /* and put the reference of the find */
  1976. put_device(&spi->dev);
  1977. break;
  1978. }
  1979. return NOTIFY_OK;
  1980. }
  1981. static struct notifier_block spi_of_notifier = {
  1982. .notifier_call = of_spi_notify,
  1983. };
  1984. #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
  1985. extern struct notifier_block spi_of_notifier;
  1986. #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
  1987. static int __init spi_init(void)
  1988. {
  1989. int status;
  1990. buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
  1991. if (!buf) {
  1992. status = -ENOMEM;
  1993. goto err0;
  1994. }
  1995. status = bus_register(&spi_bus_type);
  1996. if (status < 0)
  1997. goto err1;
  1998. status = class_register(&spi_master_class);
  1999. if (status < 0)
  2000. goto err2;
  2001. if (IS_ENABLED(CONFIG_OF_DYNAMIC))
  2002. WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
  2003. return 0;
  2004. err2:
  2005. bus_unregister(&spi_bus_type);
  2006. err1:
  2007. kfree(buf);
  2008. buf = NULL;
  2009. err0:
  2010. return status;
  2011. }
  2012. /* board_info is normally registered in arch_initcall(),
  2013. * but even essential drivers wait till later
  2014. *
  2015. * REVISIT only boardinfo really needs static linking. the rest (device and
  2016. * driver registration) _could_ be dynamically linked (modular) ... costs
  2017. * include needing to have boardinfo data structures be much more public.
  2018. */
  2019. postcore_initcall(spi_init);