spi.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875
  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. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. */
  21. #include <linux/kernel.h>
  22. #include <linux/kmod.h>
  23. #include <linux/device.h>
  24. #include <linux/init.h>
  25. #include <linux/cache.h>
  26. #include <linux/mutex.h>
  27. #include <linux/of_device.h>
  28. #include <linux/of_irq.h>
  29. #include <linux/slab.h>
  30. #include <linux/mod_devicetable.h>
  31. #include <linux/spi/spi.h>
  32. #include <linux/of_gpio.h>
  33. #include <linux/pm_runtime.h>
  34. #include <linux/export.h>
  35. #include <linux/sched/rt.h>
  36. #include <linux/delay.h>
  37. #include <linux/kthread.h>
  38. #include <linux/ioport.h>
  39. #include <linux/acpi.h>
  40. static void spidev_release(struct device *dev)
  41. {
  42. struct spi_device *spi = to_spi_device(dev);
  43. /* spi masters may cleanup for released devices */
  44. if (spi->master->cleanup)
  45. spi->master->cleanup(spi);
  46. spi_master_put(spi->master);
  47. kfree(spi);
  48. }
  49. static ssize_t
  50. modalias_show(struct device *dev, struct device_attribute *a, char *buf)
  51. {
  52. const struct spi_device *spi = to_spi_device(dev);
  53. return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
  54. }
  55. static DEVICE_ATTR_RO(modalias);
  56. static struct attribute *spi_dev_attrs[] = {
  57. &dev_attr_modalias.attr,
  58. NULL,
  59. };
  60. ATTRIBUTE_GROUPS(spi_dev);
  61. /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
  62. * and the sysfs version makes coldplug work too.
  63. */
  64. static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
  65. const struct spi_device *sdev)
  66. {
  67. while (id->name[0]) {
  68. if (!strcmp(sdev->modalias, id->name))
  69. return id;
  70. id++;
  71. }
  72. return NULL;
  73. }
  74. const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
  75. {
  76. const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
  77. return spi_match_id(sdrv->id_table, sdev);
  78. }
  79. EXPORT_SYMBOL_GPL(spi_get_device_id);
  80. static int spi_match_device(struct device *dev, struct device_driver *drv)
  81. {
  82. const struct spi_device *spi = to_spi_device(dev);
  83. const struct spi_driver *sdrv = to_spi_driver(drv);
  84. /* Attempt an OF style match */
  85. if (of_driver_match_device(dev, drv))
  86. return 1;
  87. /* Then try ACPI */
  88. if (acpi_driver_match_device(dev, drv))
  89. return 1;
  90. if (sdrv->id_table)
  91. return !!spi_match_id(sdrv->id_table, spi);
  92. return strcmp(spi->modalias, drv->name) == 0;
  93. }
  94. static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
  95. {
  96. const struct spi_device *spi = to_spi_device(dev);
  97. add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
  98. return 0;
  99. }
  100. #ifdef CONFIG_PM_SLEEP
  101. static int spi_legacy_suspend(struct device *dev, pm_message_t message)
  102. {
  103. int value = 0;
  104. struct spi_driver *drv = to_spi_driver(dev->driver);
  105. /* suspend will stop irqs and dma; no more i/o */
  106. if (drv) {
  107. if (drv->suspend)
  108. value = drv->suspend(to_spi_device(dev), message);
  109. else
  110. dev_dbg(dev, "... can't suspend\n");
  111. }
  112. return value;
  113. }
  114. static int spi_legacy_resume(struct device *dev)
  115. {
  116. int value = 0;
  117. struct spi_driver *drv = to_spi_driver(dev->driver);
  118. /* resume may restart the i/o queue */
  119. if (drv) {
  120. if (drv->resume)
  121. value = drv->resume(to_spi_device(dev));
  122. else
  123. dev_dbg(dev, "... can't resume\n");
  124. }
  125. return value;
  126. }
  127. static int spi_pm_suspend(struct device *dev)
  128. {
  129. const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
  130. if (pm)
  131. return pm_generic_suspend(dev);
  132. else
  133. return spi_legacy_suspend(dev, PMSG_SUSPEND);
  134. }
  135. static int spi_pm_resume(struct device *dev)
  136. {
  137. const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
  138. if (pm)
  139. return pm_generic_resume(dev);
  140. else
  141. return spi_legacy_resume(dev);
  142. }
  143. static int spi_pm_freeze(struct device *dev)
  144. {
  145. const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
  146. if (pm)
  147. return pm_generic_freeze(dev);
  148. else
  149. return spi_legacy_suspend(dev, PMSG_FREEZE);
  150. }
  151. static int spi_pm_thaw(struct device *dev)
  152. {
  153. const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
  154. if (pm)
  155. return pm_generic_thaw(dev);
  156. else
  157. return spi_legacy_resume(dev);
  158. }
  159. static int spi_pm_poweroff(struct device *dev)
  160. {
  161. const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
  162. if (pm)
  163. return pm_generic_poweroff(dev);
  164. else
  165. return spi_legacy_suspend(dev, PMSG_HIBERNATE);
  166. }
  167. static int spi_pm_restore(struct device *dev)
  168. {
  169. const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
  170. if (pm)
  171. return pm_generic_restore(dev);
  172. else
  173. return spi_legacy_resume(dev);
  174. }
  175. #else
  176. #define spi_pm_suspend NULL
  177. #define spi_pm_resume NULL
  178. #define spi_pm_freeze NULL
  179. #define spi_pm_thaw NULL
  180. #define spi_pm_poweroff NULL
  181. #define spi_pm_restore NULL
  182. #endif
  183. static const struct dev_pm_ops spi_pm = {
  184. .suspend = spi_pm_suspend,
  185. .resume = spi_pm_resume,
  186. .freeze = spi_pm_freeze,
  187. .thaw = spi_pm_thaw,
  188. .poweroff = spi_pm_poweroff,
  189. .restore = spi_pm_restore,
  190. SET_RUNTIME_PM_OPS(
  191. pm_generic_runtime_suspend,
  192. pm_generic_runtime_resume,
  193. NULL
  194. )
  195. };
  196. struct bus_type spi_bus_type = {
  197. .name = "spi",
  198. .dev_groups = spi_dev_groups,
  199. .match = spi_match_device,
  200. .uevent = spi_uevent,
  201. .pm = &spi_pm,
  202. };
  203. EXPORT_SYMBOL_GPL(spi_bus_type);
  204. static int spi_drv_probe(struct device *dev)
  205. {
  206. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  207. return sdrv->probe(to_spi_device(dev));
  208. }
  209. static int spi_drv_remove(struct device *dev)
  210. {
  211. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  212. return sdrv->remove(to_spi_device(dev));
  213. }
  214. static void spi_drv_shutdown(struct device *dev)
  215. {
  216. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  217. sdrv->shutdown(to_spi_device(dev));
  218. }
  219. /**
  220. * spi_register_driver - register a SPI driver
  221. * @sdrv: the driver to register
  222. * Context: can sleep
  223. */
  224. int spi_register_driver(struct spi_driver *sdrv)
  225. {
  226. sdrv->driver.bus = &spi_bus_type;
  227. if (sdrv->probe)
  228. sdrv->driver.probe = spi_drv_probe;
  229. if (sdrv->remove)
  230. sdrv->driver.remove = spi_drv_remove;
  231. if (sdrv->shutdown)
  232. sdrv->driver.shutdown = spi_drv_shutdown;
  233. return driver_register(&sdrv->driver);
  234. }
  235. EXPORT_SYMBOL_GPL(spi_register_driver);
  236. /*-------------------------------------------------------------------------*/
  237. /* SPI devices should normally not be created by SPI device drivers; that
  238. * would make them board-specific. Similarly with SPI master drivers.
  239. * Device registration normally goes into like arch/.../mach.../board-YYY.c
  240. * with other readonly (flashable) information about mainboard devices.
  241. */
  242. struct boardinfo {
  243. struct list_head list;
  244. struct spi_board_info board_info;
  245. };
  246. static LIST_HEAD(board_list);
  247. static LIST_HEAD(spi_master_list);
  248. /*
  249. * Used to protect add/del opertion for board_info list and
  250. * spi_master list, and their matching process
  251. */
  252. static DEFINE_MUTEX(board_lock);
  253. /**
  254. * spi_alloc_device - Allocate a new SPI device
  255. * @master: Controller to which device is connected
  256. * Context: can sleep
  257. *
  258. * Allows a driver to allocate and initialize a spi_device without
  259. * registering it immediately. This allows a driver to directly
  260. * fill the spi_device with device parameters before calling
  261. * spi_add_device() on it.
  262. *
  263. * Caller is responsible to call spi_add_device() on the returned
  264. * spi_device structure to add it to the SPI master. If the caller
  265. * needs to discard the spi_device without adding it, then it should
  266. * call spi_dev_put() on it.
  267. *
  268. * Returns a pointer to the new device, or NULL.
  269. */
  270. struct spi_device *spi_alloc_device(struct spi_master *master)
  271. {
  272. struct spi_device *spi;
  273. struct device *dev = master->dev.parent;
  274. if (!spi_master_get(master))
  275. return NULL;
  276. spi = kzalloc(sizeof(*spi), GFP_KERNEL);
  277. if (!spi) {
  278. dev_err(dev, "cannot alloc spi_device\n");
  279. spi_master_put(master);
  280. return NULL;
  281. }
  282. spi->master = master;
  283. spi->dev.parent = &master->dev;
  284. spi->dev.bus = &spi_bus_type;
  285. spi->dev.release = spidev_release;
  286. spi->cs_gpio = -ENOENT;
  287. device_initialize(&spi->dev);
  288. return spi;
  289. }
  290. EXPORT_SYMBOL_GPL(spi_alloc_device);
  291. /**
  292. * spi_add_device - Add spi_device allocated with spi_alloc_device
  293. * @spi: spi_device to register
  294. *
  295. * Companion function to spi_alloc_device. Devices allocated with
  296. * spi_alloc_device can be added onto the spi bus with this function.
  297. *
  298. * Returns 0 on success; negative errno on failure
  299. */
  300. int spi_add_device(struct spi_device *spi)
  301. {
  302. static DEFINE_MUTEX(spi_add_lock);
  303. struct spi_master *master = spi->master;
  304. struct device *dev = master->dev.parent;
  305. struct device *d;
  306. int status;
  307. /* Chipselects are numbered 0..max; validate. */
  308. if (spi->chip_select >= master->num_chipselect) {
  309. dev_err(dev, "cs%d >= max %d\n",
  310. spi->chip_select,
  311. master->num_chipselect);
  312. return -EINVAL;
  313. }
  314. /* Set the bus ID string */
  315. dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->master->dev),
  316. spi->chip_select);
  317. /* We need to make sure there's no other device with this
  318. * chipselect **BEFORE** we call setup(), else we'll trash
  319. * its configuration. Lock against concurrent add() calls.
  320. */
  321. mutex_lock(&spi_add_lock);
  322. d = bus_find_device_by_name(&spi_bus_type, NULL, dev_name(&spi->dev));
  323. if (d != NULL) {
  324. dev_err(dev, "chipselect %d already in use\n",
  325. spi->chip_select);
  326. put_device(d);
  327. status = -EBUSY;
  328. goto done;
  329. }
  330. if (master->cs_gpios)
  331. spi->cs_gpio = master->cs_gpios[spi->chip_select];
  332. /* Drivers may modify this initial i/o setup, but will
  333. * normally rely on the device being setup. Devices
  334. * using SPI_CS_HIGH can't coexist well otherwise...
  335. */
  336. status = spi_setup(spi);
  337. if (status < 0) {
  338. dev_err(dev, "can't setup %s, status %d\n",
  339. dev_name(&spi->dev), status);
  340. goto done;
  341. }
  342. /* Device may be bound to an active driver when this returns */
  343. status = device_add(&spi->dev);
  344. if (status < 0)
  345. dev_err(dev, "can't add %s, status %d\n",
  346. dev_name(&spi->dev), status);
  347. else
  348. dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
  349. done:
  350. mutex_unlock(&spi_add_lock);
  351. return status;
  352. }
  353. EXPORT_SYMBOL_GPL(spi_add_device);
  354. /**
  355. * spi_new_device - instantiate one new SPI device
  356. * @master: Controller to which device is connected
  357. * @chip: Describes the SPI device
  358. * Context: can sleep
  359. *
  360. * On typical mainboards, this is purely internal; and it's not needed
  361. * after board init creates the hard-wired devices. Some development
  362. * platforms may not be able to use spi_register_board_info though, and
  363. * this is exported so that for example a USB or parport based adapter
  364. * driver could add devices (which it would learn about out-of-band).
  365. *
  366. * Returns the new device, or NULL.
  367. */
  368. struct spi_device *spi_new_device(struct spi_master *master,
  369. struct spi_board_info *chip)
  370. {
  371. struct spi_device *proxy;
  372. int status;
  373. /* NOTE: caller did any chip->bus_num checks necessary.
  374. *
  375. * Also, unless we change the return value convention to use
  376. * error-or-pointer (not NULL-or-pointer), troubleshootability
  377. * suggests syslogged diagnostics are best here (ugh).
  378. */
  379. proxy = spi_alloc_device(master);
  380. if (!proxy)
  381. return NULL;
  382. WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
  383. proxy->chip_select = chip->chip_select;
  384. proxy->max_speed_hz = chip->max_speed_hz;
  385. proxy->mode = chip->mode;
  386. proxy->irq = chip->irq;
  387. strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
  388. proxy->dev.platform_data = (void *) chip->platform_data;
  389. proxy->controller_data = chip->controller_data;
  390. proxy->controller_state = NULL;
  391. status = spi_add_device(proxy);
  392. if (status < 0) {
  393. spi_dev_put(proxy);
  394. return NULL;
  395. }
  396. return proxy;
  397. }
  398. EXPORT_SYMBOL_GPL(spi_new_device);
  399. static void spi_match_master_to_boardinfo(struct spi_master *master,
  400. struct spi_board_info *bi)
  401. {
  402. struct spi_device *dev;
  403. if (master->bus_num != bi->bus_num)
  404. return;
  405. dev = spi_new_device(master, bi);
  406. if (!dev)
  407. dev_err(master->dev.parent, "can't create new device for %s\n",
  408. bi->modalias);
  409. }
  410. /**
  411. * spi_register_board_info - register SPI devices for a given board
  412. * @info: array of chip descriptors
  413. * @n: how many descriptors are provided
  414. * Context: can sleep
  415. *
  416. * Board-specific early init code calls this (probably during arch_initcall)
  417. * with segments of the SPI device table. Any device nodes are created later,
  418. * after the relevant parent SPI controller (bus_num) is defined. We keep
  419. * this table of devices forever, so that reloading a controller driver will
  420. * not make Linux forget about these hard-wired devices.
  421. *
  422. * Other code can also call this, e.g. a particular add-on board might provide
  423. * SPI devices through its expansion connector, so code initializing that board
  424. * would naturally declare its SPI devices.
  425. *
  426. * The board info passed can safely be __initdata ... but be careful of
  427. * any embedded pointers (platform_data, etc), they're copied as-is.
  428. */
  429. int spi_register_board_info(struct spi_board_info const *info, unsigned n)
  430. {
  431. struct boardinfo *bi;
  432. int i;
  433. bi = kzalloc(n * sizeof(*bi), GFP_KERNEL);
  434. if (!bi)
  435. return -ENOMEM;
  436. for (i = 0; i < n; i++, bi++, info++) {
  437. struct spi_master *master;
  438. memcpy(&bi->board_info, info, sizeof(*info));
  439. mutex_lock(&board_lock);
  440. list_add_tail(&bi->list, &board_list);
  441. list_for_each_entry(master, &spi_master_list, list)
  442. spi_match_master_to_boardinfo(master, &bi->board_info);
  443. mutex_unlock(&board_lock);
  444. }
  445. return 0;
  446. }
  447. /*-------------------------------------------------------------------------*/
  448. /**
  449. * spi_pump_messages - kthread work function which processes spi message queue
  450. * @work: pointer to kthread work struct contained in the master struct
  451. *
  452. * This function checks if there is any spi message in the queue that
  453. * needs processing and if so call out to the driver to initialize hardware
  454. * and transfer each message.
  455. *
  456. */
  457. static void spi_pump_messages(struct kthread_work *work)
  458. {
  459. struct spi_master *master =
  460. container_of(work, struct spi_master, pump_messages);
  461. unsigned long flags;
  462. bool was_busy = false;
  463. int ret;
  464. /* Lock queue and check for queue work */
  465. spin_lock_irqsave(&master->queue_lock, flags);
  466. if (list_empty(&master->queue) || !master->running) {
  467. if (!master->busy) {
  468. spin_unlock_irqrestore(&master->queue_lock, flags);
  469. return;
  470. }
  471. master->busy = false;
  472. spin_unlock_irqrestore(&master->queue_lock, flags);
  473. if (master->unprepare_transfer_hardware &&
  474. master->unprepare_transfer_hardware(master))
  475. dev_err(&master->dev,
  476. "failed to unprepare transfer hardware\n");
  477. if (master->auto_runtime_pm) {
  478. pm_runtime_mark_last_busy(master->dev.parent);
  479. pm_runtime_put_autosuspend(master->dev.parent);
  480. }
  481. return;
  482. }
  483. /* Make sure we are not already running a message */
  484. if (master->cur_msg) {
  485. spin_unlock_irqrestore(&master->queue_lock, flags);
  486. return;
  487. }
  488. /* Extract head of queue */
  489. master->cur_msg =
  490. list_entry(master->queue.next, struct spi_message, queue);
  491. list_del_init(&master->cur_msg->queue);
  492. if (master->busy)
  493. was_busy = true;
  494. else
  495. master->busy = true;
  496. spin_unlock_irqrestore(&master->queue_lock, flags);
  497. if (!was_busy && master->auto_runtime_pm) {
  498. ret = pm_runtime_get_sync(master->dev.parent);
  499. if (ret < 0) {
  500. dev_err(&master->dev, "Failed to power device: %d\n",
  501. ret);
  502. return;
  503. }
  504. }
  505. if (!was_busy && master->prepare_transfer_hardware) {
  506. ret = master->prepare_transfer_hardware(master);
  507. if (ret) {
  508. dev_err(&master->dev,
  509. "failed to prepare transfer hardware\n");
  510. if (master->auto_runtime_pm)
  511. pm_runtime_put(master->dev.parent);
  512. return;
  513. }
  514. }
  515. ret = master->transfer_one_message(master, master->cur_msg);
  516. if (ret) {
  517. dev_err(&master->dev,
  518. "failed to transfer one message from queue\n");
  519. return;
  520. }
  521. }
  522. static int spi_init_queue(struct spi_master *master)
  523. {
  524. struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
  525. INIT_LIST_HEAD(&master->queue);
  526. spin_lock_init(&master->queue_lock);
  527. master->running = false;
  528. master->busy = false;
  529. init_kthread_worker(&master->kworker);
  530. master->kworker_task = kthread_run(kthread_worker_fn,
  531. &master->kworker, "%s",
  532. dev_name(&master->dev));
  533. if (IS_ERR(master->kworker_task)) {
  534. dev_err(&master->dev, "failed to create message pump task\n");
  535. return -ENOMEM;
  536. }
  537. init_kthread_work(&master->pump_messages, spi_pump_messages);
  538. /*
  539. * Master config will indicate if this controller should run the
  540. * message pump with high (realtime) priority to reduce the transfer
  541. * latency on the bus by minimising the delay between a transfer
  542. * request and the scheduling of the message pump thread. Without this
  543. * setting the message pump thread will remain at default priority.
  544. */
  545. if (master->rt) {
  546. dev_info(&master->dev,
  547. "will run message pump with realtime priority\n");
  548. sched_setscheduler(master->kworker_task, SCHED_FIFO, &param);
  549. }
  550. return 0;
  551. }
  552. /**
  553. * spi_get_next_queued_message() - called by driver to check for queued
  554. * messages
  555. * @master: the master to check for queued messages
  556. *
  557. * If there are more messages in the queue, the next message is returned from
  558. * this call.
  559. */
  560. struct spi_message *spi_get_next_queued_message(struct spi_master *master)
  561. {
  562. struct spi_message *next;
  563. unsigned long flags;
  564. /* get a pointer to the next message, if any */
  565. spin_lock_irqsave(&master->queue_lock, flags);
  566. if (list_empty(&master->queue))
  567. next = NULL;
  568. else
  569. next = list_entry(master->queue.next,
  570. struct spi_message, queue);
  571. spin_unlock_irqrestore(&master->queue_lock, flags);
  572. return next;
  573. }
  574. EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
  575. /**
  576. * spi_finalize_current_message() - the current message is complete
  577. * @master: the master to return the message to
  578. *
  579. * Called by the driver to notify the core that the message in the front of the
  580. * queue is complete and can be removed from the queue.
  581. */
  582. void spi_finalize_current_message(struct spi_master *master)
  583. {
  584. struct spi_message *mesg;
  585. unsigned long flags;
  586. spin_lock_irqsave(&master->queue_lock, flags);
  587. mesg = master->cur_msg;
  588. master->cur_msg = NULL;
  589. queue_kthread_work(&master->kworker, &master->pump_messages);
  590. spin_unlock_irqrestore(&master->queue_lock, flags);
  591. mesg->state = NULL;
  592. if (mesg->complete)
  593. mesg->complete(mesg->context);
  594. }
  595. EXPORT_SYMBOL_GPL(spi_finalize_current_message);
  596. static int spi_start_queue(struct spi_master *master)
  597. {
  598. unsigned long flags;
  599. spin_lock_irqsave(&master->queue_lock, flags);
  600. if (master->running || master->busy) {
  601. spin_unlock_irqrestore(&master->queue_lock, flags);
  602. return -EBUSY;
  603. }
  604. master->running = true;
  605. master->cur_msg = NULL;
  606. spin_unlock_irqrestore(&master->queue_lock, flags);
  607. queue_kthread_work(&master->kworker, &master->pump_messages);
  608. return 0;
  609. }
  610. static int spi_stop_queue(struct spi_master *master)
  611. {
  612. unsigned long flags;
  613. unsigned limit = 500;
  614. int ret = 0;
  615. spin_lock_irqsave(&master->queue_lock, flags);
  616. /*
  617. * This is a bit lame, but is optimized for the common execution path.
  618. * A wait_queue on the master->busy could be used, but then the common
  619. * execution path (pump_messages) would be required to call wake_up or
  620. * friends on every SPI message. Do this instead.
  621. */
  622. while ((!list_empty(&master->queue) || master->busy) && limit--) {
  623. spin_unlock_irqrestore(&master->queue_lock, flags);
  624. msleep(10);
  625. spin_lock_irqsave(&master->queue_lock, flags);
  626. }
  627. if (!list_empty(&master->queue) || master->busy)
  628. ret = -EBUSY;
  629. else
  630. master->running = false;
  631. spin_unlock_irqrestore(&master->queue_lock, flags);
  632. if (ret) {
  633. dev_warn(&master->dev,
  634. "could not stop message queue\n");
  635. return ret;
  636. }
  637. return ret;
  638. }
  639. static int spi_destroy_queue(struct spi_master *master)
  640. {
  641. int ret;
  642. ret = spi_stop_queue(master);
  643. /*
  644. * flush_kthread_worker will block until all work is done.
  645. * If the reason that stop_queue timed out is that the work will never
  646. * finish, then it does no good to call flush/stop thread, so
  647. * return anyway.
  648. */
  649. if (ret) {
  650. dev_err(&master->dev, "problem destroying queue\n");
  651. return ret;
  652. }
  653. flush_kthread_worker(&master->kworker);
  654. kthread_stop(master->kworker_task);
  655. return 0;
  656. }
  657. /**
  658. * spi_queued_transfer - transfer function for queued transfers
  659. * @spi: spi device which is requesting transfer
  660. * @msg: spi message which is to handled is queued to driver queue
  661. */
  662. static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
  663. {
  664. struct spi_master *master = spi->master;
  665. unsigned long flags;
  666. spin_lock_irqsave(&master->queue_lock, flags);
  667. if (!master->running) {
  668. spin_unlock_irqrestore(&master->queue_lock, flags);
  669. return -ESHUTDOWN;
  670. }
  671. msg->actual_length = 0;
  672. msg->status = -EINPROGRESS;
  673. list_add_tail(&msg->queue, &master->queue);
  674. if (!master->busy)
  675. queue_kthread_work(&master->kworker, &master->pump_messages);
  676. spin_unlock_irqrestore(&master->queue_lock, flags);
  677. return 0;
  678. }
  679. static int spi_master_initialize_queue(struct spi_master *master)
  680. {
  681. int ret;
  682. master->queued = true;
  683. master->transfer = spi_queued_transfer;
  684. /* Initialize and start queue */
  685. ret = spi_init_queue(master);
  686. if (ret) {
  687. dev_err(&master->dev, "problem initializing queue\n");
  688. goto err_init_queue;
  689. }
  690. ret = spi_start_queue(master);
  691. if (ret) {
  692. dev_err(&master->dev, "problem starting queue\n");
  693. goto err_start_queue;
  694. }
  695. return 0;
  696. err_start_queue:
  697. err_init_queue:
  698. spi_destroy_queue(master);
  699. return ret;
  700. }
  701. /*-------------------------------------------------------------------------*/
  702. #if defined(CONFIG_OF)
  703. /**
  704. * of_register_spi_devices() - Register child devices onto the SPI bus
  705. * @master: Pointer to spi_master device
  706. *
  707. * Registers an spi_device for each child node of master node which has a 'reg'
  708. * property.
  709. */
  710. static void of_register_spi_devices(struct spi_master *master)
  711. {
  712. struct spi_device *spi;
  713. struct device_node *nc;
  714. int rc;
  715. u32 value;
  716. if (!master->dev.of_node)
  717. return;
  718. for_each_available_child_of_node(master->dev.of_node, nc) {
  719. /* Alloc an spi_device */
  720. spi = spi_alloc_device(master);
  721. if (!spi) {
  722. dev_err(&master->dev, "spi_device alloc error for %s\n",
  723. nc->full_name);
  724. spi_dev_put(spi);
  725. continue;
  726. }
  727. /* Select device driver */
  728. if (of_modalias_node(nc, spi->modalias,
  729. sizeof(spi->modalias)) < 0) {
  730. dev_err(&master->dev, "cannot find modalias for %s\n",
  731. nc->full_name);
  732. spi_dev_put(spi);
  733. continue;
  734. }
  735. /* Device address */
  736. rc = of_property_read_u32(nc, "reg", &value);
  737. if (rc) {
  738. dev_err(&master->dev, "%s has no valid 'reg' property (%d)\n",
  739. nc->full_name, rc);
  740. spi_dev_put(spi);
  741. continue;
  742. }
  743. spi->chip_select = value;
  744. /* Mode (clock phase/polarity/etc.) */
  745. if (of_find_property(nc, "spi-cpha", NULL))
  746. spi->mode |= SPI_CPHA;
  747. if (of_find_property(nc, "spi-cpol", NULL))
  748. spi->mode |= SPI_CPOL;
  749. if (of_find_property(nc, "spi-cs-high", NULL))
  750. spi->mode |= SPI_CS_HIGH;
  751. if (of_find_property(nc, "spi-3wire", NULL))
  752. spi->mode |= SPI_3WIRE;
  753. /* Device DUAL/QUAD mode */
  754. if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
  755. switch (value) {
  756. case 1:
  757. break;
  758. case 2:
  759. spi->mode |= SPI_TX_DUAL;
  760. break;
  761. case 4:
  762. spi->mode |= SPI_TX_QUAD;
  763. break;
  764. default:
  765. dev_err(&master->dev,
  766. "spi-tx-bus-width %d not supported\n",
  767. value);
  768. spi_dev_put(spi);
  769. continue;
  770. }
  771. }
  772. if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
  773. switch (value) {
  774. case 1:
  775. break;
  776. case 2:
  777. spi->mode |= SPI_RX_DUAL;
  778. break;
  779. case 4:
  780. spi->mode |= SPI_RX_QUAD;
  781. break;
  782. default:
  783. dev_err(&master->dev,
  784. "spi-rx-bus-width %d not supported\n",
  785. value);
  786. spi_dev_put(spi);
  787. continue;
  788. }
  789. }
  790. /* Device speed */
  791. rc = of_property_read_u32(nc, "spi-max-frequency", &value);
  792. if (rc) {
  793. dev_err(&master->dev, "%s has no valid 'spi-max-frequency' property (%d)\n",
  794. nc->full_name, rc);
  795. spi_dev_put(spi);
  796. continue;
  797. }
  798. spi->max_speed_hz = value;
  799. /* IRQ */
  800. spi->irq = irq_of_parse_and_map(nc, 0);
  801. /* Store a pointer to the node in the device structure */
  802. of_node_get(nc);
  803. spi->dev.of_node = nc;
  804. /* Register the new device */
  805. request_module("%s%s", SPI_MODULE_PREFIX, spi->modalias);
  806. rc = spi_add_device(spi);
  807. if (rc) {
  808. dev_err(&master->dev, "spi_device register error %s\n",
  809. nc->full_name);
  810. spi_dev_put(spi);
  811. }
  812. }
  813. }
  814. #else
  815. static void of_register_spi_devices(struct spi_master *master) { }
  816. #endif
  817. #ifdef CONFIG_ACPI
  818. static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
  819. {
  820. struct spi_device *spi = data;
  821. if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
  822. struct acpi_resource_spi_serialbus *sb;
  823. sb = &ares->data.spi_serial_bus;
  824. if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
  825. spi->chip_select = sb->device_selection;
  826. spi->max_speed_hz = sb->connection_speed;
  827. if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
  828. spi->mode |= SPI_CPHA;
  829. if (sb->clock_polarity == ACPI_SPI_START_HIGH)
  830. spi->mode |= SPI_CPOL;
  831. if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
  832. spi->mode |= SPI_CS_HIGH;
  833. }
  834. } else if (spi->irq < 0) {
  835. struct resource r;
  836. if (acpi_dev_resource_interrupt(ares, 0, &r))
  837. spi->irq = r.start;
  838. }
  839. /* Always tell the ACPI core to skip this resource */
  840. return 1;
  841. }
  842. static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
  843. void *data, void **return_value)
  844. {
  845. struct spi_master *master = data;
  846. struct list_head resource_list;
  847. struct acpi_device *adev;
  848. struct spi_device *spi;
  849. int ret;
  850. if (acpi_bus_get_device(handle, &adev))
  851. return AE_OK;
  852. if (acpi_bus_get_status(adev) || !adev->status.present)
  853. return AE_OK;
  854. spi = spi_alloc_device(master);
  855. if (!spi) {
  856. dev_err(&master->dev, "failed to allocate SPI device for %s\n",
  857. dev_name(&adev->dev));
  858. return AE_NO_MEMORY;
  859. }
  860. ACPI_HANDLE_SET(&spi->dev, handle);
  861. spi->irq = -1;
  862. INIT_LIST_HEAD(&resource_list);
  863. ret = acpi_dev_get_resources(adev, &resource_list,
  864. acpi_spi_add_resource, spi);
  865. acpi_dev_free_resource_list(&resource_list);
  866. if (ret < 0 || !spi->max_speed_hz) {
  867. spi_dev_put(spi);
  868. return AE_OK;
  869. }
  870. strlcpy(spi->modalias, dev_name(&adev->dev), sizeof(spi->modalias));
  871. if (spi_add_device(spi)) {
  872. dev_err(&master->dev, "failed to add SPI device %s from ACPI\n",
  873. dev_name(&adev->dev));
  874. spi_dev_put(spi);
  875. }
  876. return AE_OK;
  877. }
  878. static void acpi_register_spi_devices(struct spi_master *master)
  879. {
  880. acpi_status status;
  881. acpi_handle handle;
  882. handle = ACPI_HANDLE(master->dev.parent);
  883. if (!handle)
  884. return;
  885. status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
  886. acpi_spi_add_device, NULL,
  887. master, NULL);
  888. if (ACPI_FAILURE(status))
  889. dev_warn(&master->dev, "failed to enumerate SPI slaves\n");
  890. }
  891. #else
  892. static inline void acpi_register_spi_devices(struct spi_master *master) {}
  893. #endif /* CONFIG_ACPI */
  894. static void spi_master_release(struct device *dev)
  895. {
  896. struct spi_master *master;
  897. master = container_of(dev, struct spi_master, dev);
  898. kfree(master);
  899. }
  900. static struct class spi_master_class = {
  901. .name = "spi_master",
  902. .owner = THIS_MODULE,
  903. .dev_release = spi_master_release,
  904. };
  905. /**
  906. * spi_alloc_master - allocate SPI master controller
  907. * @dev: the controller, possibly using the platform_bus
  908. * @size: how much zeroed driver-private data to allocate; the pointer to this
  909. * memory is in the driver_data field of the returned device,
  910. * accessible with spi_master_get_devdata().
  911. * Context: can sleep
  912. *
  913. * This call is used only by SPI master controller drivers, which are the
  914. * only ones directly touching chip registers. It's how they allocate
  915. * an spi_master structure, prior to calling spi_register_master().
  916. *
  917. * This must be called from context that can sleep. It returns the SPI
  918. * master structure on success, else NULL.
  919. *
  920. * The caller is responsible for assigning the bus number and initializing
  921. * the master's methods before calling spi_register_master(); and (after errors
  922. * adding the device) calling spi_master_put() and kfree() to prevent a memory
  923. * leak.
  924. */
  925. struct spi_master *spi_alloc_master(struct device *dev, unsigned size)
  926. {
  927. struct spi_master *master;
  928. if (!dev)
  929. return NULL;
  930. master = kzalloc(size + sizeof(*master), GFP_KERNEL);
  931. if (!master)
  932. return NULL;
  933. device_initialize(&master->dev);
  934. master->bus_num = -1;
  935. master->num_chipselect = 1;
  936. master->dev.class = &spi_master_class;
  937. master->dev.parent = get_device(dev);
  938. spi_master_set_devdata(master, &master[1]);
  939. return master;
  940. }
  941. EXPORT_SYMBOL_GPL(spi_alloc_master);
  942. #ifdef CONFIG_OF
  943. static int of_spi_register_master(struct spi_master *master)
  944. {
  945. int nb, i, *cs;
  946. struct device_node *np = master->dev.of_node;
  947. if (!np)
  948. return 0;
  949. nb = of_gpio_named_count(np, "cs-gpios");
  950. master->num_chipselect = max_t(int, nb, master->num_chipselect);
  951. /* Return error only for an incorrectly formed cs-gpios property */
  952. if (nb == 0 || nb == -ENOENT)
  953. return 0;
  954. else if (nb < 0)
  955. return nb;
  956. cs = devm_kzalloc(&master->dev,
  957. sizeof(int) * master->num_chipselect,
  958. GFP_KERNEL);
  959. master->cs_gpios = cs;
  960. if (!master->cs_gpios)
  961. return -ENOMEM;
  962. for (i = 0; i < master->num_chipselect; i++)
  963. cs[i] = -ENOENT;
  964. for (i = 0; i < nb; i++)
  965. cs[i] = of_get_named_gpio(np, "cs-gpios", i);
  966. return 0;
  967. }
  968. #else
  969. static int of_spi_register_master(struct spi_master *master)
  970. {
  971. return 0;
  972. }
  973. #endif
  974. /**
  975. * spi_register_master - register SPI master controller
  976. * @master: initialized master, originally from spi_alloc_master()
  977. * Context: can sleep
  978. *
  979. * SPI master controllers connect to their drivers using some non-SPI bus,
  980. * such as the platform bus. The final stage of probe() in that code
  981. * includes calling spi_register_master() to hook up to this SPI bus glue.
  982. *
  983. * SPI controllers use board specific (often SOC specific) bus numbers,
  984. * and board-specific addressing for SPI devices combines those numbers
  985. * with chip select numbers. Since SPI does not directly support dynamic
  986. * device identification, boards need configuration tables telling which
  987. * chip is at which address.
  988. *
  989. * This must be called from context that can sleep. It returns zero on
  990. * success, else a negative error code (dropping the master's refcount).
  991. * After a successful return, the caller is responsible for calling
  992. * spi_unregister_master().
  993. */
  994. int spi_register_master(struct spi_master *master)
  995. {
  996. static atomic_t dyn_bus_id = ATOMIC_INIT((1<<15) - 1);
  997. struct device *dev = master->dev.parent;
  998. struct boardinfo *bi;
  999. int status = -ENODEV;
  1000. int dynamic = 0;
  1001. if (!dev)
  1002. return -ENODEV;
  1003. status = of_spi_register_master(master);
  1004. if (status)
  1005. return status;
  1006. /* even if it's just one always-selected device, there must
  1007. * be at least one chipselect
  1008. */
  1009. if (master->num_chipselect == 0)
  1010. return -EINVAL;
  1011. if ((master->bus_num < 0) && master->dev.of_node)
  1012. master->bus_num = of_alias_get_id(master->dev.of_node, "spi");
  1013. /* convention: dynamically assigned bus IDs count down from the max */
  1014. if (master->bus_num < 0) {
  1015. /* FIXME switch to an IDR based scheme, something like
  1016. * I2C now uses, so we can't run out of "dynamic" IDs
  1017. */
  1018. master->bus_num = atomic_dec_return(&dyn_bus_id);
  1019. dynamic = 1;
  1020. }
  1021. spin_lock_init(&master->bus_lock_spinlock);
  1022. mutex_init(&master->bus_lock_mutex);
  1023. master->bus_lock_flag = 0;
  1024. /* register the device, then userspace will see it.
  1025. * registration fails if the bus ID is in use.
  1026. */
  1027. dev_set_name(&master->dev, "spi%u", master->bus_num);
  1028. status = device_add(&master->dev);
  1029. if (status < 0)
  1030. goto done;
  1031. dev_dbg(dev, "registered master %s%s\n", dev_name(&master->dev),
  1032. dynamic ? " (dynamic)" : "");
  1033. /* If we're using a queued driver, start the queue */
  1034. if (master->transfer)
  1035. dev_info(dev, "master is unqueued, this is deprecated\n");
  1036. else {
  1037. status = spi_master_initialize_queue(master);
  1038. if (status) {
  1039. device_del(&master->dev);
  1040. goto done;
  1041. }
  1042. }
  1043. mutex_lock(&board_lock);
  1044. list_add_tail(&master->list, &spi_master_list);
  1045. list_for_each_entry(bi, &board_list, list)
  1046. spi_match_master_to_boardinfo(master, &bi->board_info);
  1047. mutex_unlock(&board_lock);
  1048. /* Register devices from the device tree and ACPI */
  1049. of_register_spi_devices(master);
  1050. acpi_register_spi_devices(master);
  1051. done:
  1052. return status;
  1053. }
  1054. EXPORT_SYMBOL_GPL(spi_register_master);
  1055. static int __unregister(struct device *dev, void *null)
  1056. {
  1057. spi_unregister_device(to_spi_device(dev));
  1058. return 0;
  1059. }
  1060. /**
  1061. * spi_unregister_master - unregister SPI master controller
  1062. * @master: the master being unregistered
  1063. * Context: can sleep
  1064. *
  1065. * This call is used only by SPI master controller drivers, which are the
  1066. * only ones directly touching chip registers.
  1067. *
  1068. * This must be called from context that can sleep.
  1069. */
  1070. void spi_unregister_master(struct spi_master *master)
  1071. {
  1072. int dummy;
  1073. if (master->queued) {
  1074. if (spi_destroy_queue(master))
  1075. dev_err(&master->dev, "queue remove failed\n");
  1076. }
  1077. mutex_lock(&board_lock);
  1078. list_del(&master->list);
  1079. mutex_unlock(&board_lock);
  1080. dummy = device_for_each_child(&master->dev, NULL, __unregister);
  1081. device_unregister(&master->dev);
  1082. }
  1083. EXPORT_SYMBOL_GPL(spi_unregister_master);
  1084. int spi_master_suspend(struct spi_master *master)
  1085. {
  1086. int ret;
  1087. /* Basically no-ops for non-queued masters */
  1088. if (!master->queued)
  1089. return 0;
  1090. ret = spi_stop_queue(master);
  1091. if (ret)
  1092. dev_err(&master->dev, "queue stop failed\n");
  1093. return ret;
  1094. }
  1095. EXPORT_SYMBOL_GPL(spi_master_suspend);
  1096. int spi_master_resume(struct spi_master *master)
  1097. {
  1098. int ret;
  1099. if (!master->queued)
  1100. return 0;
  1101. ret = spi_start_queue(master);
  1102. if (ret)
  1103. dev_err(&master->dev, "queue restart failed\n");
  1104. return ret;
  1105. }
  1106. EXPORT_SYMBOL_GPL(spi_master_resume);
  1107. static int __spi_master_match(struct device *dev, const void *data)
  1108. {
  1109. struct spi_master *m;
  1110. const u16 *bus_num = data;
  1111. m = container_of(dev, struct spi_master, dev);
  1112. return m->bus_num == *bus_num;
  1113. }
  1114. /**
  1115. * spi_busnum_to_master - look up master associated with bus_num
  1116. * @bus_num: the master's bus number
  1117. * Context: can sleep
  1118. *
  1119. * This call may be used with devices that are registered after
  1120. * arch init time. It returns a refcounted pointer to the relevant
  1121. * spi_master (which the caller must release), or NULL if there is
  1122. * no such master registered.
  1123. */
  1124. struct spi_master *spi_busnum_to_master(u16 bus_num)
  1125. {
  1126. struct device *dev;
  1127. struct spi_master *master = NULL;
  1128. dev = class_find_device(&spi_master_class, NULL, &bus_num,
  1129. __spi_master_match);
  1130. if (dev)
  1131. master = container_of(dev, struct spi_master, dev);
  1132. /* reference got in class_find_device */
  1133. return master;
  1134. }
  1135. EXPORT_SYMBOL_GPL(spi_busnum_to_master);
  1136. /*-------------------------------------------------------------------------*/
  1137. /* Core methods for SPI master protocol drivers. Some of the
  1138. * other core methods are currently defined as inline functions.
  1139. */
  1140. /**
  1141. * spi_setup - setup SPI mode and clock rate
  1142. * @spi: the device whose settings are being modified
  1143. * Context: can sleep, and no requests are queued to the device
  1144. *
  1145. * SPI protocol drivers may need to update the transfer mode if the
  1146. * device doesn't work with its default. They may likewise need
  1147. * to update clock rates or word sizes from initial values. This function
  1148. * changes those settings, and must be called from a context that can sleep.
  1149. * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
  1150. * effect the next time the device is selected and data is transferred to
  1151. * or from it. When this function returns, the spi device is deselected.
  1152. *
  1153. * Note that this call will fail if the protocol driver specifies an option
  1154. * that the underlying controller or its driver does not support. For
  1155. * example, not all hardware supports wire transfers using nine bit words,
  1156. * LSB-first wire encoding, or active-high chipselects.
  1157. */
  1158. int spi_setup(struct spi_device *spi)
  1159. {
  1160. unsigned bad_bits;
  1161. int status = 0;
  1162. /* check mode to prevent that DUAL and QUAD set at the same time
  1163. */
  1164. if (((spi->mode & SPI_TX_DUAL) && (spi->mode & SPI_TX_QUAD)) ||
  1165. ((spi->mode & SPI_RX_DUAL) && (spi->mode & SPI_RX_QUAD))) {
  1166. dev_err(&spi->dev,
  1167. "setup: can not select dual and quad at the same time\n");
  1168. return -EINVAL;
  1169. }
  1170. /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
  1171. */
  1172. if ((spi->mode & SPI_3WIRE) && (spi->mode &
  1173. (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD)))
  1174. return -EINVAL;
  1175. /* help drivers fail *cleanly* when they need options
  1176. * that aren't supported with their current master
  1177. */
  1178. bad_bits = spi->mode & ~spi->master->mode_bits;
  1179. if (bad_bits) {
  1180. dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
  1181. bad_bits);
  1182. return -EINVAL;
  1183. }
  1184. if (!spi->bits_per_word)
  1185. spi->bits_per_word = 8;
  1186. if (spi->master->setup)
  1187. status = spi->master->setup(spi);
  1188. dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
  1189. (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
  1190. (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
  1191. (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
  1192. (spi->mode & SPI_3WIRE) ? "3wire, " : "",
  1193. (spi->mode & SPI_LOOP) ? "loopback, " : "",
  1194. spi->bits_per_word, spi->max_speed_hz,
  1195. status);
  1196. return status;
  1197. }
  1198. EXPORT_SYMBOL_GPL(spi_setup);
  1199. static int __spi_async(struct spi_device *spi, struct spi_message *message)
  1200. {
  1201. struct spi_master *master = spi->master;
  1202. struct spi_transfer *xfer;
  1203. if (list_empty(&message->transfers))
  1204. return -EINVAL;
  1205. if (!message->complete)
  1206. return -EINVAL;
  1207. /* Half-duplex links include original MicroWire, and ones with
  1208. * only one data pin like SPI_3WIRE (switches direction) or where
  1209. * either MOSI or MISO is missing. They can also be caused by
  1210. * software limitations.
  1211. */
  1212. if ((master->flags & SPI_MASTER_HALF_DUPLEX)
  1213. || (spi->mode & SPI_3WIRE)) {
  1214. unsigned flags = master->flags;
  1215. list_for_each_entry(xfer, &message->transfers, transfer_list) {
  1216. if (xfer->rx_buf && xfer->tx_buf)
  1217. return -EINVAL;
  1218. if ((flags & SPI_MASTER_NO_TX) && xfer->tx_buf)
  1219. return -EINVAL;
  1220. if ((flags & SPI_MASTER_NO_RX) && xfer->rx_buf)
  1221. return -EINVAL;
  1222. }
  1223. }
  1224. /**
  1225. * Set transfer bits_per_word and max speed as spi device default if
  1226. * it is not set for this transfer.
  1227. * Set transfer tx_nbits and rx_nbits as single transfer default
  1228. * (SPI_NBITS_SINGLE) if it is not set for this transfer.
  1229. */
  1230. list_for_each_entry(xfer, &message->transfers, transfer_list) {
  1231. message->frame_length += xfer->len;
  1232. if (!xfer->bits_per_word)
  1233. xfer->bits_per_word = spi->bits_per_word;
  1234. if (!xfer->speed_hz) {
  1235. xfer->speed_hz = spi->max_speed_hz;
  1236. if (master->max_speed_hz &&
  1237. xfer->speed_hz > master->max_speed_hz)
  1238. xfer->speed_hz = master->max_speed_hz;
  1239. }
  1240. if (master->bits_per_word_mask) {
  1241. /* Only 32 bits fit in the mask */
  1242. if (xfer->bits_per_word > 32)
  1243. return -EINVAL;
  1244. if (!(master->bits_per_word_mask &
  1245. BIT(xfer->bits_per_word - 1)))
  1246. return -EINVAL;
  1247. }
  1248. if (xfer->speed_hz && master->min_speed_hz &&
  1249. xfer->speed_hz < master->min_speed_hz)
  1250. return -EINVAL;
  1251. if (xfer->speed_hz && master->max_speed_hz &&
  1252. xfer->speed_hz > master->max_speed_hz)
  1253. return -EINVAL;
  1254. if (xfer->tx_buf && !xfer->tx_nbits)
  1255. xfer->tx_nbits = SPI_NBITS_SINGLE;
  1256. if (xfer->rx_buf && !xfer->rx_nbits)
  1257. xfer->rx_nbits = SPI_NBITS_SINGLE;
  1258. /* check transfer tx/rx_nbits:
  1259. * 1. keep the value is not out of single, dual and quad
  1260. * 2. keep tx/rx_nbits is contained by mode in spi_device
  1261. * 3. if SPI_3WIRE, tx/rx_nbits should be in single
  1262. */
  1263. if (xfer->tx_buf) {
  1264. if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
  1265. xfer->tx_nbits != SPI_NBITS_DUAL &&
  1266. xfer->tx_nbits != SPI_NBITS_QUAD)
  1267. return -EINVAL;
  1268. if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
  1269. !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
  1270. return -EINVAL;
  1271. if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
  1272. !(spi->mode & SPI_TX_QUAD))
  1273. return -EINVAL;
  1274. if ((spi->mode & SPI_3WIRE) &&
  1275. (xfer->tx_nbits != SPI_NBITS_SINGLE))
  1276. return -EINVAL;
  1277. }
  1278. /* check transfer rx_nbits */
  1279. if (xfer->rx_buf) {
  1280. if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
  1281. xfer->rx_nbits != SPI_NBITS_DUAL &&
  1282. xfer->rx_nbits != SPI_NBITS_QUAD)
  1283. return -EINVAL;
  1284. if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
  1285. !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
  1286. return -EINVAL;
  1287. if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
  1288. !(spi->mode & SPI_RX_QUAD))
  1289. return -EINVAL;
  1290. if ((spi->mode & SPI_3WIRE) &&
  1291. (xfer->rx_nbits != SPI_NBITS_SINGLE))
  1292. return -EINVAL;
  1293. }
  1294. }
  1295. message->spi = spi;
  1296. message->status = -EINPROGRESS;
  1297. return master->transfer(spi, message);
  1298. }
  1299. /**
  1300. * spi_async - asynchronous SPI transfer
  1301. * @spi: device with which data will be exchanged
  1302. * @message: describes the data transfers, including completion callback
  1303. * Context: any (irqs may be blocked, etc)
  1304. *
  1305. * This call may be used in_irq and other contexts which can't sleep,
  1306. * as well as from task contexts which can sleep.
  1307. *
  1308. * The completion callback is invoked in a context which can't sleep.
  1309. * Before that invocation, the value of message->status is undefined.
  1310. * When the callback is issued, message->status holds either zero (to
  1311. * indicate complete success) or a negative error code. After that
  1312. * callback returns, the driver which issued the transfer request may
  1313. * deallocate the associated memory; it's no longer in use by any SPI
  1314. * core or controller driver code.
  1315. *
  1316. * Note that although all messages to a spi_device are handled in
  1317. * FIFO order, messages may go to different devices in other orders.
  1318. * Some device might be higher priority, or have various "hard" access
  1319. * time requirements, for example.
  1320. *
  1321. * On detection of any fault during the transfer, processing of
  1322. * the entire message is aborted, and the device is deselected.
  1323. * Until returning from the associated message completion callback,
  1324. * no other spi_message queued to that device will be processed.
  1325. * (This rule applies equally to all the synchronous transfer calls,
  1326. * which are wrappers around this core asynchronous primitive.)
  1327. */
  1328. int spi_async(struct spi_device *spi, struct spi_message *message)
  1329. {
  1330. struct spi_master *master = spi->master;
  1331. int ret;
  1332. unsigned long flags;
  1333. spin_lock_irqsave(&master->bus_lock_spinlock, flags);
  1334. if (master->bus_lock_flag)
  1335. ret = -EBUSY;
  1336. else
  1337. ret = __spi_async(spi, message);
  1338. spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
  1339. return ret;
  1340. }
  1341. EXPORT_SYMBOL_GPL(spi_async);
  1342. /**
  1343. * spi_async_locked - version of spi_async with exclusive bus usage
  1344. * @spi: device with which data will be exchanged
  1345. * @message: describes the data transfers, including completion callback
  1346. * Context: any (irqs may be blocked, etc)
  1347. *
  1348. * This call may be used in_irq and other contexts which can't sleep,
  1349. * as well as from task contexts which can sleep.
  1350. *
  1351. * The completion callback is invoked in a context which can't sleep.
  1352. * Before that invocation, the value of message->status is undefined.
  1353. * When the callback is issued, message->status holds either zero (to
  1354. * indicate complete success) or a negative error code. After that
  1355. * callback returns, the driver which issued the transfer request may
  1356. * deallocate the associated memory; it's no longer in use by any SPI
  1357. * core or controller driver code.
  1358. *
  1359. * Note that although all messages to a spi_device are handled in
  1360. * FIFO order, messages may go to different devices in other orders.
  1361. * Some device might be higher priority, or have various "hard" access
  1362. * time requirements, for example.
  1363. *
  1364. * On detection of any fault during the transfer, processing of
  1365. * the entire message is aborted, and the device is deselected.
  1366. * Until returning from the associated message completion callback,
  1367. * no other spi_message queued to that device will be processed.
  1368. * (This rule applies equally to all the synchronous transfer calls,
  1369. * which are wrappers around this core asynchronous primitive.)
  1370. */
  1371. int spi_async_locked(struct spi_device *spi, struct spi_message *message)
  1372. {
  1373. struct spi_master *master = spi->master;
  1374. int ret;
  1375. unsigned long flags;
  1376. spin_lock_irqsave(&master->bus_lock_spinlock, flags);
  1377. ret = __spi_async(spi, message);
  1378. spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
  1379. return ret;
  1380. }
  1381. EXPORT_SYMBOL_GPL(spi_async_locked);
  1382. /*-------------------------------------------------------------------------*/
  1383. /* Utility methods for SPI master protocol drivers, layered on
  1384. * top of the core. Some other utility methods are defined as
  1385. * inline functions.
  1386. */
  1387. static void spi_complete(void *arg)
  1388. {
  1389. complete(arg);
  1390. }
  1391. static int __spi_sync(struct spi_device *spi, struct spi_message *message,
  1392. int bus_locked)
  1393. {
  1394. DECLARE_COMPLETION_ONSTACK(done);
  1395. int status;
  1396. struct spi_master *master = spi->master;
  1397. message->complete = spi_complete;
  1398. message->context = &done;
  1399. if (!bus_locked)
  1400. mutex_lock(&master->bus_lock_mutex);
  1401. status = spi_async_locked(spi, message);
  1402. if (!bus_locked)
  1403. mutex_unlock(&master->bus_lock_mutex);
  1404. if (status == 0) {
  1405. wait_for_completion(&done);
  1406. status = message->status;
  1407. }
  1408. message->context = NULL;
  1409. return status;
  1410. }
  1411. /**
  1412. * spi_sync - blocking/synchronous SPI data transfers
  1413. * @spi: device with which data will be exchanged
  1414. * @message: describes the data transfers
  1415. * Context: can sleep
  1416. *
  1417. * This call may only be used from a context that may sleep. The sleep
  1418. * is non-interruptible, and has no timeout. Low-overhead controller
  1419. * drivers may DMA directly into and out of the message buffers.
  1420. *
  1421. * Note that the SPI device's chip select is active during the message,
  1422. * and then is normally disabled between messages. Drivers for some
  1423. * frequently-used devices may want to minimize costs of selecting a chip,
  1424. * by leaving it selected in anticipation that the next message will go
  1425. * to the same chip. (That may increase power usage.)
  1426. *
  1427. * Also, the caller is guaranteeing that the memory associated with the
  1428. * message will not be freed before this call returns.
  1429. *
  1430. * It returns zero on success, else a negative error code.
  1431. */
  1432. int spi_sync(struct spi_device *spi, struct spi_message *message)
  1433. {
  1434. return __spi_sync(spi, message, 0);
  1435. }
  1436. EXPORT_SYMBOL_GPL(spi_sync);
  1437. /**
  1438. * spi_sync_locked - version of spi_sync with exclusive bus usage
  1439. * @spi: device with which data will be exchanged
  1440. * @message: describes the data transfers
  1441. * Context: can sleep
  1442. *
  1443. * This call may only be used from a context that may sleep. The sleep
  1444. * is non-interruptible, and has no timeout. Low-overhead controller
  1445. * drivers may DMA directly into and out of the message buffers.
  1446. *
  1447. * This call should be used by drivers that require exclusive access to the
  1448. * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
  1449. * be released by a spi_bus_unlock call when the exclusive access is over.
  1450. *
  1451. * It returns zero on success, else a negative error code.
  1452. */
  1453. int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
  1454. {
  1455. return __spi_sync(spi, message, 1);
  1456. }
  1457. EXPORT_SYMBOL_GPL(spi_sync_locked);
  1458. /**
  1459. * spi_bus_lock - obtain a lock for exclusive SPI bus usage
  1460. * @master: SPI bus master that should be locked for exclusive bus access
  1461. * Context: can sleep
  1462. *
  1463. * This call may only be used from a context that may sleep. The sleep
  1464. * is non-interruptible, and has no timeout.
  1465. *
  1466. * This call should be used by drivers that require exclusive access to the
  1467. * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
  1468. * exclusive access is over. Data transfer must be done by spi_sync_locked
  1469. * and spi_async_locked calls when the SPI bus lock is held.
  1470. *
  1471. * It returns zero on success, else a negative error code.
  1472. */
  1473. int spi_bus_lock(struct spi_master *master)
  1474. {
  1475. unsigned long flags;
  1476. mutex_lock(&master->bus_lock_mutex);
  1477. spin_lock_irqsave(&master->bus_lock_spinlock, flags);
  1478. master->bus_lock_flag = 1;
  1479. spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
  1480. /* mutex remains locked until spi_bus_unlock is called */
  1481. return 0;
  1482. }
  1483. EXPORT_SYMBOL_GPL(spi_bus_lock);
  1484. /**
  1485. * spi_bus_unlock - release the lock for exclusive SPI bus usage
  1486. * @master: SPI bus master that was locked for exclusive bus access
  1487. * Context: can sleep
  1488. *
  1489. * This call may only be used from a context that may sleep. The sleep
  1490. * is non-interruptible, and has no timeout.
  1491. *
  1492. * This call releases an SPI bus lock previously obtained by an spi_bus_lock
  1493. * call.
  1494. *
  1495. * It returns zero on success, else a negative error code.
  1496. */
  1497. int spi_bus_unlock(struct spi_master *master)
  1498. {
  1499. master->bus_lock_flag = 0;
  1500. mutex_unlock(&master->bus_lock_mutex);
  1501. return 0;
  1502. }
  1503. EXPORT_SYMBOL_GPL(spi_bus_unlock);
  1504. /* portable code must never pass more than 32 bytes */
  1505. #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
  1506. static u8 *buf;
  1507. /**
  1508. * spi_write_then_read - SPI synchronous write followed by read
  1509. * @spi: device with which data will be exchanged
  1510. * @txbuf: data to be written (need not be dma-safe)
  1511. * @n_tx: size of txbuf, in bytes
  1512. * @rxbuf: buffer into which data will be read (need not be dma-safe)
  1513. * @n_rx: size of rxbuf, in bytes
  1514. * Context: can sleep
  1515. *
  1516. * This performs a half duplex MicroWire style transaction with the
  1517. * device, sending txbuf and then reading rxbuf. The return value
  1518. * is zero for success, else a negative errno status code.
  1519. * This call may only be used from a context that may sleep.
  1520. *
  1521. * Parameters to this routine are always copied using a small buffer;
  1522. * portable code should never use this for more than 32 bytes.
  1523. * Performance-sensitive or bulk transfer code should instead use
  1524. * spi_{async,sync}() calls with dma-safe buffers.
  1525. */
  1526. int spi_write_then_read(struct spi_device *spi,
  1527. const void *txbuf, unsigned n_tx,
  1528. void *rxbuf, unsigned n_rx)
  1529. {
  1530. static DEFINE_MUTEX(lock);
  1531. int status;
  1532. struct spi_message message;
  1533. struct spi_transfer x[2];
  1534. u8 *local_buf;
  1535. /* Use preallocated DMA-safe buffer if we can. We can't avoid
  1536. * copying here, (as a pure convenience thing), but we can
  1537. * keep heap costs out of the hot path unless someone else is
  1538. * using the pre-allocated buffer or the transfer is too large.
  1539. */
  1540. if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
  1541. local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
  1542. GFP_KERNEL | GFP_DMA);
  1543. if (!local_buf)
  1544. return -ENOMEM;
  1545. } else {
  1546. local_buf = buf;
  1547. }
  1548. spi_message_init(&message);
  1549. memset(x, 0, sizeof(x));
  1550. if (n_tx) {
  1551. x[0].len = n_tx;
  1552. spi_message_add_tail(&x[0], &message);
  1553. }
  1554. if (n_rx) {
  1555. x[1].len = n_rx;
  1556. spi_message_add_tail(&x[1], &message);
  1557. }
  1558. memcpy(local_buf, txbuf, n_tx);
  1559. x[0].tx_buf = local_buf;
  1560. x[1].rx_buf = local_buf + n_tx;
  1561. /* do the i/o */
  1562. status = spi_sync(spi, &message);
  1563. if (status == 0)
  1564. memcpy(rxbuf, x[1].rx_buf, n_rx);
  1565. if (x[0].tx_buf == buf)
  1566. mutex_unlock(&lock);
  1567. else
  1568. kfree(local_buf);
  1569. return status;
  1570. }
  1571. EXPORT_SYMBOL_GPL(spi_write_then_read);
  1572. /*-------------------------------------------------------------------------*/
  1573. static int __init spi_init(void)
  1574. {
  1575. int status;
  1576. buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
  1577. if (!buf) {
  1578. status = -ENOMEM;
  1579. goto err0;
  1580. }
  1581. status = bus_register(&spi_bus_type);
  1582. if (status < 0)
  1583. goto err1;
  1584. status = class_register(&spi_master_class);
  1585. if (status < 0)
  1586. goto err2;
  1587. return 0;
  1588. err2:
  1589. bus_unregister(&spi_bus_type);
  1590. err1:
  1591. kfree(buf);
  1592. buf = NULL;
  1593. err0:
  1594. return status;
  1595. }
  1596. /* board_info is normally registered in arch_initcall(),
  1597. * but even essential drivers wait till later
  1598. *
  1599. * REVISIT only boardinfo really needs static linking. the rest (device and
  1600. * driver registration) _could_ be dynamically linked (modular) ... costs
  1601. * include needing to have boardinfo data structures be much more public.
  1602. */
  1603. postcore_initcall(spi_init);