xref: /OK3568_Linux_fs/kernel/Documentation/spi/spi-summary.rst (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun====================================
2*4882a593SmuzhiyunOverview of Linux kernel SPI support
3*4882a593Smuzhiyun====================================
4*4882a593Smuzhiyun
5*4882a593Smuzhiyun02-Feb-2012
6*4882a593Smuzhiyun
7*4882a593SmuzhiyunWhat is SPI?
8*4882a593Smuzhiyun------------
9*4882a593SmuzhiyunThe "Serial Peripheral Interface" (SPI) is a synchronous four wire serial
10*4882a593Smuzhiyunlink used to connect microcontrollers to sensors, memory, and peripherals.
11*4882a593SmuzhiyunIt's a simple "de facto" standard, not complicated enough to acquire a
12*4882a593Smuzhiyunstandardization body.  SPI uses a master/slave configuration.
13*4882a593Smuzhiyun
14*4882a593SmuzhiyunThe three signal wires hold a clock (SCK, often on the order of 10 MHz),
15*4882a593Smuzhiyunand parallel data lines with "Master Out, Slave In" (MOSI) or "Master In,
16*4882a593SmuzhiyunSlave Out" (MISO) signals.  (Other names are also used.)  There are four
17*4882a593Smuzhiyunclocking modes through which data is exchanged; mode-0 and mode-3 are most
18*4882a593Smuzhiyuncommonly used.  Each clock cycle shifts data out and data in; the clock
19*4882a593Smuzhiyundoesn't cycle except when there is a data bit to shift.  Not all data bits
20*4882a593Smuzhiyunare used though; not every protocol uses those full duplex capabilities.
21*4882a593Smuzhiyun
22*4882a593SmuzhiyunSPI masters use a fourth "chip select" line to activate a given SPI slave
23*4882a593Smuzhiyundevice, so those three signal wires may be connected to several chips
24*4882a593Smuzhiyunin parallel.  All SPI slaves support chipselects; they are usually active
25*4882a593Smuzhiyunlow signals, labeled nCSx for slave 'x' (e.g. nCS0).  Some devices have
26*4882a593Smuzhiyunother signals, often including an interrupt to the master.
27*4882a593Smuzhiyun
28*4882a593SmuzhiyunUnlike serial busses like USB or SMBus, even low level protocols for
29*4882a593SmuzhiyunSPI slave functions are usually not interoperable between vendors
30*4882a593Smuzhiyun(except for commodities like SPI memory chips).
31*4882a593Smuzhiyun
32*4882a593Smuzhiyun  - SPI may be used for request/response style device protocols, as with
33*4882a593Smuzhiyun    touchscreen sensors and memory chips.
34*4882a593Smuzhiyun
35*4882a593Smuzhiyun  - It may also be used to stream data in either direction (half duplex),
36*4882a593Smuzhiyun    or both of them at the same time (full duplex).
37*4882a593Smuzhiyun
38*4882a593Smuzhiyun  - Some devices may use eight bit words.  Others may use different word
39*4882a593Smuzhiyun    lengths, such as streams of 12-bit or 20-bit digital samples.
40*4882a593Smuzhiyun
41*4882a593Smuzhiyun  - Words are usually sent with their most significant bit (MSB) first,
42*4882a593Smuzhiyun    but sometimes the least significant bit (LSB) goes first instead.
43*4882a593Smuzhiyun
44*4882a593Smuzhiyun  - Sometimes SPI is used to daisy-chain devices, like shift registers.
45*4882a593Smuzhiyun
46*4882a593SmuzhiyunIn the same way, SPI slaves will only rarely support any kind of automatic
47*4882a593Smuzhiyundiscovery/enumeration protocol.  The tree of slave devices accessible from
48*4882a593Smuzhiyuna given SPI master will normally be set up manually, with configuration
49*4882a593Smuzhiyuntables.
50*4882a593Smuzhiyun
51*4882a593SmuzhiyunSPI is only one of the names used by such four-wire protocols, and
52*4882a593Smuzhiyunmost controllers have no problem handling "MicroWire" (think of it as
53*4882a593Smuzhiyunhalf-duplex SPI, for request/response protocols), SSP ("Synchronous
54*4882a593SmuzhiyunSerial Protocol"), PSP ("Programmable Serial Protocol"), and other
55*4882a593Smuzhiyunrelated protocols.
56*4882a593Smuzhiyun
57*4882a593SmuzhiyunSome chips eliminate a signal line by combining MOSI and MISO, and
58*4882a593Smuzhiyunlimiting themselves to half-duplex at the hardware level.  In fact
59*4882a593Smuzhiyunsome SPI chips have this signal mode as a strapping option.  These
60*4882a593Smuzhiyuncan be accessed using the same programming interface as SPI, but of
61*4882a593Smuzhiyuncourse they won't handle full duplex transfers.  You may find such
62*4882a593Smuzhiyunchips described as using "three wire" signaling: SCK, data, nCSx.
63*4882a593Smuzhiyun(That data line is sometimes called MOMI or SISO.)
64*4882a593Smuzhiyun
65*4882a593SmuzhiyunMicrocontrollers often support both master and slave sides of the SPI
66*4882a593Smuzhiyunprotocol.  This document (and Linux) supports both the master and slave
67*4882a593Smuzhiyunsides of SPI interactions.
68*4882a593Smuzhiyun
69*4882a593Smuzhiyun
70*4882a593SmuzhiyunWho uses it?  On what kinds of systems?
71*4882a593Smuzhiyun---------------------------------------
72*4882a593SmuzhiyunLinux developers using SPI are probably writing device drivers for embedded
73*4882a593Smuzhiyunsystems boards.  SPI is used to control external chips, and it is also a
74*4882a593Smuzhiyunprotocol supported by every MMC or SD memory card.  (The older "DataFlash"
75*4882a593Smuzhiyuncards, predating MMC cards but using the same connectors and card shape,
76*4882a593Smuzhiyunsupport only SPI.)  Some PC hardware uses SPI flash for BIOS code.
77*4882a593Smuzhiyun
78*4882a593SmuzhiyunSPI slave chips range from digital/analog converters used for analog
79*4882a593Smuzhiyunsensors and codecs, to memory, to peripherals like USB controllers
80*4882a593Smuzhiyunor Ethernet adapters; and more.
81*4882a593Smuzhiyun
82*4882a593SmuzhiyunMost systems using SPI will integrate a few devices on a mainboard.
83*4882a593SmuzhiyunSome provide SPI links on expansion connectors; in cases where no
84*4882a593Smuzhiyundedicated SPI controller exists, GPIO pins can be used to create a
85*4882a593Smuzhiyunlow speed "bitbanging" adapter.  Very few systems will "hotplug" an SPI
86*4882a593Smuzhiyuncontroller; the reasons to use SPI focus on low cost and simple operation,
87*4882a593Smuzhiyunand if dynamic reconfiguration is important, USB will often be a more
88*4882a593Smuzhiyunappropriate low-pincount peripheral bus.
89*4882a593Smuzhiyun
90*4882a593SmuzhiyunMany microcontrollers that can run Linux integrate one or more I/O
91*4882a593Smuzhiyuninterfaces with SPI modes.  Given SPI support, they could use MMC or SD
92*4882a593Smuzhiyuncards without needing a special purpose MMC/SD/SDIO controller.
93*4882a593Smuzhiyun
94*4882a593Smuzhiyun
95*4882a593SmuzhiyunI'm confused.  What are these four SPI "clock modes"?
96*4882a593Smuzhiyun-----------------------------------------------------
97*4882a593SmuzhiyunIt's easy to be confused here, and the vendor documentation you'll
98*4882a593Smuzhiyunfind isn't necessarily helpful.  The four modes combine two mode bits:
99*4882a593Smuzhiyun
100*4882a593Smuzhiyun - CPOL indicates the initial clock polarity.  CPOL=0 means the
101*4882a593Smuzhiyun   clock starts low, so the first (leading) edge is rising, and
102*4882a593Smuzhiyun   the second (trailing) edge is falling.  CPOL=1 means the clock
103*4882a593Smuzhiyun   starts high, so the first (leading) edge is falling.
104*4882a593Smuzhiyun
105*4882a593Smuzhiyun - CPHA indicates the clock phase used to sample data; CPHA=0 says
106*4882a593Smuzhiyun   sample on the leading edge, CPHA=1 means the trailing edge.
107*4882a593Smuzhiyun
108*4882a593Smuzhiyun   Since the signal needs to stablize before it's sampled, CPHA=0
109*4882a593Smuzhiyun   implies that its data is written half a clock before the first
110*4882a593Smuzhiyun   clock edge.  The chipselect may have made it become available.
111*4882a593Smuzhiyun
112*4882a593SmuzhiyunChip specs won't always say "uses SPI mode X" in as many words,
113*4882a593Smuzhiyunbut their timing diagrams will make the CPOL and CPHA modes clear.
114*4882a593Smuzhiyun
115*4882a593SmuzhiyunIn the SPI mode number, CPOL is the high order bit and CPHA is the
116*4882a593Smuzhiyunlow order bit.  So when a chip's timing diagram shows the clock
117*4882a593Smuzhiyunstarting low (CPOL=0) and data stabilized for sampling during the
118*4882a593Smuzhiyuntrailing clock edge (CPHA=1), that's SPI mode 1.
119*4882a593Smuzhiyun
120*4882a593SmuzhiyunNote that the clock mode is relevant as soon as the chipselect goes
121*4882a593Smuzhiyunactive.  So the master must set the clock to inactive before selecting
122*4882a593Smuzhiyuna slave, and the slave can tell the chosen polarity by sampling the
123*4882a593Smuzhiyunclock level when its select line goes active.  That's why many devices
124*4882a593Smuzhiyunsupport for example both modes 0 and 3:  they don't care about polarity,
125*4882a593Smuzhiyunand always clock data in/out on rising clock edges.
126*4882a593Smuzhiyun
127*4882a593Smuzhiyun
128*4882a593SmuzhiyunHow do these driver programming interfaces work?
129*4882a593Smuzhiyun------------------------------------------------
130*4882a593SmuzhiyunThe <linux/spi/spi.h> header file includes kerneldoc, as does the
131*4882a593Smuzhiyunmain source code, and you should certainly read that chapter of the
132*4882a593Smuzhiyunkernel API document.  This is just an overview, so you get the big
133*4882a593Smuzhiyunpicture before those details.
134*4882a593Smuzhiyun
135*4882a593SmuzhiyunSPI requests always go into I/O queues.  Requests for a given SPI device
136*4882a593Smuzhiyunare always executed in FIFO order, and complete asynchronously through
137*4882a593Smuzhiyuncompletion callbacks.  There are also some simple synchronous wrappers
138*4882a593Smuzhiyunfor those calls, including ones for common transaction types like writing
139*4882a593Smuzhiyuna command and then reading its response.
140*4882a593Smuzhiyun
141*4882a593SmuzhiyunThere are two types of SPI driver, here called:
142*4882a593Smuzhiyun
143*4882a593Smuzhiyun  Controller drivers ...
144*4882a593Smuzhiyun        controllers may be built into System-On-Chip
145*4882a593Smuzhiyun	processors, and often support both Master and Slave roles.
146*4882a593Smuzhiyun	These drivers touch hardware registers and may use DMA.
147*4882a593Smuzhiyun	Or they can be PIO bitbangers, needing just GPIO pins.
148*4882a593Smuzhiyun
149*4882a593Smuzhiyun  Protocol drivers ...
150*4882a593Smuzhiyun        these pass messages through the controller
151*4882a593Smuzhiyun	driver to communicate with a Slave or Master device on the
152*4882a593Smuzhiyun	other side of an SPI link.
153*4882a593Smuzhiyun
154*4882a593SmuzhiyunSo for example one protocol driver might talk to the MTD layer to export
155*4882a593Smuzhiyundata to filesystems stored on SPI flash like DataFlash; and others might
156*4882a593Smuzhiyuncontrol audio interfaces, present touchscreen sensors as input interfaces,
157*4882a593Smuzhiyunor monitor temperature and voltage levels during industrial processing.
158*4882a593SmuzhiyunAnd those might all be sharing the same controller driver.
159*4882a593Smuzhiyun
160*4882a593SmuzhiyunA "struct spi_device" encapsulates the controller-side interface between
161*4882a593Smuzhiyunthose two types of drivers.
162*4882a593Smuzhiyun
163*4882a593SmuzhiyunThere is a minimal core of SPI programming interfaces, focussing on
164*4882a593Smuzhiyunusing the driver model to connect controller and protocol drivers using
165*4882a593Smuzhiyundevice tables provided by board specific initialization code.  SPI
166*4882a593Smuzhiyunshows up in sysfs in several locations::
167*4882a593Smuzhiyun
168*4882a593Smuzhiyun   /sys/devices/.../CTLR ... physical node for a given SPI controller
169*4882a593Smuzhiyun
170*4882a593Smuzhiyun   /sys/devices/.../CTLR/spiB.C ... spi_device on bus "B",
171*4882a593Smuzhiyun	chipselect C, accessed through CTLR.
172*4882a593Smuzhiyun
173*4882a593Smuzhiyun   /sys/bus/spi/devices/spiB.C ... symlink to that physical
174*4882a593Smuzhiyun	.../CTLR/spiB.C device
175*4882a593Smuzhiyun
176*4882a593Smuzhiyun   /sys/devices/.../CTLR/spiB.C/modalias ... identifies the driver
177*4882a593Smuzhiyun	that should be used with this device (for hotplug/coldplug)
178*4882a593Smuzhiyun
179*4882a593Smuzhiyun   /sys/bus/spi/drivers/D ... driver for one or more spi*.* devices
180*4882a593Smuzhiyun
181*4882a593Smuzhiyun   /sys/class/spi_master/spiB ... symlink (or actual device node) to
182*4882a593Smuzhiyun	a logical node which could hold class related state for the SPI
183*4882a593Smuzhiyun	master controller managing bus "B".  All spiB.* devices share one
184*4882a593Smuzhiyun	physical SPI bus segment, with SCLK, MOSI, and MISO.
185*4882a593Smuzhiyun
186*4882a593Smuzhiyun   /sys/devices/.../CTLR/slave ... virtual file for (un)registering the
187*4882a593Smuzhiyun	slave device for an SPI slave controller.
188*4882a593Smuzhiyun	Writing the driver name of an SPI slave handler to this file
189*4882a593Smuzhiyun	registers the slave device; writing "(null)" unregisters the slave
190*4882a593Smuzhiyun	device.
191*4882a593Smuzhiyun	Reading from this file shows the name of the slave device ("(null)"
192*4882a593Smuzhiyun	if not registered).
193*4882a593Smuzhiyun
194*4882a593Smuzhiyun   /sys/class/spi_slave/spiB ... symlink (or actual device node) to
195*4882a593Smuzhiyun	a logical node which could hold class related state for the SPI
196*4882a593Smuzhiyun	slave controller on bus "B".  When registered, a single spiB.*
197*4882a593Smuzhiyun	device is present here, possible sharing the physical SPI bus
198*4882a593Smuzhiyun	segment with other SPI slave devices.
199*4882a593Smuzhiyun
200*4882a593SmuzhiyunNote that the actual location of the controller's class state depends
201*4882a593Smuzhiyunon whether you enabled CONFIG_SYSFS_DEPRECATED or not.  At this time,
202*4882a593Smuzhiyunthe only class-specific state is the bus number ("B" in "spiB"), so
203*4882a593Smuzhiyunthose /sys/class entries are only useful to quickly identify busses.
204*4882a593Smuzhiyun
205*4882a593Smuzhiyun
206*4882a593SmuzhiyunHow does board-specific init code declare SPI devices?
207*4882a593Smuzhiyun------------------------------------------------------
208*4882a593SmuzhiyunLinux needs several kinds of information to properly configure SPI devices.
209*4882a593SmuzhiyunThat information is normally provided by board-specific code, even for
210*4882a593Smuzhiyunchips that do support some of automated discovery/enumeration.
211*4882a593Smuzhiyun
212*4882a593SmuzhiyunDeclare Controllers
213*4882a593Smuzhiyun^^^^^^^^^^^^^^^^^^^
214*4882a593Smuzhiyun
215*4882a593SmuzhiyunThe first kind of information is a list of what SPI controllers exist.
216*4882a593SmuzhiyunFor System-on-Chip (SOC) based boards, these will usually be platform
217*4882a593Smuzhiyundevices, and the controller may need some platform_data in order to
218*4882a593Smuzhiyunoperate properly.  The "struct platform_device" will include resources
219*4882a593Smuzhiyunlike the physical address of the controller's first register and its IRQ.
220*4882a593Smuzhiyun
221*4882a593SmuzhiyunPlatforms will often abstract the "register SPI controller" operation,
222*4882a593Smuzhiyunmaybe coupling it with code to initialize pin configurations, so that
223*4882a593Smuzhiyunthe arch/.../mach-*/board-*.c files for several boards can all share the
224*4882a593Smuzhiyunsame basic controller setup code.  This is because most SOCs have several
225*4882a593SmuzhiyunSPI-capable controllers, and only the ones actually usable on a given
226*4882a593Smuzhiyunboard should normally be set up and registered.
227*4882a593Smuzhiyun
228*4882a593SmuzhiyunSo for example arch/.../mach-*/board-*.c files might have code like::
229*4882a593Smuzhiyun
230*4882a593Smuzhiyun	#include <mach/spi.h>	/* for mysoc_spi_data */
231*4882a593Smuzhiyun
232*4882a593Smuzhiyun	/* if your mach-* infrastructure doesn't support kernels that can
233*4882a593Smuzhiyun	 * run on multiple boards, pdata wouldn't benefit from "__init".
234*4882a593Smuzhiyun	 */
235*4882a593Smuzhiyun	static struct mysoc_spi_data pdata __initdata = { ... };
236*4882a593Smuzhiyun
237*4882a593Smuzhiyun	static __init board_init(void)
238*4882a593Smuzhiyun	{
239*4882a593Smuzhiyun		...
240*4882a593Smuzhiyun		/* this board only uses SPI controller #2 */
241*4882a593Smuzhiyun		mysoc_register_spi(2, &pdata);
242*4882a593Smuzhiyun		...
243*4882a593Smuzhiyun	}
244*4882a593Smuzhiyun
245*4882a593SmuzhiyunAnd SOC-specific utility code might look something like::
246*4882a593Smuzhiyun
247*4882a593Smuzhiyun	#include <mach/spi.h>
248*4882a593Smuzhiyun
249*4882a593Smuzhiyun	static struct platform_device spi2 = { ... };
250*4882a593Smuzhiyun
251*4882a593Smuzhiyun	void mysoc_register_spi(unsigned n, struct mysoc_spi_data *pdata)
252*4882a593Smuzhiyun	{
253*4882a593Smuzhiyun		struct mysoc_spi_data *pdata2;
254*4882a593Smuzhiyun
255*4882a593Smuzhiyun		pdata2 = kmalloc(sizeof *pdata2, GFP_KERNEL);
256*4882a593Smuzhiyun		*pdata2 = pdata;
257*4882a593Smuzhiyun		...
258*4882a593Smuzhiyun		if (n == 2) {
259*4882a593Smuzhiyun			spi2->dev.platform_data = pdata2;
260*4882a593Smuzhiyun			register_platform_device(&spi2);
261*4882a593Smuzhiyun
262*4882a593Smuzhiyun			/* also: set up pin modes so the spi2 signals are
263*4882a593Smuzhiyun			 * visible on the relevant pins ... bootloaders on
264*4882a593Smuzhiyun			 * production boards may already have done this, but
265*4882a593Smuzhiyun			 * developer boards will often need Linux to do it.
266*4882a593Smuzhiyun			 */
267*4882a593Smuzhiyun		}
268*4882a593Smuzhiyun		...
269*4882a593Smuzhiyun	}
270*4882a593Smuzhiyun
271*4882a593SmuzhiyunNotice how the platform_data for boards may be different, even if the
272*4882a593Smuzhiyunsame SOC controller is used.  For example, on one board SPI might use
273*4882a593Smuzhiyunan external clock, where another derives the SPI clock from current
274*4882a593Smuzhiyunsettings of some master clock.
275*4882a593Smuzhiyun
276*4882a593SmuzhiyunDeclare Slave Devices
277*4882a593Smuzhiyun^^^^^^^^^^^^^^^^^^^^^
278*4882a593Smuzhiyun
279*4882a593SmuzhiyunThe second kind of information is a list of what SPI slave devices exist
280*4882a593Smuzhiyunon the target board, often with some board-specific data needed for the
281*4882a593Smuzhiyundriver to work correctly.
282*4882a593Smuzhiyun
283*4882a593SmuzhiyunNormally your arch/.../mach-*/board-*.c files would provide a small table
284*4882a593Smuzhiyunlisting the SPI devices on each board.  (This would typically be only a
285*4882a593Smuzhiyunsmall handful.)  That might look like::
286*4882a593Smuzhiyun
287*4882a593Smuzhiyun	static struct ads7846_platform_data ads_info = {
288*4882a593Smuzhiyun		.vref_delay_usecs	= 100,
289*4882a593Smuzhiyun		.x_plate_ohms		= 580,
290*4882a593Smuzhiyun		.y_plate_ohms		= 410,
291*4882a593Smuzhiyun	};
292*4882a593Smuzhiyun
293*4882a593Smuzhiyun	static struct spi_board_info spi_board_info[] __initdata = {
294*4882a593Smuzhiyun	{
295*4882a593Smuzhiyun		.modalias	= "ads7846",
296*4882a593Smuzhiyun		.platform_data	= &ads_info,
297*4882a593Smuzhiyun		.mode		= SPI_MODE_0,
298*4882a593Smuzhiyun		.irq		= GPIO_IRQ(31),
299*4882a593Smuzhiyun		.max_speed_hz	= 120000 /* max sample rate at 3V */ * 16,
300*4882a593Smuzhiyun		.bus_num	= 1,
301*4882a593Smuzhiyun		.chip_select	= 0,
302*4882a593Smuzhiyun	},
303*4882a593Smuzhiyun	};
304*4882a593Smuzhiyun
305*4882a593SmuzhiyunAgain, notice how board-specific information is provided; each chip may need
306*4882a593Smuzhiyunseveral types.  This example shows generic constraints like the fastest SPI
307*4882a593Smuzhiyunclock to allow (a function of board voltage in this case) or how an IRQ pin
308*4882a593Smuzhiyunis wired, plus chip-specific constraints like an important delay that's
309*4882a593Smuzhiyunchanged by the capacitance at one pin.
310*4882a593Smuzhiyun
311*4882a593Smuzhiyun(There's also "controller_data", information that may be useful to the
312*4882a593Smuzhiyuncontroller driver.  An example would be peripheral-specific DMA tuning
313*4882a593Smuzhiyundata or chipselect callbacks.  This is stored in spi_device later.)
314*4882a593Smuzhiyun
315*4882a593SmuzhiyunThe board_info should provide enough information to let the system work
316*4882a593Smuzhiyunwithout the chip's driver being loaded.  The most troublesome aspect of
317*4882a593Smuzhiyunthat is likely the SPI_CS_HIGH bit in the spi_device.mode field, since
318*4882a593Smuzhiyunsharing a bus with a device that interprets chipselect "backwards" is
319*4882a593Smuzhiyunnot possible until the infrastructure knows how to deselect it.
320*4882a593Smuzhiyun
321*4882a593SmuzhiyunThen your board initialization code would register that table with the SPI
322*4882a593Smuzhiyuninfrastructure, so that it's available later when the SPI master controller
323*4882a593Smuzhiyundriver is registered::
324*4882a593Smuzhiyun
325*4882a593Smuzhiyun	spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info));
326*4882a593Smuzhiyun
327*4882a593SmuzhiyunLike with other static board-specific setup, you won't unregister those.
328*4882a593Smuzhiyun
329*4882a593SmuzhiyunThe widely used "card" style computers bundle memory, cpu, and little else
330*4882a593Smuzhiyunonto a card that's maybe just thirty square centimeters.  On such systems,
331*4882a593Smuzhiyunyour ``arch/.../mach-.../board-*.c`` file would primarily provide information
332*4882a593Smuzhiyunabout the devices on the mainboard into which such a card is plugged.  That
333*4882a593Smuzhiyuncertainly includes SPI devices hooked up through the card connectors!
334*4882a593Smuzhiyun
335*4882a593Smuzhiyun
336*4882a593SmuzhiyunNon-static Configurations
337*4882a593Smuzhiyun^^^^^^^^^^^^^^^^^^^^^^^^^
338*4882a593Smuzhiyun
339*4882a593SmuzhiyunDeveloper boards often play by different rules than product boards, and one
340*4882a593Smuzhiyunexample is the potential need to hotplug SPI devices and/or controllers.
341*4882a593Smuzhiyun
342*4882a593SmuzhiyunFor those cases you might need to use spi_busnum_to_master() to look
343*4882a593Smuzhiyunup the spi bus master, and will likely need spi_new_device() to provide the
344*4882a593Smuzhiyunboard info based on the board that was hotplugged.  Of course, you'd later
345*4882a593Smuzhiyuncall at least spi_unregister_device() when that board is removed.
346*4882a593Smuzhiyun
347*4882a593SmuzhiyunWhen Linux includes support for MMC/SD/SDIO/DataFlash cards through SPI, those
348*4882a593Smuzhiyunconfigurations will also be dynamic.  Fortunately, such devices all support
349*4882a593Smuzhiyunbasic device identification probes, so they should hotplug normally.
350*4882a593Smuzhiyun
351*4882a593Smuzhiyun
352*4882a593SmuzhiyunHow do I write an "SPI Protocol Driver"?
353*4882a593Smuzhiyun----------------------------------------
354*4882a593SmuzhiyunMost SPI drivers are currently kernel drivers, but there's also support
355*4882a593Smuzhiyunfor userspace drivers.  Here we talk only about kernel drivers.
356*4882a593Smuzhiyun
357*4882a593SmuzhiyunSPI protocol drivers somewhat resemble platform device drivers::
358*4882a593Smuzhiyun
359*4882a593Smuzhiyun	static struct spi_driver CHIP_driver = {
360*4882a593Smuzhiyun		.driver = {
361*4882a593Smuzhiyun			.name		= "CHIP",
362*4882a593Smuzhiyun			.owner		= THIS_MODULE,
363*4882a593Smuzhiyun			.pm		= &CHIP_pm_ops,
364*4882a593Smuzhiyun		},
365*4882a593Smuzhiyun
366*4882a593Smuzhiyun		.probe		= CHIP_probe,
367*4882a593Smuzhiyun		.remove		= CHIP_remove,
368*4882a593Smuzhiyun	};
369*4882a593Smuzhiyun
370*4882a593SmuzhiyunThe driver core will automatically attempt to bind this driver to any SPI
371*4882a593Smuzhiyundevice whose board_info gave a modalias of "CHIP".  Your probe() code
372*4882a593Smuzhiyunmight look like this unless you're creating a device which is managing
373*4882a593Smuzhiyuna bus (appearing under /sys/class/spi_master).
374*4882a593Smuzhiyun
375*4882a593Smuzhiyun::
376*4882a593Smuzhiyun
377*4882a593Smuzhiyun	static int CHIP_probe(struct spi_device *spi)
378*4882a593Smuzhiyun	{
379*4882a593Smuzhiyun		struct CHIP			*chip;
380*4882a593Smuzhiyun		struct CHIP_platform_data	*pdata;
381*4882a593Smuzhiyun
382*4882a593Smuzhiyun		/* assuming the driver requires board-specific data: */
383*4882a593Smuzhiyun		pdata = &spi->dev.platform_data;
384*4882a593Smuzhiyun		if (!pdata)
385*4882a593Smuzhiyun			return -ENODEV;
386*4882a593Smuzhiyun
387*4882a593Smuzhiyun		/* get memory for driver's per-chip state */
388*4882a593Smuzhiyun		chip = kzalloc(sizeof *chip, GFP_KERNEL);
389*4882a593Smuzhiyun		if (!chip)
390*4882a593Smuzhiyun			return -ENOMEM;
391*4882a593Smuzhiyun		spi_set_drvdata(spi, chip);
392*4882a593Smuzhiyun
393*4882a593Smuzhiyun		... etc
394*4882a593Smuzhiyun		return 0;
395*4882a593Smuzhiyun	}
396*4882a593Smuzhiyun
397*4882a593SmuzhiyunAs soon as it enters probe(), the driver may issue I/O requests to
398*4882a593Smuzhiyunthe SPI device using "struct spi_message".  When remove() returns,
399*4882a593Smuzhiyunor after probe() fails, the driver guarantees that it won't submit
400*4882a593Smuzhiyunany more such messages.
401*4882a593Smuzhiyun
402*4882a593Smuzhiyun  - An spi_message is a sequence of protocol operations, executed
403*4882a593Smuzhiyun    as one atomic sequence.  SPI driver controls include:
404*4882a593Smuzhiyun
405*4882a593Smuzhiyun      + when bidirectional reads and writes start ... by how its
406*4882a593Smuzhiyun        sequence of spi_transfer requests is arranged;
407*4882a593Smuzhiyun
408*4882a593Smuzhiyun      + which I/O buffers are used ... each spi_transfer wraps a
409*4882a593Smuzhiyun        buffer for each transfer direction, supporting full duplex
410*4882a593Smuzhiyun        (two pointers, maybe the same one in both cases) and half
411*4882a593Smuzhiyun        duplex (one pointer is NULL) transfers;
412*4882a593Smuzhiyun
413*4882a593Smuzhiyun      + optionally defining short delays after transfers ... using
414*4882a593Smuzhiyun        the spi_transfer.delay_usecs setting (this delay can be the
415*4882a593Smuzhiyun        only protocol effect, if the buffer length is zero);
416*4882a593Smuzhiyun
417*4882a593Smuzhiyun      + whether the chipselect becomes inactive after a transfer and
418*4882a593Smuzhiyun        any delay ... by using the spi_transfer.cs_change flag;
419*4882a593Smuzhiyun
420*4882a593Smuzhiyun      + hinting whether the next message is likely to go to this same
421*4882a593Smuzhiyun        device ... using the spi_transfer.cs_change flag on the last
422*4882a593Smuzhiyun	transfer in that atomic group, and potentially saving costs
423*4882a593Smuzhiyun	for chip deselect and select operations.
424*4882a593Smuzhiyun
425*4882a593Smuzhiyun  - Follow standard kernel rules, and provide DMA-safe buffers in
426*4882a593Smuzhiyun    your messages.  That way controller drivers using DMA aren't forced
427*4882a593Smuzhiyun    to make extra copies unless the hardware requires it (e.g. working
428*4882a593Smuzhiyun    around hardware errata that force the use of bounce buffering).
429*4882a593Smuzhiyun
430*4882a593Smuzhiyun    If standard dma_map_single() handling of these buffers is inappropriate,
431*4882a593Smuzhiyun    you can use spi_message.is_dma_mapped to tell the controller driver
432*4882a593Smuzhiyun    that you've already provided the relevant DMA addresses.
433*4882a593Smuzhiyun
434*4882a593Smuzhiyun  - The basic I/O primitive is spi_async().  Async requests may be
435*4882a593Smuzhiyun    issued in any context (irq handler, task, etc) and completion
436*4882a593Smuzhiyun    is reported using a callback provided with the message.
437*4882a593Smuzhiyun    After any detected error, the chip is deselected and processing
438*4882a593Smuzhiyun    of that spi_message is aborted.
439*4882a593Smuzhiyun
440*4882a593Smuzhiyun  - There are also synchronous wrappers like spi_sync(), and wrappers
441*4882a593Smuzhiyun    like spi_read(), spi_write(), and spi_write_then_read().  These
442*4882a593Smuzhiyun    may be issued only in contexts that may sleep, and they're all
443*4882a593Smuzhiyun    clean (and small, and "optional") layers over spi_async().
444*4882a593Smuzhiyun
445*4882a593Smuzhiyun  - The spi_write_then_read() call, and convenience wrappers around
446*4882a593Smuzhiyun    it, should only be used with small amounts of data where the
447*4882a593Smuzhiyun    cost of an extra copy may be ignored.  It's designed to support
448*4882a593Smuzhiyun    common RPC-style requests, such as writing an eight bit command
449*4882a593Smuzhiyun    and reading a sixteen bit response -- spi_w8r16() being one its
450*4882a593Smuzhiyun    wrappers, doing exactly that.
451*4882a593Smuzhiyun
452*4882a593SmuzhiyunSome drivers may need to modify spi_device characteristics like the
453*4882a593Smuzhiyuntransfer mode, wordsize, or clock rate.  This is done with spi_setup(),
454*4882a593Smuzhiyunwhich would normally be called from probe() before the first I/O is
455*4882a593Smuzhiyundone to the device.  However, that can also be called at any time
456*4882a593Smuzhiyunthat no message is pending for that device.
457*4882a593Smuzhiyun
458*4882a593SmuzhiyunWhile "spi_device" would be the bottom boundary of the driver, the
459*4882a593Smuzhiyunupper boundaries might include sysfs (especially for sensor readings),
460*4882a593Smuzhiyunthe input layer, ALSA, networking, MTD, the character device framework,
461*4882a593Smuzhiyunor other Linux subsystems.
462*4882a593Smuzhiyun
463*4882a593SmuzhiyunNote that there are two types of memory your driver must manage as part
464*4882a593Smuzhiyunof interacting with SPI devices.
465*4882a593Smuzhiyun
466*4882a593Smuzhiyun  - I/O buffers use the usual Linux rules, and must be DMA-safe.
467*4882a593Smuzhiyun    You'd normally allocate them from the heap or free page pool.
468*4882a593Smuzhiyun    Don't use the stack, or anything that's declared "static".
469*4882a593Smuzhiyun
470*4882a593Smuzhiyun  - The spi_message and spi_transfer metadata used to glue those
471*4882a593Smuzhiyun    I/O buffers into a group of protocol transactions.  These can
472*4882a593Smuzhiyun    be allocated anywhere it's convenient, including as part of
473*4882a593Smuzhiyun    other allocate-once driver data structures.  Zero-init these.
474*4882a593Smuzhiyun
475*4882a593SmuzhiyunIf you like, spi_message_alloc() and spi_message_free() convenience
476*4882a593Smuzhiyunroutines are available to allocate and zero-initialize an spi_message
477*4882a593Smuzhiyunwith several transfers.
478*4882a593Smuzhiyun
479*4882a593Smuzhiyun
480*4882a593SmuzhiyunHow do I write an "SPI Master Controller Driver"?
481*4882a593Smuzhiyun-------------------------------------------------
482*4882a593SmuzhiyunAn SPI controller will probably be registered on the platform_bus; write
483*4882a593Smuzhiyuna driver to bind to the device, whichever bus is involved.
484*4882a593Smuzhiyun
485*4882a593SmuzhiyunThe main task of this type of driver is to provide an "spi_master".
486*4882a593SmuzhiyunUse spi_alloc_master() to allocate the master, and spi_master_get_devdata()
487*4882a593Smuzhiyunto get the driver-private data allocated for that device.
488*4882a593Smuzhiyun
489*4882a593Smuzhiyun::
490*4882a593Smuzhiyun
491*4882a593Smuzhiyun	struct spi_master	*master;
492*4882a593Smuzhiyun	struct CONTROLLER	*c;
493*4882a593Smuzhiyun
494*4882a593Smuzhiyun	master = spi_alloc_master(dev, sizeof *c);
495*4882a593Smuzhiyun	if (!master)
496*4882a593Smuzhiyun		return -ENODEV;
497*4882a593Smuzhiyun
498*4882a593Smuzhiyun	c = spi_master_get_devdata(master);
499*4882a593Smuzhiyun
500*4882a593SmuzhiyunThe driver will initialize the fields of that spi_master, including the
501*4882a593Smuzhiyunbus number (maybe the same as the platform device ID) and three methods
502*4882a593Smuzhiyunused to interact with the SPI core and SPI protocol drivers.  It will
503*4882a593Smuzhiyunalso initialize its own internal state.  (See below about bus numbering
504*4882a593Smuzhiyunand those methods.)
505*4882a593Smuzhiyun
506*4882a593SmuzhiyunAfter you initialize the spi_master, then use spi_register_master() to
507*4882a593Smuzhiyunpublish it to the rest of the system. At that time, device nodes for the
508*4882a593Smuzhiyuncontroller and any predeclared spi devices will be made available, and
509*4882a593Smuzhiyunthe driver model core will take care of binding them to drivers.
510*4882a593Smuzhiyun
511*4882a593SmuzhiyunIf you need to remove your SPI controller driver, spi_unregister_master()
512*4882a593Smuzhiyunwill reverse the effect of spi_register_master().
513*4882a593Smuzhiyun
514*4882a593Smuzhiyun
515*4882a593SmuzhiyunBus Numbering
516*4882a593Smuzhiyun^^^^^^^^^^^^^
517*4882a593Smuzhiyun
518*4882a593SmuzhiyunBus numbering is important, since that's how Linux identifies a given
519*4882a593SmuzhiyunSPI bus (shared SCK, MOSI, MISO).  Valid bus numbers start at zero.  On
520*4882a593SmuzhiyunSOC systems, the bus numbers should match the numbers defined by the chip
521*4882a593Smuzhiyunmanufacturer.  For example, hardware controller SPI2 would be bus number 2,
522*4882a593Smuzhiyunand spi_board_info for devices connected to it would use that number.
523*4882a593Smuzhiyun
524*4882a593SmuzhiyunIf you don't have such hardware-assigned bus number, and for some reason
525*4882a593Smuzhiyunyou can't just assign them, then provide a negative bus number.  That will
526*4882a593Smuzhiyunthen be replaced by a dynamically assigned number. You'd then need to treat
527*4882a593Smuzhiyunthis as a non-static configuration (see above).
528*4882a593Smuzhiyun
529*4882a593Smuzhiyun
530*4882a593SmuzhiyunSPI Master Methods
531*4882a593Smuzhiyun^^^^^^^^^^^^^^^^^^
532*4882a593Smuzhiyun
533*4882a593Smuzhiyun``master->setup(struct spi_device *spi)``
534*4882a593Smuzhiyun	This sets up the device clock rate, SPI mode, and word sizes.
535*4882a593Smuzhiyun	Drivers may change the defaults provided by board_info, and then
536*4882a593Smuzhiyun	call spi_setup(spi) to invoke this routine.  It may sleep.
537*4882a593Smuzhiyun
538*4882a593Smuzhiyun	Unless each SPI slave has its own configuration registers, don't
539*4882a593Smuzhiyun	change them right away ... otherwise drivers could corrupt I/O
540*4882a593Smuzhiyun	that's in progress for other SPI devices.
541*4882a593Smuzhiyun
542*4882a593Smuzhiyun	.. note::
543*4882a593Smuzhiyun
544*4882a593Smuzhiyun		BUG ALERT:  for some reason the first version of
545*4882a593Smuzhiyun		many spi_master drivers seems to get this wrong.
546*4882a593Smuzhiyun		When you code setup(), ASSUME that the controller
547*4882a593Smuzhiyun		is actively processing transfers for another device.
548*4882a593Smuzhiyun
549*4882a593Smuzhiyun``master->cleanup(struct spi_device *spi)``
550*4882a593Smuzhiyun	Your controller driver may use spi_device.controller_state to hold
551*4882a593Smuzhiyun	state it dynamically associates with that device.  If you do that,
552*4882a593Smuzhiyun	be sure to provide the cleanup() method to free that state.
553*4882a593Smuzhiyun
554*4882a593Smuzhiyun``master->prepare_transfer_hardware(struct spi_master *master)``
555*4882a593Smuzhiyun	This will be called by the queue mechanism to signal to the driver
556*4882a593Smuzhiyun	that a message is coming in soon, so the subsystem requests the
557*4882a593Smuzhiyun	driver to prepare the transfer hardware by issuing this call.
558*4882a593Smuzhiyun	This may sleep.
559*4882a593Smuzhiyun
560*4882a593Smuzhiyun``master->unprepare_transfer_hardware(struct spi_master *master)``
561*4882a593Smuzhiyun	This will be called by the queue mechanism to signal to the driver
562*4882a593Smuzhiyun	that there are no more messages pending in the queue and it may
563*4882a593Smuzhiyun	relax the hardware (e.g. by power management calls). This may sleep.
564*4882a593Smuzhiyun
565*4882a593Smuzhiyun``master->transfer_one_message(struct spi_master *master, struct spi_message *mesg)``
566*4882a593Smuzhiyun	The subsystem calls the driver to transfer a single message while
567*4882a593Smuzhiyun	queuing transfers that arrive in the meantime. When the driver is
568*4882a593Smuzhiyun	finished with this message, it must call
569*4882a593Smuzhiyun	spi_finalize_current_message() so the subsystem can issue the next
570*4882a593Smuzhiyun	message. This may sleep.
571*4882a593Smuzhiyun
572*4882a593Smuzhiyun``master->transfer_one(struct spi_master *master, struct spi_device *spi, struct spi_transfer *transfer)``
573*4882a593Smuzhiyun	The subsystem calls the driver to transfer a single transfer while
574*4882a593Smuzhiyun	queuing transfers that arrive in the meantime. When the driver is
575*4882a593Smuzhiyun	finished with this transfer, it must call
576*4882a593Smuzhiyun	spi_finalize_current_transfer() so the subsystem can issue the next
577*4882a593Smuzhiyun	transfer. This may sleep. Note: transfer_one and transfer_one_message
578*4882a593Smuzhiyun	are mutually exclusive; when both are set, the generic subsystem does
579*4882a593Smuzhiyun	not call your transfer_one callback.
580*4882a593Smuzhiyun
581*4882a593Smuzhiyun	Return values:
582*4882a593Smuzhiyun
583*4882a593Smuzhiyun	* negative errno: error
584*4882a593Smuzhiyun	* 0: transfer is finished
585*4882a593Smuzhiyun	* 1: transfer is still in progress
586*4882a593Smuzhiyun
587*4882a593Smuzhiyun``master->set_cs_timing(struct spi_device *spi, u8 setup_clk_cycles, u8 hold_clk_cycles, u8 inactive_clk_cycles)``
588*4882a593Smuzhiyun	This method allows SPI client drivers to request SPI master controller
589*4882a593Smuzhiyun	for configuring device specific CS setup, hold and inactive timing
590*4882a593Smuzhiyun	requirements.
591*4882a593Smuzhiyun
592*4882a593SmuzhiyunDeprecated Methods
593*4882a593Smuzhiyun^^^^^^^^^^^^^^^^^^
594*4882a593Smuzhiyun
595*4882a593Smuzhiyun``master->transfer(struct spi_device *spi, struct spi_message *message)``
596*4882a593Smuzhiyun	This must not sleep. Its responsibility is to arrange that the
597*4882a593Smuzhiyun	transfer happens and its complete() callback is issued. The two
598*4882a593Smuzhiyun	will normally happen later, after other transfers complete, and
599*4882a593Smuzhiyun	if the controller is idle it will need to be kickstarted. This
600*4882a593Smuzhiyun	method is not used on queued controllers and must be NULL if
601*4882a593Smuzhiyun	transfer_one_message() and (un)prepare_transfer_hardware() are
602*4882a593Smuzhiyun	implemented.
603*4882a593Smuzhiyun
604*4882a593Smuzhiyun
605*4882a593SmuzhiyunSPI Message Queue
606*4882a593Smuzhiyun^^^^^^^^^^^^^^^^^
607*4882a593Smuzhiyun
608*4882a593SmuzhiyunIf you are happy with the standard queueing mechanism provided by the
609*4882a593SmuzhiyunSPI subsystem, just implement the queued methods specified above. Using
610*4882a593Smuzhiyunthe message queue has the upside of centralizing a lot of code and
611*4882a593Smuzhiyunproviding pure process-context execution of methods. The message queue
612*4882a593Smuzhiyuncan also be elevated to realtime priority on high-priority SPI traffic.
613*4882a593Smuzhiyun
614*4882a593SmuzhiyunUnless the queueing mechanism in the SPI subsystem is selected, the bulk
615*4882a593Smuzhiyunof the driver will be managing the I/O queue fed by the now deprecated
616*4882a593Smuzhiyunfunction transfer().
617*4882a593Smuzhiyun
618*4882a593SmuzhiyunThat queue could be purely conceptual.  For example, a driver used only
619*4882a593Smuzhiyunfor low-frequency sensor access might be fine using synchronous PIO.
620*4882a593Smuzhiyun
621*4882a593SmuzhiyunBut the queue will probably be very real, using message->queue, PIO,
622*4882a593Smuzhiyunoften DMA (especially if the root filesystem is in SPI flash), and
623*4882a593Smuzhiyunexecution contexts like IRQ handlers, tasklets, or workqueues (such
624*4882a593Smuzhiyunas keventd).  Your driver can be as fancy, or as simple, as you need.
625*4882a593SmuzhiyunSuch a transfer() method would normally just add the message to a
626*4882a593Smuzhiyunqueue, and then start some asynchronous transfer engine (unless it's
627*4882a593Smuzhiyunalready running).
628*4882a593Smuzhiyun
629*4882a593Smuzhiyun
630*4882a593SmuzhiyunTHANKS TO
631*4882a593Smuzhiyun---------
632*4882a593SmuzhiyunContributors to Linux-SPI discussions include (in alphabetical order,
633*4882a593Smuzhiyunby last name):
634*4882a593Smuzhiyun
635*4882a593Smuzhiyun- Mark Brown
636*4882a593Smuzhiyun- David Brownell
637*4882a593Smuzhiyun- Russell King
638*4882a593Smuzhiyun- Grant Likely
639*4882a593Smuzhiyun- Dmitry Pervushin
640*4882a593Smuzhiyun- Stephen Street
641*4882a593Smuzhiyun- Mark Underwood
642*4882a593Smuzhiyun- Andrew Victor
643*4882a593Smuzhiyun- Linus Walleij
644*4882a593Smuzhiyun- Vitaly Wool
645