162306a36Sopenharmony_ci====================================
262306a36Sopenharmony_ciOverview of Linux kernel SPI support
362306a36Sopenharmony_ci====================================
462306a36Sopenharmony_ci
562306a36Sopenharmony_ci02-Feb-2012
662306a36Sopenharmony_ci
762306a36Sopenharmony_ciWhat is SPI?
862306a36Sopenharmony_ci------------
962306a36Sopenharmony_ciThe "Serial Peripheral Interface" (SPI) is a synchronous four wire serial
1062306a36Sopenharmony_cilink used to connect microcontrollers to sensors, memory, and peripherals.
1162306a36Sopenharmony_ciIt's a simple "de facto" standard, not complicated enough to acquire a
1262306a36Sopenharmony_cistandardization body.  SPI uses a master/slave configuration.
1362306a36Sopenharmony_ci
1462306a36Sopenharmony_ciThe three signal wires hold a clock (SCK, often on the order of 10 MHz),
1562306a36Sopenharmony_ciand parallel data lines with "Master Out, Slave In" (MOSI) or "Master In,
1662306a36Sopenharmony_ciSlave Out" (MISO) signals.  (Other names are also used.)  There are four
1762306a36Sopenharmony_ciclocking modes through which data is exchanged; mode-0 and mode-3 are most
1862306a36Sopenharmony_cicommonly used.  Each clock cycle shifts data out and data in; the clock
1962306a36Sopenharmony_cidoesn't cycle except when there is a data bit to shift.  Not all data bits
2062306a36Sopenharmony_ciare used though; not every protocol uses those full duplex capabilities.
2162306a36Sopenharmony_ci
2262306a36Sopenharmony_ciSPI masters use a fourth "chip select" line to activate a given SPI slave
2362306a36Sopenharmony_cidevice, so those three signal wires may be connected to several chips
2462306a36Sopenharmony_ciin parallel.  All SPI slaves support chipselects; they are usually active
2562306a36Sopenharmony_cilow signals, labeled nCSx for slave 'x' (e.g. nCS0).  Some devices have
2662306a36Sopenharmony_ciother signals, often including an interrupt to the master.
2762306a36Sopenharmony_ci
2862306a36Sopenharmony_ciUnlike serial busses like USB or SMBus, even low level protocols for
2962306a36Sopenharmony_ciSPI slave functions are usually not interoperable between vendors
3062306a36Sopenharmony_ci(except for commodities like SPI memory chips).
3162306a36Sopenharmony_ci
3262306a36Sopenharmony_ci  - SPI may be used for request/response style device protocols, as with
3362306a36Sopenharmony_ci    touchscreen sensors and memory chips.
3462306a36Sopenharmony_ci
3562306a36Sopenharmony_ci  - It may also be used to stream data in either direction (half duplex),
3662306a36Sopenharmony_ci    or both of them at the same time (full duplex).
3762306a36Sopenharmony_ci
3862306a36Sopenharmony_ci  - Some devices may use eight bit words.  Others may use different word
3962306a36Sopenharmony_ci    lengths, such as streams of 12-bit or 20-bit digital samples.
4062306a36Sopenharmony_ci
4162306a36Sopenharmony_ci  - Words are usually sent with their most significant bit (MSB) first,
4262306a36Sopenharmony_ci    but sometimes the least significant bit (LSB) goes first instead.
4362306a36Sopenharmony_ci
4462306a36Sopenharmony_ci  - Sometimes SPI is used to daisy-chain devices, like shift registers.
4562306a36Sopenharmony_ci
4662306a36Sopenharmony_ciIn the same way, SPI slaves will only rarely support any kind of automatic
4762306a36Sopenharmony_cidiscovery/enumeration protocol.  The tree of slave devices accessible from
4862306a36Sopenharmony_cia given SPI master will normally be set up manually, with configuration
4962306a36Sopenharmony_citables.
5062306a36Sopenharmony_ci
5162306a36Sopenharmony_ciSPI is only one of the names used by such four-wire protocols, and
5262306a36Sopenharmony_cimost controllers have no problem handling "MicroWire" (think of it as
5362306a36Sopenharmony_cihalf-duplex SPI, for request/response protocols), SSP ("Synchronous
5462306a36Sopenharmony_ciSerial Protocol"), PSP ("Programmable Serial Protocol"), and other
5562306a36Sopenharmony_cirelated protocols.
5662306a36Sopenharmony_ci
5762306a36Sopenharmony_ciSome chips eliminate a signal line by combining MOSI and MISO, and
5862306a36Sopenharmony_cilimiting themselves to half-duplex at the hardware level.  In fact
5962306a36Sopenharmony_cisome SPI chips have this signal mode as a strapping option.  These
6062306a36Sopenharmony_cican be accessed using the same programming interface as SPI, but of
6162306a36Sopenharmony_cicourse they won't handle full duplex transfers.  You may find such
6262306a36Sopenharmony_cichips described as using "three wire" signaling: SCK, data, nCSx.
6362306a36Sopenharmony_ci(That data line is sometimes called MOMI or SISO.)
6462306a36Sopenharmony_ci
6562306a36Sopenharmony_ciMicrocontrollers often support both master and slave sides of the SPI
6662306a36Sopenharmony_ciprotocol.  This document (and Linux) supports both the master and slave
6762306a36Sopenharmony_cisides of SPI interactions.
6862306a36Sopenharmony_ci
6962306a36Sopenharmony_ci
7062306a36Sopenharmony_ciWho uses it?  On what kinds of systems?
7162306a36Sopenharmony_ci---------------------------------------
7262306a36Sopenharmony_ciLinux developers using SPI are probably writing device drivers for embedded
7362306a36Sopenharmony_cisystems boards.  SPI is used to control external chips, and it is also a
7462306a36Sopenharmony_ciprotocol supported by every MMC or SD memory card.  (The older "DataFlash"
7562306a36Sopenharmony_cicards, predating MMC cards but using the same connectors and card shape,
7662306a36Sopenharmony_cisupport only SPI.)  Some PC hardware uses SPI flash for BIOS code.
7762306a36Sopenharmony_ci
7862306a36Sopenharmony_ciSPI slave chips range from digital/analog converters used for analog
7962306a36Sopenharmony_cisensors and codecs, to memory, to peripherals like USB controllers
8062306a36Sopenharmony_cior Ethernet adapters; and more.
8162306a36Sopenharmony_ci
8262306a36Sopenharmony_ciMost systems using SPI will integrate a few devices on a mainboard.
8362306a36Sopenharmony_ciSome provide SPI links on expansion connectors; in cases where no
8462306a36Sopenharmony_cidedicated SPI controller exists, GPIO pins can be used to create a
8562306a36Sopenharmony_cilow speed "bitbanging" adapter.  Very few systems will "hotplug" an SPI
8662306a36Sopenharmony_cicontroller; the reasons to use SPI focus on low cost and simple operation,
8762306a36Sopenharmony_ciand if dynamic reconfiguration is important, USB will often be a more
8862306a36Sopenharmony_ciappropriate low-pincount peripheral bus.
8962306a36Sopenharmony_ci
9062306a36Sopenharmony_ciMany microcontrollers that can run Linux integrate one or more I/O
9162306a36Sopenharmony_ciinterfaces with SPI modes.  Given SPI support, they could use MMC or SD
9262306a36Sopenharmony_cicards without needing a special purpose MMC/SD/SDIO controller.
9362306a36Sopenharmony_ci
9462306a36Sopenharmony_ci
9562306a36Sopenharmony_ciI'm confused.  What are these four SPI "clock modes"?
9662306a36Sopenharmony_ci-----------------------------------------------------
9762306a36Sopenharmony_ciIt's easy to be confused here, and the vendor documentation you'll
9862306a36Sopenharmony_cifind isn't necessarily helpful.  The four modes combine two mode bits:
9962306a36Sopenharmony_ci
10062306a36Sopenharmony_ci - CPOL indicates the initial clock polarity.  CPOL=0 means the
10162306a36Sopenharmony_ci   clock starts low, so the first (leading) edge is rising, and
10262306a36Sopenharmony_ci   the second (trailing) edge is falling.  CPOL=1 means the clock
10362306a36Sopenharmony_ci   starts high, so the first (leading) edge is falling.
10462306a36Sopenharmony_ci
10562306a36Sopenharmony_ci - CPHA indicates the clock phase used to sample data; CPHA=0 says
10662306a36Sopenharmony_ci   sample on the leading edge, CPHA=1 means the trailing edge.
10762306a36Sopenharmony_ci
10862306a36Sopenharmony_ci   Since the signal needs to stabilize before it's sampled, CPHA=0
10962306a36Sopenharmony_ci   implies that its data is written half a clock before the first
11062306a36Sopenharmony_ci   clock edge.  The chipselect may have made it become available.
11162306a36Sopenharmony_ci
11262306a36Sopenharmony_ciChip specs won't always say "uses SPI mode X" in as many words,
11362306a36Sopenharmony_cibut their timing diagrams will make the CPOL and CPHA modes clear.
11462306a36Sopenharmony_ci
11562306a36Sopenharmony_ciIn the SPI mode number, CPOL is the high order bit and CPHA is the
11662306a36Sopenharmony_cilow order bit.  So when a chip's timing diagram shows the clock
11762306a36Sopenharmony_cistarting low (CPOL=0) and data stabilized for sampling during the
11862306a36Sopenharmony_citrailing clock edge (CPHA=1), that's SPI mode 1.
11962306a36Sopenharmony_ci
12062306a36Sopenharmony_ciNote that the clock mode is relevant as soon as the chipselect goes
12162306a36Sopenharmony_ciactive.  So the master must set the clock to inactive before selecting
12262306a36Sopenharmony_cia slave, and the slave can tell the chosen polarity by sampling the
12362306a36Sopenharmony_ciclock level when its select line goes active.  That's why many devices
12462306a36Sopenharmony_cisupport for example both modes 0 and 3:  they don't care about polarity,
12562306a36Sopenharmony_ciand always clock data in/out on rising clock edges.
12662306a36Sopenharmony_ci
12762306a36Sopenharmony_ci
12862306a36Sopenharmony_ciHow do these driver programming interfaces work?
12962306a36Sopenharmony_ci------------------------------------------------
13062306a36Sopenharmony_ciThe <linux/spi/spi.h> header file includes kerneldoc, as does the
13162306a36Sopenharmony_cimain source code, and you should certainly read that chapter of the
13262306a36Sopenharmony_cikernel API document.  This is just an overview, so you get the big
13362306a36Sopenharmony_cipicture before those details.
13462306a36Sopenharmony_ci
13562306a36Sopenharmony_ciSPI requests always go into I/O queues.  Requests for a given SPI device
13662306a36Sopenharmony_ciare always executed in FIFO order, and complete asynchronously through
13762306a36Sopenharmony_cicompletion callbacks.  There are also some simple synchronous wrappers
13862306a36Sopenharmony_cifor those calls, including ones for common transaction types like writing
13962306a36Sopenharmony_cia command and then reading its response.
14062306a36Sopenharmony_ci
14162306a36Sopenharmony_ciThere are two types of SPI driver, here called:
14262306a36Sopenharmony_ci
14362306a36Sopenharmony_ci  Controller drivers ...
14462306a36Sopenharmony_ci        controllers may be built into System-On-Chip
14562306a36Sopenharmony_ci	processors, and often support both Master and Slave roles.
14662306a36Sopenharmony_ci	These drivers touch hardware registers and may use DMA.
14762306a36Sopenharmony_ci	Or they can be PIO bitbangers, needing just GPIO pins.
14862306a36Sopenharmony_ci
14962306a36Sopenharmony_ci  Protocol drivers ...
15062306a36Sopenharmony_ci        these pass messages through the controller
15162306a36Sopenharmony_ci	driver to communicate with a Slave or Master device on the
15262306a36Sopenharmony_ci	other side of an SPI link.
15362306a36Sopenharmony_ci
15462306a36Sopenharmony_ciSo for example one protocol driver might talk to the MTD layer to export
15562306a36Sopenharmony_cidata to filesystems stored on SPI flash like DataFlash; and others might
15662306a36Sopenharmony_cicontrol audio interfaces, present touchscreen sensors as input interfaces,
15762306a36Sopenharmony_cior monitor temperature and voltage levels during industrial processing.
15862306a36Sopenharmony_ciAnd those might all be sharing the same controller driver.
15962306a36Sopenharmony_ci
16062306a36Sopenharmony_ciA "struct spi_device" encapsulates the controller-side interface between
16162306a36Sopenharmony_cithose two types of drivers.
16262306a36Sopenharmony_ci
16362306a36Sopenharmony_ciThere is a minimal core of SPI programming interfaces, focussing on
16462306a36Sopenharmony_ciusing the driver model to connect controller and protocol drivers using
16562306a36Sopenharmony_cidevice tables provided by board specific initialization code.  SPI
16662306a36Sopenharmony_cishows up in sysfs in several locations::
16762306a36Sopenharmony_ci
16862306a36Sopenharmony_ci   /sys/devices/.../CTLR ... physical node for a given SPI controller
16962306a36Sopenharmony_ci
17062306a36Sopenharmony_ci   /sys/devices/.../CTLR/spiB.C ... spi_device on bus "B",
17162306a36Sopenharmony_ci	chipselect C, accessed through CTLR.
17262306a36Sopenharmony_ci
17362306a36Sopenharmony_ci   /sys/bus/spi/devices/spiB.C ... symlink to that physical
17462306a36Sopenharmony_ci	.../CTLR/spiB.C device
17562306a36Sopenharmony_ci
17662306a36Sopenharmony_ci   /sys/devices/.../CTLR/spiB.C/modalias ... identifies the driver
17762306a36Sopenharmony_ci	that should be used with this device (for hotplug/coldplug)
17862306a36Sopenharmony_ci
17962306a36Sopenharmony_ci   /sys/bus/spi/drivers/D ... driver for one or more spi*.* devices
18062306a36Sopenharmony_ci
18162306a36Sopenharmony_ci   /sys/class/spi_master/spiB ... symlink to a logical node which could hold
18262306a36Sopenharmony_ci	class related state for the SPI master controller managing bus "B".
18362306a36Sopenharmony_ci	All spiB.* devices share one physical SPI bus segment, with SCLK,
18462306a36Sopenharmony_ci	MOSI, and MISO.
18562306a36Sopenharmony_ci
18662306a36Sopenharmony_ci   /sys/devices/.../CTLR/slave ... virtual file for (un)registering the
18762306a36Sopenharmony_ci	slave device for an SPI slave controller.
18862306a36Sopenharmony_ci	Writing the driver name of an SPI slave handler to this file
18962306a36Sopenharmony_ci	registers the slave device; writing "(null)" unregisters the slave
19062306a36Sopenharmony_ci	device.
19162306a36Sopenharmony_ci	Reading from this file shows the name of the slave device ("(null)"
19262306a36Sopenharmony_ci	if not registered).
19362306a36Sopenharmony_ci
19462306a36Sopenharmony_ci   /sys/class/spi_slave/spiB ... symlink to a logical node which could hold
19562306a36Sopenharmony_ci	class related state for the SPI slave controller on bus "B".  When
19662306a36Sopenharmony_ci	registered, a single spiB.* device is present here, possible sharing
19762306a36Sopenharmony_ci	the physical SPI bus segment with other SPI slave devices.
19862306a36Sopenharmony_ci
19962306a36Sopenharmony_ciAt this time, the only class-specific state is the bus number ("B" in "spiB"),
20062306a36Sopenharmony_ciso those /sys/class entries are only useful to quickly identify busses.
20162306a36Sopenharmony_ci
20262306a36Sopenharmony_ci
20362306a36Sopenharmony_ciHow does board-specific init code declare SPI devices?
20462306a36Sopenharmony_ci------------------------------------------------------
20562306a36Sopenharmony_ciLinux needs several kinds of information to properly configure SPI devices.
20662306a36Sopenharmony_ciThat information is normally provided by board-specific code, even for
20762306a36Sopenharmony_cichips that do support some of automated discovery/enumeration.
20862306a36Sopenharmony_ci
20962306a36Sopenharmony_ciDeclare Controllers
21062306a36Sopenharmony_ci^^^^^^^^^^^^^^^^^^^
21162306a36Sopenharmony_ci
21262306a36Sopenharmony_ciThe first kind of information is a list of what SPI controllers exist.
21362306a36Sopenharmony_ciFor System-on-Chip (SOC) based boards, these will usually be platform
21462306a36Sopenharmony_cidevices, and the controller may need some platform_data in order to
21562306a36Sopenharmony_cioperate properly.  The "struct platform_device" will include resources
21662306a36Sopenharmony_cilike the physical address of the controller's first register and its IRQ.
21762306a36Sopenharmony_ci
21862306a36Sopenharmony_ciPlatforms will often abstract the "register SPI controller" operation,
21962306a36Sopenharmony_cimaybe coupling it with code to initialize pin configurations, so that
22062306a36Sopenharmony_cithe arch/.../mach-*/board-*.c files for several boards can all share the
22162306a36Sopenharmony_cisame basic controller setup code.  This is because most SOCs have several
22262306a36Sopenharmony_ciSPI-capable controllers, and only the ones actually usable on a given
22362306a36Sopenharmony_ciboard should normally be set up and registered.
22462306a36Sopenharmony_ci
22562306a36Sopenharmony_ciSo for example arch/.../mach-*/board-*.c files might have code like::
22662306a36Sopenharmony_ci
22762306a36Sopenharmony_ci	#include <mach/spi.h>	/* for mysoc_spi_data */
22862306a36Sopenharmony_ci
22962306a36Sopenharmony_ci	/* if your mach-* infrastructure doesn't support kernels that can
23062306a36Sopenharmony_ci	 * run on multiple boards, pdata wouldn't benefit from "__init".
23162306a36Sopenharmony_ci	 */
23262306a36Sopenharmony_ci	static struct mysoc_spi_data pdata __initdata = { ... };
23362306a36Sopenharmony_ci
23462306a36Sopenharmony_ci	static __init board_init(void)
23562306a36Sopenharmony_ci	{
23662306a36Sopenharmony_ci		...
23762306a36Sopenharmony_ci		/* this board only uses SPI controller #2 */
23862306a36Sopenharmony_ci		mysoc_register_spi(2, &pdata);
23962306a36Sopenharmony_ci		...
24062306a36Sopenharmony_ci	}
24162306a36Sopenharmony_ci
24262306a36Sopenharmony_ciAnd SOC-specific utility code might look something like::
24362306a36Sopenharmony_ci
24462306a36Sopenharmony_ci	#include <mach/spi.h>
24562306a36Sopenharmony_ci
24662306a36Sopenharmony_ci	static struct platform_device spi2 = { ... };
24762306a36Sopenharmony_ci
24862306a36Sopenharmony_ci	void mysoc_register_spi(unsigned n, struct mysoc_spi_data *pdata)
24962306a36Sopenharmony_ci	{
25062306a36Sopenharmony_ci		struct mysoc_spi_data *pdata2;
25162306a36Sopenharmony_ci
25262306a36Sopenharmony_ci		pdata2 = kmalloc(sizeof *pdata2, GFP_KERNEL);
25362306a36Sopenharmony_ci		*pdata2 = pdata;
25462306a36Sopenharmony_ci		...
25562306a36Sopenharmony_ci		if (n == 2) {
25662306a36Sopenharmony_ci			spi2->dev.platform_data = pdata2;
25762306a36Sopenharmony_ci			register_platform_device(&spi2);
25862306a36Sopenharmony_ci
25962306a36Sopenharmony_ci			/* also: set up pin modes so the spi2 signals are
26062306a36Sopenharmony_ci			 * visible on the relevant pins ... bootloaders on
26162306a36Sopenharmony_ci			 * production boards may already have done this, but
26262306a36Sopenharmony_ci			 * developer boards will often need Linux to do it.
26362306a36Sopenharmony_ci			 */
26462306a36Sopenharmony_ci		}
26562306a36Sopenharmony_ci		...
26662306a36Sopenharmony_ci	}
26762306a36Sopenharmony_ci
26862306a36Sopenharmony_ciNotice how the platform_data for boards may be different, even if the
26962306a36Sopenharmony_cisame SOC controller is used.  For example, on one board SPI might use
27062306a36Sopenharmony_cian external clock, where another derives the SPI clock from current
27162306a36Sopenharmony_cisettings of some master clock.
27262306a36Sopenharmony_ci
27362306a36Sopenharmony_ciDeclare Slave Devices
27462306a36Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^
27562306a36Sopenharmony_ci
27662306a36Sopenharmony_ciThe second kind of information is a list of what SPI slave devices exist
27762306a36Sopenharmony_cion the target board, often with some board-specific data needed for the
27862306a36Sopenharmony_cidriver to work correctly.
27962306a36Sopenharmony_ci
28062306a36Sopenharmony_ciNormally your arch/.../mach-*/board-*.c files would provide a small table
28162306a36Sopenharmony_cilisting the SPI devices on each board.  (This would typically be only a
28262306a36Sopenharmony_cismall handful.)  That might look like::
28362306a36Sopenharmony_ci
28462306a36Sopenharmony_ci	static struct ads7846_platform_data ads_info = {
28562306a36Sopenharmony_ci		.vref_delay_usecs	= 100,
28662306a36Sopenharmony_ci		.x_plate_ohms		= 580,
28762306a36Sopenharmony_ci		.y_plate_ohms		= 410,
28862306a36Sopenharmony_ci	};
28962306a36Sopenharmony_ci
29062306a36Sopenharmony_ci	static struct spi_board_info spi_board_info[] __initdata = {
29162306a36Sopenharmony_ci	{
29262306a36Sopenharmony_ci		.modalias	= "ads7846",
29362306a36Sopenharmony_ci		.platform_data	= &ads_info,
29462306a36Sopenharmony_ci		.mode		= SPI_MODE_0,
29562306a36Sopenharmony_ci		.irq		= GPIO_IRQ(31),
29662306a36Sopenharmony_ci		.max_speed_hz	= 120000 /* max sample rate at 3V */ * 16,
29762306a36Sopenharmony_ci		.bus_num	= 1,
29862306a36Sopenharmony_ci		.chip_select	= 0,
29962306a36Sopenharmony_ci	},
30062306a36Sopenharmony_ci	};
30162306a36Sopenharmony_ci
30262306a36Sopenharmony_ciAgain, notice how board-specific information is provided; each chip may need
30362306a36Sopenharmony_ciseveral types.  This example shows generic constraints like the fastest SPI
30462306a36Sopenharmony_ciclock to allow (a function of board voltage in this case) or how an IRQ pin
30562306a36Sopenharmony_ciis wired, plus chip-specific constraints like an important delay that's
30662306a36Sopenharmony_cichanged by the capacitance at one pin.
30762306a36Sopenharmony_ci
30862306a36Sopenharmony_ci(There's also "controller_data", information that may be useful to the
30962306a36Sopenharmony_cicontroller driver.  An example would be peripheral-specific DMA tuning
31062306a36Sopenharmony_cidata or chipselect callbacks.  This is stored in spi_device later.)
31162306a36Sopenharmony_ci
31262306a36Sopenharmony_ciThe board_info should provide enough information to let the system work
31362306a36Sopenharmony_ciwithout the chip's driver being loaded.  The most troublesome aspect of
31462306a36Sopenharmony_cithat is likely the SPI_CS_HIGH bit in the spi_device.mode field, since
31562306a36Sopenharmony_cisharing a bus with a device that interprets chipselect "backwards" is
31662306a36Sopenharmony_cinot possible until the infrastructure knows how to deselect it.
31762306a36Sopenharmony_ci
31862306a36Sopenharmony_ciThen your board initialization code would register that table with the SPI
31962306a36Sopenharmony_ciinfrastructure, so that it's available later when the SPI master controller
32062306a36Sopenharmony_cidriver is registered::
32162306a36Sopenharmony_ci
32262306a36Sopenharmony_ci	spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info));
32362306a36Sopenharmony_ci
32462306a36Sopenharmony_ciLike with other static board-specific setup, you won't unregister those.
32562306a36Sopenharmony_ci
32662306a36Sopenharmony_ciThe widely used "card" style computers bundle memory, cpu, and little else
32762306a36Sopenharmony_cionto a card that's maybe just thirty square centimeters.  On such systems,
32862306a36Sopenharmony_ciyour ``arch/.../mach-.../board-*.c`` file would primarily provide information
32962306a36Sopenharmony_ciabout the devices on the mainboard into which such a card is plugged.  That
33062306a36Sopenharmony_cicertainly includes SPI devices hooked up through the card connectors!
33162306a36Sopenharmony_ci
33262306a36Sopenharmony_ci
33362306a36Sopenharmony_ciNon-static Configurations
33462306a36Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^^^^^
33562306a36Sopenharmony_ci
33662306a36Sopenharmony_ciWhen Linux includes support for MMC/SD/SDIO/DataFlash cards through SPI, those
33762306a36Sopenharmony_ciconfigurations will also be dynamic.  Fortunately, such devices all support
33862306a36Sopenharmony_cibasic device identification probes, so they should hotplug normally.
33962306a36Sopenharmony_ci
34062306a36Sopenharmony_ci
34162306a36Sopenharmony_ciHow do I write an "SPI Protocol Driver"?
34262306a36Sopenharmony_ci----------------------------------------
34362306a36Sopenharmony_ciMost SPI drivers are currently kernel drivers, but there's also support
34462306a36Sopenharmony_cifor userspace drivers.  Here we talk only about kernel drivers.
34562306a36Sopenharmony_ci
34662306a36Sopenharmony_ciSPI protocol drivers somewhat resemble platform device drivers::
34762306a36Sopenharmony_ci
34862306a36Sopenharmony_ci	static struct spi_driver CHIP_driver = {
34962306a36Sopenharmony_ci		.driver = {
35062306a36Sopenharmony_ci			.name		= "CHIP",
35162306a36Sopenharmony_ci			.owner		= THIS_MODULE,
35262306a36Sopenharmony_ci			.pm		= &CHIP_pm_ops,
35362306a36Sopenharmony_ci		},
35462306a36Sopenharmony_ci
35562306a36Sopenharmony_ci		.probe		= CHIP_probe,
35662306a36Sopenharmony_ci		.remove		= CHIP_remove,
35762306a36Sopenharmony_ci	};
35862306a36Sopenharmony_ci
35962306a36Sopenharmony_ciThe driver core will automatically attempt to bind this driver to any SPI
36062306a36Sopenharmony_cidevice whose board_info gave a modalias of "CHIP".  Your probe() code
36162306a36Sopenharmony_cimight look like this unless you're creating a device which is managing
36262306a36Sopenharmony_cia bus (appearing under /sys/class/spi_master).
36362306a36Sopenharmony_ci
36462306a36Sopenharmony_ci::
36562306a36Sopenharmony_ci
36662306a36Sopenharmony_ci	static int CHIP_probe(struct spi_device *spi)
36762306a36Sopenharmony_ci	{
36862306a36Sopenharmony_ci		struct CHIP			*chip;
36962306a36Sopenharmony_ci		struct CHIP_platform_data	*pdata;
37062306a36Sopenharmony_ci
37162306a36Sopenharmony_ci		/* assuming the driver requires board-specific data: */
37262306a36Sopenharmony_ci		pdata = &spi->dev.platform_data;
37362306a36Sopenharmony_ci		if (!pdata)
37462306a36Sopenharmony_ci			return -ENODEV;
37562306a36Sopenharmony_ci
37662306a36Sopenharmony_ci		/* get memory for driver's per-chip state */
37762306a36Sopenharmony_ci		chip = kzalloc(sizeof *chip, GFP_KERNEL);
37862306a36Sopenharmony_ci		if (!chip)
37962306a36Sopenharmony_ci			return -ENOMEM;
38062306a36Sopenharmony_ci		spi_set_drvdata(spi, chip);
38162306a36Sopenharmony_ci
38262306a36Sopenharmony_ci		... etc
38362306a36Sopenharmony_ci		return 0;
38462306a36Sopenharmony_ci	}
38562306a36Sopenharmony_ci
38662306a36Sopenharmony_ciAs soon as it enters probe(), the driver may issue I/O requests to
38762306a36Sopenharmony_cithe SPI device using "struct spi_message".  When remove() returns,
38862306a36Sopenharmony_cior after probe() fails, the driver guarantees that it won't submit
38962306a36Sopenharmony_ciany more such messages.
39062306a36Sopenharmony_ci
39162306a36Sopenharmony_ci  - An spi_message is a sequence of protocol operations, executed
39262306a36Sopenharmony_ci    as one atomic sequence.  SPI driver controls include:
39362306a36Sopenharmony_ci
39462306a36Sopenharmony_ci      + when bidirectional reads and writes start ... by how its
39562306a36Sopenharmony_ci        sequence of spi_transfer requests is arranged;
39662306a36Sopenharmony_ci
39762306a36Sopenharmony_ci      + which I/O buffers are used ... each spi_transfer wraps a
39862306a36Sopenharmony_ci        buffer for each transfer direction, supporting full duplex
39962306a36Sopenharmony_ci        (two pointers, maybe the same one in both cases) and half
40062306a36Sopenharmony_ci        duplex (one pointer is NULL) transfers;
40162306a36Sopenharmony_ci
40262306a36Sopenharmony_ci      + optionally defining short delays after transfers ... using
40362306a36Sopenharmony_ci        the spi_transfer.delay.value setting (this delay can be the
40462306a36Sopenharmony_ci        only protocol effect, if the buffer length is zero) ...
40562306a36Sopenharmony_ci        when specifying this delay the default spi_transfer.delay.unit
40662306a36Sopenharmony_ci        is microseconds, however this can be adjusted to clock cycles
40762306a36Sopenharmony_ci        or nanoseconds if needed;
40862306a36Sopenharmony_ci
40962306a36Sopenharmony_ci      + whether the chipselect becomes inactive after a transfer and
41062306a36Sopenharmony_ci        any delay ... by using the spi_transfer.cs_change flag;
41162306a36Sopenharmony_ci
41262306a36Sopenharmony_ci      + hinting whether the next message is likely to go to this same
41362306a36Sopenharmony_ci        device ... using the spi_transfer.cs_change flag on the last
41462306a36Sopenharmony_ci	transfer in that atomic group, and potentially saving costs
41562306a36Sopenharmony_ci	for chip deselect and select operations.
41662306a36Sopenharmony_ci
41762306a36Sopenharmony_ci  - Follow standard kernel rules, and provide DMA-safe buffers in
41862306a36Sopenharmony_ci    your messages.  That way controller drivers using DMA aren't forced
41962306a36Sopenharmony_ci    to make extra copies unless the hardware requires it (e.g. working
42062306a36Sopenharmony_ci    around hardware errata that force the use of bounce buffering).
42162306a36Sopenharmony_ci
42262306a36Sopenharmony_ci    If standard dma_map_single() handling of these buffers is inappropriate,
42362306a36Sopenharmony_ci    you can use spi_message.is_dma_mapped to tell the controller driver
42462306a36Sopenharmony_ci    that you've already provided the relevant DMA addresses.
42562306a36Sopenharmony_ci
42662306a36Sopenharmony_ci  - The basic I/O primitive is spi_async().  Async requests may be
42762306a36Sopenharmony_ci    issued in any context (irq handler, task, etc) and completion
42862306a36Sopenharmony_ci    is reported using a callback provided with the message.
42962306a36Sopenharmony_ci    After any detected error, the chip is deselected and processing
43062306a36Sopenharmony_ci    of that spi_message is aborted.
43162306a36Sopenharmony_ci
43262306a36Sopenharmony_ci  - There are also synchronous wrappers like spi_sync(), and wrappers
43362306a36Sopenharmony_ci    like spi_read(), spi_write(), and spi_write_then_read().  These
43462306a36Sopenharmony_ci    may be issued only in contexts that may sleep, and they're all
43562306a36Sopenharmony_ci    clean (and small, and "optional") layers over spi_async().
43662306a36Sopenharmony_ci
43762306a36Sopenharmony_ci  - The spi_write_then_read() call, and convenience wrappers around
43862306a36Sopenharmony_ci    it, should only be used with small amounts of data where the
43962306a36Sopenharmony_ci    cost of an extra copy may be ignored.  It's designed to support
44062306a36Sopenharmony_ci    common RPC-style requests, such as writing an eight bit command
44162306a36Sopenharmony_ci    and reading a sixteen bit response -- spi_w8r16() being one its
44262306a36Sopenharmony_ci    wrappers, doing exactly that.
44362306a36Sopenharmony_ci
44462306a36Sopenharmony_ciSome drivers may need to modify spi_device characteristics like the
44562306a36Sopenharmony_citransfer mode, wordsize, or clock rate.  This is done with spi_setup(),
44662306a36Sopenharmony_ciwhich would normally be called from probe() before the first I/O is
44762306a36Sopenharmony_cidone to the device.  However, that can also be called at any time
44862306a36Sopenharmony_cithat no message is pending for that device.
44962306a36Sopenharmony_ci
45062306a36Sopenharmony_ciWhile "spi_device" would be the bottom boundary of the driver, the
45162306a36Sopenharmony_ciupper boundaries might include sysfs (especially for sensor readings),
45262306a36Sopenharmony_cithe input layer, ALSA, networking, MTD, the character device framework,
45362306a36Sopenharmony_cior other Linux subsystems.
45462306a36Sopenharmony_ci
45562306a36Sopenharmony_ciNote that there are two types of memory your driver must manage as part
45662306a36Sopenharmony_ciof interacting with SPI devices.
45762306a36Sopenharmony_ci
45862306a36Sopenharmony_ci  - I/O buffers use the usual Linux rules, and must be DMA-safe.
45962306a36Sopenharmony_ci    You'd normally allocate them from the heap or free page pool.
46062306a36Sopenharmony_ci    Don't use the stack, or anything that's declared "static".
46162306a36Sopenharmony_ci
46262306a36Sopenharmony_ci  - The spi_message and spi_transfer metadata used to glue those
46362306a36Sopenharmony_ci    I/O buffers into a group of protocol transactions.  These can
46462306a36Sopenharmony_ci    be allocated anywhere it's convenient, including as part of
46562306a36Sopenharmony_ci    other allocate-once driver data structures.  Zero-init these.
46662306a36Sopenharmony_ci
46762306a36Sopenharmony_ciIf you like, spi_message_alloc() and spi_message_free() convenience
46862306a36Sopenharmony_ciroutines are available to allocate and zero-initialize an spi_message
46962306a36Sopenharmony_ciwith several transfers.
47062306a36Sopenharmony_ci
47162306a36Sopenharmony_ci
47262306a36Sopenharmony_ciHow do I write an "SPI Master Controller Driver"?
47362306a36Sopenharmony_ci-------------------------------------------------
47462306a36Sopenharmony_ciAn SPI controller will probably be registered on the platform_bus; write
47562306a36Sopenharmony_cia driver to bind to the device, whichever bus is involved.
47662306a36Sopenharmony_ci
47762306a36Sopenharmony_ciThe main task of this type of driver is to provide an "spi_master".
47862306a36Sopenharmony_ciUse spi_alloc_master() to allocate the master, and spi_master_get_devdata()
47962306a36Sopenharmony_cito get the driver-private data allocated for that device.
48062306a36Sopenharmony_ci
48162306a36Sopenharmony_ci::
48262306a36Sopenharmony_ci
48362306a36Sopenharmony_ci	struct spi_master	*master;
48462306a36Sopenharmony_ci	struct CONTROLLER	*c;
48562306a36Sopenharmony_ci
48662306a36Sopenharmony_ci	master = spi_alloc_master(dev, sizeof *c);
48762306a36Sopenharmony_ci	if (!master)
48862306a36Sopenharmony_ci		return -ENODEV;
48962306a36Sopenharmony_ci
49062306a36Sopenharmony_ci	c = spi_master_get_devdata(master);
49162306a36Sopenharmony_ci
49262306a36Sopenharmony_ciThe driver will initialize the fields of that spi_master, including the
49362306a36Sopenharmony_cibus number (maybe the same as the platform device ID) and three methods
49462306a36Sopenharmony_ciused to interact with the SPI core and SPI protocol drivers.  It will
49562306a36Sopenharmony_cialso initialize its own internal state.  (See below about bus numbering
49662306a36Sopenharmony_ciand those methods.)
49762306a36Sopenharmony_ci
49862306a36Sopenharmony_ciAfter you initialize the spi_master, then use spi_register_master() to
49962306a36Sopenharmony_cipublish it to the rest of the system. At that time, device nodes for the
50062306a36Sopenharmony_cicontroller and any predeclared spi devices will be made available, and
50162306a36Sopenharmony_cithe driver model core will take care of binding them to drivers.
50262306a36Sopenharmony_ci
50362306a36Sopenharmony_ciIf you need to remove your SPI controller driver, spi_unregister_master()
50462306a36Sopenharmony_ciwill reverse the effect of spi_register_master().
50562306a36Sopenharmony_ci
50662306a36Sopenharmony_ci
50762306a36Sopenharmony_ciBus Numbering
50862306a36Sopenharmony_ci^^^^^^^^^^^^^
50962306a36Sopenharmony_ci
51062306a36Sopenharmony_ciBus numbering is important, since that's how Linux identifies a given
51162306a36Sopenharmony_ciSPI bus (shared SCK, MOSI, MISO).  Valid bus numbers start at zero.  On
51262306a36Sopenharmony_ciSOC systems, the bus numbers should match the numbers defined by the chip
51362306a36Sopenharmony_cimanufacturer.  For example, hardware controller SPI2 would be bus number 2,
51462306a36Sopenharmony_ciand spi_board_info for devices connected to it would use that number.
51562306a36Sopenharmony_ci
51662306a36Sopenharmony_ciIf you don't have such hardware-assigned bus number, and for some reason
51762306a36Sopenharmony_ciyou can't just assign them, then provide a negative bus number.  That will
51862306a36Sopenharmony_cithen be replaced by a dynamically assigned number. You'd then need to treat
51962306a36Sopenharmony_cithis as a non-static configuration (see above).
52062306a36Sopenharmony_ci
52162306a36Sopenharmony_ci
52262306a36Sopenharmony_ciSPI Master Methods
52362306a36Sopenharmony_ci^^^^^^^^^^^^^^^^^^
52462306a36Sopenharmony_ci
52562306a36Sopenharmony_ci``master->setup(struct spi_device *spi)``
52662306a36Sopenharmony_ci	This sets up the device clock rate, SPI mode, and word sizes.
52762306a36Sopenharmony_ci	Drivers may change the defaults provided by board_info, and then
52862306a36Sopenharmony_ci	call spi_setup(spi) to invoke this routine.  It may sleep.
52962306a36Sopenharmony_ci
53062306a36Sopenharmony_ci	Unless each SPI slave has its own configuration registers, don't
53162306a36Sopenharmony_ci	change them right away ... otherwise drivers could corrupt I/O
53262306a36Sopenharmony_ci	that's in progress for other SPI devices.
53362306a36Sopenharmony_ci
53462306a36Sopenharmony_ci	.. note::
53562306a36Sopenharmony_ci
53662306a36Sopenharmony_ci		BUG ALERT:  for some reason the first version of
53762306a36Sopenharmony_ci		many spi_master drivers seems to get this wrong.
53862306a36Sopenharmony_ci		When you code setup(), ASSUME that the controller
53962306a36Sopenharmony_ci		is actively processing transfers for another device.
54062306a36Sopenharmony_ci
54162306a36Sopenharmony_ci``master->cleanup(struct spi_device *spi)``
54262306a36Sopenharmony_ci	Your controller driver may use spi_device.controller_state to hold
54362306a36Sopenharmony_ci	state it dynamically associates with that device.  If you do that,
54462306a36Sopenharmony_ci	be sure to provide the cleanup() method to free that state.
54562306a36Sopenharmony_ci
54662306a36Sopenharmony_ci``master->prepare_transfer_hardware(struct spi_master *master)``
54762306a36Sopenharmony_ci	This will be called by the queue mechanism to signal to the driver
54862306a36Sopenharmony_ci	that a message is coming in soon, so the subsystem requests the
54962306a36Sopenharmony_ci	driver to prepare the transfer hardware by issuing this call.
55062306a36Sopenharmony_ci	This may sleep.
55162306a36Sopenharmony_ci
55262306a36Sopenharmony_ci``master->unprepare_transfer_hardware(struct spi_master *master)``
55362306a36Sopenharmony_ci	This will be called by the queue mechanism to signal to the driver
55462306a36Sopenharmony_ci	that there are no more messages pending in the queue and it may
55562306a36Sopenharmony_ci	relax the hardware (e.g. by power management calls). This may sleep.
55662306a36Sopenharmony_ci
55762306a36Sopenharmony_ci``master->transfer_one_message(struct spi_master *master, struct spi_message *mesg)``
55862306a36Sopenharmony_ci	The subsystem calls the driver to transfer a single message while
55962306a36Sopenharmony_ci	queuing transfers that arrive in the meantime. When the driver is
56062306a36Sopenharmony_ci	finished with this message, it must call
56162306a36Sopenharmony_ci	spi_finalize_current_message() so the subsystem can issue the next
56262306a36Sopenharmony_ci	message. This may sleep.
56362306a36Sopenharmony_ci
56462306a36Sopenharmony_ci``master->transfer_one(struct spi_master *master, struct spi_device *spi, struct spi_transfer *transfer)``
56562306a36Sopenharmony_ci	The subsystem calls the driver to transfer a single transfer while
56662306a36Sopenharmony_ci	queuing transfers that arrive in the meantime. When the driver is
56762306a36Sopenharmony_ci	finished with this transfer, it must call
56862306a36Sopenharmony_ci	spi_finalize_current_transfer() so the subsystem can issue the next
56962306a36Sopenharmony_ci	transfer. This may sleep. Note: transfer_one and transfer_one_message
57062306a36Sopenharmony_ci	are mutually exclusive; when both are set, the generic subsystem does
57162306a36Sopenharmony_ci	not call your transfer_one callback.
57262306a36Sopenharmony_ci
57362306a36Sopenharmony_ci	Return values:
57462306a36Sopenharmony_ci
57562306a36Sopenharmony_ci	* negative errno: error
57662306a36Sopenharmony_ci	* 0: transfer is finished
57762306a36Sopenharmony_ci	* 1: transfer is still in progress
57862306a36Sopenharmony_ci
57962306a36Sopenharmony_ci``master->set_cs_timing(struct spi_device *spi, u8 setup_clk_cycles, u8 hold_clk_cycles, u8 inactive_clk_cycles)``
58062306a36Sopenharmony_ci	This method allows SPI client drivers to request SPI master controller
58162306a36Sopenharmony_ci	for configuring device specific CS setup, hold and inactive timing
58262306a36Sopenharmony_ci	requirements.
58362306a36Sopenharmony_ci
58462306a36Sopenharmony_ciDeprecated Methods
58562306a36Sopenharmony_ci^^^^^^^^^^^^^^^^^^
58662306a36Sopenharmony_ci
58762306a36Sopenharmony_ci``master->transfer(struct spi_device *spi, struct spi_message *message)``
58862306a36Sopenharmony_ci	This must not sleep. Its responsibility is to arrange that the
58962306a36Sopenharmony_ci	transfer happens and its complete() callback is issued. The two
59062306a36Sopenharmony_ci	will normally happen later, after other transfers complete, and
59162306a36Sopenharmony_ci	if the controller is idle it will need to be kickstarted. This
59262306a36Sopenharmony_ci	method is not used on queued controllers and must be NULL if
59362306a36Sopenharmony_ci	transfer_one_message() and (un)prepare_transfer_hardware() are
59462306a36Sopenharmony_ci	implemented.
59562306a36Sopenharmony_ci
59662306a36Sopenharmony_ci
59762306a36Sopenharmony_ciSPI Message Queue
59862306a36Sopenharmony_ci^^^^^^^^^^^^^^^^^
59962306a36Sopenharmony_ci
60062306a36Sopenharmony_ciIf you are happy with the standard queueing mechanism provided by the
60162306a36Sopenharmony_ciSPI subsystem, just implement the queued methods specified above. Using
60262306a36Sopenharmony_cithe message queue has the upside of centralizing a lot of code and
60362306a36Sopenharmony_ciproviding pure process-context execution of methods. The message queue
60462306a36Sopenharmony_cican also be elevated to realtime priority on high-priority SPI traffic.
60562306a36Sopenharmony_ci
60662306a36Sopenharmony_ciUnless the queueing mechanism in the SPI subsystem is selected, the bulk
60762306a36Sopenharmony_ciof the driver will be managing the I/O queue fed by the now deprecated
60862306a36Sopenharmony_cifunction transfer().
60962306a36Sopenharmony_ci
61062306a36Sopenharmony_ciThat queue could be purely conceptual.  For example, a driver used only
61162306a36Sopenharmony_cifor low-frequency sensor access might be fine using synchronous PIO.
61262306a36Sopenharmony_ci
61362306a36Sopenharmony_ciBut the queue will probably be very real, using message->queue, PIO,
61462306a36Sopenharmony_cioften DMA (especially if the root filesystem is in SPI flash), and
61562306a36Sopenharmony_ciexecution contexts like IRQ handlers, tasklets, or workqueues (such
61662306a36Sopenharmony_cias keventd).  Your driver can be as fancy, or as simple, as you need.
61762306a36Sopenharmony_ciSuch a transfer() method would normally just add the message to a
61862306a36Sopenharmony_ciqueue, and then start some asynchronous transfer engine (unless it's
61962306a36Sopenharmony_cialready running).
62062306a36Sopenharmony_ci
62162306a36Sopenharmony_ci
62262306a36Sopenharmony_ciTHANKS TO
62362306a36Sopenharmony_ci---------
62462306a36Sopenharmony_ciContributors to Linux-SPI discussions include (in alphabetical order,
62562306a36Sopenharmony_ciby last name):
62662306a36Sopenharmony_ci
62762306a36Sopenharmony_ci- Mark Brown
62862306a36Sopenharmony_ci- David Brownell
62962306a36Sopenharmony_ci- Russell King
63062306a36Sopenharmony_ci- Grant Likely
63162306a36Sopenharmony_ci- Dmitry Pervushin
63262306a36Sopenharmony_ci- Stephen Street
63362306a36Sopenharmony_ci- Mark Underwood
63462306a36Sopenharmony_ci- Andrew Victor
63562306a36Sopenharmony_ci- Linus Walleij
63662306a36Sopenharmony_ci- Vitaly Wool
637