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