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