spi.c 63 KB

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