spi.c 63 KB

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