spi-summary 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. Overview of Linux kernel SPI support
  2. ====================================
  3. 22-Nov-2005
  4. What is SPI?
  5. ------------
  6. The "Serial Peripheral Interface" (SPI) is a four-wire point-to-point
  7. serial link used to connect microcontrollers to sensors and memory.
  8. The three signal wires hold a clock (SCLK, often on the order of 10 MHz),
  9. and parallel data lines with "Master Out, Slave In" (MOSI) or "Master In,
  10. Slave Out" (MISO) signals. (Other names are also used.) There are four
  11. clocking modes through which data is exchanged; mode-0 and mode-3 are most
  12. commonly used.
  13. SPI masters may use a "chip select" line to activate a given SPI slave
  14. device, so those three signal wires may be connected to several chips
  15. in parallel. All SPI slaves support chipselects. Some devices have
  16. other signals, often including an interrupt to the master.
  17. Unlike serial busses like USB or SMBUS, even low level protocols for
  18. SPI slave functions are usually not interoperable between vendors
  19. (except for cases like SPI memory chips).
  20. - SPI may be used for request/response style device protocols, as with
  21. touchscreen sensors and memory chips.
  22. - It may also be used to stream data in either direction (half duplex),
  23. or both of them at the same time (full duplex).
  24. - Some devices may use eight bit words. Others may different word
  25. lengths, such as streams of 12-bit or 20-bit digital samples.
  26. In the same way, SPI slaves will only rarely support any kind of automatic
  27. discovery/enumeration protocol. The tree of slave devices accessible from
  28. a given SPI master will normally be set up manually, with configuration
  29. tables.
  30. SPI is only one of the names used by such four-wire protocols, and
  31. most controllers have no problem handling "MicroWire" (think of it as
  32. half-duplex SPI, for request/response protocols), SSP ("Synchronous
  33. Serial Protocol"), PSP ("Programmable Serial Protocol"), and other
  34. related protocols.
  35. Microcontrollers often support both master and slave sides of the SPI
  36. protocol. This document (and Linux) currently only supports the master
  37. side of SPI interactions.
  38. Who uses it? On what kinds of systems?
  39. ---------------------------------------
  40. Linux developers using SPI are probably writing device drivers for embedded
  41. systems boards. SPI is used to control external chips, and it is also a
  42. protocol supported by every MMC or SD memory card. (The older "DataFlash"
  43. cards, predating MMC cards but using the same connectors and card shape,
  44. support only SPI.) Some PC hardware uses SPI flash for BIOS code.
  45. SPI slave chips range from digital/analog converters used for analog
  46. sensors and codecs, to memory, to peripherals like USB controllers
  47. or Ethernet adapters; and more.
  48. Most systems using SPI will integrate a few devices on a mainboard.
  49. Some provide SPI links on expansion connectors; in cases where no
  50. dedicated SPI controller exists, GPIO pins can be used to create a
  51. low speed "bitbanging" adapter. Very few systems will "hotplug" an SPI
  52. controller; the reasons to use SPI focus on low cost and simple operation,
  53. and if dynamic reconfiguration is important, USB will often be a more
  54. appropriate low-pincount peripheral bus.
  55. Many microcontrollers that can run Linux integrate one or more I/O
  56. interfaces with SPI modes. Given SPI support, they could use MMC or SD
  57. cards without needing a special purpose MMC/SD/SDIO controller.
  58. How do these driver programming interfaces work?
  59. ------------------------------------------------
  60. The <linux/spi/spi.h> header file includes kerneldoc, as does the
  61. main source code, and you should certainly read that. This is just
  62. an overview, so you get the big picture before the details.
  63. There are two types of SPI driver, here called:
  64. Controller drivers ... these are often built in to System-On-Chip
  65. processors, and often support both Master and Slave roles.
  66. These drivers touch hardware registers and may use DMA.
  67. Protocol drivers ... these pass messages through the controller
  68. driver to communicate with a Slave or Master device on the
  69. other side of an SPI link.
  70. So for example one protocol driver might talk to the MTD layer to export
  71. data to filesystems stored on SPI flash like DataFlash; and others might
  72. control audio interfaces, present touchscreen sensors as input interfaces,
  73. or monitor temperature and voltage levels during industrial processing.
  74. And those might all be sharing the same controller driver.
  75. A "struct spi_device" encapsulates the master-side interface between
  76. those two types of driver. At this writing, Linux has no slave side
  77. programming interface.
  78. There is a minimal core of SPI programming interfaces, focussing on
  79. using driver model to connect controller and protocol drivers using
  80. device tables provided by board specific initialization code. SPI
  81. shows up in sysfs in several locations:
  82. /sys/devices/.../CTLR/spiB.C ... spi_device for on bus "B",
  83. chipselect C, accessed through CTLR.
  84. /sys/bus/spi/devices/spiB.C ... symlink to the physical
  85. spiB-C device
  86. /sys/bus/spi/drivers/D ... driver for one or more spi*.* devices
  87. /sys/class/spi_master/spiB ... class device for the controller
  88. managing bus "B". All the spiB.* devices share the same
  89. physical SPI bus segment, with SCLK, MOSI, and MISO.
  90. The basic I/O primitive submits an asynchronous message to an I/O queue
  91. maintained by the controller driver. A completion callback is issued
  92. asynchronously when the data transfer(s) in that message completes.
  93. There are also some simple synchronous wrappers for those calls.
  94. How does board-specific init code declare SPI devices?
  95. ------------------------------------------------------
  96. Linux needs several kinds of information to properly configure SPI devices.
  97. That information is normally provided by board-specific code, even for
  98. chips that do support some of automated discovery/enumeration.
  99. DECLARE CONTROLLERS
  100. The first kind of information is a list of what SPI controllers exist.
  101. For System-on-Chip (SOC) based boards, these will usually be platform
  102. devices, and the controller may need some platform_data in order to
  103. operate properly. The "struct platform_device" will include resources
  104. like the physical address of the controller's first register and its IRQ.
  105. Platforms will often abstract the "register SPI controller" operation,
  106. maybe coupling it with code to initialize pin configurations, so that
  107. the arch/.../mach-*/board-*.c files for several boards can all share the
  108. same basic controller setup code. This is because most SOCs have several
  109. SPI-capable controllers, and only the ones actually usable on a given
  110. board should normally be set up and registered.
  111. So for example arch/.../mach-*/board-*.c files might have code like:
  112. #include <asm/arch/spi.h> /* for mysoc_spi_data */
  113. /* if your mach-* infrastructure doesn't support kernels that can
  114. * run on multiple boards, pdata wouldn't benefit from "__init".
  115. */
  116. static struct mysoc_spi_data __init pdata = { ... };
  117. static __init board_init(void)
  118. {
  119. ...
  120. /* this board only uses SPI controller #2 */
  121. mysoc_register_spi(2, &pdata);
  122. ...
  123. }
  124. And SOC-specific utility code might look something like:
  125. #include <asm/arch/spi.h>
  126. static struct platform_device spi2 = { ... };
  127. void mysoc_register_spi(unsigned n, struct mysoc_spi_data *pdata)
  128. {
  129. struct mysoc_spi_data *pdata2;
  130. pdata2 = kmalloc(sizeof *pdata2, GFP_KERNEL);
  131. *pdata2 = pdata;
  132. ...
  133. if (n == 2) {
  134. spi2->dev.platform_data = pdata2;
  135. register_platform_device(&spi2);
  136. /* also: set up pin modes so the spi2 signals are
  137. * visible on the relevant pins ... bootloaders on
  138. * production boards may already have done this, but
  139. * developer boards will often need Linux to do it.
  140. */
  141. }
  142. ...
  143. }
  144. Notice how the platform_data for boards may be different, even if the
  145. same SOC controller is used. For example, on one board SPI might use
  146. an external clock, where another derives the SPI clock from current
  147. settings of some master clock.
  148. DECLARE SLAVE DEVICES
  149. The second kind of information is a list of what SPI slave devices exist
  150. on the target board, often with some board-specific data needed for the
  151. driver to work correctly.
  152. Normally your arch/.../mach-*/board-*.c files would provide a small table
  153. listing the SPI devices on each board. (This would typically be only a
  154. small handful.) That might look like:
  155. static struct ads7846_platform_data ads_info = {
  156. .vref_delay_usecs = 100,
  157. .x_plate_ohms = 580,
  158. .y_plate_ohms = 410,
  159. };
  160. static struct spi_board_info spi_board_info[] __initdata = {
  161. {
  162. .modalias = "ads7846",
  163. .platform_data = &ads_info,
  164. .mode = SPI_MODE_0,
  165. .irq = GPIO_IRQ(31),
  166. .max_speed_hz = 120000 /* max sample rate at 3V */ * 16,
  167. .bus_num = 1,
  168. .chip_select = 0,
  169. },
  170. };
  171. Again, notice how board-specific information is provided; each chip may need
  172. several types. This example shows generic constraints like the fastest SPI
  173. clock to allow (a function of board voltage in this case) or how an IRQ pin
  174. is wired, plus chip-specific constraints like an important delay that's
  175. changed by the capacitance at one pin.
  176. (There's also "controller_data", information that may be useful to the
  177. controller driver. An example would be peripheral-specific DMA tuning
  178. data or chipselect callbacks. This is stored in spi_device later.)
  179. The board_info should provide enough information to let the system work
  180. without the chip's driver being loaded. The most troublesome aspect of
  181. that is likely the SPI_CS_HIGH bit in the spi_device.mode field, since
  182. sharing a bus with a device that interprets chipselect "backwards" is
  183. not possible.
  184. Then your board initialization code would register that table with the SPI
  185. infrastructure, so that it's available later when the SPI master controller
  186. driver is registered:
  187. spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info));
  188. Like with other static board-specific setup, you won't unregister those.
  189. NON-STATIC CONFIGURATIONS
  190. Developer boards often play by different rules than product boards, and one
  191. example is the potential need to hotplug SPI devices and/or controllers.
  192. For those cases you might need to use use spi_busnum_to_master() to look
  193. up the spi bus master, and will likely need spi_new_device() to provide the
  194. board info based on the board that was hotplugged. Of course, you'd later
  195. call at least spi_unregister_device() when that board is removed.
  196. How do I write an "SPI Protocol Driver"?
  197. ----------------------------------------
  198. All SPI drivers are currently kernel drivers. A userspace driver API
  199. would just be another kernel driver, probably offering some lowlevel
  200. access through aio_read(), aio_write(), and ioctl() calls and using the
  201. standard userspace sysfs mechanisms to bind to a given SPI device.
  202. SPI protocol drivers are normal device drivers, with no more wrapper
  203. than needed by platform devices:
  204. static struct device_driver CHIP_driver = {
  205. .name = "CHIP",
  206. .bus = &spi_bus_type,
  207. .probe = CHIP_probe,
  208. .remove = __exit_p(CHIP_remove),
  209. .suspend = CHIP_suspend,
  210. .resume = CHIP_resume,
  211. };
  212. The SPI core will autmatically attempt to bind this driver to any SPI
  213. device whose board_info gave a modalias of "CHIP". Your probe() code
  214. might look like this unless you're creating a class_device:
  215. static int __init CHIP_probe(struct device *dev)
  216. {
  217. struct spi_device *spi = to_spi_device(dev);
  218. struct CHIP *chip;
  219. struct CHIP_platform_data *pdata = dev->platform_data;
  220. /* get memory for driver's per-chip state */
  221. chip = kzalloc(sizeof *chip, GFP_KERNEL);
  222. if (!chip)
  223. return -ENOMEM;
  224. dev_set_drvdata(dev, chip);
  225. ... etc
  226. return 0;
  227. }
  228. As soon as it enters probe(), the driver may issue I/O requests to
  229. the SPI device using "struct spi_message". When remove() returns,
  230. the driver guarantees that it won't submit any more such messages.
  231. - An spi_message is a sequence of of protocol operations, executed
  232. as one atomic sequence. SPI driver controls include:
  233. + when bidirectional reads and writes start ... by how its
  234. sequence of spi_transfer requests is arranged;
  235. + optionally defining short delays after transfers ... using
  236. the spi_transfer.delay_usecs setting;
  237. + whether the chipselect becomes inactive after a transfer and
  238. any delay ... by using the spi_transfer.cs_change flag;
  239. + hinting whether the next message is likely to go to this same
  240. device ... using the spi_transfer.cs_change flag on the last
  241. transfer in that atomic group, and potentially saving costs
  242. for chip deselect and select operations.
  243. - Follow standard kernel rules, and provide DMA-safe buffers in
  244. your messages. That way controller drivers using DMA aren't forced
  245. to make extra copies unless the hardware requires it (e.g. working
  246. around hardware errata that force the use of bounce buffering).
  247. If standard dma_map_single() handling of these buffers is inappropriate,
  248. you can use spi_message.is_dma_mapped to tell the controller driver
  249. that you've already provided the relevant DMA addresses.
  250. - The basic I/O primitive is spi_async(). Async requests may be
  251. issued in any context (irq handler, task, etc) and completion
  252. is reported using a callback provided with the message.
  253. - There are also synchronous wrappers like spi_sync(), and wrappers
  254. like spi_read(), spi_write(), and spi_write_then_read(). These
  255. may be issued only in contexts that may sleep, and they're all
  256. clean (and small, and "optional") layers over spi_async().
  257. - The spi_write_then_read() call, and convenience wrappers around
  258. it, should only be used with small amounts of data where the
  259. cost of an extra copy may be ignored. It's designed to support
  260. common RPC-style requests, such as writing an eight bit command
  261. and reading a sixteen bit response -- spi_w8r16() being one its
  262. wrappers, doing exactly that.
  263. Some drivers may need to modify spi_device characteristics like the
  264. transfer mode, wordsize, or clock rate. This is done with spi_setup(),
  265. which would normally be called from probe() before the first I/O is
  266. done to the device.
  267. While "spi_device" would be the bottom boundary of the driver, the
  268. upper boundaries might include sysfs (especially for sensor readings),
  269. the input layer, ALSA, networking, MTD, the character device framework,
  270. or other Linux subsystems.
  271. How do I write an "SPI Master Controller Driver"?
  272. -------------------------------------------------
  273. An SPI controller will probably be registered on the platform_bus; write
  274. a driver to bind to the device, whichever bus is involved.
  275. The main task of this type of driver is to provide an "spi_master".
  276. Use spi_alloc_master() to allocate the master, and class_get_devdata()
  277. to get the driver-private data allocated for that device.
  278. struct spi_master *master;
  279. struct CONTROLLER *c;
  280. master = spi_alloc_master(dev, sizeof *c);
  281. if (!master)
  282. return -ENODEV;
  283. c = class_get_devdata(&master->cdev);
  284. The driver will initialize the fields of that spi_master, including the
  285. bus number (maybe the same as the platform device ID) and three methods
  286. used to interact with the SPI core and SPI protocol drivers. It will
  287. also initialize its own internal state.
  288. master->setup(struct spi_device *spi)
  289. This sets up the device clock rate, SPI mode, and word sizes.
  290. Drivers may change the defaults provided by board_info, and then
  291. call spi_setup(spi) to invoke this routine. It may sleep.
  292. master->transfer(struct spi_device *spi, struct spi_message *message)
  293. This must not sleep. Its responsibility is arrange that the
  294. transfer happens and its complete() callback is issued; the two
  295. will normally happen later, after other transfers complete.
  296. master->cleanup(struct spi_device *spi)
  297. Your controller driver may use spi_device.controller_state to hold
  298. state it dynamically associates with that device. If you do that,
  299. be sure to provide the cleanup() method to free that state.
  300. The bulk of the driver will be managing the I/O queue fed by transfer().
  301. That queue could be purely conceptual. For example, a driver used only
  302. for low-frequency sensor acess might be fine using synchronous PIO.
  303. But the queue will probably be very real, using message->queue, PIO,
  304. often DMA (especially if the root filesystem is in SPI flash), and
  305. execution contexts like IRQ handlers, tasklets, or workqueues (such
  306. as keventd). Your driver can be as fancy, or as simple, as you need.
  307. THANKS TO
  308. ---------
  309. Contributors to Linux-SPI discussions include (in alphabetical order,
  310. by last name):
  311. David Brownell
  312. Russell King
  313. Dmitry Pervushin
  314. Stephen Street
  315. Mark Underwood
  316. Andrew Victor
  317. Vitaly Wool