aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDavid Brownell <david-b@pacbell.net>2006-01-08 16:34:19 -0500
committerGreg Kroah-Hartman <gregkh@suse.de>2006-01-13 19:29:54 -0500
commit8ae12a0d85987dc138f8c944cb78a92bf466cea0 (patch)
treeca032f25bb26f88cc35d68c6f8065143ce64a6a8
parent67daf5f11f06b9b15f8320de1d237ccc2e74fe43 (diff)
[PATCH] spi: simple SPI framework
This is the core of a small SPI framework, implementing the model of a queue of messages which complete asynchronously (with thin synchronous wrappers on top). - It's still less than 2KB of ".text" (ARM). If there's got to be a mid-layer for something so simple, that's the right size budget. :) - The guts use board-specific SPI device tables to build the driver model tree. (Hardware probing is rarely an option.) - This version of Kconfig includes no drivers. At this writing there are two known master controller drivers (PXA/SSP, OMAP MicroWire) and three protocol drivers (CS8415a, ADS7846, DataFlash) with LKML mentions of other drivers in development. - No userspace API. There are several implementations to compare. Implement them like any other driver, and bind them with sysfs. The changes from last version posted to LKML (on 11-Nov-2005) are minor, and include: - One bugfix (removes a FIXME), with the visible effect of making device names be "spiB.C" where B is the bus number and C is the chipselect. - The "caller provides DMA mappings" mechanism now has kerneldoc, for DMA drivers that want to be fancy. - Hey, the framework init can be subsys_init. Even though board init logic fires earlier, at arch_init ... since the framework init is for driver support, and the board init support uses static init. - Various additional spec/doc clarifications based on discussions with other folk. It adds a brief "thank you" at the end, for folk who've helped nudge this framework into existence. As I've said before, I think that "protocol tweaking" is the main support that this driver framework will need to evolve. From: Mark Underwood <basicmark@yahoo.com> Update the SPI framework to remove a potential priority inversion case by reverting to kmalloc if the pre-allocated DMA-safe buffer isn't available. Signed-off-by: David Brownell <dbrownell@users.sourceforge.net> Signed-off-by: Andrew Morton <akpm@osdl.org> Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>
-rw-r--r--Documentation/spi/spi-summary416
-rw-r--r--arch/arm/Kconfig2
-rw-r--r--drivers/Kconfig2
-rw-r--r--drivers/Makefile1
-rw-r--r--drivers/spi/Kconfig76
-rw-r--r--drivers/spi/Makefile23
-rw-r--r--drivers/spi/spi.c568
-rw-r--r--include/linux/spi/spi.h542
8 files changed, 1630 insertions, 0 deletions
diff --git a/Documentation/spi/spi-summary b/Documentation/spi/spi-summary
new file mode 100644
index 000000000000..00497f95ca4b
--- /dev/null
+++ b/Documentation/spi/spi-summary
@@ -0,0 +1,416 @@
1Overview of Linux kernel SPI support
2====================================
3
422-Nov-2005
5
6What is SPI?
7------------
8The "Serial Peripheral Interface" (SPI) is a four-wire point-to-point
9serial link used to connect microcontrollers to sensors and memory.
10
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
15commonly used.
16
17SPI masters may use a "chip select" line to activate a given SPI slave
18device, so those three signal wires may be connected to several chips
19in parallel. All SPI slaves support chipselects. Some devices have
20other signals, often including an interrupt to the master.
21
22Unlike serial busses like USB or SMBUS, even low level protocols for
23SPI slave functions are usually not interoperable between vendors
24(except for cases like SPI memory chips).
25
26 - SPI may be used for request/response style device protocols, as with
27 touchscreen sensors and memory chips.
28
29 - It may also be used to stream data in either direction (half duplex),
30 or both of them at the same time (full duplex).
31
32 - Some devices may use eight bit words. Others may different word
33 lengths, such as streams of 12-bit or 20-bit digital samples.
34
35In the same way, SPI slaves will only rarely support any kind of automatic
36discovery/enumeration protocol. The tree of slave devices accessible from
37a given SPI master will normally be set up manually, with configuration
38tables.
39
40SPI is only one of the names used by such four-wire protocols, and
41most controllers have no problem handling "MicroWire" (think of it as
42half-duplex SPI, for request/response protocols), SSP ("Synchronous
43Serial Protocol"), PSP ("Programmable Serial Protocol"), and other
44related protocols.
45
46Microcontrollers often support both master and slave sides of the SPI
47protocol. This document (and Linux) currently only supports the master
48side of SPI interactions.
49
50
51Who uses it? On what kinds of systems?
52---------------------------------------
53Linux developers using SPI are probably writing device drivers for embedded
54systems boards. SPI is used to control external chips, and it is also a
55protocol supported by every MMC or SD memory card. (The older "DataFlash"
56cards, predating MMC cards but using the same connectors and card shape,
57support only SPI.) Some PC hardware uses SPI flash for BIOS code.
58
59SPI slave chips range from digital/analog converters used for analog
60sensors and codecs, to memory, to peripherals like USB controllers
61or Ethernet adapters; and more.
62
63Most systems using SPI will integrate a few devices on a mainboard.
64Some provide SPI links on expansion connectors; in cases where no
65dedicated SPI controller exists, GPIO pins can be used to create a
66low speed "bitbanging" adapter. Very few systems will "hotplug" an SPI
67controller; the reasons to use SPI focus on low cost and simple operation,
68and if dynamic reconfiguration is important, USB will often be a more
69appropriate low-pincount peripheral bus.
70
71Many microcontrollers that can run Linux integrate one or more I/O
72interfaces with SPI modes. Given SPI support, they could use MMC or SD
73cards without needing a special purpose MMC/SD/SDIO controller.
74
75
76How do these driver programming interfaces work?
77------------------------------------------------
78The <linux/spi/spi.h> header file includes kerneldoc, as does the
79main source code, and you should certainly read that. This is just
80an overview, so you get the big picture before the details.
81
82There are two types of SPI driver, here called:
83
84 Controller drivers ... these are often built in to System-On-Chip
85 processors, and often support both Master and Slave roles.
86 These drivers touch hardware registers and may use DMA.
87
88 Protocol drivers ... these pass messages through the controller
89 driver to communicate with a Slave or Master device on the
90 other side of an SPI link.
91
92So for example one protocol driver might talk to the MTD layer to export
93data to filesystems stored on SPI flash like DataFlash; and others might
94control audio interfaces, present touchscreen sensors as input interfaces,
95or monitor temperature and voltage levels during industrial processing.
96And those might all be sharing the same controller driver.
97
98A "struct spi_device" encapsulates the master-side interface between
99those two types of driver. At this writing, Linux has no slave side
100programming interface.
101
102There is a minimal core of SPI programming interfaces, focussing on
103using driver model to connect controller and protocol drivers using
104device tables provided by board specific initialization code. SPI
105shows up in sysfs in several locations:
106
107 /sys/devices/.../CTLR/spiB.C ... spi_device for on bus "B",
108 chipselect C, accessed through CTLR.
109
110 /sys/bus/spi/devices/spiB.C ... symlink to the physical
111 spiB-C device
112
113 /sys/bus/spi/drivers/D ... driver for one or more spi*.* devices
114
115 /sys/class/spi_master/spiB ... class device for the controller
116 managing bus "B". All the spiB.* devices share the same
117 physical SPI bus segment, with SCLK, MOSI, and MISO.
118
119The basic I/O primitive submits an asynchronous message to an I/O queue
120maintained by the controller driver. A completion callback is issued
121asynchronously when the data transfer(s) in that message completes.
122There are also some simple synchronous wrappers for those calls.
123
124
125How does board-specific init code declare SPI devices?
126------------------------------------------------------
127Linux needs several kinds of information to properly configure SPI devices.
128That information is normally provided by board-specific code, even for
129chips that do support some of automated discovery/enumeration.
130
131DECLARE CONTROLLERS
132
133The first kind of information is a list of what SPI controllers exist.
134For System-on-Chip (SOC) based boards, these will usually be platform
135devices, and the controller may need some platform_data in order to
136operate properly. The "struct platform_device" will include resources
137like the physical address of the controller's first register and its IRQ.
138
139Platforms will often abstract the "register SPI controller" operation,
140maybe coupling it with code to initialize pin configurations, so that
141the arch/.../mach-*/board-*.c files for several boards can all share the
142same basic controller setup code. This is because most SOCs have several
143SPI-capable controllers, and only the ones actually usable on a given
144board should normally be set up and registered.
145
146So for example arch/.../mach-*/board-*.c files might have code like:
147
148 #include <asm/arch/spi.h> /* for mysoc_spi_data */
149
150 /* if your mach-* infrastructure doesn't support kernels that can
151 * run on multiple boards, pdata wouldn't benefit from "__init".
152 */
153 static struct mysoc_spi_data __init pdata = { ... };
154
155 static __init board_init(void)
156 {
157 ...
158 /* this board only uses SPI controller #2 */
159 mysoc_register_spi(2, &pdata);
160 ...
161 }
162
163And SOC-specific utility code might look something like:
164
165 #include <asm/arch/spi.h>
166
167 static struct platform_device spi2 = { ... };
168
169 void mysoc_register_spi(unsigned n, struct mysoc_spi_data *pdata)
170 {
171 struct mysoc_spi_data *pdata2;
172
173 pdata2 = kmalloc(sizeof *pdata2, GFP_KERNEL);
174 *pdata2 = pdata;
175 ...
176 if (n == 2) {
177 spi2->dev.platform_data = pdata2;
178 register_platform_device(&spi2);
179
180 /* also: set up pin modes so the spi2 signals are
181 * visible on the relevant pins ... bootloaders on
182 * production boards may already have done this, but
183 * developer boards will often need Linux to do it.
184 */
185 }
186 ...
187 }
188
189Notice how the platform_data for boards may be different, even if the
190same SOC controller is used. For example, on one board SPI might use
191an external clock, where another derives the SPI clock from current
192settings of some master clock.
193
194
195DECLARE SLAVE DEVICES
196
197The second kind of information is a list of what SPI slave devices exist
198on the target board, often with some board-specific data needed for the
199driver to work correctly.
200
201Normally your arch/.../mach-*/board-*.c files would provide a small table
202listing the SPI devices on each board. (This would typically be only a
203small handful.) That might look like:
204
205 static struct ads7846_platform_data ads_info = {
206 .vref_delay_usecs = 100,
207 .x_plate_ohms = 580,
208 .y_plate_ohms = 410,
209 };
210
211 static struct spi_board_info spi_board_info[] __initdata = {
212 {
213 .modalias = "ads7846",
214 .platform_data = &ads_info,
215 .mode = SPI_MODE_0,
216 .irq = GPIO_IRQ(31),
217 .max_speed_hz = 120000 /* max sample rate at 3V */ * 16,
218 .bus_num = 1,
219 .chip_select = 0,
220 },
221 };
222
223Again, notice how board-specific information is provided; each chip may need
224several types. This example shows generic constraints like the fastest SPI
225clock to allow (a function of board voltage in this case) or how an IRQ pin
226is wired, plus chip-specific constraints like an important delay that's
227changed by the capacitance at one pin.
228
229(There's also "controller_data", information that may be useful to the
230controller driver. An example would be peripheral-specific DMA tuning
231data or chipselect callbacks. This is stored in spi_device later.)
232
233The board_info should provide enough information to let the system work
234without the chip's driver being loaded. The most troublesome aspect of
235that is likely the SPI_CS_HIGH bit in the spi_device.mode field, since
236sharing a bus with a device that interprets chipselect "backwards" is
237not possible.
238
239Then your board initialization code would register that table with the SPI
240infrastructure, so that it's available later when the SPI master controller
241driver is registered:
242
243 spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info));
244
245Like with other static board-specific setup, you won't unregister those.
246
247
248NON-STATIC CONFIGURATIONS
249
250Developer boards often play by different rules than product boards, and one
251example is the potential need to hotplug SPI devices and/or controllers.
252
253For those cases you might need to use use spi_busnum_to_master() to look
254up the spi bus master, and will likely need spi_new_device() to provide the
255board info based on the board that was hotplugged. Of course, you'd later
256call at least spi_unregister_device() when that board is removed.
257
258
259How do I write an "SPI Protocol Driver"?
260----------------------------------------
261All SPI drivers are currently kernel drivers. A userspace driver API
262would just be another kernel driver, probably offering some lowlevel
263access through aio_read(), aio_write(), and ioctl() calls and using the
264standard userspace sysfs mechanisms to bind to a given SPI device.
265
266SPI protocol drivers are normal device drivers, with no more wrapper
267than needed by platform devices:
268
269 static struct device_driver CHIP_driver = {
270 .name = "CHIP",
271 .bus = &spi_bus_type,
272 .probe = CHIP_probe,
273 .remove = __exit_p(CHIP_remove),
274 .suspend = CHIP_suspend,
275 .resume = CHIP_resume,
276 };
277
278The SPI core will autmatically attempt to bind this driver to any SPI
279device whose board_info gave a modalias of "CHIP". Your probe() code
280might look like this unless you're creating a class_device:
281
282 static int __init CHIP_probe(struct device *dev)
283 {
284 struct spi_device *spi = to_spi_device(dev);
285 struct CHIP *chip;
286 struct CHIP_platform_data *pdata = dev->platform_data;
287
288 /* get memory for driver's per-chip state */
289 chip = kzalloc(sizeof *chip, GFP_KERNEL);
290 if (!chip)
291 return -ENOMEM;
292 dev_set_drvdata(dev, chip);
293
294 ... etc
295 return 0;
296 }
297
298As soon as it enters probe(), the driver may issue I/O requests to
299the SPI device using "struct spi_message". When remove() returns,
300the driver guarantees that it won't submit any more such messages.
301
302 - An spi_message is a sequence of of protocol operations, executed
303 as one atomic sequence. SPI driver controls include:
304
305 + when bidirectional reads and writes start ... by how its
306 sequence of spi_transfer requests is arranged;
307
308 + optionally defining short delays after transfers ... using
309 the spi_transfer.delay_usecs setting;
310
311 + whether the chipselect becomes inactive after a transfer and
312 any delay ... by using the spi_transfer.cs_change flag;
313
314 + hinting whether the next message is likely to go to this same
315 device ... using the spi_transfer.cs_change flag on the last
316 transfer in that atomic group, and potentially saving costs
317 for chip deselect and select operations.
318
319 - Follow standard kernel rules, and provide DMA-safe buffers in
320 your messages. That way controller drivers using DMA aren't forced
321 to make extra copies unless the hardware requires it (e.g. working
322 around hardware errata that force the use of bounce buffering).
323
324 If standard dma_map_single() handling of these buffers is inappropriate,
325 you can use spi_message.is_dma_mapped to tell the controller driver
326 that you've already provided the relevant DMA addresses.
327
328 - The basic I/O primitive is spi_async(). Async requests may be
329 issued in any context (irq handler, task, etc) and completion
330 is reported using a callback provided with the message.
331
332 - There are also synchronous wrappers like spi_sync(), and wrappers
333 like spi_read(), spi_write(), and spi_write_then_read(). These
334 may be issued only in contexts that may sleep, and they're all
335 clean (and small, and "optional") layers over spi_async().
336
337 - The spi_write_then_read() call, and convenience wrappers around
338 it, should only be used with small amounts of data where the
339 cost of an extra copy may be ignored. It's designed to support
340 common RPC-style requests, such as writing an eight bit command
341 and reading a sixteen bit response -- spi_w8r16() being one its
342 wrappers, doing exactly that.
343
344Some drivers may need to modify spi_device characteristics like the
345transfer mode, wordsize, or clock rate. This is done with spi_setup(),
346which would normally be called from probe() before the first I/O is
347done to the device.
348
349While "spi_device" would be the bottom boundary of the driver, the
350upper boundaries might include sysfs (especially for sensor readings),
351the input layer, ALSA, networking, MTD, the character device framework,
352or other Linux subsystems.
353
354
355How do I write an "SPI Master Controller Driver"?
356-------------------------------------------------
357An SPI controller will probably be registered on the platform_bus; write
358a driver to bind to the device, whichever bus is involved.
359
360The main task of this type of driver is to provide an "spi_master".
361Use spi_alloc_master() to allocate the master, and class_get_devdata()
362to get the driver-private data allocated for that device.
363
364 struct spi_master *master;
365 struct CONTROLLER *c;
366
367 master = spi_alloc_master(dev, sizeof *c);
368 if (!master)
369 return -ENODEV;
370
371 c = class_get_devdata(&master->cdev);
372
373The driver will initialize the fields of that spi_master, including the
374bus number (maybe the same as the platform device ID) and three methods
375used to interact with the SPI core and SPI protocol drivers. It will
376also initialize its own internal state.
377
378 master->setup(struct spi_device *spi)
379 This sets up the device clock rate, SPI mode, and word sizes.
380 Drivers may change the defaults provided by board_info, and then
381 call spi_setup(spi) to invoke this routine. It may sleep.
382
383 master->transfer(struct spi_device *spi, struct spi_message *message)
384 This must not sleep. Its responsibility is arrange that the
385 transfer happens and its complete() callback is issued; the two
386 will normally happen later, after other transfers complete.
387
388 master->cleanup(struct spi_device *spi)
389 Your controller driver may use spi_device.controller_state to hold
390 state it dynamically associates with that device. If you do that,
391 be sure to provide the cleanup() method to free that state.
392
393The bulk of the driver will be managing the I/O queue fed by transfer().
394
395That queue could be purely conceptual. For example, a driver used only
396for low-frequency sensor acess might be fine using synchronous PIO.
397
398But the queue will probably be very real, using message->queue, PIO,
399often DMA (especially if the root filesystem is in SPI flash), and
400execution contexts like IRQ handlers, tasklets, or workqueues (such
401as keventd). Your driver can be as fancy, or as simple, as you need.
402
403
404THANKS TO
405---------
406Contributors to Linux-SPI discussions include (in alphabetical order,
407by last name):
408
409David Brownell
410Russell King
411Dmitry Pervushin
412Stephen Street
413Mark Underwood
414Andrew Victor
415Vitaly Wool
416
diff --git a/arch/arm/Kconfig b/arch/arm/Kconfig
index 50b9afa8ae6d..3cfd82a05b20 100644
--- a/arch/arm/Kconfig
+++ b/arch/arm/Kconfig
@@ -729,6 +729,8 @@ source "drivers/char/Kconfig"
729 729
730source "drivers/i2c/Kconfig" 730source "drivers/i2c/Kconfig"
731 731
732source "drivers/spi/Kconfig"
733
732source "drivers/hwmon/Kconfig" 734source "drivers/hwmon/Kconfig"
733 735
734#source "drivers/l3/Kconfig" 736#source "drivers/l3/Kconfig"
diff --git a/drivers/Kconfig b/drivers/Kconfig
index 48f446d3c671..283c089537bc 100644
--- a/drivers/Kconfig
+++ b/drivers/Kconfig
@@ -44,6 +44,8 @@ source "drivers/char/Kconfig"
44 44
45source "drivers/i2c/Kconfig" 45source "drivers/i2c/Kconfig"
46 46
47source "drivers/spi/Kconfig"
48
47source "drivers/w1/Kconfig" 49source "drivers/w1/Kconfig"
48 50
49source "drivers/hwmon/Kconfig" 51source "drivers/hwmon/Kconfig"
diff --git a/drivers/Makefile b/drivers/Makefile
index 7fc3f0f08b29..7c45050ecd03 100644
--- a/drivers/Makefile
+++ b/drivers/Makefile
@@ -41,6 +41,7 @@ obj-$(CONFIG_FUSION) += message/
41obj-$(CONFIG_IEEE1394) += ieee1394/ 41obj-$(CONFIG_IEEE1394) += ieee1394/
42obj-y += cdrom/ 42obj-y += cdrom/
43obj-$(CONFIG_MTD) += mtd/ 43obj-$(CONFIG_MTD) += mtd/
44obj-$(CONFIG_SPI) += spi/
44obj-$(CONFIG_PCCARD) += pcmcia/ 45obj-$(CONFIG_PCCARD) += pcmcia/
45obj-$(CONFIG_DIO) += dio/ 46obj-$(CONFIG_DIO) += dio/
46obj-$(CONFIG_SBUS) += sbus/ 47obj-$(CONFIG_SBUS) += sbus/
diff --git a/drivers/spi/Kconfig b/drivers/spi/Kconfig
new file mode 100644
index 000000000000..d3105104a297
--- /dev/null
+++ b/drivers/spi/Kconfig
@@ -0,0 +1,76 @@
1#
2# SPI driver configuration
3#
4# NOTE: the reason this doesn't show SPI slave support is mostly that
5# nobody's needed a slave side API yet. The master-role API is not
6# fully appropriate there, so it'd need some thought to do well.
7#
8menu "SPI support"
9
10config SPI
11 bool "SPI support"
12 help
13 The "Serial Peripheral Interface" is a low level synchronous
14 protocol. Chips that support SPI can have data transfer rates
15 up to several tens of Mbit/sec. Chips are addressed with a
16 controller and a chipselect. Most SPI slaves don't support
17 dynamic device discovery; some are even write-only or read-only.
18
19 SPI is widely used by microcontollers to talk with sensors,
20 eeprom and flash memory, codecs and various other controller
21 chips, analog to digital (and d-to-a) converters, and more.
22 MMC and SD cards can be accessed using SPI protocol; and for
23 DataFlash cards used in MMC sockets, SPI must always be used.
24
25 SPI is one of a family of similar protocols using a four wire
26 interface (select, clock, data in, data out) including Microwire
27 (half duplex), SSP, SSI, and PSP. This driver framework should
28 work with most such devices and controllers.
29
30config SPI_DEBUG
31 boolean "Debug support for SPI drivers"
32 depends on SPI && DEBUG_KERNEL
33 help
34 Say "yes" to enable debug messaging (like dev_dbg and pr_debug),
35 sysfs, and debugfs support in SPI controller and protocol drivers.
36
37#
38# MASTER side ... talking to discrete SPI slave chips including microcontrollers
39#
40
41config SPI_MASTER
42# boolean "SPI Master Support"
43 boolean
44 default SPI
45 help
46 If your system has an master-capable SPI controller (which
47 provides the clock and chipselect), you can enable that
48 controller and the protocol drivers for the SPI slave chips
49 that are connected.
50
51comment "SPI Master Controller Drivers"
52 depends on SPI_MASTER
53
54
55#
56# Add new SPI master controllers in alphabetical order above this line
57#
58
59
60#
61# There are lots of SPI device types, with sensors and memory
62# being probably the most widely used ones.
63#
64comment "SPI Protocol Masters"
65 depends on SPI_MASTER
66
67
68#
69# Add new SPI protocol masters in alphabetical order above this line
70#
71
72
73# (slave support would go here)
74
75endmenu # "SPI support"
76
diff --git a/drivers/spi/Makefile b/drivers/spi/Makefile
new file mode 100644
index 000000000000..afd2321753b3
--- /dev/null
+++ b/drivers/spi/Makefile
@@ -0,0 +1,23 @@
1#
2# Makefile for kernel SPI drivers.
3#
4
5ifeq ($(CONFIG_SPI_DEBUG),y)
6EXTRA_CFLAGS += -DDEBUG
7endif
8
9# small core, mostly translating board-specific
10# config declarations into driver model code
11obj-$(CONFIG_SPI_MASTER) += spi.o
12
13# SPI master controller drivers (bus)
14# ... add above this line ...
15
16# SPI protocol drivers (device/link on bus)
17# ... add above this line ...
18
19# SPI slave controller drivers (upstream link)
20# ... add above this line ...
21
22# SPI slave drivers (protocol for that link)
23# ... add above this line ...
diff --git a/drivers/spi/spi.c b/drivers/spi/spi.c
new file mode 100644
index 000000000000..7cd356b17644
--- /dev/null
+++ b/drivers/spi/spi.c
@@ -0,0 +1,568 @@
1/*
2 * spi.c - SPI init/core code
3 *
4 * Copyright (C) 2005 David Brownell
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21#include <linux/autoconf.h>
22#include <linux/kernel.h>
23#include <linux/device.h>
24#include <linux/init.h>
25#include <linux/cache.h>
26#include <linux/spi/spi.h>
27
28
29/* SPI bustype and spi_master class are registered during early boot,
30 * usually before board init code provides the SPI device tables, and
31 * are available later when driver init code needs them.
32 *
33 * Drivers for SPI devices started out like those for platform bus
34 * devices. But both have changed in 2.6.15; maybe this should get
35 * an "spi_driver" structure at some point (not currently needed)
36 */
37static void spidev_release(struct device *dev)
38{
39 const struct spi_device *spi = to_spi_device(dev);
40
41 /* spi masters may cleanup for released devices */
42 if (spi->master->cleanup)
43 spi->master->cleanup(spi);
44
45 class_device_put(&spi->master->cdev);
46 kfree(dev);
47}
48
49static ssize_t
50modalias_show(struct device *dev, struct device_attribute *a, char *buf)
51{
52 const struct spi_device *spi = to_spi_device(dev);
53
54 return snprintf(buf, BUS_ID_SIZE + 1, "%s\n", spi->modalias);
55}
56
57static struct device_attribute spi_dev_attrs[] = {
58 __ATTR_RO(modalias),
59 __ATTR_NULL,
60};
61
62/* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
63 * and the sysfs version makes coldplug work too.
64 */
65
66static int spi_match_device(struct device *dev, struct device_driver *drv)
67{
68 const struct spi_device *spi = to_spi_device(dev);
69
70 return strncmp(spi->modalias, drv->name, BUS_ID_SIZE) == 0;
71}
72
73static int spi_uevent(struct device *dev, char **envp, int num_envp,
74 char *buffer, int buffer_size)
75{
76 const struct spi_device *spi = to_spi_device(dev);
77
78 envp[0] = buffer;
79 snprintf(buffer, buffer_size, "MODALIAS=%s", spi->modalias);
80 envp[1] = NULL;
81 return 0;
82}
83
84#ifdef CONFIG_PM
85
86/* Suspend/resume in "struct device_driver" don't really need that
87 * strange third parameter, so we just make it a constant and expect
88 * SPI drivers to ignore it just like most platform drivers do.
89 *
90 * NOTE: the suspend() method for an spi_master controller driver
91 * should verify that all its child devices are marked as suspended;
92 * suspend requests delivered through sysfs power/state files don't
93 * enforce such constraints.
94 */
95static int spi_suspend(struct device *dev, pm_message_t message)
96{
97 int value;
98
99 if (!dev->driver || !dev->driver->suspend)
100 return 0;
101
102 /* suspend will stop irqs and dma; no more i/o */
103 value = dev->driver->suspend(dev, message);
104 if (value == 0)
105 dev->power.power_state = message;
106 return value;
107}
108
109static int spi_resume(struct device *dev)
110{
111 int value;
112
113 if (!dev->driver || !dev->driver->resume)
114 return 0;
115
116 /* resume may restart the i/o queue */
117 value = dev->driver->resume(dev);
118 if (value == 0)
119 dev->power.power_state = PMSG_ON;
120 return value;
121}
122
123#else
124#define spi_suspend NULL
125#define spi_resume NULL
126#endif
127
128struct bus_type spi_bus_type = {
129 .name = "spi",
130 .dev_attrs = spi_dev_attrs,
131 .match = spi_match_device,
132 .uevent = spi_uevent,
133 .suspend = spi_suspend,
134 .resume = spi_resume,
135};
136EXPORT_SYMBOL_GPL(spi_bus_type);
137
138/*-------------------------------------------------------------------------*/
139
140/* SPI devices should normally not be created by SPI device drivers; that
141 * would make them board-specific. Similarly with SPI master drivers.
142 * Device registration normally goes into like arch/.../mach.../board-YYY.c
143 * with other readonly (flashable) information about mainboard devices.
144 */
145
146struct boardinfo {
147 struct list_head list;
148 unsigned n_board_info;
149 struct spi_board_info board_info[0];
150};
151
152static LIST_HEAD(board_list);
153static DECLARE_MUTEX(board_lock);
154
155
156/* On typical mainboards, this is purely internal; and it's not needed
157 * after board init creates the hard-wired devices. Some development
158 * platforms may not be able to use spi_register_board_info though, and
159 * this is exported so that for example a USB or parport based adapter
160 * driver could add devices (which it would learn about out-of-band).
161 */
162struct spi_device *__init_or_module
163spi_new_device(struct spi_master *master, struct spi_board_info *chip)
164{
165 struct spi_device *proxy;
166 struct device *dev = master->cdev.dev;
167 int status;
168
169 /* NOTE: caller did any chip->bus_num checks necessary */
170
171 if (!class_device_get(&master->cdev))
172 return NULL;
173
174 proxy = kzalloc(sizeof *proxy, GFP_KERNEL);
175 if (!proxy) {
176 dev_err(dev, "can't alloc dev for cs%d\n",
177 chip->chip_select);
178 goto fail;
179 }
180 proxy->master = master;
181 proxy->chip_select = chip->chip_select;
182 proxy->max_speed_hz = chip->max_speed_hz;
183 proxy->irq = chip->irq;
184 proxy->modalias = chip->modalias;
185
186 snprintf(proxy->dev.bus_id, sizeof proxy->dev.bus_id,
187 "%s.%u", master->cdev.class_id,
188 chip->chip_select);
189 proxy->dev.parent = dev;
190 proxy->dev.bus = &spi_bus_type;
191 proxy->dev.platform_data = (void *) chip->platform_data;
192 proxy->controller_data = chip->controller_data;
193 proxy->controller_state = NULL;
194 proxy->dev.release = spidev_release;
195
196 /* drivers may modify this default i/o setup */
197 status = master->setup(proxy);
198 if (status < 0) {
199 dev_dbg(dev, "can't %s %s, status %d\n",
200 "setup", proxy->dev.bus_id, status);
201 goto fail;
202 }
203
204 /* driver core catches callers that misbehave by defining
205 * devices that already exist.
206 */
207 status = device_register(&proxy->dev);
208 if (status < 0) {
209 dev_dbg(dev, "can't %s %s, status %d\n",
210 "add", proxy->dev.bus_id, status);
211fail:
212 class_device_put(&master->cdev);
213 kfree(proxy);
214 return NULL;
215 }
216 dev_dbg(dev, "registered child %s\n", proxy->dev.bus_id);
217 return proxy;
218}
219EXPORT_SYMBOL_GPL(spi_new_device);
220
221/*
222 * Board-specific early init code calls this (probably during arch_initcall)
223 * with segments of the SPI device table. Any device nodes are created later,
224 * after the relevant parent SPI controller (bus_num) is defined. We keep
225 * this table of devices forever, so that reloading a controller driver will
226 * not make Linux forget about these hard-wired devices.
227 *
228 * Other code can also call this, e.g. a particular add-on board might provide
229 * SPI devices through its expansion connector, so code initializing that board
230 * would naturally declare its SPI devices.
231 *
232 * The board info passed can safely be __initdata ... but be careful of
233 * any embedded pointers (platform_data, etc), they're copied as-is.
234 */
235int __init
236spi_register_board_info(struct spi_board_info const *info, unsigned n)
237{
238 struct boardinfo *bi;
239
240 bi = kmalloc (sizeof (*bi) + n * sizeof (*info), GFP_KERNEL);
241 if (!bi)
242 return -ENOMEM;
243 bi->n_board_info = n;
244 memcpy(bi->board_info, info, n * sizeof (*info));
245
246 down(&board_lock);
247 list_add_tail(&bi->list, &board_list);
248 up(&board_lock);
249 return 0;
250}
251EXPORT_SYMBOL_GPL(spi_register_board_info);
252
253/* FIXME someone should add support for a __setup("spi", ...) that
254 * creates board info from kernel command lines
255 */
256
257static void __init_or_module
258scan_boardinfo(struct spi_master *master)
259{
260 struct boardinfo *bi;
261 struct device *dev = master->cdev.dev;
262
263 down(&board_lock);
264 list_for_each_entry(bi, &board_list, list) {
265 struct spi_board_info *chip = bi->board_info;
266 unsigned n;
267
268 for (n = bi->n_board_info; n > 0; n--, chip++) {
269 if (chip->bus_num != master->bus_num)
270 continue;
271 /* some controllers only have one chip, so they
272 * might not use chipselects. otherwise, the
273 * chipselects are numbered 0..max.
274 */
275 if (chip->chip_select >= master->num_chipselect
276 && master->num_chipselect) {
277 dev_dbg(dev, "cs%d > max %d\n",
278 chip->chip_select,
279 master->num_chipselect);
280 continue;
281 }
282 (void) spi_new_device(master, chip);
283 }
284 }
285 up(&board_lock);
286}
287
288/*-------------------------------------------------------------------------*/
289
290static void spi_master_release(struct class_device *cdev)
291{
292 struct spi_master *master;
293
294 master = container_of(cdev, struct spi_master, cdev);
295 put_device(master->cdev.dev);
296 master->cdev.dev = NULL;
297 kfree(master);
298}
299
300static struct class spi_master_class = {
301 .name = "spi_master",
302 .owner = THIS_MODULE,
303 .release = spi_master_release,
304};
305
306
307/**
308 * spi_alloc_master - allocate SPI master controller
309 * @dev: the controller, possibly using the platform_bus
310 * @size: how much driver-private data to preallocate; a pointer to this
311 * memory in the class_data field of the returned class_device
312 *
313 * This call is used only by SPI master controller drivers, which are the
314 * only ones directly touching chip registers. It's how they allocate
315 * an spi_master structure, prior to calling spi_add_master().
316 *
317 * This must be called from context that can sleep. It returns the SPI
318 * master structure on success, else NULL.
319 *
320 * The caller is responsible for assigning the bus number and initializing
321 * the master's methods before calling spi_add_master(), or else (on error)
322 * calling class_device_put() to prevent a memory leak.
323 */
324struct spi_master * __init_or_module
325spi_alloc_master(struct device *dev, unsigned size)
326{
327 struct spi_master *master;
328
329 master = kzalloc(size + sizeof *master, SLAB_KERNEL);
330 if (!master)
331 return NULL;
332
333 master->cdev.class = &spi_master_class;
334 master->cdev.dev = get_device(dev);
335 class_set_devdata(&master->cdev, &master[1]);
336
337 return master;
338}
339EXPORT_SYMBOL_GPL(spi_alloc_master);
340
341/**
342 * spi_register_master - register SPI master controller
343 * @master: initialized master, originally from spi_alloc_master()
344 *
345 * SPI master controllers connect to their drivers using some non-SPI bus,
346 * such as the platform bus. The final stage of probe() in that code
347 * includes calling spi_register_master() to hook up to this SPI bus glue.
348 *
349 * SPI controllers use board specific (often SOC specific) bus numbers,
350 * and board-specific addressing for SPI devices combines those numbers
351 * with chip select numbers. Since SPI does not directly support dynamic
352 * device identification, boards need configuration tables telling which
353 * chip is at which address.
354 *
355 * This must be called from context that can sleep. It returns zero on
356 * success, else a negative error code (dropping the master's refcount).
357 */
358int __init_or_module
359spi_register_master(struct spi_master *master)
360{
361 static atomic_t dyn_bus_id = ATOMIC_INIT(0);
362 struct device *dev = master->cdev.dev;
363 int status = -ENODEV;
364 int dynamic = 0;
365
366 /* convention: dynamically assigned bus IDs count down from the max */
367 if (master->bus_num == 0) {
368 master->bus_num = atomic_dec_return(&dyn_bus_id);
369 dynamic = 0;
370 }
371
372 /* register the device, then userspace will see it.
373 * registration fails if the bus ID is in use.
374 */
375 snprintf(master->cdev.class_id, sizeof master->cdev.class_id,
376 "spi%u", master->bus_num);
377 status = class_device_register(&master->cdev);
378 if (status < 0) {
379 class_device_put(&master->cdev);
380 goto done;
381 }
382 dev_dbg(dev, "registered master %s%s\n", master->cdev.class_id,
383 dynamic ? " (dynamic)" : "");
384
385 /* populate children from any spi device tables */
386 scan_boardinfo(master);
387 status = 0;
388done:
389 return status;
390}
391EXPORT_SYMBOL_GPL(spi_register_master);
392
393
394static int __unregister(struct device *dev, void *unused)
395{
396 /* note: before about 2.6.14-rc1 this would corrupt memory: */
397 device_unregister(dev);
398 return 0;
399}
400
401/**
402 * spi_unregister_master - unregister SPI master controller
403 * @master: the master being unregistered
404 *
405 * This call is used only by SPI master controller drivers, which are the
406 * only ones directly touching chip registers.
407 *
408 * This must be called from context that can sleep.
409 */
410void spi_unregister_master(struct spi_master *master)
411{
412 class_device_unregister(&master->cdev);
413 (void) device_for_each_child(master->cdev.dev, NULL, __unregister);
414}
415EXPORT_SYMBOL_GPL(spi_unregister_master);
416
417/**
418 * spi_busnum_to_master - look up master associated with bus_num
419 * @bus_num: the master's bus number
420 *
421 * This call may be used with devices that are registered after
422 * arch init time. It returns a refcounted pointer to the relevant
423 * spi_master (which the caller must release), or NULL if there is
424 * no such master registered.
425 */
426struct spi_master *spi_busnum_to_master(u16 bus_num)
427{
428 if (bus_num) {
429 char name[8];
430 struct kobject *bus;
431
432 snprintf(name, sizeof name, "spi%u", bus_num);
433 bus = kset_find_obj(&spi_master_class.subsys.kset, name);
434 if (bus)
435 return container_of(bus, struct spi_master, cdev.kobj);
436 }
437 return NULL;
438}
439EXPORT_SYMBOL_GPL(spi_busnum_to_master);
440
441
442/*-------------------------------------------------------------------------*/
443
444/**
445 * spi_sync - blocking/synchronous SPI data transfers
446 * @spi: device with which data will be exchanged
447 * @message: describes the data transfers
448 *
449 * This call may only be used from a context that may sleep. The sleep
450 * is non-interruptible, and has no timeout. Low-overhead controller
451 * drivers may DMA directly into and out of the message buffers.
452 *
453 * Note that the SPI device's chip select is active during the message,
454 * and then is normally disabled between messages. Drivers for some
455 * frequently-used devices may want to minimize costs of selecting a chip,
456 * by leaving it selected in anticipation that the next message will go
457 * to the same chip. (That may increase power usage.)
458 *
459 * The return value is a negative error code if the message could not be
460 * submitted, else zero. When the value is zero, then message->status is
461 * also defined: it's the completion code for the transfer, either zero
462 * or a negative error code from the controller driver.
463 */
464int spi_sync(struct spi_device *spi, struct spi_message *message)
465{
466 DECLARE_COMPLETION(done);
467 int status;
468
469 message->complete = (void (*)(void *)) complete;
470 message->context = &done;
471 status = spi_async(spi, message);
472 if (status == 0)
473 wait_for_completion(&done);
474 message->context = NULL;
475 return status;
476}
477EXPORT_SYMBOL_GPL(spi_sync);
478
479#define SPI_BUFSIZ (SMP_CACHE_BYTES)
480
481static u8 *buf;
482
483/**
484 * spi_write_then_read - SPI synchronous write followed by read
485 * @spi: device with which data will be exchanged
486 * @txbuf: data to be written (need not be dma-safe)
487 * @n_tx: size of txbuf, in bytes
488 * @rxbuf: buffer into which data will be read
489 * @n_rx: size of rxbuf, in bytes (need not be dma-safe)
490 *
491 * This performs a half duplex MicroWire style transaction with the
492 * device, sending txbuf and then reading rxbuf. The return value
493 * is zero for success, else a negative errno status code.
494 *
495 * Parameters to this routine are always copied using a small buffer,
496 * large transfers should use use spi_{async,sync}() calls with
497 * dma-safe buffers.
498 */
499int spi_write_then_read(struct spi_device *spi,
500 const u8 *txbuf, unsigned n_tx,
501 u8 *rxbuf, unsigned n_rx)
502{
503 static DECLARE_MUTEX(lock);
504
505 int status;
506 struct spi_message message;
507 struct spi_transfer x[2];
508 u8 *local_buf;
509
510 /* Use preallocated DMA-safe buffer. We can't avoid copying here,
511 * (as a pure convenience thing), but we can keep heap costs
512 * out of the hot path ...
513 */
514 if ((n_tx + n_rx) > SPI_BUFSIZ)
515 return -EINVAL;
516
517 /* ... unless someone else is using the pre-allocated buffer */
518 if (down_trylock(&lock)) {
519 local_buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
520 if (!local_buf)
521 return -ENOMEM;
522 } else
523 local_buf = buf;
524
525 memset(x, 0, sizeof x);
526
527 memcpy(local_buf, txbuf, n_tx);
528 x[0].tx_buf = local_buf;
529 x[0].len = n_tx;
530
531 x[1].rx_buf = local_buf + n_tx;
532 x[1].len = n_rx;
533
534 /* do the i/o */
535 message.transfers = x;
536 message.n_transfer = ARRAY_SIZE(x);
537 status = spi_sync(spi, &message);
538 if (status == 0) {
539 memcpy(rxbuf, x[1].rx_buf, n_rx);
540 status = message.status;
541 }
542
543 if (x[0].tx_buf == buf)
544 up(&lock);
545 else
546 kfree(local_buf);
547
548 return status;
549}
550EXPORT_SYMBOL_GPL(spi_write_then_read);
551
552/*-------------------------------------------------------------------------*/
553
554static int __init spi_init(void)
555{
556 buf = kmalloc(SPI_BUFSIZ, SLAB_KERNEL);
557 if (!buf)
558 return -ENOMEM;
559
560 bus_register(&spi_bus_type);
561 class_register(&spi_master_class);
562 return 0;
563}
564/* board_info is normally registered in arch_initcall(),
565 * but even essential drivers wait till later
566 */
567subsys_initcall(spi_init);
568
diff --git a/include/linux/spi/spi.h b/include/linux/spi/spi.h
new file mode 100644
index 000000000000..51a6769114df
--- /dev/null
+++ b/include/linux/spi/spi.h
@@ -0,0 +1,542 @@
1/*
2 * Copyright (C) 2005 David Brownell
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19#ifndef __LINUX_SPI_H
20#define __LINUX_SPI_H
21
22/*
23 * INTERFACES between SPI master drivers and infrastructure
24 * (There's no SPI slave support for Linux yet...)
25 *
26 * A "struct device_driver" for an spi_device uses "spi_bus_type" and
27 * needs no special API wrappers (much like platform_bus). These drivers
28 * are bound to devices based on their names (much like platform_bus),
29 * and are available in dev->driver.
30 */
31extern struct bus_type spi_bus_type;
32
33/**
34 * struct spi_device - Master side proxy for an SPI slave device
35 * @dev: Driver model representation of the device.
36 * @master: SPI controller used with the device.
37 * @max_speed_hz: Maximum clock rate to be used with this chip
38 * (on this board); may be changed by the device's driver.
39 * @chip-select: Chipselect, distinguishing chips handled by "master".
40 * @mode: The spi mode defines how data is clocked out and in.
41 * This may be changed by the device's driver.
42 * @bits_per_word: Data transfers involve one or more words; word sizes
43 * like eight or 12 bits are common. In-memory wordsizes are
44 * powers of two bytes (e.g. 20 bit samples use 32 bits).
45 * This may be changed by the device's driver.
46 * @irq: Negative, or the number passed to request_irq() to receive
47 * interrupts from this device.
48 * @controller_state: Controller's runtime state
49 * @controller_data: Static board-specific definitions for controller, such
50 * as FIFO initialization parameters; from board_info.controller_data
51 *
52 * An spi_device is used to interchange data between an SPI slave
53 * (usually a discrete chip) and CPU memory.
54 *
55 * In "dev", the platform_data is used to hold information about this
56 * device that's meaningful to the device's protocol driver, but not
57 * to its controller. One example might be an identifier for a chip
58 * variant with slightly different functionality.
59 */
60struct spi_device {
61 struct device dev;
62 struct spi_master *master;
63 u32 max_speed_hz;
64 u8 chip_select;
65 u8 mode;
66#define SPI_CPHA 0x01 /* clock phase */
67#define SPI_CPOL 0x02 /* clock polarity */
68#define SPI_MODE_0 (0|0)
69#define SPI_MODE_1 (0|SPI_CPHA)
70#define SPI_MODE_2 (SPI_CPOL|0)
71#define SPI_MODE_3 (SPI_CPOL|SPI_CPHA)
72#define SPI_CS_HIGH 0x04 /* chipselect active high? */
73 u8 bits_per_word;
74 int irq;
75 void *controller_state;
76 const void *controller_data;
77 const char *modalias;
78
79 // likely need more hooks for more protocol options affecting how
80 // the controller talks to its chips, like:
81 // - bit order (default is wordwise msb-first)
82 // - memory packing (12 bit samples into low bits, others zeroed)
83 // - priority
84 // - chipselect delays
85 // - ...
86};
87
88static inline struct spi_device *to_spi_device(struct device *dev)
89{
90 return container_of(dev, struct spi_device, dev);
91}
92
93/* most drivers won't need to care about device refcounting */
94static inline struct spi_device *spi_dev_get(struct spi_device *spi)
95{
96 return (spi && get_device(&spi->dev)) ? spi : NULL;
97}
98
99static inline void spi_dev_put(struct spi_device *spi)
100{
101 if (spi)
102 put_device(&spi->dev);
103}
104
105/* ctldata is for the bus_master driver's runtime state */
106static inline void *spi_get_ctldata(struct spi_device *spi)
107{
108 return spi->controller_state;
109}
110
111static inline void spi_set_ctldata(struct spi_device *spi, void *state)
112{
113 spi->controller_state = state;
114}
115
116
117struct spi_message;
118
119
120/**
121 * struct spi_master - interface to SPI master controller
122 * @cdev: class interface to this driver
123 * @bus_num: board-specific (and often SOC-specific) identifier for a
124 * given SPI controller.
125 * @num_chipselects: chipselects are used to distinguish individual
126 * SPI slaves, and are numbered from zero to num_chipselects.
127 * each slave has a chipselect signal, but it's common that not
128 * every chipselect is connected to a slave.
129 * @setup: updates the device mode and clocking records used by a
130 * device's SPI controller; protocol code may call this.
131 * @transfer: adds a message to the controller's transfer queue.
132 * @cleanup: frees controller-specific state
133 *
134 * Each SPI master controller can communicate with one or more spi_device
135 * children. These make a small bus, sharing MOSI, MISO and SCK signals
136 * but not chip select signals. Each device may be configured to use a
137 * different clock rate, since those shared signals are ignored unless
138 * the chip is selected.
139 *
140 * The driver for an SPI controller manages access to those devices through
141 * a queue of spi_message transactions, copyin data between CPU memory and
142 * an SPI slave device). For each such message it queues, it calls the
143 * message's completion function when the transaction completes.
144 */
145struct spi_master {
146 struct class_device cdev;
147
148 /* other than zero (== assign one dynamically), bus_num is fully
149 * board-specific. usually that simplifies to being SOC-specific.
150 * example: one SOC has three SPI controllers, numbered 1..3,
151 * and one board's schematics might show it using SPI-2. software
152 * would normally use bus_num=2 for that controller.
153 */
154 u16 bus_num;
155
156 /* chipselects will be integral to many controllers; some others
157 * might use board-specific GPIOs.
158 */
159 u16 num_chipselect;
160
161 /* setup mode and clock, etc (spi driver may call many times) */
162 int (*setup)(struct spi_device *spi);
163
164 /* bidirectional bulk transfers
165 *
166 * + The transfer() method may not sleep; its main role is
167 * just to add the message to the queue.
168 * + For now there's no remove-from-queue operation, or
169 * any other request management
170 * + To a given spi_device, message queueing is pure fifo
171 *
172 * + The master's main job is to process its message queue,
173 * selecting a chip then transferring data
174 * + If there are multiple spi_device children, the i/o queue
175 * arbitration algorithm is unspecified (round robin, fifo,
176 * priority, reservations, preemption, etc)
177 *
178 * + Chipselect stays active during the entire message
179 * (unless modified by spi_transfer.cs_change != 0).
180 * + The message transfers use clock and SPI mode parameters
181 * previously established by setup() for this device
182 */
183 int (*transfer)(struct spi_device *spi,
184 struct spi_message *mesg);
185
186 /* called on release() to free memory provided by spi_master */
187 void (*cleanup)(const struct spi_device *spi);
188};
189
190/* the spi driver core manages memory for the spi_master classdev */
191extern struct spi_master *
192spi_alloc_master(struct device *host, unsigned size);
193
194extern int spi_register_master(struct spi_master *master);
195extern void spi_unregister_master(struct spi_master *master);
196
197extern struct spi_master *spi_busnum_to_master(u16 busnum);
198
199/*---------------------------------------------------------------------------*/
200
201/*
202 * I/O INTERFACE between SPI controller and protocol drivers
203 *
204 * Protocol drivers use a queue of spi_messages, each transferring data
205 * between the controller and memory buffers.
206 *
207 * The spi_messages themselves consist of a series of read+write transfer
208 * segments. Those segments always read the same number of bits as they
209 * write; but one or the other is easily ignored by passing a null buffer
210 * pointer. (This is unlike most types of I/O API, because SPI hardware
211 * is full duplex.)
212 *
213 * NOTE: Allocation of spi_transfer and spi_message memory is entirely
214 * up to the protocol driver, which guarantees the integrity of both (as
215 * well as the data buffers) for as long as the message is queued.
216 */
217
218/**
219 * struct spi_transfer - a read/write buffer pair
220 * @tx_buf: data to be written (dma-safe address), or NULL
221 * @rx_buf: data to be read (dma-safe address), or NULL
222 * @tx_dma: DMA address of buffer, if spi_message.is_dma_mapped
223 * @rx_dma: DMA address of buffer, if spi_message.is_dma_mapped
224 * @len: size of rx and tx buffers (in bytes)
225 * @cs_change: affects chipselect after this transfer completes
226 * @delay_usecs: microseconds to delay after this transfer before
227 * (optionally) changing the chipselect status, then starting
228 * the next transfer or completing this spi_message.
229 *
230 * SPI transfers always write the same number of bytes as they read.
231 * Protocol drivers should always provide rx_buf and/or tx_buf.
232 * In some cases, they may also want to provide DMA addresses for
233 * the data being transferred; that may reduce overhead, when the
234 * underlying driver uses dma.
235 *
236 * All SPI transfers start with the relevant chipselect active. Drivers
237 * can change behavior of the chipselect after the transfer finishes
238 * (including any mandatory delay). The normal behavior is to leave it
239 * selected, except for the last transfer in a message. Setting cs_change
240 * allows two additional behavior options:
241 *
242 * (i) If the transfer isn't the last one in the message, this flag is
243 * used to make the chipselect briefly go inactive in the middle of the
244 * message. Toggling chipselect in this way may be needed to terminate
245 * a chip command, letting a single spi_message perform all of group of
246 * chip transactions together.
247 *
248 * (ii) When the transfer is the last one in the message, the chip may
249 * stay selected until the next transfer. This is purely a performance
250 * hint; the controller driver may need to select a different device
251 * for the next message.
252 */
253struct spi_transfer {
254 /* it's ok if tx_buf == rx_buf (right?)
255 * for MicroWire, one buffer must be null
256 * buffers must work with dma_*map_single() calls
257 */
258 const void *tx_buf;
259 void *rx_buf;
260 unsigned len;
261
262 dma_addr_t tx_dma;
263 dma_addr_t rx_dma;
264
265 unsigned cs_change:1;
266 u16 delay_usecs;
267};
268
269/**
270 * struct spi_message - one multi-segment SPI transaction
271 * @transfers: the segements of the transaction
272 * @n_transfer: how many segments
273 * @spi: SPI device to which the transaction is queued
274 * @is_dma_mapped: if true, the caller provided both dma and cpu virtual
275 * addresses for each transfer buffer
276 * @complete: called to report transaction completions
277 * @context: the argument to complete() when it's called
278 * @actual_length: how many bytes were transferd
279 * @status: zero for success, else negative errno
280 * @queue: for use by whichever driver currently owns the message
281 * @state: for use by whichever driver currently owns the message
282 */
283struct spi_message {
284 struct spi_transfer *transfers;
285 unsigned n_transfer;
286
287 struct spi_device *spi;
288
289 unsigned is_dma_mapped:1;
290
291 /* REVISIT: we might want a flag affecting the behavior of the
292 * last transfer ... allowing things like "read 16 bit length L"
293 * immediately followed by "read L bytes". Basically imposing
294 * a specific message scheduling algorithm.
295 *
296 * Some controller drivers (message-at-a-time queue processing)
297 * could provide that as their default scheduling algorithm. But
298 * others (with multi-message pipelines) would need a flag to
299 * tell them about such special cases.
300 */
301
302 /* completion is reported through a callback */
303 void FASTCALL((*complete)(void *context));
304 void *context;
305 unsigned actual_length;
306 int status;
307
308 /* for optional use by whatever driver currently owns the
309 * spi_message ... between calls to spi_async and then later
310 * complete(), that's the spi_master controller driver.
311 */
312 struct list_head queue;
313 void *state;
314};
315
316/**
317 * spi_setup -- setup SPI mode and clock rate
318 * @spi: the device whose settings are being modified
319 *
320 * SPI protocol drivers may need to update the transfer mode if the
321 * device doesn't work with the mode 0 default. They may likewise need
322 * to update clock rates or word sizes from initial values. This function
323 * changes those settings, and must be called from a context that can sleep.
324 */
325static inline int
326spi_setup(struct spi_device *spi)
327{
328 return spi->master->setup(spi);
329}
330
331
332/**
333 * spi_async -- asynchronous SPI transfer
334 * @spi: device with which data will be exchanged
335 * @message: describes the data transfers, including completion callback
336 *
337 * This call may be used in_irq and other contexts which can't sleep,
338 * as well as from task contexts which can sleep.
339 *
340 * The completion callback is invoked in a context which can't sleep.
341 * Before that invocation, the value of message->status is undefined.
342 * When the callback is issued, message->status holds either zero (to
343 * indicate complete success) or a negative error code.
344 *
345 * Note that although all messages to a spi_device are handled in
346 * FIFO order, messages may go to different devices in other orders.
347 * Some device might be higher priority, or have various "hard" access
348 * time requirements, for example.
349 */
350static inline int
351spi_async(struct spi_device *spi, struct spi_message *message)
352{
353 message->spi = spi;
354 return spi->master->transfer(spi, message);
355}
356
357/*---------------------------------------------------------------------------*/
358
359/* All these synchronous SPI transfer routines are utilities layered
360 * over the core async transfer primitive. Here, "synchronous" means
361 * they will sleep uninterruptibly until the async transfer completes.
362 */
363
364extern int spi_sync(struct spi_device *spi, struct spi_message *message);
365
366/**
367 * spi_write - SPI synchronous write
368 * @spi: device to which data will be written
369 * @buf: data buffer
370 * @len: data buffer size
371 *
372 * This writes the buffer and returns zero or a negative error code.
373 * Callable only from contexts that can sleep.
374 */
375static inline int
376spi_write(struct spi_device *spi, const u8 *buf, size_t len)
377{
378 struct spi_transfer t = {
379 .tx_buf = buf,
380 .rx_buf = NULL,
381 .len = len,
382 .cs_change = 0,
383 };
384 struct spi_message m = {
385 .transfers = &t,
386 .n_transfer = 1,
387 };
388
389 return spi_sync(spi, &m);
390}
391
392/**
393 * spi_read - SPI synchronous read
394 * @spi: device from which data will be read
395 * @buf: data buffer
396 * @len: data buffer size
397 *
398 * This writes the buffer and returns zero or a negative error code.
399 * Callable only from contexts that can sleep.
400 */
401static inline int
402spi_read(struct spi_device *spi, u8 *buf, size_t len)
403{
404 struct spi_transfer t = {
405 .tx_buf = NULL,
406 .rx_buf = buf,
407 .len = len,
408 .cs_change = 0,
409 };
410 struct spi_message m = {
411 .transfers = &t,
412 .n_transfer = 1,
413 };
414
415 return spi_sync(spi, &m);
416}
417
418extern int spi_write_then_read(struct spi_device *spi,
419 const u8 *txbuf, unsigned n_tx,
420 u8 *rxbuf, unsigned n_rx);
421
422/**
423 * spi_w8r8 - SPI synchronous 8 bit write followed by 8 bit read
424 * @spi: device with which data will be exchanged
425 * @cmd: command to be written before data is read back
426 *
427 * This returns the (unsigned) eight bit number returned by the
428 * device, or else a negative error code. Callable only from
429 * contexts that can sleep.
430 */
431static inline ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)
432{
433 ssize_t status;
434 u8 result;
435
436 status = spi_write_then_read(spi, &cmd, 1, &result, 1);
437
438 /* return negative errno or unsigned value */
439 return (status < 0) ? status : result;
440}
441
442/**
443 * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read
444 * @spi: device with which data will be exchanged
445 * @cmd: command to be written before data is read back
446 *
447 * This returns the (unsigned) sixteen bit number returned by the
448 * device, or else a negative error code. Callable only from
449 * contexts that can sleep.
450 *
451 * The number is returned in wire-order, which is at least sometimes
452 * big-endian.
453 */
454static inline ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)
455{
456 ssize_t status;
457 u16 result;
458
459 status = spi_write_then_read(spi, &cmd, 1, (u8 *) &result, 2);
460
461 /* return negative errno or unsigned value */
462 return (status < 0) ? status : result;
463}
464
465/*---------------------------------------------------------------------------*/
466
467/*
468 * INTERFACE between board init code and SPI infrastructure.
469 *
470 * No SPI driver ever sees these SPI device table segments, but
471 * it's how the SPI core (or adapters that get hotplugged) grows
472 * the driver model tree.
473 *
474 * As a rule, SPI devices can't be probed. Instead, board init code
475 * provides a table listing the devices which are present, with enough
476 * information to bind and set up the device's driver. There's basic
477 * support for nonstatic configurations too; enough to handle adding
478 * parport adapters, or microcontrollers acting as USB-to-SPI bridges.
479 */
480
481/* board-specific information about each SPI device */
482struct spi_board_info {
483 /* the device name and module name are coupled, like platform_bus;
484 * "modalias" is normally the driver name.
485 *
486 * platform_data goes to spi_device.dev.platform_data,
487 * controller_data goes to spi_device.platform_data,
488 * irq is copied too
489 */
490 char modalias[KOBJ_NAME_LEN];
491 const void *platform_data;
492 const void *controller_data;
493 int irq;
494
495 /* slower signaling on noisy or low voltage boards */
496 u32 max_speed_hz;
497
498
499 /* bus_num is board specific and matches the bus_num of some
500 * spi_master that will probably be registered later.
501 *
502 * chip_select reflects how this chip is wired to that master;
503 * it's less than num_chipselect.
504 */
505 u16 bus_num;
506 u16 chip_select;
507
508 /* ... may need additional spi_device chip config data here.
509 * avoid stuff protocol drivers can set; but include stuff
510 * needed to behave without being bound to a driver:
511 * - chipselect polarity
512 * - quirks like clock rate mattering when not selected
513 */
514};
515
516#ifdef CONFIG_SPI
517extern int
518spi_register_board_info(struct spi_board_info const *info, unsigned n);
519#else
520/* board init code may ignore whether SPI is configured or not */
521static inline int
522spi_register_board_info(struct spi_board_info const *info, unsigned n)
523 { return 0; }
524#endif
525
526
527/* If you're hotplugging an adapter with devices (parport, usb, etc)
528 * use spi_new_device() to describe each device. You can also call
529 * spi_unregister_device() to get start making that device vanish,
530 * but normally that would be handled by spi_unregister_master().
531 */
532extern struct spi_device *
533spi_new_device(struct spi_master *, struct spi_board_info *);
534
535static inline void
536spi_unregister_device(struct spi_device *spi)
537{
538 if (spi)
539 device_unregister(&spi->dev);
540}
541
542#endif /* __LINUX_SPI_H */