aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLinus Torvalds <torvalds@g5.osdl.org>2006-01-14 13:43:26 -0500
committerLinus Torvalds <torvalds@g5.osdl.org>2006-01-14 13:43:26 -0500
commit61b7efddc5256225099d13185659e9ad9d8abc8a (patch)
tree7cbfec9c0012b07c7a236a953f5e067304725415
parent3e2b32b69308e974cd1167beaf266d3c716e4734 (diff)
parent2e10c84b9cf0b2d269c5629048d8d6e35eaf6b2b (diff)
Merge master.kernel.org:/pub/scm/linux/kernel/git/gregkh/spi-2.6
-rw-r--r--Documentation/spi/butterfly57
-rw-r--r--Documentation/spi/spi-summary457
-rw-r--r--arch/arm/Kconfig2
-rw-r--r--drivers/Kconfig2
-rw-r--r--drivers/Makefile1
-rw-r--r--drivers/input/touchscreen/Kconfig13
-rw-r--r--drivers/input/touchscreen/Makefile1
-rw-r--r--drivers/input/touchscreen/ads7846.c625
-rw-r--r--drivers/mtd/devices/Kconfig16
-rw-r--r--drivers/mtd/devices/Makefile2
-rw-r--r--drivers/mtd/devices/m25p80.c582
-rw-r--r--drivers/mtd/devices/mtd_dataflash.c629
-rw-r--r--drivers/spi/Kconfig109
-rw-r--r--drivers/spi/Makefile25
-rw-r--r--drivers/spi/spi.c642
-rw-r--r--drivers/spi/spi_bitbang.c472
-rw-r--r--drivers/spi/spi_butterfly.c423
-rw-r--r--include/linux/spi/ads7846.h18
-rw-r--r--include/linux/spi/flash.h31
-rw-r--r--include/linux/spi/spi.h668
-rw-r--r--include/linux/spi/spi_bitbang.h135
21 files changed, 4910 insertions, 0 deletions
diff --git a/Documentation/spi/butterfly b/Documentation/spi/butterfly
new file mode 100644
index 000000000000..a2e8c8d90e35
--- /dev/null
+++ b/Documentation/spi/butterfly
@@ -0,0 +1,57 @@
1spi_butterfly - parport-to-butterfly adapter driver
2===================================================
3
4This is a hardware and software project that includes building and using
5a parallel port adapter cable, together with an "AVR Butterfly" to run
6firmware for user interfacing and/or sensors. A Butterfly is a $US20
7battery powered card with an AVR microcontroller and lots of goodies:
8sensors, LCD, flash, toggle stick, and more. You can use AVR-GCC to
9develop firmware for this, and flash it using this adapter cable.
10
11You can make this adapter from an old printer cable and solder things
12directly to the Butterfly. Or (if you have the parts and skills) you
13can come up with something fancier, providing ciruit protection to the
14Butterfly and the printer port, or with a better power supply than two
15signal pins from the printer port.
16
17
18The first cable connections will hook Linux up to one SPI bus, with the
19AVR and a DataFlash chip; and to the AVR reset line. This is all you
20need to reflash the firmware, and the pins are the standard Atmel "ISP"
21connector pins (used also on non-Butterfly AVR boards).
22
23 Signal Butterfly Parport (DB-25)
24 ------ --------- ---------------
25 SCK = J403.PB1/SCK = pin 2/D0
26 RESET = J403.nRST = pin 3/D1
27 VCC = J403.VCC_EXT = pin 8/D6
28 MOSI = J403.PB2/MOSI = pin 9/D7
29 MISO = J403.PB3/MISO = pin 11/S7,nBUSY
30 GND = J403.GND = pin 23/GND
31
32Then to let Linux master that bus to talk to the DataFlash chip, you must
33(a) flash new firmware that disables SPI (set PRR.2, and disable pullups
34by clearing PORTB.[0-3]); (b) configure the mtd_dataflash driver; and
35(c) cable in the chipselect.
36
37 Signal Butterfly Parport (DB-25)
38 ------ --------- ---------------
39 VCC = J400.VCC_EXT = pin 7/D5
40 SELECT = J400.PB0/nSS = pin 17/C3,nSELECT
41 GND = J400.GND = pin 24/GND
42
43The "USI" controller, using J405, can be used for a second SPI bus. That
44would let you talk to the AVR over SPI, running firmware that makes it act
45as an SPI slave, while letting either Linux or the AVR use the DataFlash.
46There are plenty of spare parport pins to wire this one up, such as:
47
48 Signal Butterfly Parport (DB-25)
49 ------ --------- ---------------
50 SCK = J403.PE4/USCK = pin 5/D3
51 MOSI = J403.PE5/DI = pin 6/D4
52 MISO = J403.PE6/DO = pin 12/S5,nPAPEROUT
53 GND = J403.GND = pin 22/GND
54
55 IRQ = J402.PF4 = pin 10/S6,ACK
56 GND = J402.GND(P2) = pin 25/GND
57
diff --git a/Documentation/spi/spi-summary b/Documentation/spi/spi-summary
new file mode 100644
index 000000000000..a5ffba33a351
--- /dev/null
+++ b/Documentation/spi/spi-summary
@@ -0,0 +1,457 @@
1Overview of Linux kernel SPI support
2====================================
3
402-Dec-2005
5
6What is SPI?
7------------
8The "Serial Peripheral Interface" (SPI) is a synchronous four wire serial
9link used to connect microcontrollers to sensors, memory, and peripherals.
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. Each clock cycle shifts data out and data in; the clock
16doesn't cycle except when there is data to shift.
17
18SPI masters may use a "chip select" line to activate a given SPI slave
19device, so those three signal wires may be connected to several chips
20in parallel. All SPI slaves support chipselects. Some devices have
21other signals, often including an interrupt to the master.
22
23Unlike serial busses like USB or SMBUS, even low level protocols for
24SPI slave functions are usually not interoperable between vendors
25(except for cases like SPI memory chips).
26
27 - SPI may be used for request/response style device protocols, as with
28 touchscreen sensors and memory chips.
29
30 - It may also be used to stream data in either direction (half duplex),
31 or both of them at the same time (full duplex).
32
33 - Some devices may use eight bit words. Others may different word
34 lengths, such as streams of 12-bit or 20-bit digital samples.
35
36In the same way, SPI slaves will only rarely support any kind of automatic
37discovery/enumeration protocol. The tree of slave devices accessible from
38a given SPI master will normally be set up manually, with configuration
39tables.
40
41SPI is only one of the names used by such four-wire protocols, and
42most controllers have no problem handling "MicroWire" (think of it as
43half-duplex SPI, for request/response protocols), SSP ("Synchronous
44Serial Protocol"), PSP ("Programmable Serial Protocol"), and other
45related protocols.
46
47Microcontrollers often support both master and slave sides of the SPI
48protocol. This document (and Linux) currently only supports the master
49side of SPI interactions.
50
51
52Who uses it? On what kinds of systems?
53---------------------------------------
54Linux developers using SPI are probably writing device drivers for embedded
55systems boards. SPI is used to control external chips, and it is also a
56protocol supported by every MMC or SD memory card. (The older "DataFlash"
57cards, predating MMC cards but using the same connectors and card shape,
58support only SPI.) Some PC hardware uses SPI flash for BIOS code.
59
60SPI slave chips range from digital/analog converters used for analog
61sensors and codecs, to memory, to peripherals like USB controllers
62or Ethernet adapters; and more.
63
64Most systems using SPI will integrate a few devices on a mainboard.
65Some provide SPI links on expansion connectors; in cases where no
66dedicated SPI controller exists, GPIO pins can be used to create a
67low speed "bitbanging" adapter. Very few systems will "hotplug" an SPI
68controller; the reasons to use SPI focus on low cost and simple operation,
69and if dynamic reconfiguration is important, USB will often be a more
70appropriate low-pincount peripheral bus.
71
72Many microcontrollers that can run Linux integrate one or more I/O
73interfaces with SPI modes. Given SPI support, they could use MMC or SD
74cards without needing a special purpose MMC/SD/SDIO controller.
75
76
77How do these driver programming interfaces work?
78------------------------------------------------
79The <linux/spi/spi.h> header file includes kerneldoc, as does the
80main source code, and you should certainly read that. This is just
81an overview, so you get the big picture before the details.
82
83SPI requests always go into I/O queues. Requests for a given SPI device
84are always executed in FIFO order, and complete asynchronously through
85completion callbacks. There are also some simple synchronous wrappers
86for those calls, including ones for common transaction types like writing
87a command and then reading its response.
88
89There are two types of SPI driver, here called:
90
91 Controller drivers ... these are often built in to System-On-Chip
92 processors, and often support both Master and Slave roles.
93 These drivers touch hardware registers and may use DMA.
94 Or they can be PIO bitbangers, needing just GPIO pins.
95
96 Protocol drivers ... these pass messages through the controller
97 driver to communicate with a Slave or Master device on the
98 other side of an SPI link.
99
100So for example one protocol driver might talk to the MTD layer to export
101data to filesystems stored on SPI flash like DataFlash; and others might
102control audio interfaces, present touchscreen sensors as input interfaces,
103or monitor temperature and voltage levels during industrial processing.
104And those might all be sharing the same controller driver.
105
106A "struct spi_device" encapsulates the master-side interface between
107those two types of driver. At this writing, Linux has no slave side
108programming interface.
109
110There is a minimal core of SPI programming interfaces, focussing on
111using driver model to connect controller and protocol drivers using
112device tables provided by board specific initialization code. SPI
113shows up in sysfs in several locations:
114
115 /sys/devices/.../CTLR/spiB.C ... spi_device for on bus "B",
116 chipselect C, accessed through CTLR.
117
118 /sys/devices/.../CTLR/spiB.C/modalias ... identifies the driver
119 that should be used with this device (for hotplug/coldplug)
120
121 /sys/bus/spi/devices/spiB.C ... symlink to the physical
122 spiB-C device
123
124 /sys/bus/spi/drivers/D ... driver for one or more spi*.* devices
125
126 /sys/class/spi_master/spiB ... class device for the controller
127 managing bus "B". All the spiB.* devices share the same
128 physical SPI bus segment, with SCLK, MOSI, and MISO.
129
130
131How does board-specific init code declare SPI devices?
132------------------------------------------------------
133Linux needs several kinds of information to properly configure SPI devices.
134That information is normally provided by board-specific code, even for
135chips that do support some of automated discovery/enumeration.
136
137DECLARE CONTROLLERS
138
139The first kind of information is a list of what SPI controllers exist.
140For System-on-Chip (SOC) based boards, these will usually be platform
141devices, and the controller may need some platform_data in order to
142operate properly. The "struct platform_device" will include resources
143like the physical address of the controller's first register and its IRQ.
144
145Platforms will often abstract the "register SPI controller" operation,
146maybe coupling it with code to initialize pin configurations, so that
147the arch/.../mach-*/board-*.c files for several boards can all share the
148same basic controller setup code. This is because most SOCs have several
149SPI-capable controllers, and only the ones actually usable on a given
150board should normally be set up and registered.
151
152So for example arch/.../mach-*/board-*.c files might have code like:
153
154 #include <asm/arch/spi.h> /* for mysoc_spi_data */
155
156 /* if your mach-* infrastructure doesn't support kernels that can
157 * run on multiple boards, pdata wouldn't benefit from "__init".
158 */
159 static struct mysoc_spi_data __init pdata = { ... };
160
161 static __init board_init(void)
162 {
163 ...
164 /* this board only uses SPI controller #2 */
165 mysoc_register_spi(2, &pdata);
166 ...
167 }
168
169And SOC-specific utility code might look something like:
170
171 #include <asm/arch/spi.h>
172
173 static struct platform_device spi2 = { ... };
174
175 void mysoc_register_spi(unsigned n, struct mysoc_spi_data *pdata)
176 {
177 struct mysoc_spi_data *pdata2;
178
179 pdata2 = kmalloc(sizeof *pdata2, GFP_KERNEL);
180 *pdata2 = pdata;
181 ...
182 if (n == 2) {
183 spi2->dev.platform_data = pdata2;
184 register_platform_device(&spi2);
185
186 /* also: set up pin modes so the spi2 signals are
187 * visible on the relevant pins ... bootloaders on
188 * production boards may already have done this, but
189 * developer boards will often need Linux to do it.
190 */
191 }
192 ...
193 }
194
195Notice how the platform_data for boards may be different, even if the
196same SOC controller is used. For example, on one board SPI might use
197an external clock, where another derives the SPI clock from current
198settings of some master clock.
199
200
201DECLARE SLAVE DEVICES
202
203The second kind of information is a list of what SPI slave devices exist
204on the target board, often with some board-specific data needed for the
205driver to work correctly.
206
207Normally your arch/.../mach-*/board-*.c files would provide a small table
208listing the SPI devices on each board. (This would typically be only a
209small handful.) That might look like:
210
211 static struct ads7846_platform_data ads_info = {
212 .vref_delay_usecs = 100,
213 .x_plate_ohms = 580,
214 .y_plate_ohms = 410,
215 };
216
217 static struct spi_board_info spi_board_info[] __initdata = {
218 {
219 .modalias = "ads7846",
220 .platform_data = &ads_info,
221 .mode = SPI_MODE_0,
222 .irq = GPIO_IRQ(31),
223 .max_speed_hz = 120000 /* max sample rate at 3V */ * 16,
224 .bus_num = 1,
225 .chip_select = 0,
226 },
227 };
228
229Again, notice how board-specific information is provided; each chip may need
230several types. This example shows generic constraints like the fastest SPI
231clock to allow (a function of board voltage in this case) or how an IRQ pin
232is wired, plus chip-specific constraints like an important delay that's
233changed by the capacitance at one pin.
234
235(There's also "controller_data", information that may be useful to the
236controller driver. An example would be peripheral-specific DMA tuning
237data or chipselect callbacks. This is stored in spi_device later.)
238
239The board_info should provide enough information to let the system work
240without the chip's driver being loaded. The most troublesome aspect of
241that is likely the SPI_CS_HIGH bit in the spi_device.mode field, since
242sharing a bus with a device that interprets chipselect "backwards" is
243not possible.
244
245Then your board initialization code would register that table with the SPI
246infrastructure, so that it's available later when the SPI master controller
247driver is registered:
248
249 spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info));
250
251Like with other static board-specific setup, you won't unregister those.
252
253The widely used "card" style computers bundle memory, cpu, and little else
254onto a card that's maybe just thirty square centimeters. On such systems,
255your arch/.../mach-.../board-*.c file would primarily provide information
256about the devices on the mainboard into which such a card is plugged. That
257certainly includes SPI devices hooked up through the card connectors!
258
259
260NON-STATIC CONFIGURATIONS
261
262Developer boards often play by different rules than product boards, and one
263example is the potential need to hotplug SPI devices and/or controllers.
264
265For those cases you might need to use use spi_busnum_to_master() to look
266up the spi bus master, and will likely need spi_new_device() to provide the
267board info based on the board that was hotplugged. Of course, you'd later
268call at least spi_unregister_device() when that board is removed.
269
270When Linux includes support for MMC/SD/SDIO/DataFlash cards through SPI, those
271configurations will also be dynamic. Fortunately, those devices all support
272basic device identification probes, so that support should hotplug normally.
273
274
275How do I write an "SPI Protocol Driver"?
276----------------------------------------
277All SPI drivers are currently kernel drivers. A userspace driver API
278would just be another kernel driver, probably offering some lowlevel
279access through aio_read(), aio_write(), and ioctl() calls and using the
280standard userspace sysfs mechanisms to bind to a given SPI device.
281
282SPI protocol drivers somewhat resemble platform device drivers:
283
284 static struct spi_driver CHIP_driver = {
285 .driver = {
286 .name = "CHIP",
287 .bus = &spi_bus_type,
288 .owner = THIS_MODULE,
289 },
290
291 .probe = CHIP_probe,
292 .remove = __devexit_p(CHIP_remove),
293 .suspend = CHIP_suspend,
294 .resume = CHIP_resume,
295 };
296
297The driver core will autmatically attempt to bind this driver to any SPI
298device whose board_info gave a modalias of "CHIP". Your probe() code
299might look like this unless you're creating a class_device:
300
301 static int __devinit CHIP_probe(struct spi_device *spi)
302 {
303 struct CHIP *chip;
304 struct CHIP_platform_data *pdata;
305
306 /* assuming the driver requires board-specific data: */
307 pdata = &spi->dev.platform_data;
308 if (!pdata)
309 return -ENODEV;
310
311 /* get memory for driver's per-chip state */
312 chip = kzalloc(sizeof *chip, GFP_KERNEL);
313 if (!chip)
314 return -ENOMEM;
315 dev_set_drvdata(&spi->dev, chip);
316
317 ... etc
318 return 0;
319 }
320
321As soon as it enters probe(), the driver may issue I/O requests to
322the SPI device using "struct spi_message". When remove() returns,
323the driver guarantees that it won't submit any more such messages.
324
325 - An spi_message is a sequence of of protocol operations, executed
326 as one atomic sequence. SPI driver controls include:
327
328 + when bidirectional reads and writes start ... by how its
329 sequence of spi_transfer requests is arranged;
330
331 + optionally defining short delays after transfers ... using
332 the spi_transfer.delay_usecs setting;
333
334 + whether the chipselect becomes inactive after a transfer and
335 any delay ... by using the spi_transfer.cs_change flag;
336
337 + hinting whether the next message is likely to go to this same
338 device ... using the spi_transfer.cs_change flag on the last
339 transfer in that atomic group, and potentially saving costs
340 for chip deselect and select operations.
341
342 - Follow standard kernel rules, and provide DMA-safe buffers in
343 your messages. That way controller drivers using DMA aren't forced
344 to make extra copies unless the hardware requires it (e.g. working
345 around hardware errata that force the use of bounce buffering).
346
347 If standard dma_map_single() handling of these buffers is inappropriate,
348 you can use spi_message.is_dma_mapped to tell the controller driver
349 that you've already provided the relevant DMA addresses.
350
351 - The basic I/O primitive is spi_async(). Async requests may be
352 issued in any context (irq handler, task, etc) and completion
353 is reported using a callback provided with the message.
354 After any detected error, the chip is deselected and processing
355 of that spi_message is aborted.
356
357 - There are also synchronous wrappers like spi_sync(), and wrappers
358 like spi_read(), spi_write(), and spi_write_then_read(). These
359 may be issued only in contexts that may sleep, and they're all
360 clean (and small, and "optional") layers over spi_async().
361
362 - The spi_write_then_read() call, and convenience wrappers around
363 it, should only be used with small amounts of data where the
364 cost of an extra copy may be ignored. It's designed to support
365 common RPC-style requests, such as writing an eight bit command
366 and reading a sixteen bit response -- spi_w8r16() being one its
367 wrappers, doing exactly that.
368
369Some drivers may need to modify spi_device characteristics like the
370transfer mode, wordsize, or clock rate. This is done with spi_setup(),
371which would normally be called from probe() before the first I/O is
372done to the device.
373
374While "spi_device" would be the bottom boundary of the driver, the
375upper boundaries might include sysfs (especially for sensor readings),
376the input layer, ALSA, networking, MTD, the character device framework,
377or other Linux subsystems.
378
379Note that there are two types of memory your driver must manage as part
380of interacting with SPI devices.
381
382 - I/O buffers use the usual Linux rules, and must be DMA-safe.
383 You'd normally allocate them from the heap or free page pool.
384 Don't use the stack, or anything that's declared "static".
385
386 - The spi_message and spi_transfer metadata used to glue those
387 I/O buffers into a group of protocol transactions. These can
388 be allocated anywhere it's convenient, including as part of
389 other allocate-once driver data structures. Zero-init these.
390
391If you like, spi_message_alloc() and spi_message_free() convenience
392routines are available to allocate and zero-initialize an spi_message
393with several transfers.
394
395
396How do I write an "SPI Master Controller Driver"?
397-------------------------------------------------
398An SPI controller will probably be registered on the platform_bus; write
399a driver to bind to the device, whichever bus is involved.
400
401The main task of this type of driver is to provide an "spi_master".
402Use spi_alloc_master() to allocate the master, and class_get_devdata()
403to get the driver-private data allocated for that device.
404
405 struct spi_master *master;
406 struct CONTROLLER *c;
407
408 master = spi_alloc_master(dev, sizeof *c);
409 if (!master)
410 return -ENODEV;
411
412 c = class_get_devdata(&master->cdev);
413
414The driver will initialize the fields of that spi_master, including the
415bus number (maybe the same as the platform device ID) and three methods
416used to interact with the SPI core and SPI protocol drivers. It will
417also initialize its own internal state.
418
419 master->setup(struct spi_device *spi)
420 This sets up the device clock rate, SPI mode, and word sizes.
421 Drivers may change the defaults provided by board_info, and then
422 call spi_setup(spi) to invoke this routine. It may sleep.
423
424 master->transfer(struct spi_device *spi, struct spi_message *message)
425 This must not sleep. Its responsibility is arrange that the
426 transfer happens and its complete() callback is issued; the two
427 will normally happen later, after other transfers complete.
428
429 master->cleanup(struct spi_device *spi)
430 Your controller driver may use spi_device.controller_state to hold
431 state it dynamically associates with that device. If you do that,
432 be sure to provide the cleanup() method to free that state.
433
434The bulk of the driver will be managing the I/O queue fed by transfer().
435
436That queue could be purely conceptual. For example, a driver used only
437for low-frequency sensor acess might be fine using synchronous PIO.
438
439But the queue will probably be very real, using message->queue, PIO,
440often DMA (especially if the root filesystem is in SPI flash), and
441execution contexts like IRQ handlers, tasklets, or workqueues (such
442as keventd). Your driver can be as fancy, or as simple, as you need.
443
444
445THANKS TO
446---------
447Contributors to Linux-SPI discussions include (in alphabetical order,
448by last name):
449
450David Brownell
451Russell King
452Dmitry Pervushin
453Stephen Street
454Mark Underwood
455Andrew Victor
456Vitaly Wool
457
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/input/touchscreen/Kconfig b/drivers/input/touchscreen/Kconfig
index 21d55ed4b88a..2c674023a6ac 100644
--- a/drivers/input/touchscreen/Kconfig
+++ b/drivers/input/touchscreen/Kconfig
@@ -11,6 +11,19 @@ menuconfig INPUT_TOUCHSCREEN
11 11
12if INPUT_TOUCHSCREEN 12if INPUT_TOUCHSCREEN
13 13
14config TOUCHSCREEN_ADS7846
15 tristate "ADS 7846 based touchscreens"
16 depends on SPI_MASTER
17 help
18 Say Y here if you have a touchscreen interface using the
19 ADS7846 controller, and your board-specific initialization
20 code includes that in its table of SPI devices.
21
22 If unsure, say N (but it's safe to say "Y").
23
24 To compile this driver as a module, choose M here: the
25 module will be called ads7846.
26
14config TOUCHSCREEN_BITSY 27config TOUCHSCREEN_BITSY
15 tristate "Compaq iPAQ H3600 (Bitsy) touchscreen" 28 tristate "Compaq iPAQ H3600 (Bitsy) touchscreen"
16 depends on SA1100_BITSY 29 depends on SA1100_BITSY
diff --git a/drivers/input/touchscreen/Makefile b/drivers/input/touchscreen/Makefile
index 6842869c9a26..5e5557c43121 100644
--- a/drivers/input/touchscreen/Makefile
+++ b/drivers/input/touchscreen/Makefile
@@ -4,6 +4,7 @@
4 4
5# Each configuration option enables a list of files. 5# Each configuration option enables a list of files.
6 6
7obj-$(CONFIG_TOUCHSCREEN_ADS7846) += ads7846.o
7obj-$(CONFIG_TOUCHSCREEN_BITSY) += h3600_ts_input.o 8obj-$(CONFIG_TOUCHSCREEN_BITSY) += h3600_ts_input.o
8obj-$(CONFIG_TOUCHSCREEN_CORGI) += corgi_ts.o 9obj-$(CONFIG_TOUCHSCREEN_CORGI) += corgi_ts.o
9obj-$(CONFIG_TOUCHSCREEN_GUNZE) += gunze.o 10obj-$(CONFIG_TOUCHSCREEN_GUNZE) += gunze.o
diff --git a/drivers/input/touchscreen/ads7846.c b/drivers/input/touchscreen/ads7846.c
new file mode 100644
index 000000000000..dd8c6a9ffc76
--- /dev/null
+++ b/drivers/input/touchscreen/ads7846.c
@@ -0,0 +1,625 @@
1/*
2 * ADS7846 based touchscreen and sensor driver
3 *
4 * Copyright (c) 2005 David Brownell
5 *
6 * Using code from:
7 * - corgi_ts.c
8 * Copyright (C) 2004-2005 Richard Purdie
9 * - omap_ts.[hc], ads7846.h, ts_osk.c
10 * Copyright (C) 2002 MontaVista Software
11 * Copyright (C) 2004 Texas Instruments
12 * Copyright (C) 2005 Dirk Behme
13 *
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License version 2 as
16 * published by the Free Software Foundation.
17 */
18#include <linux/device.h>
19#include <linux/init.h>
20#include <linux/delay.h>
21#include <linux/input.h>
22#include <linux/interrupt.h>
23#include <linux/slab.h>
24#include <linux/spi/spi.h>
25#include <linux/spi/ads7846.h>
26
27#ifdef CONFIG_ARM
28#include <asm/mach-types.h>
29#ifdef CONFIG_ARCH_OMAP
30#include <asm/arch/gpio.h>
31#endif
32
33#else
34#define set_irq_type(irq,type) do{}while(0)
35#endif
36
37
38/*
39 * This code has been lightly tested on an ads7846.
40 * Support for ads7843 and ads7845 has only been stubbed in.
41 *
42 * Not yet done: investigate the values reported. Are x/y/pressure
43 * event values sane enough for X11? How accurate are the temperature
44 * and voltage readings? (System-specific calibration should support
45 * accuracy of 0.3 degrees C; otherwise it's 2.0 degrees.)
46 *
47 * app note sbaa036 talks in more detail about accurate sampling...
48 * that ought to help in situations like LCDs inducing noise (which
49 * can also be helped by using synch signals) and more generally.
50 */
51
52#define TS_POLL_PERIOD msecs_to_jiffies(10)
53
54struct ts_event {
55 /* For portability, we can't read 12 bit values using SPI (which
56 * would make the controller deliver them as native byteorder u16
57 * with msbs zeroed). Instead, we read them as two 8-byte values,
58 * which need byteswapping then range adjustment.
59 */
60 __be16 x;
61 __be16 y;
62 __be16 z1, z2;
63};
64
65struct ads7846 {
66 struct input_dev input;
67 char phys[32];
68
69 struct spi_device *spi;
70 u16 model;
71 u16 vref_delay_usecs;
72 u16 x_plate_ohms;
73
74 struct ts_event tc;
75
76 struct spi_transfer xfer[8];
77 struct spi_message msg;
78
79 spinlock_t lock;
80 struct timer_list timer; /* P: lock */
81 unsigned pendown:1; /* P: lock */
82 unsigned pending:1; /* P: lock */
83// FIXME remove "irq_disabled"
84 unsigned irq_disabled:1; /* P: lock */
85};
86
87/* leave chip selected when we're done, for quicker re-select? */
88#if 0
89#define CS_CHANGE(xfer) ((xfer).cs_change = 1)
90#else
91#define CS_CHANGE(xfer) ((xfer).cs_change = 0)
92#endif
93
94/*--------------------------------------------------------------------------*/
95
96/* The ADS7846 has touchscreen and other sensors.
97 * Earlier ads784x chips are somewhat compatible.
98 */
99#define ADS_START (1 << 7)
100#define ADS_A2A1A0_d_y (1 << 4) /* differential */
101#define ADS_A2A1A0_d_z1 (3 << 4) /* differential */
102#define ADS_A2A1A0_d_z2 (4 << 4) /* differential */
103#define ADS_A2A1A0_d_x (5 << 4) /* differential */
104#define ADS_A2A1A0_temp0 (0 << 4) /* non-differential */
105#define ADS_A2A1A0_vbatt (2 << 4) /* non-differential */
106#define ADS_A2A1A0_vaux (6 << 4) /* non-differential */
107#define ADS_A2A1A0_temp1 (7 << 4) /* non-differential */
108#define ADS_8_BIT (1 << 3)
109#define ADS_12_BIT (0 << 3)
110#define ADS_SER (1 << 2) /* non-differential */
111#define ADS_DFR (0 << 2) /* differential */
112#define ADS_PD10_PDOWN (0 << 0) /* lowpower mode + penirq */
113#define ADS_PD10_ADC_ON (1 << 0) /* ADC on */
114#define ADS_PD10_REF_ON (2 << 0) /* vREF on + penirq */
115#define ADS_PD10_ALL_ON (3 << 0) /* ADC + vREF on */
116
117#define MAX_12BIT ((1<<12)-1)
118
119/* leave ADC powered up (disables penirq) between differential samples */
120#define READ_12BIT_DFR(x) (ADS_START | ADS_A2A1A0_d_ ## x \
121 | ADS_12_BIT | ADS_DFR)
122
123static const u8 read_y = READ_12BIT_DFR(y) | ADS_PD10_ADC_ON;
124static const u8 read_z1 = READ_12BIT_DFR(z1) | ADS_PD10_ADC_ON;
125static const u8 read_z2 = READ_12BIT_DFR(z2) | ADS_PD10_ADC_ON;
126static const u8 read_x = READ_12BIT_DFR(x) | ADS_PD10_PDOWN; /* LAST */
127
128/* single-ended samples need to first power up reference voltage;
129 * we leave both ADC and VREF powered
130 */
131#define READ_12BIT_SER(x) (ADS_START | ADS_A2A1A0_ ## x \
132 | ADS_12_BIT | ADS_SER)
133
134static const u8 ref_on = READ_12BIT_DFR(x) | ADS_PD10_ALL_ON;
135static const u8 ref_off = READ_12BIT_DFR(y) | ADS_PD10_PDOWN;
136
137/*--------------------------------------------------------------------------*/
138
139/*
140 * Non-touchscreen sensors only use single-ended conversions.
141 */
142
143struct ser_req {
144 u8 command;
145 u16 scratch;
146 __be16 sample;
147 struct spi_message msg;
148 struct spi_transfer xfer[6];
149};
150
151static int ads7846_read12_ser(struct device *dev, unsigned command)
152{
153 struct spi_device *spi = to_spi_device(dev);
154 struct ads7846 *ts = dev_get_drvdata(dev);
155 struct ser_req *req = kzalloc(sizeof *req, SLAB_KERNEL);
156 int status;
157 int sample;
158 int i;
159
160 if (!req)
161 return -ENOMEM;
162
163 INIT_LIST_HEAD(&req->msg.transfers);
164
165 /* activate reference, so it has time to settle; */
166 req->xfer[0].tx_buf = &ref_on;
167 req->xfer[0].len = 1;
168 req->xfer[1].rx_buf = &req->scratch;
169 req->xfer[1].len = 2;
170
171 /*
172 * for external VREF, 0 usec (and assume it's always on);
173 * for 1uF, use 800 usec;
174 * no cap, 100 usec.
175 */
176 req->xfer[1].delay_usecs = ts->vref_delay_usecs;
177
178 /* take sample */
179 req->command = (u8) command;
180 req->xfer[2].tx_buf = &req->command;
181 req->xfer[2].len = 1;
182 req->xfer[3].rx_buf = &req->sample;
183 req->xfer[3].len = 2;
184
185 /* REVISIT: take a few more samples, and compare ... */
186
187 /* turn off reference */
188 req->xfer[4].tx_buf = &ref_off;
189 req->xfer[4].len = 1;
190 req->xfer[5].rx_buf = &req->scratch;
191 req->xfer[5].len = 2;
192
193 CS_CHANGE(req->xfer[5]);
194
195 /* group all the transfers together, so we can't interfere with
196 * reading touchscreen state; disable penirq while sampling
197 */
198 for (i = 0; i < 6; i++)
199 spi_message_add_tail(&req->xfer[i], &req->msg);
200
201 disable_irq(spi->irq);
202 status = spi_sync(spi, &req->msg);
203 enable_irq(spi->irq);
204
205 if (req->msg.status)
206 status = req->msg.status;
207 sample = be16_to_cpu(req->sample);
208 sample = sample >> 4;
209 kfree(req);
210
211 return status ? status : sample;
212}
213
214#define SHOW(name) static ssize_t \
215name ## _show(struct device *dev, struct device_attribute *attr, char *buf) \
216{ \
217 ssize_t v = ads7846_read12_ser(dev, \
218 READ_12BIT_SER(name) | ADS_PD10_ALL_ON); \
219 if (v < 0) \
220 return v; \
221 return sprintf(buf, "%u\n", (unsigned) v); \
222} \
223static DEVICE_ATTR(name, S_IRUGO, name ## _show, NULL);
224
225SHOW(temp0)
226SHOW(temp1)
227SHOW(vaux)
228SHOW(vbatt)
229
230/*--------------------------------------------------------------------------*/
231
232/*
233 * PENIRQ only kicks the timer. The timer only reissues the SPI transfer,
234 * to retrieve touchscreen status.
235 *
236 * The SPI transfer completion callback does the real work. It reports
237 * touchscreen events and reactivates the timer (or IRQ) as appropriate.
238 */
239
240static void ads7846_rx(void *ads)
241{
242 struct ads7846 *ts = ads;
243 unsigned Rt;
244 unsigned sync = 0;
245 u16 x, y, z1, z2;
246 unsigned long flags;
247
248 /* adjust: 12 bit samples (left aligned), built from
249 * two 8 bit values writen msb-first.
250 */
251 x = be16_to_cpu(ts->tc.x) >> 4;
252 y = be16_to_cpu(ts->tc.y) >> 4;
253 z1 = be16_to_cpu(ts->tc.z1) >> 4;
254 z2 = be16_to_cpu(ts->tc.z2) >> 4;
255
256 /* range filtering */
257 if (x == MAX_12BIT)
258 x = 0;
259
260 if (x && z1 && ts->spi->dev.power.power_state.event == PM_EVENT_ON) {
261 /* compute touch pressure resistance using equation #2 */
262 Rt = z2;
263 Rt -= z1;
264 Rt *= x;
265 Rt *= ts->x_plate_ohms;
266 Rt /= z1;
267 Rt = (Rt + 2047) >> 12;
268 } else
269 Rt = 0;
270
271 /* NOTE: "pendown" is inferred from pressure; we don't rely on
272 * being able to check nPENIRQ status, or "friendly" trigger modes
273 * (both-edges is much better than just-falling or low-level).
274 *
275 * REVISIT: some boards may require reading nPENIRQ; it's
276 * needed on 7843. and 7845 reads pressure differently...
277 *
278 * REVISIT: the touchscreen might not be connected; this code
279 * won't notice that, even if nPENIRQ never fires ...
280 */
281 if (!ts->pendown && Rt != 0) {
282 input_report_key(&ts->input, BTN_TOUCH, 1);
283 sync = 1;
284 } else if (ts->pendown && Rt == 0) {
285 input_report_key(&ts->input, BTN_TOUCH, 0);
286 sync = 1;
287 }
288
289 if (Rt) {
290 input_report_abs(&ts->input, ABS_X, x);
291 input_report_abs(&ts->input, ABS_Y, y);
292 input_report_abs(&ts->input, ABS_PRESSURE, Rt);
293 sync = 1;
294 }
295 if (sync)
296 input_sync(&ts->input);
297
298#ifdef VERBOSE
299 if (Rt || ts->pendown)
300 pr_debug("%s: %d/%d/%d%s\n", ts->spi->dev.bus_id,
301 x, y, Rt, Rt ? "" : " UP");
302#endif
303
304 /* don't retrigger while we're suspended */
305 spin_lock_irqsave(&ts->lock, flags);
306
307 ts->pendown = (Rt != 0);
308 ts->pending = 0;
309
310 if (ts->spi->dev.power.power_state.event == PM_EVENT_ON) {
311 if (ts->pendown)
312 mod_timer(&ts->timer, jiffies + TS_POLL_PERIOD);
313 else if (ts->irq_disabled) {
314 ts->irq_disabled = 0;
315 enable_irq(ts->spi->irq);
316 }
317 }
318
319 spin_unlock_irqrestore(&ts->lock, flags);
320}
321
322static void ads7846_timer(unsigned long handle)
323{
324 struct ads7846 *ts = (void *)handle;
325 int status = 0;
326 unsigned long flags;
327
328 spin_lock_irqsave(&ts->lock, flags);
329 if (!ts->pending) {
330 ts->pending = 1;
331 if (!ts->irq_disabled) {
332 ts->irq_disabled = 1;
333 disable_irq(ts->spi->irq);
334 }
335 status = spi_async(ts->spi, &ts->msg);
336 if (status)
337 dev_err(&ts->spi->dev, "spi_async --> %d\n",
338 status);
339 }
340 spin_unlock_irqrestore(&ts->lock, flags);
341}
342
343static irqreturn_t ads7846_irq(int irq, void *handle, struct pt_regs *regs)
344{
345 ads7846_timer((unsigned long) handle);
346 return IRQ_HANDLED;
347}
348
349/*--------------------------------------------------------------------------*/
350
351static int
352ads7846_suspend(struct spi_device *spi, pm_message_t message)
353{
354 struct ads7846 *ts = dev_get_drvdata(&spi->dev);
355 unsigned long flags;
356
357 spin_lock_irqsave(&ts->lock, flags);
358
359 spi->dev.power.power_state = message;
360
361 /* are we waiting for IRQ, or polling? */
362 if (!ts->pendown) {
363 if (!ts->irq_disabled) {
364 ts->irq_disabled = 1;
365 disable_irq(ts->spi->irq);
366 }
367 } else {
368 /* polling; force a final SPI completion;
369 * that will clean things up neatly
370 */
371 if (!ts->pending)
372 mod_timer(&ts->timer, jiffies);
373
374 while (ts->pendown || ts->pending) {
375 spin_unlock_irqrestore(&ts->lock, flags);
376 udelay(10);
377 spin_lock_irqsave(&ts->lock, flags);
378 }
379 }
380
381 /* we know the chip's in lowpower mode since we always
382 * leave it that way after every request
383 */
384
385 spin_unlock_irqrestore(&ts->lock, flags);
386 return 0;
387}
388
389static int ads7846_resume(struct spi_device *spi)
390{
391 struct ads7846 *ts = dev_get_drvdata(&spi->dev);
392
393 ts->irq_disabled = 0;
394 enable_irq(ts->spi->irq);
395 spi->dev.power.power_state = PMSG_ON;
396 return 0;
397}
398
399static int __devinit ads7846_probe(struct spi_device *spi)
400{
401 struct ads7846 *ts;
402 struct ads7846_platform_data *pdata = spi->dev.platform_data;
403 struct spi_transfer *x;
404 int i;
405
406 if (!spi->irq) {
407 dev_dbg(&spi->dev, "no IRQ?\n");
408 return -ENODEV;
409 }
410
411 if (!pdata) {
412 dev_dbg(&spi->dev, "no platform data?\n");
413 return -ENODEV;
414 }
415
416 /* don't exceed max specified sample rate */
417 if (spi->max_speed_hz > (125000 * 16)) {
418 dev_dbg(&spi->dev, "f(sample) %d KHz?\n",
419 (spi->max_speed_hz/16)/1000);
420 return -EINVAL;
421 }
422
423 /* We'd set the wordsize to 12 bits ... except that some controllers
424 * will then treat the 8 bit command words as 12 bits (and drop the
425 * four MSBs of the 12 bit result). Result: inputs must be shifted
426 * to discard the four garbage LSBs.
427 */
428
429 if (!(ts = kzalloc(sizeof(struct ads7846), GFP_KERNEL)))
430 return -ENOMEM;
431
432 dev_set_drvdata(&spi->dev, ts);
433
434 ts->spi = spi;
435 spi->dev.power.power_state = PMSG_ON;
436
437 init_timer(&ts->timer);
438 ts->timer.data = (unsigned long) ts;
439 ts->timer.function = ads7846_timer;
440
441 ts->model = pdata->model ? : 7846;
442 ts->vref_delay_usecs = pdata->vref_delay_usecs ? : 100;
443 ts->x_plate_ohms = pdata->x_plate_ohms ? : 400;
444
445 init_input_dev(&ts->input);
446
447 ts->input.dev = &spi->dev;
448 ts->input.name = "ADS784x Touchscreen";
449 snprintf(ts->phys, sizeof ts->phys, "%s/input0", spi->dev.bus_id);
450 ts->input.phys = ts->phys;
451
452 ts->input.evbit[0] = BIT(EV_KEY) | BIT(EV_ABS);
453 ts->input.keybit[LONG(BTN_TOUCH)] = BIT(BTN_TOUCH);
454 input_set_abs_params(&ts->input, ABS_X,
455 pdata->x_min ? : 0,
456 pdata->x_max ? : MAX_12BIT,
457 0, 0);
458 input_set_abs_params(&ts->input, ABS_Y,
459 pdata->y_min ? : 0,
460 pdata->y_max ? : MAX_12BIT,
461 0, 0);
462 input_set_abs_params(&ts->input, ABS_PRESSURE,
463 pdata->pressure_min, pdata->pressure_max, 0, 0);
464
465 input_register_device(&ts->input);
466
467 /* set up the transfers to read touchscreen state; this assumes we
468 * use formula #2 for pressure, not #3.
469 */
470 x = ts->xfer;
471
472 /* y- still on; turn on only y+ (and ADC) */
473 x->tx_buf = &read_y;
474 x->len = 1;
475 x++;
476 x->rx_buf = &ts->tc.y;
477 x->len = 2;
478 x++;
479
480 /* turn y+ off, x- on; we'll use formula #2 */
481 if (ts->model == 7846) {
482 x->tx_buf = &read_z1;
483 x->len = 1;
484 x++;
485 x->rx_buf = &ts->tc.z1;
486 x->len = 2;
487 x++;
488
489 x->tx_buf = &read_z2;
490 x->len = 1;
491 x++;
492 x->rx_buf = &ts->tc.z2;
493 x->len = 2;
494 x++;
495 }
496
497 /* turn y- off, x+ on, then leave in lowpower */
498 x->tx_buf = &read_x;
499 x->len = 1;
500 x++;
501 x->rx_buf = &ts->tc.x;
502 x->len = 2;
503 x++;
504
505 CS_CHANGE(x[-1]);
506
507 for (i = 0; i < x - ts->xfer; i++)
508 spi_message_add_tail(&ts->xfer[i], &ts->msg);
509 ts->msg.complete = ads7846_rx;
510 ts->msg.context = ts;
511
512 if (request_irq(spi->irq, ads7846_irq, SA_SAMPLE_RANDOM,
513 spi->dev.bus_id, ts)) {
514 dev_dbg(&spi->dev, "irq %d busy?\n", spi->irq);
515 input_unregister_device(&ts->input);
516 kfree(ts);
517 return -EBUSY;
518 }
519 set_irq_type(spi->irq, IRQT_FALLING);
520
521 dev_info(&spi->dev, "touchscreen, irq %d\n", spi->irq);
522
523 /* take a first sample, leaving nPENIRQ active; avoid
524 * the touchscreen, in case it's not connected.
525 */
526 (void) ads7846_read12_ser(&spi->dev,
527 READ_12BIT_SER(vaux) | ADS_PD10_ALL_ON);
528
529 /* ads7843/7845 don't have temperature sensors, and
530 * use the other sensors a bit differently too
531 */
532 if (ts->model == 7846) {
533 device_create_file(&spi->dev, &dev_attr_temp0);
534 device_create_file(&spi->dev, &dev_attr_temp1);
535 }
536 if (ts->model != 7845)
537 device_create_file(&spi->dev, &dev_attr_vbatt);
538 device_create_file(&spi->dev, &dev_attr_vaux);
539
540 return 0;
541}
542
543static int __devexit ads7846_remove(struct spi_device *spi)
544{
545 struct ads7846 *ts = dev_get_drvdata(&spi->dev);
546
547 ads7846_suspend(spi, PMSG_SUSPEND);
548 free_irq(ts->spi->irq, ts);
549 if (ts->irq_disabled)
550 enable_irq(ts->spi->irq);
551
552 if (ts->model == 7846) {
553 device_remove_file(&spi->dev, &dev_attr_temp0);
554 device_remove_file(&spi->dev, &dev_attr_temp1);
555 }
556 if (ts->model != 7845)
557 device_remove_file(&spi->dev, &dev_attr_vbatt);
558 device_remove_file(&spi->dev, &dev_attr_vaux);
559
560 input_unregister_device(&ts->input);
561 kfree(ts);
562
563 dev_dbg(&spi->dev, "unregistered touchscreen\n");
564 return 0;
565}
566
567static struct spi_driver ads7846_driver = {
568 .driver = {
569 .name = "ads7846",
570 .bus = &spi_bus_type,
571 .owner = THIS_MODULE,
572 },
573 .probe = ads7846_probe,
574 .remove = __devexit_p(ads7846_remove),
575 .suspend = ads7846_suspend,
576 .resume = ads7846_resume,
577};
578
579static int __init ads7846_init(void)
580{
581 /* grr, board-specific init should stay out of drivers!! */
582
583#ifdef CONFIG_ARCH_OMAP
584 if (machine_is_omap_osk()) {
585 /* GPIO4 = PENIRQ; GPIO6 = BUSY */
586 omap_request_gpio(4);
587 omap_set_gpio_direction(4, 1);
588 omap_request_gpio(6);
589 omap_set_gpio_direction(6, 1);
590 }
591 // also TI 1510 Innovator, bitbanging through FPGA
592 // also Nokia 770
593 // also Palm Tungsten T2
594#endif
595
596 // PXA:
597 // also Dell Axim X50
598 // also HP iPaq H191x/H192x/H415x/H435x
599 // also Intel Lubbock (additional to UCB1400; as temperature sensor)
600 // also Sharp Zaurus C7xx, C8xx (corgi/sheperd/husky)
601
602 // Atmel at91sam9261-EK uses ads7843
603
604 // also various AMD Au1x00 devel boards
605
606 return spi_register_driver(&ads7846_driver);
607}
608module_init(ads7846_init);
609
610static void __exit ads7846_exit(void)
611{
612 spi_unregister_driver(&ads7846_driver);
613
614#ifdef CONFIG_ARCH_OMAP
615 if (machine_is_omap_osk()) {
616 omap_free_gpio(4);
617 omap_free_gpio(6);
618 }
619#endif
620
621}
622module_exit(ads7846_exit);
623
624MODULE_DESCRIPTION("ADS7846 TouchScreen Driver");
625MODULE_LICENSE("GPL");
diff --git a/drivers/mtd/devices/Kconfig b/drivers/mtd/devices/Kconfig
index 9a2aa4033c6a..5038e90ceb12 100644
--- a/drivers/mtd/devices/Kconfig
+++ b/drivers/mtd/devices/Kconfig
@@ -47,6 +47,22 @@ config MTD_MS02NV
47 accelerator. Say Y here if you have a DECstation 5000/2x0 or a 47 accelerator. Say Y here if you have a DECstation 5000/2x0 or a
48 DECsystem 5900 equipped with such a module. 48 DECsystem 5900 equipped with such a module.
49 49
50config MTD_DATAFLASH
51 tristate "Support for AT45xxx DataFlash"
52 depends on MTD && SPI_MASTER && EXPERIMENTAL
53 help
54 This enables access to AT45xxx DataFlash chips, using SPI.
55 Sometimes DataFlash chips are packaged inside MMC-format
56 cards; at this writing, the MMC stack won't handle those.
57
58config MTD_M25P80
59 tristate "Support for M25 SPI Flash"
60 depends on MTD && SPI_MASTER && EXPERIMENTAL
61 help
62 This enables access to ST M25P80 and similar SPI flash chips,
63 used for program and data storage. Set up your spi devices
64 with the right board-specific platform data.
65
50config MTD_SLRAM 66config MTD_SLRAM
51 tristate "Uncached system RAM" 67 tristate "Uncached system RAM"
52 depends on MTD 68 depends on MTD
diff --git a/drivers/mtd/devices/Makefile b/drivers/mtd/devices/Makefile
index e38db348057d..7c5ed2178380 100644
--- a/drivers/mtd/devices/Makefile
+++ b/drivers/mtd/devices/Makefile
@@ -23,3 +23,5 @@ obj-$(CONFIG_MTD_MTDRAM) += mtdram.o
23obj-$(CONFIG_MTD_LART) += lart.o 23obj-$(CONFIG_MTD_LART) += lart.o
24obj-$(CONFIG_MTD_BLKMTD) += blkmtd.o 24obj-$(CONFIG_MTD_BLKMTD) += blkmtd.o
25obj-$(CONFIG_MTD_BLOCK2MTD) += block2mtd.o 25obj-$(CONFIG_MTD_BLOCK2MTD) += block2mtd.o
26obj-$(CONFIG_MTD_DATAFLASH) += mtd_dataflash.o
27obj-$(CONFIG_MTD_M25P80) += m25p80.o
diff --git a/drivers/mtd/devices/m25p80.c b/drivers/mtd/devices/m25p80.c
new file mode 100644
index 000000000000..d5f24089be71
--- /dev/null
+++ b/drivers/mtd/devices/m25p80.c
@@ -0,0 +1,582 @@
1/*
2 * MTD SPI driver for ST M25Pxx flash chips
3 *
4 * Author: Mike Lavender, mike@steroidmicros.com
5 *
6 * Copyright (c) 2005, Intec Automation Inc.
7 *
8 * Some parts are based on lart.c by Abraham Van Der Merwe
9 *
10 * Cleaned up and generalized based on mtd_dataflash.c
11 *
12 * This code is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License version 2 as
14 * published by the Free Software Foundation.
15 *
16 */
17
18#include <linux/init.h>
19#include <linux/module.h>
20#include <linux/device.h>
21#include <linux/interrupt.h>
22#include <linux/interrupt.h>
23#include <linux/mtd/mtd.h>
24#include <linux/mtd/partitions.h>
25#include <linux/spi/spi.h>
26#include <linux/spi/flash.h>
27
28#include <asm/semaphore.h>
29
30
31/* NOTE: AT 25F and SST 25LF series are very similar,
32 * but commands for sector erase and chip id differ...
33 */
34
35#define FLASH_PAGESIZE 256
36
37/* Flash opcodes. */
38#define OPCODE_WREN 6 /* Write enable */
39#define OPCODE_RDSR 5 /* Read status register */
40#define OPCODE_READ 3 /* Read data bytes */
41#define OPCODE_PP 2 /* Page program */
42#define OPCODE_SE 0xd8 /* Sector erase */
43#define OPCODE_RES 0xab /* Read Electronic Signature */
44#define OPCODE_RDID 0x9f /* Read JEDEC ID */
45
46/* Status Register bits. */
47#define SR_WIP 1 /* Write in progress */
48#define SR_WEL 2 /* Write enable latch */
49#define SR_BP0 4 /* Block protect 0 */
50#define SR_BP1 8 /* Block protect 1 */
51#define SR_BP2 0x10 /* Block protect 2 */
52#define SR_SRWD 0x80 /* SR write protect */
53
54/* Define max times to check status register before we give up. */
55#define MAX_READY_WAIT_COUNT 100000
56
57
58#ifdef CONFIG_MTD_PARTITIONS
59#define mtd_has_partitions() (1)
60#else
61#define mtd_has_partitions() (0)
62#endif
63
64/****************************************************************************/
65
66struct m25p {
67 struct spi_device *spi;
68 struct semaphore lock;
69 struct mtd_info mtd;
70 unsigned partitioned;
71 u8 command[4];
72};
73
74static inline struct m25p *mtd_to_m25p(struct mtd_info *mtd)
75{
76 return container_of(mtd, struct m25p, mtd);
77}
78
79/****************************************************************************/
80
81/*
82 * Internal helper functions
83 */
84
85/*
86 * Read the status register, returning its value in the location
87 * Return the status register value.
88 * Returns negative if error occurred.
89 */
90static int read_sr(struct m25p *flash)
91{
92 ssize_t retval;
93 u8 code = OPCODE_RDSR;
94 u8 val;
95
96 retval = spi_write_then_read(flash->spi, &code, 1, &val, 1);
97
98 if (retval < 0) {
99 dev_err(&flash->spi->dev, "error %d reading SR\n",
100 (int) retval);
101 return retval;
102 }
103
104 return val;
105}
106
107
108/*
109 * Set write enable latch with Write Enable command.
110 * Returns negative if error occurred.
111 */
112static inline int write_enable(struct m25p *flash)
113{
114 u8 code = OPCODE_WREN;
115
116 return spi_write_then_read(flash->spi, &code, 1, NULL, 0);
117}
118
119
120/*
121 * Service routine to read status register until ready, or timeout occurs.
122 * Returns non-zero if error.
123 */
124static int wait_till_ready(struct m25p *flash)
125{
126 int count;
127 int sr;
128
129 /* one chip guarantees max 5 msec wait here after page writes,
130 * but potentially three seconds (!) after page erase.
131 */
132 for (count = 0; count < MAX_READY_WAIT_COUNT; count++) {
133 if ((sr = read_sr(flash)) < 0)
134 break;
135 else if (!(sr & SR_WIP))
136 return 0;
137
138 /* REVISIT sometimes sleeping would be best */
139 }
140
141 return 1;
142}
143
144
145/*
146 * Erase one sector of flash memory at offset ``offset'' which is any
147 * address within the sector which should be erased.
148 *
149 * Returns 0 if successful, non-zero otherwise.
150 */
151static int erase_sector(struct m25p *flash, u32 offset)
152{
153 DEBUG(MTD_DEBUG_LEVEL3, "%s: %s at 0x%08x\n", flash->spi->dev.bus_id,
154 __FUNCTION__, offset);
155
156 /* Wait until finished previous write command. */
157 if (wait_till_ready(flash))
158 return 1;
159
160 /* Send write enable, then erase commands. */
161 write_enable(flash);
162
163 /* Set up command buffer. */
164 flash->command[0] = OPCODE_SE;
165 flash->command[1] = offset >> 16;
166 flash->command[2] = offset >> 8;
167 flash->command[3] = offset;
168
169 spi_write(flash->spi, flash->command, sizeof(flash->command));
170
171 return 0;
172}
173
174/****************************************************************************/
175
176/*
177 * MTD implementation
178 */
179
180/*
181 * Erase an address range on the flash chip. The address range may extend
182 * one or more erase sectors. Return an error is there is a problem erasing.
183 */
184static int m25p80_erase(struct mtd_info *mtd, struct erase_info *instr)
185{
186 struct m25p *flash = mtd_to_m25p(mtd);
187 u32 addr,len;
188
189 DEBUG(MTD_DEBUG_LEVEL2, "%s: %s %s 0x%08x, len %zd\n",
190 flash->spi->dev.bus_id, __FUNCTION__, "at",
191 (u32)instr->addr, instr->len);
192
193 /* sanity checks */
194 if (instr->addr + instr->len > flash->mtd.size)
195 return -EINVAL;
196 if ((instr->addr % mtd->erasesize) != 0
197 || (instr->len % mtd->erasesize) != 0) {
198 return -EINVAL;
199 }
200
201 addr = instr->addr;
202 len = instr->len;
203
204 down(&flash->lock);
205
206 /* now erase those sectors */
207 while (len) {
208 if (erase_sector(flash, addr)) {
209 instr->state = MTD_ERASE_FAILED;
210 up(&flash->lock);
211 return -EIO;
212 }
213
214 addr += mtd->erasesize;
215 len -= mtd->erasesize;
216 }
217
218 up(&flash->lock);
219
220 instr->state = MTD_ERASE_DONE;
221 mtd_erase_callback(instr);
222
223 return 0;
224}
225
226/*
227 * Read an address range from the flash chip. The address range
228 * may be any size provided it is within the physical boundaries.
229 */
230static int m25p80_read(struct mtd_info *mtd, loff_t from, size_t len,
231 size_t *retlen, u_char *buf)
232{
233 struct m25p *flash = mtd_to_m25p(mtd);
234 struct spi_transfer t[2];
235 struct spi_message m;
236
237 DEBUG(MTD_DEBUG_LEVEL2, "%s: %s %s 0x%08x, len %zd\n",
238 flash->spi->dev.bus_id, __FUNCTION__, "from",
239 (u32)from, len);
240
241 /* sanity checks */
242 if (!len)
243 return 0;
244
245 if (from + len > flash->mtd.size)
246 return -EINVAL;
247
248 spi_message_init(&m);
249 memset(t, 0, (sizeof t));
250
251 t[0].tx_buf = flash->command;
252 t[0].len = sizeof(flash->command);
253 spi_message_add_tail(&t[0], &m);
254
255 t[1].rx_buf = buf;
256 t[1].len = len;
257 spi_message_add_tail(&t[1], &m);
258
259 /* Byte count starts at zero. */
260 if (retlen)
261 *retlen = 0;
262
263 down(&flash->lock);
264
265 /* Wait till previous write/erase is done. */
266 if (wait_till_ready(flash)) {
267 /* REVISIT status return?? */
268 up(&flash->lock);
269 return 1;
270 }
271
272 /* NOTE: OPCODE_FAST_READ (if available) is faster... */
273
274 /* Set up the write data buffer. */
275 flash->command[0] = OPCODE_READ;
276 flash->command[1] = from >> 16;
277 flash->command[2] = from >> 8;
278 flash->command[3] = from;
279
280 spi_sync(flash->spi, &m);
281
282 *retlen = m.actual_length - sizeof(flash->command);
283
284 up(&flash->lock);
285
286 return 0;
287}
288
289/*
290 * Write an address range to the flash chip. Data must be written in
291 * FLASH_PAGESIZE chunks. The address range may be any size provided
292 * it is within the physical boundaries.
293 */
294static int m25p80_write(struct mtd_info *mtd, loff_t to, size_t len,
295 size_t *retlen, const u_char *buf)
296{
297 struct m25p *flash = mtd_to_m25p(mtd);
298 u32 page_offset, page_size;
299 struct spi_transfer t[2];
300 struct spi_message m;
301
302 DEBUG(MTD_DEBUG_LEVEL2, "%s: %s %s 0x%08x, len %zd\n",
303 flash->spi->dev.bus_id, __FUNCTION__, "to",
304 (u32)to, len);
305
306 if (retlen)
307 *retlen = 0;
308
309 /* sanity checks */
310 if (!len)
311 return(0);
312
313 if (to + len > flash->mtd.size)
314 return -EINVAL;
315
316 spi_message_init(&m);
317 memset(t, 0, (sizeof t));
318
319 t[0].tx_buf = flash->command;
320 t[0].len = sizeof(flash->command);
321 spi_message_add_tail(&t[0], &m);
322
323 t[1].tx_buf = buf;
324 spi_message_add_tail(&t[1], &m);
325
326 down(&flash->lock);
327
328 /* Wait until finished previous write command. */
329 if (wait_till_ready(flash))
330 return 1;
331
332 write_enable(flash);
333
334 /* Set up the opcode in the write buffer. */
335 flash->command[0] = OPCODE_PP;
336 flash->command[1] = to >> 16;
337 flash->command[2] = to >> 8;
338 flash->command[3] = to;
339
340 /* what page do we start with? */
341 page_offset = to % FLASH_PAGESIZE;
342
343 /* do all the bytes fit onto one page? */
344 if (page_offset + len <= FLASH_PAGESIZE) {
345 t[1].len = len;
346
347 spi_sync(flash->spi, &m);
348
349 *retlen = m.actual_length - sizeof(flash->command);
350 } else {
351 u32 i;
352
353 /* the size of data remaining on the first page */
354 page_size = FLASH_PAGESIZE - page_offset;
355
356 t[1].len = page_size;
357 spi_sync(flash->spi, &m);
358
359 *retlen = m.actual_length - sizeof(flash->command);
360
361 /* write everything in PAGESIZE chunks */
362 for (i = page_size; i < len; i += page_size) {
363 page_size = len - i;
364 if (page_size > FLASH_PAGESIZE)
365 page_size = FLASH_PAGESIZE;
366
367 /* write the next page to flash */
368 flash->command[1] = (to + i) >> 16;
369 flash->command[2] = (to + i) >> 8;
370 flash->command[3] = (to + i);
371
372 t[1].tx_buf = buf + i;
373 t[1].len = page_size;
374
375 wait_till_ready(flash);
376
377 write_enable(flash);
378
379 spi_sync(flash->spi, &m);
380
381 if (retlen)
382 *retlen += m.actual_length
383 - sizeof(flash->command);
384 }
385 }
386
387 up(&flash->lock);
388
389 return 0;
390}
391
392
393/****************************************************************************/
394
395/*
396 * SPI device driver setup and teardown
397 */
398
399struct flash_info {
400 char *name;
401 u8 id;
402 u16 jedec_id;
403 unsigned sector_size;
404 unsigned n_sectors;
405};
406
407static struct flash_info __devinitdata m25p_data [] = {
408 /* REVISIT: fill in JEDEC ids, for parts that have them */
409 { "m25p05", 0x05, 0x0000, 32 * 1024, 2 },
410 { "m25p10", 0x10, 0x0000, 32 * 1024, 4 },
411 { "m25p20", 0x11, 0x0000, 64 * 1024, 4 },
412 { "m25p40", 0x12, 0x0000, 64 * 1024, 8 },
413 { "m25p80", 0x13, 0x0000, 64 * 1024, 16 },
414 { "m25p16", 0x14, 0x0000, 64 * 1024, 32 },
415 { "m25p32", 0x15, 0x0000, 64 * 1024, 64 },
416 { "m25p64", 0x16, 0x2017, 64 * 1024, 128 },
417};
418
419/*
420 * board specific setup should have ensured the SPI clock used here
421 * matches what the READ command supports, at least until this driver
422 * understands FAST_READ (for clocks over 25 MHz).
423 */
424static int __devinit m25p_probe(struct spi_device *spi)
425{
426 struct flash_platform_data *data;
427 struct m25p *flash;
428 struct flash_info *info;
429 unsigned i;
430
431 /* Platform data helps sort out which chip type we have, as
432 * well as how this board partitions it.
433 */
434 data = spi->dev.platform_data;
435 if (!data || !data->type) {
436 /* FIXME some chips can identify themselves with RES
437 * or JEDEC get-id commands. Try them ...
438 */
439 DEBUG(MTD_DEBUG_LEVEL1, "%s: no chip id\n",
440 flash->spi->dev.bus_id);
441 return -ENODEV;
442 }
443
444 for (i = 0, info = m25p_data; i < ARRAY_SIZE(m25p_data); i++, info++) {
445 if (strcmp(data->type, info->name) == 0)
446 break;
447 }
448 if (i == ARRAY_SIZE(m25p_data)) {
449 DEBUG(MTD_DEBUG_LEVEL1, "%s: unrecognized id %s\n",
450 flash->spi->dev.bus_id, data->type);
451 return -ENODEV;
452 }
453
454 flash = kzalloc(sizeof *flash, SLAB_KERNEL);
455 if (!flash)
456 return -ENOMEM;
457
458 flash->spi = spi;
459 init_MUTEX(&flash->lock);
460 dev_set_drvdata(&spi->dev, flash);
461
462 if (data->name)
463 flash->mtd.name = data->name;
464 else
465 flash->mtd.name = spi->dev.bus_id;
466
467 flash->mtd.type = MTD_NORFLASH;
468 flash->mtd.flags = MTD_CAP_NORFLASH;
469 flash->mtd.size = info->sector_size * info->n_sectors;
470 flash->mtd.erasesize = info->sector_size;
471 flash->mtd.erase = m25p80_erase;
472 flash->mtd.read = m25p80_read;
473 flash->mtd.write = m25p80_write;
474
475 dev_info(&spi->dev, "%s (%d Kbytes)\n", info->name,
476 flash->mtd.size / 1024);
477
478 DEBUG(MTD_DEBUG_LEVEL2,
479 "mtd .name = %s, .size = 0x%.8x (%uM) "
480 ".erasesize = 0x%.8x (%uK) .numeraseregions = %d\n",
481 flash->mtd.name,
482 flash->mtd.size, flash->mtd.size / (1024*1024),
483 flash->mtd.erasesize, flash->mtd.erasesize / 1024,
484 flash->mtd.numeraseregions);
485
486 if (flash->mtd.numeraseregions)
487 for (i = 0; i < flash->mtd.numeraseregions; i++)
488 DEBUG(MTD_DEBUG_LEVEL2,
489 "mtd.eraseregions[%d] = { .offset = 0x%.8x, "
490 ".erasesize = 0x%.8x (%uK), "
491 ".numblocks = %d }\n",
492 i, flash->mtd.eraseregions[i].offset,
493 flash->mtd.eraseregions[i].erasesize,
494 flash->mtd.eraseregions[i].erasesize / 1024,
495 flash->mtd.eraseregions[i].numblocks);
496
497
498 /* partitions should match sector boundaries; and it may be good to
499 * use readonly partitions for writeprotected sectors (BP2..BP0).
500 */
501 if (mtd_has_partitions()) {
502 struct mtd_partition *parts = NULL;
503 int nr_parts = 0;
504
505#ifdef CONFIG_MTD_CMDLINE_PARTS
506 static const char *part_probes[] = { "cmdlinepart", NULL, };
507
508 nr_parts = parse_mtd_partitions(&flash->mtd,
509 part_probes, &parts, 0);
510#endif
511
512 if (nr_parts <= 0 && data && data->parts) {
513 parts = data->parts;
514 nr_parts = data->nr_parts;
515 }
516
517 if (nr_parts > 0) {
518 for (i = 0; i < data->nr_parts; i++) {
519 DEBUG(MTD_DEBUG_LEVEL2, "partitions[%d] = "
520 "{.name = %s, .offset = 0x%.8x, "
521 ".size = 0x%.8x (%uK) }\n",
522 i, data->parts[i].name,
523 data->parts[i].offset,
524 data->parts[i].size,
525 data->parts[i].size / 1024);
526 }
527 flash->partitioned = 1;
528 return add_mtd_partitions(&flash->mtd, parts, nr_parts);
529 }
530 } else if (data->nr_parts)
531 dev_warn(&spi->dev, "ignoring %d default partitions on %s\n",
532 data->nr_parts, data->name);
533
534 return add_mtd_device(&flash->mtd) == 1 ? -ENODEV : 0;
535}
536
537
538static int __devexit m25p_remove(struct spi_device *spi)
539{
540 struct m25p *flash = dev_get_drvdata(&spi->dev);
541 int status;
542
543 /* Clean up MTD stuff. */
544 if (mtd_has_partitions() && flash->partitioned)
545 status = del_mtd_partitions(&flash->mtd);
546 else
547 status = del_mtd_device(&flash->mtd);
548 if (status == 0)
549 kfree(flash);
550 return 0;
551}
552
553
554static struct spi_driver m25p80_driver = {
555 .driver = {
556 .name = "m25p80",
557 .bus = &spi_bus_type,
558 .owner = THIS_MODULE,
559 },
560 .probe = m25p_probe,
561 .remove = __devexit_p(m25p_remove),
562};
563
564
565static int m25p80_init(void)
566{
567 return spi_register_driver(&m25p80_driver);
568}
569
570
571static void m25p80_exit(void)
572{
573 spi_unregister_driver(&m25p80_driver);
574}
575
576
577module_init(m25p80_init);
578module_exit(m25p80_exit);
579
580MODULE_LICENSE("GPL");
581MODULE_AUTHOR("Mike Lavender");
582MODULE_DESCRIPTION("MTD SPI driver for ST M25Pxx flash chips");
diff --git a/drivers/mtd/devices/mtd_dataflash.c b/drivers/mtd/devices/mtd_dataflash.c
new file mode 100644
index 000000000000..155737e7483f
--- /dev/null
+++ b/drivers/mtd/devices/mtd_dataflash.c
@@ -0,0 +1,629 @@
1/*
2 * Atmel AT45xxx DataFlash MTD driver for lightweight SPI framework
3 *
4 * Largely derived from at91_dataflash.c:
5 * Copyright (C) 2003-2005 SAN People (Pty) Ltd
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11*/
12#include <linux/config.h>
13#include <linux/module.h>
14#include <linux/init.h>
15#include <linux/slab.h>
16#include <linux/delay.h>
17#include <linux/device.h>
18#include <linux/spi/spi.h>
19#include <linux/spi/flash.h>
20
21#include <linux/mtd/mtd.h>
22#include <linux/mtd/partitions.h>
23
24
25/*
26 * DataFlash is a kind of SPI flash. Most AT45 chips have two buffers in
27 * each chip, which may be used for double buffered I/O; but this driver
28 * doesn't (yet) use these for any kind of i/o overlap or prefetching.
29 *
30 * Sometimes DataFlash is packaged in MMC-format cards, although the
31 * MMC stack can't use SPI (yet), or distinguish between MMC and DataFlash
32 * protocols during enumeration.
33 */
34
35#define CONFIG_DATAFLASH_WRITE_VERIFY
36
37/* reads can bypass the buffers */
38#define OP_READ_CONTINUOUS 0xE8
39#define OP_READ_PAGE 0xD2
40
41/* group B requests can run even while status reports "busy" */
42#define OP_READ_STATUS 0xD7 /* group B */
43
44/* move data between host and buffer */
45#define OP_READ_BUFFER1 0xD4 /* group B */
46#define OP_READ_BUFFER2 0xD6 /* group B */
47#define OP_WRITE_BUFFER1 0x84 /* group B */
48#define OP_WRITE_BUFFER2 0x87 /* group B */
49
50/* erasing flash */
51#define OP_ERASE_PAGE 0x81
52#define OP_ERASE_BLOCK 0x50
53
54/* move data between buffer and flash */
55#define OP_TRANSFER_BUF1 0x53
56#define OP_TRANSFER_BUF2 0x55
57#define OP_MREAD_BUFFER1 0xD4
58#define OP_MREAD_BUFFER2 0xD6
59#define OP_MWERASE_BUFFER1 0x83
60#define OP_MWERASE_BUFFER2 0x86
61#define OP_MWRITE_BUFFER1 0x88 /* sector must be pre-erased */
62#define OP_MWRITE_BUFFER2 0x89 /* sector must be pre-erased */
63
64/* write to buffer, then write-erase to flash */
65#define OP_PROGRAM_VIA_BUF1 0x82
66#define OP_PROGRAM_VIA_BUF2 0x85
67
68/* compare buffer to flash */
69#define OP_COMPARE_BUF1 0x60
70#define OP_COMPARE_BUF2 0x61
71
72/* read flash to buffer, then write-erase to flash */
73#define OP_REWRITE_VIA_BUF1 0x58
74#define OP_REWRITE_VIA_BUF2 0x59
75
76/* newer chips report JEDEC manufacturer and device IDs; chip
77 * serial number and OTP bits; and per-sector writeprotect.
78 */
79#define OP_READ_ID 0x9F
80#define OP_READ_SECURITY 0x77
81#define OP_WRITE_SECURITY 0x9A /* OTP bits */
82
83
84struct dataflash {
85 u8 command[4];
86 char name[24];
87
88 unsigned partitioned:1;
89
90 unsigned short page_offset; /* offset in flash address */
91 unsigned int page_size; /* of bytes per page */
92
93 struct semaphore lock;
94 struct spi_device *spi;
95
96 struct mtd_info mtd;
97};
98
99#ifdef CONFIG_MTD_PARTITIONS
100#define mtd_has_partitions() (1)
101#else
102#define mtd_has_partitions() (0)
103#endif
104
105/* ......................................................................... */
106
107/*
108 * Return the status of the DataFlash device.
109 */
110static inline int dataflash_status(struct spi_device *spi)
111{
112 /* NOTE: at45db321c over 25 MHz wants to write
113 * a dummy byte after the opcode...
114 */
115 return spi_w8r8(spi, OP_READ_STATUS);
116}
117
118/*
119 * Poll the DataFlash device until it is READY.
120 * This usually takes 5-20 msec or so; more for sector erase.
121 */
122static int dataflash_waitready(struct spi_device *spi)
123{
124 int status;
125
126 for (;;) {
127 status = dataflash_status(spi);
128 if (status < 0) {
129 DEBUG(MTD_DEBUG_LEVEL1, "%s: status %d?\n",
130 spi->dev.bus_id, status);
131 status = 0;
132 }
133
134 if (status & (1 << 7)) /* RDY/nBSY */
135 return status;
136
137 msleep(3);
138 }
139}
140
141/* ......................................................................... */
142
143/*
144 * Erase pages of flash.
145 */
146static int dataflash_erase(struct mtd_info *mtd, struct erase_info *instr)
147{
148 struct dataflash *priv = (struct dataflash *)mtd->priv;
149 struct spi_device *spi = priv->spi;
150 struct spi_transfer x = { .tx_dma = 0, };
151 struct spi_message msg;
152 unsigned blocksize = priv->page_size << 3;
153 u8 *command;
154
155 DEBUG(MTD_DEBUG_LEVEL2, "%s: erase addr=0x%x len 0x%x\n",
156 spi->dev.bus_id,
157 instr->addr, instr->len);
158
159 /* Sanity checks */
160 if ((instr->addr + instr->len) > mtd->size
161 || (instr->len % priv->page_size) != 0
162 || (instr->addr % priv->page_size) != 0)
163 return -EINVAL;
164
165 spi_message_init(&msg);
166
167 x.tx_buf = command = priv->command;
168 x.len = 4;
169 spi_message_add_tail(&x, &msg);
170
171 down(&priv->lock);
172 while (instr->len > 0) {
173 unsigned int pageaddr;
174 int status;
175 int do_block;
176
177 /* Calculate flash page address; use block erase (for speed) if
178 * we're at a block boundary and need to erase the whole block.
179 */
180 pageaddr = instr->addr / priv->page_size;
181 do_block = (pageaddr & 0x7) == 0 && instr->len <= blocksize;
182 pageaddr = pageaddr << priv->page_offset;
183
184 command[0] = do_block ? OP_ERASE_BLOCK : OP_ERASE_PAGE;
185 command[1] = (u8)(pageaddr >> 16);
186 command[2] = (u8)(pageaddr >> 8);
187 command[3] = 0;
188
189 DEBUG(MTD_DEBUG_LEVEL3, "ERASE %s: (%x) %x %x %x [%i]\n",
190 do_block ? "block" : "page",
191 command[0], command[1], command[2], command[3],
192 pageaddr);
193
194 status = spi_sync(spi, &msg);
195 (void) dataflash_waitready(spi);
196
197 if (status < 0) {
198 printk(KERN_ERR "%s: erase %x, err %d\n",
199 spi->dev.bus_id, pageaddr, status);
200 /* REVISIT: can retry instr->retries times; or
201 * giveup and instr->fail_addr = instr->addr;
202 */
203 continue;
204 }
205
206 if (do_block) {
207 instr->addr += blocksize;
208 instr->len -= blocksize;
209 } else {
210 instr->addr += priv->page_size;
211 instr->len -= priv->page_size;
212 }
213 }
214 up(&priv->lock);
215
216 /* Inform MTD subsystem that erase is complete */
217 instr->state = MTD_ERASE_DONE;
218 mtd_erase_callback(instr);
219
220 return 0;
221}
222
223/*
224 * Read from the DataFlash device.
225 * from : Start offset in flash device
226 * len : Amount to read
227 * retlen : About of data actually read
228 * buf : Buffer containing the data
229 */
230static int dataflash_read(struct mtd_info *mtd, loff_t from, size_t len,
231 size_t *retlen, u_char *buf)
232{
233 struct dataflash *priv = (struct dataflash *)mtd->priv;
234 struct spi_transfer x[2] = { { .tx_dma = 0, }, };
235 struct spi_message msg;
236 unsigned int addr;
237 u8 *command;
238 int status;
239
240 DEBUG(MTD_DEBUG_LEVEL2, "%s: read 0x%x..0x%x\n",
241 priv->spi->dev.bus_id, (unsigned)from, (unsigned)(from + len));
242
243 *retlen = 0;
244
245 /* Sanity checks */
246 if (!len)
247 return 0;
248 if (from + len > mtd->size)
249 return -EINVAL;
250
251 /* Calculate flash page/byte address */
252 addr = (((unsigned)from / priv->page_size) << priv->page_offset)
253 + ((unsigned)from % priv->page_size);
254
255 command = priv->command;
256
257 DEBUG(MTD_DEBUG_LEVEL3, "READ: (%x) %x %x %x\n",
258 command[0], command[1], command[2], command[3]);
259
260 spi_message_init(&msg);
261
262 x[0].tx_buf = command;
263 x[0].len = 8;
264 spi_message_add_tail(&x[0], &msg);
265
266 x[1].rx_buf = buf;
267 x[1].len = len;
268 spi_message_add_tail(&x[1], &msg);
269
270 down(&priv->lock);
271
272 /* Continuous read, max clock = f(car) which may be less than
273 * the peak rate available. Some chips support commands with
274 * fewer "don't care" bytes. Both buffers stay unchanged.
275 */
276 command[0] = OP_READ_CONTINUOUS;
277 command[1] = (u8)(addr >> 16);
278 command[2] = (u8)(addr >> 8);
279 command[3] = (u8)(addr >> 0);
280 /* plus 4 "don't care" bytes */
281
282 status = spi_sync(priv->spi, &msg);
283 up(&priv->lock);
284
285 if (status >= 0) {
286 *retlen = msg.actual_length - 8;
287 status = 0;
288 } else
289 DEBUG(MTD_DEBUG_LEVEL1, "%s: read %x..%x --> %d\n",
290 priv->spi->dev.bus_id,
291 (unsigned)from, (unsigned)(from + len),
292 status);
293 return status;
294}
295
296/*
297 * Write to the DataFlash device.
298 * to : Start offset in flash device
299 * len : Amount to write
300 * retlen : Amount of data actually written
301 * buf : Buffer containing the data
302 */
303static int dataflash_write(struct mtd_info *mtd, loff_t to, size_t len,
304 size_t * retlen, const u_char * buf)
305{
306 struct dataflash *priv = (struct dataflash *)mtd->priv;
307 struct spi_device *spi = priv->spi;
308 struct spi_transfer x[2] = { { .tx_dma = 0, }, };
309 struct spi_message msg;
310 unsigned int pageaddr, addr, offset, writelen;
311 size_t remaining = len;
312 u_char *writebuf = (u_char *) buf;
313 int status = -EINVAL;
314 u8 *command;
315
316 DEBUG(MTD_DEBUG_LEVEL2, "%s: write 0x%x..0x%x\n",
317 spi->dev.bus_id, (unsigned)to, (unsigned)(to + len));
318
319 *retlen = 0;
320
321 /* Sanity checks */
322 if (!len)
323 return 0;
324 if ((to + len) > mtd->size)
325 return -EINVAL;
326
327 spi_message_init(&msg);
328
329 x[0].tx_buf = command = priv->command;
330 x[0].len = 4;
331 spi_message_add_tail(&x[0], &msg);
332
333 pageaddr = ((unsigned)to / priv->page_size);
334 offset = ((unsigned)to % priv->page_size);
335 if (offset + len > priv->page_size)
336 writelen = priv->page_size - offset;
337 else
338 writelen = len;
339
340 down(&priv->lock);
341 while (remaining > 0) {
342 DEBUG(MTD_DEBUG_LEVEL3, "write @ %i:%i len=%i\n",
343 pageaddr, offset, writelen);
344
345 /* REVISIT:
346 * (a) each page in a sector must be rewritten at least
347 * once every 10K sibling erase/program operations.
348 * (b) for pages that are already erased, we could
349 * use WRITE+MWRITE not PROGRAM for ~30% speedup.
350 * (c) WRITE to buffer could be done while waiting for
351 * a previous MWRITE/MWERASE to complete ...
352 * (d) error handling here seems to be mostly missing.
353 *
354 * Two persistent bits per page, plus a per-sector counter,
355 * could support (a) and (b) ... we might consider using
356 * the second half of sector zero, which is just one block,
357 * to track that state. (On AT91, that sector should also
358 * support boot-from-DataFlash.)
359 */
360
361 addr = pageaddr << priv->page_offset;
362
363 /* (1) Maybe transfer partial page to Buffer1 */
364 if (writelen != priv->page_size) {
365 command[0] = OP_TRANSFER_BUF1;
366 command[1] = (addr & 0x00FF0000) >> 16;
367 command[2] = (addr & 0x0000FF00) >> 8;
368 command[3] = 0;
369
370 DEBUG(MTD_DEBUG_LEVEL3, "TRANSFER: (%x) %x %x %x\n",
371 command[0], command[1], command[2], command[3]);
372
373 status = spi_sync(spi, &msg);
374 if (status < 0)
375 DEBUG(MTD_DEBUG_LEVEL1, "%s: xfer %u -> %d \n",
376 spi->dev.bus_id, addr, status);
377
378 (void) dataflash_waitready(priv->spi);
379 }
380
381 /* (2) Program full page via Buffer1 */
382 addr += offset;
383 command[0] = OP_PROGRAM_VIA_BUF1;
384 command[1] = (addr & 0x00FF0000) >> 16;
385 command[2] = (addr & 0x0000FF00) >> 8;
386 command[3] = (addr & 0x000000FF);
387
388 DEBUG(MTD_DEBUG_LEVEL3, "PROGRAM: (%x) %x %x %x\n",
389 command[0], command[1], command[2], command[3]);
390
391 x[1].tx_buf = writebuf;
392 x[1].len = writelen;
393 spi_message_add_tail(x + 1, &msg);
394 status = spi_sync(spi, &msg);
395 spi_transfer_del(x + 1);
396 if (status < 0)
397 DEBUG(MTD_DEBUG_LEVEL1, "%s: pgm %u/%u -> %d \n",
398 spi->dev.bus_id, addr, writelen, status);
399
400 (void) dataflash_waitready(priv->spi);
401
402
403#ifdef CONFIG_DATAFLASH_WRITE_VERIFY
404
405 /* (3) Compare to Buffer1 */
406 addr = pageaddr << priv->page_offset;
407 command[0] = OP_COMPARE_BUF1;
408 command[1] = (addr & 0x00FF0000) >> 16;
409 command[2] = (addr & 0x0000FF00) >> 8;
410 command[3] = 0;
411
412 DEBUG(MTD_DEBUG_LEVEL3, "COMPARE: (%x) %x %x %x\n",
413 command[0], command[1], command[2], command[3]);
414
415 status = spi_sync(spi, &msg);
416 if (status < 0)
417 DEBUG(MTD_DEBUG_LEVEL1, "%s: compare %u -> %d \n",
418 spi->dev.bus_id, addr, status);
419
420 status = dataflash_waitready(priv->spi);
421
422 /* Check result of the compare operation */
423 if ((status & (1 << 6)) == 1) {
424 printk(KERN_ERR "%s: compare page %u, err %d\n",
425 spi->dev.bus_id, pageaddr, status);
426 remaining = 0;
427 status = -EIO;
428 break;
429 } else
430 status = 0;
431
432#endif /* CONFIG_DATAFLASH_WRITE_VERIFY */
433
434 remaining = remaining - writelen;
435 pageaddr++;
436 offset = 0;
437 writebuf += writelen;
438 *retlen += writelen;
439
440 if (remaining > priv->page_size)
441 writelen = priv->page_size;
442 else
443 writelen = remaining;
444 }
445 up(&priv->lock);
446
447 return status;
448}
449
450/* ......................................................................... */
451
452/*
453 * Register DataFlash device with MTD subsystem.
454 */
455static int __devinit
456add_dataflash(struct spi_device *spi, char *name,
457 int nr_pages, int pagesize, int pageoffset)
458{
459 struct dataflash *priv;
460 struct mtd_info *device;
461 struct flash_platform_data *pdata = spi->dev.platform_data;
462
463 priv = (struct dataflash *) kzalloc(sizeof *priv, GFP_KERNEL);
464 if (!priv)
465 return -ENOMEM;
466
467 init_MUTEX(&priv->lock);
468 priv->spi = spi;
469 priv->page_size = pagesize;
470 priv->page_offset = pageoffset;
471
472 /* name must be usable with cmdlinepart */
473 sprintf(priv->name, "spi%d.%d-%s",
474 spi->master->bus_num, spi->chip_select,
475 name);
476
477 device = &priv->mtd;
478 device->name = (pdata && pdata->name) ? pdata->name : priv->name;
479 device->size = nr_pages * pagesize;
480 device->erasesize = pagesize;
481 device->owner = THIS_MODULE;
482 device->type = MTD_DATAFLASH;
483 device->flags = MTD_CAP_NORFLASH;
484 device->erase = dataflash_erase;
485 device->read = dataflash_read;
486 device->write = dataflash_write;
487 device->priv = priv;
488
489 dev_info(&spi->dev, "%s (%d KBytes)\n", name, device->size/1024);
490 dev_set_drvdata(&spi->dev, priv);
491
492 if (mtd_has_partitions()) {
493 struct mtd_partition *parts;
494 int nr_parts = 0;
495
496#ifdef CONFIG_MTD_CMDLINE_PARTS
497 static const char *part_probes[] = { "cmdlinepart", NULL, };
498
499 nr_parts = parse_mtd_partitions(device, part_probes, &parts, 0);
500#endif
501
502 if (nr_parts <= 0 && pdata && pdata->parts) {
503 parts = pdata->parts;
504 nr_parts = pdata->nr_parts;
505 }
506
507 if (nr_parts > 0) {
508 priv->partitioned = 1;
509 return add_mtd_partitions(device, parts, nr_parts);
510 }
511 } else if (pdata && pdata->nr_parts)
512 dev_warn(&spi->dev, "ignoring %d default partitions on %s\n",
513 pdata->nr_parts, device->name);
514
515 return add_mtd_device(device) == 1 ? -ENODEV : 0;
516}
517
518/*
519 * Detect and initialize DataFlash device:
520 *
521 * Device Density ID code #Pages PageSize Offset
522 * AT45DB011B 1Mbit (128K) xx0011xx (0x0c) 512 264 9
523 * AT45DB021B 2Mbit (256K) xx0101xx (0x14) 1025 264 9
524 * AT45DB041B 4Mbit (512K) xx0111xx (0x1c) 2048 264 9
525 * AT45DB081B 8Mbit (1M) xx1001xx (0x24) 4096 264 9
526 * AT45DB0161B 16Mbit (2M) xx1011xx (0x2c) 4096 528 10
527 * AT45DB0321B 32Mbit (4M) xx1101xx (0x34) 8192 528 10
528 * AT45DB0642 64Mbit (8M) xx111xxx (0x3c) 8192 1056 11
529 * AT45DB1282 128Mbit (16M) xx0100xx (0x10) 16384 1056 11
530 */
531static int __devinit dataflash_probe(struct spi_device *spi)
532{
533 int status;
534
535 status = dataflash_status(spi);
536 if (status <= 0 || status == 0xff) {
537 DEBUG(MTD_DEBUG_LEVEL1, "%s: status error %d\n",
538 spi->dev.bus_id, status);
539 if (status == 0xff)
540 status = -ENODEV;
541 return status;
542 }
543
544 /* if there's a device there, assume it's dataflash.
545 * board setup should have set spi->max_speed_max to
546 * match f(car) for continuous reads, mode 0 or 3.
547 */
548 switch (status & 0x3c) {
549 case 0x0c: /* 0 0 1 1 x x */
550 status = add_dataflash(spi, "AT45DB011B", 512, 264, 9);
551 break;
552 case 0x14: /* 0 1 0 1 x x */
553 status = add_dataflash(spi, "AT45DB021B", 1025, 264, 9);
554 break;
555 case 0x1c: /* 0 1 1 1 x x */
556 status = add_dataflash(spi, "AT45DB041x", 2048, 264, 9);
557 break;
558 case 0x24: /* 1 0 0 1 x x */
559 status = add_dataflash(spi, "AT45DB081B", 4096, 264, 9);
560 break;
561 case 0x2c: /* 1 0 1 1 x x */
562 status = add_dataflash(spi, "AT45DB161x", 4096, 528, 10);
563 break;
564 case 0x34: /* 1 1 0 1 x x */
565 status = add_dataflash(spi, "AT45DB321x", 8192, 528, 10);
566 break;
567 case 0x38: /* 1 1 1 x x x */
568 case 0x3c:
569 status = add_dataflash(spi, "AT45DB642x", 8192, 1056, 11);
570 break;
571 /* obsolete AT45DB1282 not (yet?) supported */
572 default:
573 DEBUG(MTD_DEBUG_LEVEL1, "%s: unsupported device (%x)\n",
574 spi->dev.bus_id, status & 0x3c);
575 status = -ENODEV;
576 }
577
578 if (status < 0)
579 DEBUG(MTD_DEBUG_LEVEL1, "%s: add_dataflash --> %d\n",
580 spi->dev.bus_id, status);
581
582 return status;
583}
584
585static int __devexit dataflash_remove(struct spi_device *spi)
586{
587 struct dataflash *flash = dev_get_drvdata(&spi->dev);
588 int status;
589
590 DEBUG(MTD_DEBUG_LEVEL1, "%s: remove\n", spi->dev.bus_id);
591
592 if (mtd_has_partitions() && flash->partitioned)
593 status = del_mtd_partitions(&flash->mtd);
594 else
595 status = del_mtd_device(&flash->mtd);
596 if (status == 0)
597 kfree(flash);
598 return status;
599}
600
601static struct spi_driver dataflash_driver = {
602 .driver = {
603 .name = "mtd_dataflash",
604 .bus = &spi_bus_type,
605 .owner = THIS_MODULE,
606 },
607
608 .probe = dataflash_probe,
609 .remove = __devexit_p(dataflash_remove),
610
611 /* FIXME: investigate suspend and resume... */
612};
613
614static int __init dataflash_init(void)
615{
616 return spi_register_driver(&dataflash_driver);
617}
618module_init(dataflash_init);
619
620static void __exit dataflash_exit(void)
621{
622 spi_unregister_driver(&dataflash_driver);
623}
624module_exit(dataflash_exit);
625
626
627MODULE_LICENSE("GPL");
628MODULE_AUTHOR("Andrew Victor, David Brownell");
629MODULE_DESCRIPTION("MTD DataFlash driver");
diff --git a/drivers/spi/Kconfig b/drivers/spi/Kconfig
new file mode 100644
index 000000000000..b77dbd63e596
--- /dev/null
+++ b/drivers/spi/Kconfig
@@ -0,0 +1,109 @@
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
54config SPI_BITBANG
55 tristate "Bitbanging SPI master"
56 depends on SPI_MASTER && EXPERIMENTAL
57 help
58 With a few GPIO pins, your system can bitbang the SPI protocol.
59 Select this to get SPI support through I/O pins (GPIO, parallel
60 port, etc). Or, some systems' SPI master controller drivers use
61 this code to manage the per-word or per-transfer accesses to the
62 hardware shift registers.
63
64 This is library code, and is automatically selected by drivers that
65 need it. You only need to select this explicitly to support driver
66 modules that aren't part of this kernel tree.
67
68config SPI_BUTTERFLY
69 tristate "Parallel port adapter for AVR Butterfly (DEVELOPMENT)"
70 depends on SPI_MASTER && PARPORT && EXPERIMENTAL
71 select SPI_BITBANG
72 help
73 This uses a custom parallel port cable to connect to an AVR
74 Butterfly <http://www.atmel.com/products/avr/butterfly>, an
75 inexpensive battery powered microcontroller evaluation board.
76 This same cable can be used to flash new firmware.
77
78config SPI_BUTTERFLY
79 tristate "Parallel port adapter for AVR Butterfly (DEVELOPMENT)"
80 depends on SPI_MASTER && PARPORT && EXPERIMENTAL
81 select SPI_BITBANG
82 help
83 This uses a custom parallel port cable to connect to an AVR
84 Butterfly <http://www.atmel.com/products/avr/butterfly>, an
85 inexpensive battery powered microcontroller evaluation board.
86 This same cable can be used to flash new firmware.
87
88#
89# Add new SPI master controllers in alphabetical order above this line
90#
91
92
93#
94# There are lots of SPI device types, with sensors and memory
95# being probably the most widely used ones.
96#
97comment "SPI Protocol Masters"
98 depends on SPI_MASTER
99
100
101#
102# Add new SPI protocol masters in alphabetical order above this line
103#
104
105
106# (slave support would go here)
107
108endmenu # "SPI support"
109
diff --git a/drivers/spi/Makefile b/drivers/spi/Makefile
new file mode 100644
index 000000000000..c2c87e845abf
--- /dev/null
+++ b/drivers/spi/Makefile
@@ -0,0 +1,25 @@
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)
14obj-$(CONFIG_SPI_BITBANG) += spi_bitbang.o
15obj-$(CONFIG_SPI_BUTTERFLY) += spi_butterfly.o
16# ... add above this line ...
17
18# SPI protocol drivers (device/link on bus)
19# ... add above this line ...
20
21# SPI slave controller drivers (upstream link)
22# ... add above this line ...
23
24# SPI slave drivers (protocol for that link)
25# ... add above this line ...
diff --git a/drivers/spi/spi.c b/drivers/spi/spi.c
new file mode 100644
index 000000000000..791c4dc550ae
--- /dev/null
+++ b/drivers/spi/spi.c
@@ -0,0 +1,642 @@
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 after board init code
30 * provides the SPI device tables, ensuring that both are present by the
31 * time controller driver registration causes spi_devices to "enumerate".
32 */
33static void spidev_release(struct device *dev)
34{
35 const struct spi_device *spi = to_spi_device(dev);
36
37 /* spi masters may cleanup for released devices */
38 if (spi->master->cleanup)
39 spi->master->cleanup(spi);
40
41 spi_master_put(spi->master);
42 kfree(dev);
43}
44
45static ssize_t
46modalias_show(struct device *dev, struct device_attribute *a, char *buf)
47{
48 const struct spi_device *spi = to_spi_device(dev);
49
50 return snprintf(buf, BUS_ID_SIZE + 1, "%s\n", spi->modalias);
51}
52
53static struct device_attribute spi_dev_attrs[] = {
54 __ATTR_RO(modalias),
55 __ATTR_NULL,
56};
57
58/* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
59 * and the sysfs version makes coldplug work too.
60 */
61
62static int spi_match_device(struct device *dev, struct device_driver *drv)
63{
64 const struct spi_device *spi = to_spi_device(dev);
65
66 return strncmp(spi->modalias, drv->name, BUS_ID_SIZE) == 0;
67}
68
69static int spi_uevent(struct device *dev, char **envp, int num_envp,
70 char *buffer, int buffer_size)
71{
72 const struct spi_device *spi = to_spi_device(dev);
73
74 envp[0] = buffer;
75 snprintf(buffer, buffer_size, "MODALIAS=%s", spi->modalias);
76 envp[1] = NULL;
77 return 0;
78}
79
80#ifdef CONFIG_PM
81
82/*
83 * NOTE: the suspend() method for an spi_master controller driver
84 * should verify that all its child devices are marked as suspended;
85 * suspend requests delivered through sysfs power/state files don't
86 * enforce such constraints.
87 */
88static int spi_suspend(struct device *dev, pm_message_t message)
89{
90 int value;
91 struct spi_driver *drv = to_spi_driver(dev->driver);
92
93 if (!drv->suspend)
94 return 0;
95
96 /* suspend will stop irqs and dma; no more i/o */
97 value = drv->suspend(to_spi_device(dev), message);
98 if (value == 0)
99 dev->power.power_state = message;
100 return value;
101}
102
103static int spi_resume(struct device *dev)
104{
105 int value;
106 struct spi_driver *drv = to_spi_driver(dev->driver);
107
108 if (!drv->resume)
109 return 0;
110
111 /* resume may restart the i/o queue */
112 value = drv->resume(to_spi_device(dev));
113 if (value == 0)
114 dev->power.power_state = PMSG_ON;
115 return value;
116}
117
118#else
119#define spi_suspend NULL
120#define spi_resume NULL
121#endif
122
123struct bus_type spi_bus_type = {
124 .name = "spi",
125 .dev_attrs = spi_dev_attrs,
126 .match = spi_match_device,
127 .uevent = spi_uevent,
128 .suspend = spi_suspend,
129 .resume = spi_resume,
130};
131EXPORT_SYMBOL_GPL(spi_bus_type);
132
133
134static int spi_drv_probe(struct device *dev)
135{
136 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
137
138 return sdrv->probe(to_spi_device(dev));
139}
140
141static int spi_drv_remove(struct device *dev)
142{
143 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
144
145 return sdrv->remove(to_spi_device(dev));
146}
147
148static void spi_drv_shutdown(struct device *dev)
149{
150 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
151
152 sdrv->shutdown(to_spi_device(dev));
153}
154
155int spi_register_driver(struct spi_driver *sdrv)
156{
157 sdrv->driver.bus = &spi_bus_type;
158 if (sdrv->probe)
159 sdrv->driver.probe = spi_drv_probe;
160 if (sdrv->remove)
161 sdrv->driver.remove = spi_drv_remove;
162 if (sdrv->shutdown)
163 sdrv->driver.shutdown = spi_drv_shutdown;
164 return driver_register(&sdrv->driver);
165}
166EXPORT_SYMBOL_GPL(spi_register_driver);
167
168/*-------------------------------------------------------------------------*/
169
170/* SPI devices should normally not be created by SPI device drivers; that
171 * would make them board-specific. Similarly with SPI master drivers.
172 * Device registration normally goes into like arch/.../mach.../board-YYY.c
173 * with other readonly (flashable) information about mainboard devices.
174 */
175
176struct boardinfo {
177 struct list_head list;
178 unsigned n_board_info;
179 struct spi_board_info board_info[0];
180};
181
182static LIST_HEAD(board_list);
183static DECLARE_MUTEX(board_lock);
184
185
186/* On typical mainboards, this is purely internal; and it's not needed
187 * after board init creates the hard-wired devices. Some development
188 * platforms may not be able to use spi_register_board_info though, and
189 * this is exported so that for example a USB or parport based adapter
190 * driver could add devices (which it would learn about out-of-band).
191 */
192struct spi_device *__init_or_module
193spi_new_device(struct spi_master *master, struct spi_board_info *chip)
194{
195 struct spi_device *proxy;
196 struct device *dev = master->cdev.dev;
197 int status;
198
199 /* NOTE: caller did any chip->bus_num checks necessary */
200
201 if (!spi_master_get(master))
202 return NULL;
203
204 proxy = kzalloc(sizeof *proxy, GFP_KERNEL);
205 if (!proxy) {
206 dev_err(dev, "can't alloc dev for cs%d\n",
207 chip->chip_select);
208 goto fail;
209 }
210 proxy->master = master;
211 proxy->chip_select = chip->chip_select;
212 proxy->max_speed_hz = chip->max_speed_hz;
213 proxy->irq = chip->irq;
214 proxy->modalias = chip->modalias;
215
216 snprintf(proxy->dev.bus_id, sizeof proxy->dev.bus_id,
217 "%s.%u", master->cdev.class_id,
218 chip->chip_select);
219 proxy->dev.parent = dev;
220 proxy->dev.bus = &spi_bus_type;
221 proxy->dev.platform_data = (void *) chip->platform_data;
222 proxy->controller_data = chip->controller_data;
223 proxy->controller_state = NULL;
224 proxy->dev.release = spidev_release;
225
226 /* drivers may modify this default i/o setup */
227 status = master->setup(proxy);
228 if (status < 0) {
229 dev_dbg(dev, "can't %s %s, status %d\n",
230 "setup", proxy->dev.bus_id, status);
231 goto fail;
232 }
233
234 /* driver core catches callers that misbehave by defining
235 * devices that already exist.
236 */
237 status = device_register(&proxy->dev);
238 if (status < 0) {
239 dev_dbg(dev, "can't %s %s, status %d\n",
240 "add", proxy->dev.bus_id, status);
241 goto fail;
242 }
243 dev_dbg(dev, "registered child %s\n", proxy->dev.bus_id);
244 return proxy;
245
246fail:
247 spi_master_put(master);
248 kfree(proxy);
249 return NULL;
250}
251EXPORT_SYMBOL_GPL(spi_new_device);
252
253/*
254 * Board-specific early init code calls this (probably during arch_initcall)
255 * with segments of the SPI device table. Any device nodes are created later,
256 * after the relevant parent SPI controller (bus_num) is defined. We keep
257 * this table of devices forever, so that reloading a controller driver will
258 * not make Linux forget about these hard-wired devices.
259 *
260 * Other code can also call this, e.g. a particular add-on board might provide
261 * SPI devices through its expansion connector, so code initializing that board
262 * would naturally declare its SPI devices.
263 *
264 * The board info passed can safely be __initdata ... but be careful of
265 * any embedded pointers (platform_data, etc), they're copied as-is.
266 */
267int __init
268spi_register_board_info(struct spi_board_info const *info, unsigned n)
269{
270 struct boardinfo *bi;
271
272 bi = kmalloc(sizeof(*bi) + n * sizeof *info, GFP_KERNEL);
273 if (!bi)
274 return -ENOMEM;
275 bi->n_board_info = n;
276 memcpy(bi->board_info, info, n * sizeof *info);
277
278 down(&board_lock);
279 list_add_tail(&bi->list, &board_list);
280 up(&board_lock);
281 return 0;
282}
283EXPORT_SYMBOL_GPL(spi_register_board_info);
284
285/* FIXME someone should add support for a __setup("spi", ...) that
286 * creates board info from kernel command lines
287 */
288
289static void __init_or_module
290scan_boardinfo(struct spi_master *master)
291{
292 struct boardinfo *bi;
293 struct device *dev = master->cdev.dev;
294
295 down(&board_lock);
296 list_for_each_entry(bi, &board_list, list) {
297 struct spi_board_info *chip = bi->board_info;
298 unsigned n;
299
300 for (n = bi->n_board_info; n > 0; n--, chip++) {
301 if (chip->bus_num != master->bus_num)
302 continue;
303 /* some controllers only have one chip, so they
304 * might not use chipselects. otherwise, the
305 * chipselects are numbered 0..max.
306 */
307 if (chip->chip_select >= master->num_chipselect
308 && master->num_chipselect) {
309 dev_dbg(dev, "cs%d > max %d\n",
310 chip->chip_select,
311 master->num_chipselect);
312 continue;
313 }
314 (void) spi_new_device(master, chip);
315 }
316 }
317 up(&board_lock);
318}
319
320/*-------------------------------------------------------------------------*/
321
322static void spi_master_release(struct class_device *cdev)
323{
324 struct spi_master *master;
325
326 master = container_of(cdev, struct spi_master, cdev);
327 kfree(master);
328}
329
330static struct class spi_master_class = {
331 .name = "spi_master",
332 .owner = THIS_MODULE,
333 .release = spi_master_release,
334};
335
336
337/**
338 * spi_alloc_master - allocate SPI master controller
339 * @dev: the controller, possibly using the platform_bus
340 * @size: how much driver-private data to preallocate; the pointer to this
341 * memory is in the class_data field of the returned class_device,
342 * accessible with spi_master_get_devdata().
343 *
344 * This call is used only by SPI master controller drivers, which are the
345 * only ones directly touching chip registers. It's how they allocate
346 * an spi_master structure, prior to calling spi_add_master().
347 *
348 * This must be called from context that can sleep. It returns the SPI
349 * master structure on success, else NULL.
350 *
351 * The caller is responsible for assigning the bus number and initializing
352 * the master's methods before calling spi_add_master(); and (after errors
353 * adding the device) calling spi_master_put() to prevent a memory leak.
354 */
355struct spi_master * __init_or_module
356spi_alloc_master(struct device *dev, unsigned size)
357{
358 struct spi_master *master;
359
360 if (!dev)
361 return NULL;
362
363 master = kzalloc(size + sizeof *master, SLAB_KERNEL);
364 if (!master)
365 return NULL;
366
367 class_device_initialize(&master->cdev);
368 master->cdev.class = &spi_master_class;
369 master->cdev.dev = get_device(dev);
370 spi_master_set_devdata(master, &master[1]);
371
372 return master;
373}
374EXPORT_SYMBOL_GPL(spi_alloc_master);
375
376/**
377 * spi_register_master - register SPI master controller
378 * @master: initialized master, originally from spi_alloc_master()
379 *
380 * SPI master controllers connect to their drivers using some non-SPI bus,
381 * such as the platform bus. The final stage of probe() in that code
382 * includes calling spi_register_master() to hook up to this SPI bus glue.
383 *
384 * SPI controllers use board specific (often SOC specific) bus numbers,
385 * and board-specific addressing for SPI devices combines those numbers
386 * with chip select numbers. Since SPI does not directly support dynamic
387 * device identification, boards need configuration tables telling which
388 * chip is at which address.
389 *
390 * This must be called from context that can sleep. It returns zero on
391 * success, else a negative error code (dropping the master's refcount).
392 * After a successful return, the caller is responsible for calling
393 * spi_unregister_master().
394 */
395int __init_or_module
396spi_register_master(struct spi_master *master)
397{
398 static atomic_t dyn_bus_id = ATOMIC_INIT(0);
399 struct device *dev = master->cdev.dev;
400 int status = -ENODEV;
401 int dynamic = 0;
402
403 if (!dev)
404 return -ENODEV;
405
406 /* convention: dynamically assigned bus IDs count down from the max */
407 if (master->bus_num == 0) {
408 master->bus_num = atomic_dec_return(&dyn_bus_id);
409 dynamic = 1;
410 }
411
412 /* register the device, then userspace will see it.
413 * registration fails if the bus ID is in use.
414 */
415 snprintf(master->cdev.class_id, sizeof master->cdev.class_id,
416 "spi%u", master->bus_num);
417 status = class_device_add(&master->cdev);
418 if (status < 0)
419 goto done;
420 dev_dbg(dev, "registered master %s%s\n", master->cdev.class_id,
421 dynamic ? " (dynamic)" : "");
422
423 /* populate children from any spi device tables */
424 scan_boardinfo(master);
425 status = 0;
426done:
427 return status;
428}
429EXPORT_SYMBOL_GPL(spi_register_master);
430
431
432static int __unregister(struct device *dev, void *unused)
433{
434 /* note: before about 2.6.14-rc1 this would corrupt memory: */
435 spi_unregister_device(to_spi_device(dev));
436 return 0;
437}
438
439/**
440 * spi_unregister_master - unregister SPI master controller
441 * @master: the master being unregistered
442 *
443 * This call is used only by SPI master controller drivers, which are the
444 * only ones directly touching chip registers.
445 *
446 * This must be called from context that can sleep.
447 */
448void spi_unregister_master(struct spi_master *master)
449{
450 (void) device_for_each_child(master->cdev.dev, NULL, __unregister);
451 class_device_unregister(&master->cdev);
452 master->cdev.dev = NULL;
453}
454EXPORT_SYMBOL_GPL(spi_unregister_master);
455
456/**
457 * spi_busnum_to_master - look up master associated with bus_num
458 * @bus_num: the master's bus number
459 *
460 * This call may be used with devices that are registered after
461 * arch init time. It returns a refcounted pointer to the relevant
462 * spi_master (which the caller must release), or NULL if there is
463 * no such master registered.
464 */
465struct spi_master *spi_busnum_to_master(u16 bus_num)
466{
467 if (bus_num) {
468 char name[8];
469 struct kobject *bus;
470
471 snprintf(name, sizeof name, "spi%u", bus_num);
472 bus = kset_find_obj(&spi_master_class.subsys.kset, name);
473 if (bus)
474 return container_of(bus, struct spi_master, cdev.kobj);
475 }
476 return NULL;
477}
478EXPORT_SYMBOL_GPL(spi_busnum_to_master);
479
480
481/*-------------------------------------------------------------------------*/
482
483static void spi_complete(void *arg)
484{
485 complete(arg);
486}
487
488/**
489 * spi_sync - blocking/synchronous SPI data transfers
490 * @spi: device with which data will be exchanged
491 * @message: describes the data transfers
492 *
493 * This call may only be used from a context that may sleep. The sleep
494 * is non-interruptible, and has no timeout. Low-overhead controller
495 * drivers may DMA directly into and out of the message buffers.
496 *
497 * Note that the SPI device's chip select is active during the message,
498 * and then is normally disabled between messages. Drivers for some
499 * frequently-used devices may want to minimize costs of selecting a chip,
500 * by leaving it selected in anticipation that the next message will go
501 * to the same chip. (That may increase power usage.)
502 *
503 * Also, the caller is guaranteeing that the memory associated with the
504 * message will not be freed before this call returns.
505 *
506 * The return value is a negative error code if the message could not be
507 * submitted, else zero. When the value is zero, then message->status is
508 * also defined: it's the completion code for the transfer, either zero
509 * or a negative error code from the controller driver.
510 */
511int spi_sync(struct spi_device *spi, struct spi_message *message)
512{
513 DECLARE_COMPLETION(done);
514 int status;
515
516 message->complete = spi_complete;
517 message->context = &done;
518 status = spi_async(spi, message);
519 if (status == 0)
520 wait_for_completion(&done);
521 message->context = NULL;
522 return status;
523}
524EXPORT_SYMBOL_GPL(spi_sync);
525
526#define SPI_BUFSIZ (SMP_CACHE_BYTES)
527
528static u8 *buf;
529
530/**
531 * spi_write_then_read - SPI synchronous write followed by read
532 * @spi: device with which data will be exchanged
533 * @txbuf: data to be written (need not be dma-safe)
534 * @n_tx: size of txbuf, in bytes
535 * @rxbuf: buffer into which data will be read
536 * @n_rx: size of rxbuf, in bytes (need not be dma-safe)
537 *
538 * This performs a half duplex MicroWire style transaction with the
539 * device, sending txbuf and then reading rxbuf. The return value
540 * is zero for success, else a negative errno status code.
541 * This call may only be used from a context that may sleep.
542 *
543 * Parameters to this routine are always copied using a small buffer;
544 * performance-sensitive or bulk transfer code should instead use
545 * spi_{async,sync}() calls with dma-safe buffers.
546 */
547int spi_write_then_read(struct spi_device *spi,
548 const u8 *txbuf, unsigned n_tx,
549 u8 *rxbuf, unsigned n_rx)
550{
551 static DECLARE_MUTEX(lock);
552
553 int status;
554 struct spi_message message;
555 struct spi_transfer x[2];
556 u8 *local_buf;
557
558 /* Use preallocated DMA-safe buffer. We can't avoid copying here,
559 * (as a pure convenience thing), but we can keep heap costs
560 * out of the hot path ...
561 */
562 if ((n_tx + n_rx) > SPI_BUFSIZ)
563 return -EINVAL;
564
565 spi_message_init(&message);
566 memset(x, 0, sizeof x);
567 if (n_tx) {
568 x[0].len = n_tx;
569 spi_message_add_tail(&x[0], &message);
570 }
571 if (n_rx) {
572 x[1].len = n_rx;
573 spi_message_add_tail(&x[1], &message);
574 }
575
576 /* ... unless someone else is using the pre-allocated buffer */
577 if (down_trylock(&lock)) {
578 local_buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
579 if (!local_buf)
580 return -ENOMEM;
581 } else
582 local_buf = buf;
583
584 memcpy(local_buf, txbuf, n_tx);
585 x[0].tx_buf = local_buf;
586 x[1].rx_buf = local_buf + n_tx;
587
588 /* do the i/o */
589 status = spi_sync(spi, &message);
590 if (status == 0) {
591 memcpy(rxbuf, x[1].rx_buf, n_rx);
592 status = message.status;
593 }
594
595 if (x[0].tx_buf == buf)
596 up(&lock);
597 else
598 kfree(local_buf);
599
600 return status;
601}
602EXPORT_SYMBOL_GPL(spi_write_then_read);
603
604/*-------------------------------------------------------------------------*/
605
606static int __init spi_init(void)
607{
608 int status;
609
610 buf = kmalloc(SPI_BUFSIZ, SLAB_KERNEL);
611 if (!buf) {
612 status = -ENOMEM;
613 goto err0;
614 }
615
616 status = bus_register(&spi_bus_type);
617 if (status < 0)
618 goto err1;
619
620 status = class_register(&spi_master_class);
621 if (status < 0)
622 goto err2;
623 return 0;
624
625err2:
626 bus_unregister(&spi_bus_type);
627err1:
628 kfree(buf);
629 buf = NULL;
630err0:
631 return status;
632}
633
634/* board_info is normally registered in arch_initcall(),
635 * but even essential drivers wait till later
636 *
637 * REVISIT only boardinfo really needs static linking. the rest (device and
638 * driver registration) _could_ be dynamically linked (modular) ... costs
639 * include needing to have boardinfo data structures be much more public.
640 */
641subsys_initcall(spi_init);
642
diff --git a/drivers/spi/spi_bitbang.c b/drivers/spi/spi_bitbang.c
new file mode 100644
index 000000000000..f037e5593269
--- /dev/null
+++ b/drivers/spi/spi_bitbang.c
@@ -0,0 +1,472 @@
1/*
2 * spi_bitbang.c - polling/bitbanging SPI master controller driver utilities
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include <linux/config.h>
20#include <linux/init.h>
21#include <linux/spinlock.h>
22#include <linux/workqueue.h>
23#include <linux/interrupt.h>
24#include <linux/delay.h>
25#include <linux/errno.h>
26#include <linux/platform_device.h>
27
28#include <linux/spi/spi.h>
29#include <linux/spi/spi_bitbang.h>
30
31
32/*----------------------------------------------------------------------*/
33
34/*
35 * FIRST PART (OPTIONAL): word-at-a-time spi_transfer support.
36 * Use this for GPIO or shift-register level hardware APIs.
37 *
38 * spi_bitbang_cs is in spi_device->controller_state, which is unavailable
39 * to glue code. These bitbang setup() and cleanup() routines are always
40 * used, though maybe they're called from controller-aware code.
41 *
42 * chipselect() and friends may use use spi_device->controller_data and
43 * controller registers as appropriate.
44 *
45 *
46 * NOTE: SPI controller pins can often be used as GPIO pins instead,
47 * which means you could use a bitbang driver either to get hardware
48 * working quickly, or testing for differences that aren't speed related.
49 */
50
51struct spi_bitbang_cs {
52 unsigned nsecs; /* (clock cycle time)/2 */
53 u32 (*txrx_word)(struct spi_device *spi, unsigned nsecs,
54 u32 word, u8 bits);
55 unsigned (*txrx_bufs)(struct spi_device *,
56 u32 (*txrx_word)(
57 struct spi_device *spi,
58 unsigned nsecs,
59 u32 word, u8 bits),
60 unsigned, struct spi_transfer *);
61};
62
63static unsigned bitbang_txrx_8(
64 struct spi_device *spi,
65 u32 (*txrx_word)(struct spi_device *spi,
66 unsigned nsecs,
67 u32 word, u8 bits),
68 unsigned ns,
69 struct spi_transfer *t
70) {
71 unsigned bits = spi->bits_per_word;
72 unsigned count = t->len;
73 const u8 *tx = t->tx_buf;
74 u8 *rx = t->rx_buf;
75
76 while (likely(count > 0)) {
77 u8 word = 0;
78
79 if (tx)
80 word = *tx++;
81 word = txrx_word(spi, ns, word, bits);
82 if (rx)
83 *rx++ = word;
84 count -= 1;
85 }
86 return t->len - count;
87}
88
89static unsigned bitbang_txrx_16(
90 struct spi_device *spi,
91 u32 (*txrx_word)(struct spi_device *spi,
92 unsigned nsecs,
93 u32 word, u8 bits),
94 unsigned ns,
95 struct spi_transfer *t
96) {
97 unsigned bits = spi->bits_per_word;
98 unsigned count = t->len;
99 const u16 *tx = t->tx_buf;
100 u16 *rx = t->rx_buf;
101
102 while (likely(count > 1)) {
103 u16 word = 0;
104
105 if (tx)
106 word = *tx++;
107 word = txrx_word(spi, ns, word, bits);
108 if (rx)
109 *rx++ = word;
110 count -= 2;
111 }
112 return t->len - count;
113}
114
115static unsigned bitbang_txrx_32(
116 struct spi_device *spi,
117 u32 (*txrx_word)(struct spi_device *spi,
118 unsigned nsecs,
119 u32 word, u8 bits),
120 unsigned ns,
121 struct spi_transfer *t
122) {
123 unsigned bits = spi->bits_per_word;
124 unsigned count = t->len;
125 const u32 *tx = t->tx_buf;
126 u32 *rx = t->rx_buf;
127
128 while (likely(count > 3)) {
129 u32 word = 0;
130
131 if (tx)
132 word = *tx++;
133 word = txrx_word(spi, ns, word, bits);
134 if (rx)
135 *rx++ = word;
136 count -= 4;
137 }
138 return t->len - count;
139}
140
141/**
142 * spi_bitbang_setup - default setup for per-word I/O loops
143 */
144int spi_bitbang_setup(struct spi_device *spi)
145{
146 struct spi_bitbang_cs *cs = spi->controller_state;
147 struct spi_bitbang *bitbang;
148
149 if (!spi->max_speed_hz)
150 return -EINVAL;
151
152 if (!cs) {
153 cs = kzalloc(sizeof *cs, SLAB_KERNEL);
154 if (!cs)
155 return -ENOMEM;
156 spi->controller_state = cs;
157 }
158 bitbang = spi_master_get_devdata(spi->master);
159
160 if (!spi->bits_per_word)
161 spi->bits_per_word = 8;
162
163 /* spi_transfer level calls that work per-word */
164 if (spi->bits_per_word <= 8)
165 cs->txrx_bufs = bitbang_txrx_8;
166 else if (spi->bits_per_word <= 16)
167 cs->txrx_bufs = bitbang_txrx_16;
168 else if (spi->bits_per_word <= 32)
169 cs->txrx_bufs = bitbang_txrx_32;
170 else
171 return -EINVAL;
172
173 /* per-word shift register access, in hardware or bitbanging */
174 cs->txrx_word = bitbang->txrx_word[spi->mode & (SPI_CPOL|SPI_CPHA)];
175 if (!cs->txrx_word)
176 return -EINVAL;
177
178 /* nsecs = (clock period)/2 */
179 cs->nsecs = (1000000000/2) / (spi->max_speed_hz);
180 if (cs->nsecs > MAX_UDELAY_MS * 1000)
181 return -EINVAL;
182
183 dev_dbg(&spi->dev, "%s, mode %d, %u bits/w, %u nsec\n",
184 __FUNCTION__, spi->mode & (SPI_CPOL | SPI_CPHA),
185 spi->bits_per_word, 2 * cs->nsecs);
186
187 /* NOTE we _need_ to call chipselect() early, ideally with adapter
188 * setup, unless the hardware defaults cooperate to avoid confusion
189 * between normal (active low) and inverted chipselects.
190 */
191
192 /* deselect chip (low or high) */
193 spin_lock(&bitbang->lock);
194 if (!bitbang->busy) {
195 bitbang->chipselect(spi, BITBANG_CS_INACTIVE);
196 ndelay(cs->nsecs);
197 }
198 spin_unlock(&bitbang->lock);
199
200 return 0;
201}
202EXPORT_SYMBOL_GPL(spi_bitbang_setup);
203
204/**
205 * spi_bitbang_cleanup - default cleanup for per-word I/O loops
206 */
207void spi_bitbang_cleanup(const struct spi_device *spi)
208{
209 kfree(spi->controller_state);
210}
211EXPORT_SYMBOL_GPL(spi_bitbang_cleanup);
212
213static int spi_bitbang_bufs(struct spi_device *spi, struct spi_transfer *t)
214{
215 struct spi_bitbang_cs *cs = spi->controller_state;
216 unsigned nsecs = cs->nsecs;
217
218 return cs->txrx_bufs(spi, cs->txrx_word, nsecs, t);
219}
220
221/*----------------------------------------------------------------------*/
222
223/*
224 * SECOND PART ... simple transfer queue runner.
225 *
226 * This costs a task context per controller, running the queue by
227 * performing each transfer in sequence. Smarter hardware can queue
228 * several DMA transfers at once, and process several controller queues
229 * in parallel; this driver doesn't match such hardware very well.
230 *
231 * Drivers can provide word-at-a-time i/o primitives, or provide
232 * transfer-at-a-time ones to leverage dma or fifo hardware.
233 */
234static void bitbang_work(void *_bitbang)
235{
236 struct spi_bitbang *bitbang = _bitbang;
237 unsigned long flags;
238
239 spin_lock_irqsave(&bitbang->lock, flags);
240 bitbang->busy = 1;
241 while (!list_empty(&bitbang->queue)) {
242 struct spi_message *m;
243 struct spi_device *spi;
244 unsigned nsecs;
245 struct spi_transfer *t = NULL;
246 unsigned tmp;
247 unsigned cs_change;
248 int status;
249
250 m = container_of(bitbang->queue.next, struct spi_message,
251 queue);
252 list_del_init(&m->queue);
253 spin_unlock_irqrestore(&bitbang->lock, flags);
254
255 /* FIXME this is made-up ... the correct value is known to
256 * word-at-a-time bitbang code, and presumably chipselect()
257 * should enforce these requirements too?
258 */
259 nsecs = 100;
260
261 spi = m->spi;
262 tmp = 0;
263 cs_change = 1;
264 status = 0;
265
266 list_for_each_entry (t, &m->transfers, transfer_list) {
267 if (bitbang->shutdown) {
268 status = -ESHUTDOWN;
269 break;
270 }
271
272 /* set up default clock polarity, and activate chip;
273 * this implicitly updates clock and spi modes as
274 * previously recorded for this device via setup().
275 * (and also deselects any other chip that might be
276 * selected ...)
277 */
278 if (cs_change) {
279 bitbang->chipselect(spi, BITBANG_CS_ACTIVE);
280 ndelay(nsecs);
281 }
282 cs_change = t->cs_change;
283 if (!t->tx_buf && !t->rx_buf && t->len) {
284 status = -EINVAL;
285 break;
286 }
287
288 /* transfer data. the lower level code handles any
289 * new dma mappings it needs. our caller always gave
290 * us dma-safe buffers.
291 */
292 if (t->len) {
293 /* REVISIT dma API still needs a designated
294 * DMA_ADDR_INVALID; ~0 might be better.
295 */
296 if (!m->is_dma_mapped)
297 t->rx_dma = t->tx_dma = 0;
298 status = bitbang->txrx_bufs(spi, t);
299 }
300 if (status != t->len) {
301 if (status > 0)
302 status = -EMSGSIZE;
303 break;
304 }
305 m->actual_length += status;
306 status = 0;
307
308 /* protocol tweaks before next transfer */
309 if (t->delay_usecs)
310 udelay(t->delay_usecs);
311
312 if (!cs_change)
313 continue;
314 if (t->transfer_list.next == &m->transfers)
315 break;
316
317 /* sometimes a short mid-message deselect of the chip
318 * may be needed to terminate a mode or command
319 */
320 ndelay(nsecs);
321 bitbang->chipselect(spi, BITBANG_CS_INACTIVE);
322 ndelay(nsecs);
323 }
324
325 m->status = status;
326 m->complete(m->context);
327
328 /* normally deactivate chipselect ... unless no error and
329 * cs_change has hinted that the next message will probably
330 * be for this chip too.
331 */
332 if (!(status == 0 && cs_change)) {
333 ndelay(nsecs);
334 bitbang->chipselect(spi, BITBANG_CS_INACTIVE);
335 ndelay(nsecs);
336 }
337
338 spin_lock_irqsave(&bitbang->lock, flags);
339 }
340 bitbang->busy = 0;
341 spin_unlock_irqrestore(&bitbang->lock, flags);
342}
343
344/**
345 * spi_bitbang_transfer - default submit to transfer queue
346 */
347int spi_bitbang_transfer(struct spi_device *spi, struct spi_message *m)
348{
349 struct spi_bitbang *bitbang;
350 unsigned long flags;
351
352 m->actual_length = 0;
353 m->status = -EINPROGRESS;
354
355 bitbang = spi_master_get_devdata(spi->master);
356 if (bitbang->shutdown)
357 return -ESHUTDOWN;
358
359 spin_lock_irqsave(&bitbang->lock, flags);
360 list_add_tail(&m->queue, &bitbang->queue);
361 queue_work(bitbang->workqueue, &bitbang->work);
362 spin_unlock_irqrestore(&bitbang->lock, flags);
363
364 return 0;
365}
366EXPORT_SYMBOL_GPL(spi_bitbang_transfer);
367
368/*----------------------------------------------------------------------*/
369
370/**
371 * spi_bitbang_start - start up a polled/bitbanging SPI master driver
372 * @bitbang: driver handle
373 *
374 * Caller should have zero-initialized all parts of the structure, and then
375 * provided callbacks for chip selection and I/O loops. If the master has
376 * a transfer method, its final step should call spi_bitbang_transfer; or,
377 * that's the default if the transfer routine is not initialized. It should
378 * also set up the bus number and number of chipselects.
379 *
380 * For i/o loops, provide callbacks either per-word (for bitbanging, or for
381 * hardware that basically exposes a shift register) or per-spi_transfer
382 * (which takes better advantage of hardware like fifos or DMA engines).
383 *
384 * Drivers using per-word I/O loops should use (or call) spi_bitbang_setup and
385 * spi_bitbang_cleanup to handle those spi master methods. Those methods are
386 * the defaults if the bitbang->txrx_bufs routine isn't initialized.
387 *
388 * This routine registers the spi_master, which will process requests in a
389 * dedicated task, keeping IRQs unblocked most of the time. To stop
390 * processing those requests, call spi_bitbang_stop().
391 */
392int spi_bitbang_start(struct spi_bitbang *bitbang)
393{
394 int status;
395
396 if (!bitbang->master || !bitbang->chipselect)
397 return -EINVAL;
398
399 INIT_WORK(&bitbang->work, bitbang_work, bitbang);
400 spin_lock_init(&bitbang->lock);
401 INIT_LIST_HEAD(&bitbang->queue);
402
403 if (!bitbang->master->transfer)
404 bitbang->master->transfer = spi_bitbang_transfer;
405 if (!bitbang->txrx_bufs) {
406 bitbang->use_dma = 0;
407 bitbang->txrx_bufs = spi_bitbang_bufs;
408 if (!bitbang->master->setup) {
409 bitbang->master->setup = spi_bitbang_setup;
410 bitbang->master->cleanup = spi_bitbang_cleanup;
411 }
412 } else if (!bitbang->master->setup)
413 return -EINVAL;
414
415 /* this task is the only thing to touch the SPI bits */
416 bitbang->busy = 0;
417 bitbang->workqueue = create_singlethread_workqueue(
418 bitbang->master->cdev.dev->bus_id);
419 if (bitbang->workqueue == NULL) {
420 status = -EBUSY;
421 goto err1;
422 }
423
424 /* driver may get busy before register() returns, especially
425 * if someone registered boardinfo for devices
426 */
427 status = spi_register_master(bitbang->master);
428 if (status < 0)
429 goto err2;
430
431 return status;
432
433err2:
434 destroy_workqueue(bitbang->workqueue);
435err1:
436 return status;
437}
438EXPORT_SYMBOL_GPL(spi_bitbang_start);
439
440/**
441 * spi_bitbang_stop - stops the task providing spi communication
442 */
443int spi_bitbang_stop(struct spi_bitbang *bitbang)
444{
445 unsigned limit = 500;
446
447 spin_lock_irq(&bitbang->lock);
448 bitbang->shutdown = 0;
449 while (!list_empty(&bitbang->queue) && limit--) {
450 spin_unlock_irq(&bitbang->lock);
451
452 dev_dbg(bitbang->master->cdev.dev, "wait for queue\n");
453 msleep(10);
454
455 spin_lock_irq(&bitbang->lock);
456 }
457 spin_unlock_irq(&bitbang->lock);
458 if (!list_empty(&bitbang->queue)) {
459 dev_err(bitbang->master->cdev.dev, "queue didn't empty\n");
460 return -EBUSY;
461 }
462
463 destroy_workqueue(bitbang->workqueue);
464
465 spi_unregister_master(bitbang->master);
466
467 return 0;
468}
469EXPORT_SYMBOL_GPL(spi_bitbang_stop);
470
471MODULE_LICENSE("GPL");
472
diff --git a/drivers/spi/spi_butterfly.c b/drivers/spi/spi_butterfly.c
new file mode 100644
index 000000000000..79a3c59615ab
--- /dev/null
+++ b/drivers/spi/spi_butterfly.c
@@ -0,0 +1,423 @@
1/*
2 * spi_butterfly.c - parport-to-butterfly adapter
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#include <linux/config.h>
21#include <linux/kernel.h>
22#include <linux/init.h>
23#include <linux/delay.h>
24#include <linux/platform_device.h>
25#include <linux/parport.h>
26
27#include <linux/spi/spi.h>
28#include <linux/spi/spi_bitbang.h>
29#include <linux/spi/flash.h>
30
31#include <linux/mtd/partitions.h>
32
33
34/*
35 * This uses SPI to talk with an "AVR Butterfly", which is a $US20 card
36 * with a battery powered AVR microcontroller and lots of goodies. You
37 * can use GCC to develop firmware for this.
38 *
39 * See Documentation/spi/butterfly for information about how to build
40 * and use this custom parallel port cable.
41 */
42
43#undef HAVE_USI /* nyet */
44
45
46/* DATA output bits (pins 2..9 == D0..D7) */
47#define butterfly_nreset (1 << 1) /* pin 3 */
48
49#define spi_sck_bit (1 << 0) /* pin 2 */
50#define spi_mosi_bit (1 << 7) /* pin 9 */
51
52#define usi_sck_bit (1 << 3) /* pin 5 */
53#define usi_mosi_bit (1 << 4) /* pin 6 */
54
55#define vcc_bits ((1 << 6) | (1 << 5)) /* pins 7, 8 */
56
57/* STATUS input bits */
58#define spi_miso_bit PARPORT_STATUS_BUSY /* pin 11 */
59
60#define usi_miso_bit PARPORT_STATUS_PAPEROUT /* pin 12 */
61
62/* CONTROL output bits */
63#define spi_cs_bit PARPORT_CONTROL_SELECT /* pin 17 */
64/* USI uses no chipselect */
65
66
67
68static inline struct butterfly *spidev_to_pp(struct spi_device *spi)
69{
70 return spi->controller_data;
71}
72
73static inline int is_usidev(struct spi_device *spi)
74{
75#ifdef HAVE_USI
76 return spi->chip_select != 1;
77#else
78 return 0;
79#endif
80}
81
82
83struct butterfly {
84 /* REVISIT ... for now, this must be first */
85 struct spi_bitbang bitbang;
86
87 struct parport *port;
88 struct pardevice *pd;
89
90 u8 lastbyte;
91
92 struct spi_device *dataflash;
93 struct spi_device *butterfly;
94 struct spi_board_info info[2];
95
96};
97
98/*----------------------------------------------------------------------*/
99
100/*
101 * these routines may be slower than necessary because they're hiding
102 * the fact that there are two different SPI busses on this cable: one
103 * to the DataFlash chip (or AVR SPI controller), the other to the
104 * AVR USI controller.
105 */
106
107static inline void
108setsck(struct spi_device *spi, int is_on)
109{
110 struct butterfly *pp = spidev_to_pp(spi);
111 u8 bit, byte = pp->lastbyte;
112
113 if (is_usidev(spi))
114 bit = usi_sck_bit;
115 else
116 bit = spi_sck_bit;
117
118 if (is_on)
119 byte |= bit;
120 else
121 byte &= ~bit;
122 parport_write_data(pp->port, byte);
123 pp->lastbyte = byte;
124}
125
126static inline void
127setmosi(struct spi_device *spi, int is_on)
128{
129 struct butterfly *pp = spidev_to_pp(spi);
130 u8 bit, byte = pp->lastbyte;
131
132 if (is_usidev(spi))
133 bit = usi_mosi_bit;
134 else
135 bit = spi_mosi_bit;
136
137 if (is_on)
138 byte |= bit;
139 else
140 byte &= ~bit;
141 parport_write_data(pp->port, byte);
142 pp->lastbyte = byte;
143}
144
145static inline int getmiso(struct spi_device *spi)
146{
147 struct butterfly *pp = spidev_to_pp(spi);
148 int value;
149 u8 bit;
150
151 if (is_usidev(spi))
152 bit = usi_miso_bit;
153 else
154 bit = spi_miso_bit;
155
156 /* only STATUS_BUSY is NOT negated */
157 value = !(parport_read_status(pp->port) & bit);
158 return (bit == PARPORT_STATUS_BUSY) ? value : !value;
159}
160
161static void butterfly_chipselect(struct spi_device *spi, int value)
162{
163 struct butterfly *pp = spidev_to_pp(spi);
164
165 /* set default clock polarity */
166 if (value)
167 setsck(spi, spi->mode & SPI_CPOL);
168
169 /* no chipselect on this USI link config */
170 if (is_usidev(spi))
171 return;
172
173 /* here, value == "activate or not" */
174
175 /* most PARPORT_CONTROL_* bits are negated */
176 if (spi_cs_bit == PARPORT_CONTROL_INIT)
177 value = !value;
178
179 /* here, value == "bit value to write in control register" */
180
181 parport_frob_control(pp->port, spi_cs_bit, value ? spi_cs_bit : 0);
182}
183
184
185/* we only needed to implement one mode here, and choose SPI_MODE_0 */
186
187#define spidelay(X) do{}while(0)
188//#define spidelay ndelay
189
190#define EXPAND_BITBANG_TXRX
191#include <linux/spi/spi_bitbang.h>
192
193static u32
194butterfly_txrx_word_mode0(struct spi_device *spi,
195 unsigned nsecs,
196 u32 word, u8 bits)
197{
198 return bitbang_txrx_be_cpha0(spi, nsecs, 0, word, bits);
199}
200
201/*----------------------------------------------------------------------*/
202
203/* override default partitioning with cmdlinepart */
204static struct mtd_partition partitions[] = { {
205 /* JFFS2 wants partitions of 4*N blocks for this device ... */
206
207 /* sector 0 = 8 pages * 264 bytes/page (1 block)
208 * sector 1 = 248 pages * 264 bytes/page
209 */
210 .name = "bookkeeping", // 66 KB
211 .offset = 0,
212 .size = (8 + 248) * 264,
213// .mask_flags = MTD_WRITEABLE,
214}, {
215 /* sector 2 = 256 pages * 264 bytes/page
216 * sectors 3-5 = 512 pages * 264 bytes/page
217 */
218 .name = "filesystem", // 462 KB
219 .offset = MTDPART_OFS_APPEND,
220 .size = MTDPART_SIZ_FULL,
221} };
222
223static struct flash_platform_data flash = {
224 .name = "butterflash",
225 .parts = partitions,
226 .nr_parts = ARRAY_SIZE(partitions),
227};
228
229
230/* REVISIT remove this ugly global and its "only one" limitation */
231static struct butterfly *butterfly;
232
233static void butterfly_attach(struct parport *p)
234{
235 struct pardevice *pd;
236 int status;
237 struct butterfly *pp;
238 struct spi_master *master;
239 struct platform_device *pdev;
240
241 if (butterfly)
242 return;
243
244 /* REVISIT: this just _assumes_ a butterfly is there ... no probe,
245 * and no way to be selective about what it binds to.
246 */
247
248 /* FIXME where should master->cdev.dev come from?
249 * e.g. /sys/bus/pnp0/00:0b, some PCI thing, etc
250 * setting up a platform device like this is an ugly kluge...
251 */
252 pdev = platform_device_register_simple("butterfly", -1, NULL, 0);
253
254 master = spi_alloc_master(&pdev->dev, sizeof *pp);
255 if (!master) {
256 status = -ENOMEM;
257 goto done;
258 }
259 pp = spi_master_get_devdata(master);
260
261 /*
262 * SPI and bitbang hookup
263 *
264 * use default setup(), cleanup(), and transfer() methods; and
265 * only bother implementing mode 0. Start it later.
266 */
267 master->bus_num = 42;
268 master->num_chipselect = 2;
269
270 pp->bitbang.master = spi_master_get(master);
271 pp->bitbang.chipselect = butterfly_chipselect;
272 pp->bitbang.txrx_word[SPI_MODE_0] = butterfly_txrx_word_mode0;
273
274 /*
275 * parport hookup
276 */
277 pp->port = p;
278 pd = parport_register_device(p, "spi_butterfly",
279 NULL, NULL, NULL,
280 0 /* FLAGS */, pp);
281 if (!pd) {
282 status = -ENOMEM;
283 goto clean0;
284 }
285 pp->pd = pd;
286
287 status = parport_claim(pd);
288 if (status < 0)
289 goto clean1;
290
291 /*
292 * Butterfly reset, powerup, run firmware
293 */
294 pr_debug("%s: powerup/reset Butterfly\n", p->name);
295
296 /* nCS for dataflash (this bit is inverted on output) */
297 parport_frob_control(pp->port, spi_cs_bit, 0);
298
299 /* stabilize power with chip in reset (nRESET), and
300 * both spi_sck_bit and usi_sck_bit clear (CPOL=0)
301 */
302 pp->lastbyte |= vcc_bits;
303 parport_write_data(pp->port, pp->lastbyte);
304 msleep(5);
305
306 /* take it out of reset; assume long reset delay */
307 pp->lastbyte |= butterfly_nreset;
308 parport_write_data(pp->port, pp->lastbyte);
309 msleep(100);
310
311
312 /*
313 * Start SPI ... for now, hide that we're two physical busses.
314 */
315 status = spi_bitbang_start(&pp->bitbang);
316 if (status < 0)
317 goto clean2;
318
319 /* Bus 1 lets us talk to at45db041b (firmware disables AVR)
320 * or AVR (firmware resets at45, acts as spi slave)
321 */
322 pp->info[0].max_speed_hz = 15 * 1000 * 1000;
323 strcpy(pp->info[0].modalias, "mtd_dataflash");
324 pp->info[0].platform_data = &flash;
325 pp->info[0].chip_select = 1;
326 pp->info[0].controller_data = pp;
327 pp->dataflash = spi_new_device(pp->bitbang.master, &pp->info[0]);
328 if (pp->dataflash)
329 pr_debug("%s: dataflash at %s\n", p->name,
330 pp->dataflash->dev.bus_id);
331
332#ifdef HAVE_USI
333 /* even more custom AVR firmware */
334 pp->info[1].max_speed_hz = 10 /* ?? */ * 1000 * 1000;
335 strcpy(pp->info[1].modalias, "butterfly");
336 // pp->info[1].platform_data = ... TBD ... ;
337 pp->info[1].chip_select = 2,
338 pp->info[1].controller_data = pp;
339 pp->butterfly = spi_new_device(pp->bitbang.master, &pp->info[1]);
340 if (pp->butterfly)
341 pr_debug("%s: butterfly at %s\n", p->name,
342 pp->butterfly->dev.bus_id);
343
344 /* FIXME setup ACK for the IRQ line ... */
345#endif
346
347 // dev_info(_what?_, ...)
348 pr_info("%s: AVR Butterfly\n", p->name);
349 butterfly = pp;
350 return;
351
352clean2:
353 /* turn off VCC */
354 parport_write_data(pp->port, 0);
355
356 parport_release(pp->pd);
357clean1:
358 parport_unregister_device(pd);
359clean0:
360 (void) spi_master_put(pp->bitbang.master);
361done:
362 platform_device_unregister(pdev);
363 pr_debug("%s: butterfly probe, fail %d\n", p->name, status);
364}
365
366static void butterfly_detach(struct parport *p)
367{
368 struct butterfly *pp;
369 struct platform_device *pdev;
370 int status;
371
372 /* FIXME this global is ugly ... but, how to quickly get from
373 * the parport to the "struct butterfly" associated with it?
374 * "old school" driver-internal device lists?
375 */
376 if (!butterfly || butterfly->port != p)
377 return;
378 pp = butterfly;
379 butterfly = NULL;
380
381#ifdef HAVE_USI
382 spi_unregister_device(pp->butterfly);
383 pp->butterfly = NULL;
384#endif
385 spi_unregister_device(pp->dataflash);
386 pp->dataflash = NULL;
387
388 status = spi_bitbang_stop(&pp->bitbang);
389
390 /* turn off VCC */
391 parport_write_data(pp->port, 0);
392 msleep(10);
393
394 parport_release(pp->pd);
395 parport_unregister_device(pp->pd);
396
397 pdev = to_platform_device(pp->bitbang.master->cdev.dev);
398
399 (void) spi_master_put(pp->bitbang.master);
400
401 platform_device_unregister(pdev);
402}
403
404static struct parport_driver butterfly_driver = {
405 .name = "spi_butterfly",
406 .attach = butterfly_attach,
407 .detach = butterfly_detach,
408};
409
410
411static int __init butterfly_init(void)
412{
413 return parport_register_driver(&butterfly_driver);
414}
415device_initcall(butterfly_init);
416
417static void __exit butterfly_exit(void)
418{
419 parport_unregister_driver(&butterfly_driver);
420}
421module_exit(butterfly_exit);
422
423MODULE_LICENSE("GPL");
diff --git a/include/linux/spi/ads7846.h b/include/linux/spi/ads7846.h
new file mode 100644
index 000000000000..72261e0f2ac1
--- /dev/null
+++ b/include/linux/spi/ads7846.h
@@ -0,0 +1,18 @@
1/* linux/spi/ads7846.h */
2
3/* Touchscreen characteristics vary between boards and models. The
4 * platform_data for the device's "struct device" holds this information.
5 *
6 * It's OK if the min/max values are zero.
7 */
8struct ads7846_platform_data {
9 u16 model; /* 7843, 7845, 7846. */
10 u16 vref_delay_usecs; /* 0 for external vref; etc */
11 u16 x_plate_ohms;
12 u16 y_plate_ohms;
13
14 u16 x_min, x_max;
15 u16 y_min, y_max;
16 u16 pressure_min, pressure_max;
17};
18
diff --git a/include/linux/spi/flash.h b/include/linux/spi/flash.h
new file mode 100644
index 000000000000..3f22932e67a4
--- /dev/null
+++ b/include/linux/spi/flash.h
@@ -0,0 +1,31 @@
1#ifndef LINUX_SPI_FLASH_H
2#define LINUX_SPI_FLASH_H
3
4struct mtd_partition;
5
6/**
7 * struct flash_platform_data: board-specific flash data
8 * @name: optional flash device name (eg, as used with mtdparts=)
9 * @parts: optional array of mtd_partitions for static partitioning
10 * @nr_parts: number of mtd_partitions for static partitoning
11 * @type: optional flash device type (e.g. m25p80 vs m25p64), for use
12 * with chips that can't be queried for JEDEC or other IDs
13 *
14 * Board init code (in arch/.../mach-xxx/board-yyy.c files) can
15 * provide information about SPI flash parts (such as DataFlash) to
16 * help set up the device and its appropriate default partitioning.
17 *
18 * Note that for DataFlash, sizes for pages, blocks, and sectors are
19 * rarely powers of two; and partitions should be sector-aligned.
20 */
21struct flash_platform_data {
22 char *name;
23 struct mtd_partition *parts;
24 unsigned int nr_parts;
25
26 char *type;
27
28 /* we'll likely add more ... use JEDEC IDs, etc */
29};
30
31#endif
diff --git a/include/linux/spi/spi.h b/include/linux/spi/spi.h
new file mode 100644
index 000000000000..b05f1463a267
--- /dev/null
+++ b/include/linux/spi/spi.h
@@ -0,0 +1,668 @@
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-side drivers and SPI infrastructure.
24 * (There's no SPI slave support for Linux yet...)
25 */
26extern struct bus_type spi_bus_type;
27
28/**
29 * struct spi_device - Master side proxy for an SPI slave device
30 * @dev: Driver model representation of the device.
31 * @master: SPI controller used with the device.
32 * @max_speed_hz: Maximum clock rate to be used with this chip
33 * (on this board); may be changed by the device's driver.
34 * @chip-select: Chipselect, distinguishing chips handled by "master".
35 * @mode: The spi mode defines how data is clocked out and in.
36 * This may be changed by the device's driver.
37 * @bits_per_word: Data transfers involve one or more words; word sizes
38 * like eight or 12 bits are common. In-memory wordsizes are
39 * powers of two bytes (e.g. 20 bit samples use 32 bits).
40 * This may be changed by the device's driver.
41 * @irq: Negative, or the number passed to request_irq() to receive
42 * interrupts from this device.
43 * @controller_state: Controller's runtime state
44 * @controller_data: Board-specific definitions for controller, such as
45 * FIFO initialization parameters; from board_info.controller_data
46 *
47 * An spi_device is used to interchange data between an SPI slave
48 * (usually a discrete chip) and CPU memory.
49 *
50 * In "dev", the platform_data is used to hold information about this
51 * device that's meaningful to the device's protocol driver, but not
52 * to its controller. One example might be an identifier for a chip
53 * variant with slightly different functionality.
54 */
55struct spi_device {
56 struct device dev;
57 struct spi_master *master;
58 u32 max_speed_hz;
59 u8 chip_select;
60 u8 mode;
61#define SPI_CPHA 0x01 /* clock phase */
62#define SPI_CPOL 0x02 /* clock polarity */
63#define SPI_MODE_0 (0|0) /* (original MicroWire) */
64#define SPI_MODE_1 (0|SPI_CPHA)
65#define SPI_MODE_2 (SPI_CPOL|0)
66#define SPI_MODE_3 (SPI_CPOL|SPI_CPHA)
67#define SPI_CS_HIGH 0x04 /* chipselect active high? */
68 u8 bits_per_word;
69 int irq;
70 void *controller_state;
71 void *controller_data;
72 const char *modalias;
73
74 // likely need more hooks for more protocol options affecting how
75 // the controller talks to each chip, like:
76 // - bit order (default is wordwise msb-first)
77 // - memory packing (12 bit samples into low bits, others zeroed)
78 // - priority
79 // - drop chipselect after each word
80 // - chipselect delays
81 // - ...
82};
83
84static inline struct spi_device *to_spi_device(struct device *dev)
85{
86 return dev ? container_of(dev, struct spi_device, dev) : NULL;
87}
88
89/* most drivers won't need to care about device refcounting */
90static inline struct spi_device *spi_dev_get(struct spi_device *spi)
91{
92 return (spi && get_device(&spi->dev)) ? spi : NULL;
93}
94
95static inline void spi_dev_put(struct spi_device *spi)
96{
97 if (spi)
98 put_device(&spi->dev);
99}
100
101/* ctldata is for the bus_master driver's runtime state */
102static inline void *spi_get_ctldata(struct spi_device *spi)
103{
104 return spi->controller_state;
105}
106
107static inline void spi_set_ctldata(struct spi_device *spi, void *state)
108{
109 spi->controller_state = state;
110}
111
112
113struct spi_message;
114
115
116
117struct spi_driver {
118 int (*probe)(struct spi_device *spi);
119 int (*remove)(struct spi_device *spi);
120 void (*shutdown)(struct spi_device *spi);
121 int (*suspend)(struct spi_device *spi, pm_message_t mesg);
122 int (*resume)(struct spi_device *spi);
123 struct device_driver driver;
124};
125
126static inline struct spi_driver *to_spi_driver(struct device_driver *drv)
127{
128 return drv ? container_of(drv, struct spi_driver, driver) : NULL;
129}
130
131extern int spi_register_driver(struct spi_driver *sdrv);
132
133static inline void spi_unregister_driver(struct spi_driver *sdrv)
134{
135 if (!sdrv)
136 return;
137 driver_unregister(&sdrv->driver);
138}
139
140
141
142/**
143 * struct spi_master - interface to SPI master controller
144 * @cdev: class interface to this driver
145 * @bus_num: board-specific (and often SOC-specific) identifier for a
146 * given SPI controller.
147 * @num_chipselect: chipselects are used to distinguish individual
148 * SPI slaves, and are numbered from zero to num_chipselects.
149 * each slave has a chipselect signal, but it's common that not
150 * every chipselect is connected to a slave.
151 * @setup: updates the device mode and clocking records used by a
152 * device's SPI controller; protocol code may call this.
153 * @transfer: adds a message to the controller's transfer queue.
154 * @cleanup: frees controller-specific state
155 *
156 * Each SPI master controller can communicate with one or more spi_device
157 * children. These make a small bus, sharing MOSI, MISO and SCK signals
158 * but not chip select signals. Each device may be configured to use a
159 * different clock rate, since those shared signals are ignored unless
160 * the chip is selected.
161 *
162 * The driver for an SPI controller manages access to those devices through
163 * a queue of spi_message transactions, copyin data between CPU memory and
164 * an SPI slave device). For each such message it queues, it calls the
165 * message's completion function when the transaction completes.
166 */
167struct spi_master {
168 struct class_device cdev;
169
170 /* other than zero (== assign one dynamically), bus_num is fully
171 * board-specific. usually that simplifies to being SOC-specific.
172 * example: one SOC has three SPI controllers, numbered 1..3,
173 * and one board's schematics might show it using SPI-2. software
174 * would normally use bus_num=2 for that controller.
175 */
176 u16 bus_num;
177
178 /* chipselects will be integral to many controllers; some others
179 * might use board-specific GPIOs.
180 */
181 u16 num_chipselect;
182
183 /* setup mode and clock, etc (spi driver may call many times) */
184 int (*setup)(struct spi_device *spi);
185
186 /* bidirectional bulk transfers
187 *
188 * + The transfer() method may not sleep; its main role is
189 * just to add the message to the queue.
190 * + For now there's no remove-from-queue operation, or
191 * any other request management
192 * + To a given spi_device, message queueing is pure fifo
193 *
194 * + The master's main job is to process its message queue,
195 * selecting a chip then transferring data
196 * + If there are multiple spi_device children, the i/o queue
197 * arbitration algorithm is unspecified (round robin, fifo,
198 * priority, reservations, preemption, etc)
199 *
200 * + Chipselect stays active during the entire message
201 * (unless modified by spi_transfer.cs_change != 0).
202 * + The message transfers use clock and SPI mode parameters
203 * previously established by setup() for this device
204 */
205 int (*transfer)(struct spi_device *spi,
206 struct spi_message *mesg);
207
208 /* called on release() to free memory provided by spi_master */
209 void (*cleanup)(const struct spi_device *spi);
210};
211
212static inline void *spi_master_get_devdata(struct spi_master *master)
213{
214 return class_get_devdata(&master->cdev);
215}
216
217static inline void spi_master_set_devdata(struct spi_master *master, void *data)
218{
219 class_set_devdata(&master->cdev, data);
220}
221
222static inline struct spi_master *spi_master_get(struct spi_master *master)
223{
224 if (!master || !class_device_get(&master->cdev))
225 return NULL;
226 return master;
227}
228
229static inline void spi_master_put(struct spi_master *master)
230{
231 if (master)
232 class_device_put(&master->cdev);
233}
234
235
236/* the spi driver core manages memory for the spi_master classdev */
237extern struct spi_master *
238spi_alloc_master(struct device *host, unsigned size);
239
240extern int spi_register_master(struct spi_master *master);
241extern void spi_unregister_master(struct spi_master *master);
242
243extern struct spi_master *spi_busnum_to_master(u16 busnum);
244
245/*---------------------------------------------------------------------------*/
246
247/*
248 * I/O INTERFACE between SPI controller and protocol drivers
249 *
250 * Protocol drivers use a queue of spi_messages, each transferring data
251 * between the controller and memory buffers.
252 *
253 * The spi_messages themselves consist of a series of read+write transfer
254 * segments. Those segments always read the same number of bits as they
255 * write; but one or the other is easily ignored by passing a null buffer
256 * pointer. (This is unlike most types of I/O API, because SPI hardware
257 * is full duplex.)
258 *
259 * NOTE: Allocation of spi_transfer and spi_message memory is entirely
260 * up to the protocol driver, which guarantees the integrity of both (as
261 * well as the data buffers) for as long as the message is queued.
262 */
263
264/**
265 * struct spi_transfer - a read/write buffer pair
266 * @tx_buf: data to be written (dma-safe memory), or NULL
267 * @rx_buf: data to be read (dma-safe memory), or NULL
268 * @tx_dma: DMA address of tx_buf, if spi_message.is_dma_mapped
269 * @rx_dma: DMA address of rx_buf, if spi_message.is_dma_mapped
270 * @len: size of rx and tx buffers (in bytes)
271 * @cs_change: affects chipselect after this transfer completes
272 * @delay_usecs: microseconds to delay after this transfer before
273 * (optionally) changing the chipselect status, then starting
274 * the next transfer or completing this spi_message.
275 * @transfer_list: transfers are sequenced through spi_message.transfers
276 *
277 * SPI transfers always write the same number of bytes as they read.
278 * Protocol drivers should always provide rx_buf and/or tx_buf.
279 * In some cases, they may also want to provide DMA addresses for
280 * the data being transferred; that may reduce overhead, when the
281 * underlying driver uses dma.
282 *
283 * If the transmit buffer is null, undefined data will be shifted out
284 * while filling rx_buf. If the receive buffer is null, the data
285 * shifted in will be discarded. Only "len" bytes shift out (or in).
286 * It's an error to try to shift out a partial word. (For example, by
287 * shifting out three bytes with word size of sixteen or twenty bits;
288 * the former uses two bytes per word, the latter uses four bytes.)
289 *
290 * All SPI transfers start with the relevant chipselect active. Normally
291 * it stays selected until after the last transfer in a message. Drivers
292 * can affect the chipselect signal using cs_change:
293 *
294 * (i) If the transfer isn't the last one in the message, this flag is
295 * used to make the chipselect briefly go inactive in the middle of the
296 * message. Toggling chipselect in this way may be needed to terminate
297 * a chip command, letting a single spi_message perform all of group of
298 * chip transactions together.
299 *
300 * (ii) When the transfer is the last one in the message, the chip may
301 * stay selected until the next transfer. This is purely a performance
302 * hint; the controller driver may need to select a different device
303 * for the next message.
304 *
305 * The code that submits an spi_message (and its spi_transfers)
306 * to the lower layers is responsible for managing its memory.
307 * Zero-initialize every field you don't set up explicitly, to
308 * insulate against future API updates. After you submit a message
309 * and its transfers, ignore them until its completion callback.
310 */
311struct spi_transfer {
312 /* it's ok if tx_buf == rx_buf (right?)
313 * for MicroWire, one buffer must be null
314 * buffers must work with dma_*map_single() calls, unless
315 * spi_message.is_dma_mapped reports a pre-existing mapping
316 */
317 const void *tx_buf;
318 void *rx_buf;
319 unsigned len;
320
321 dma_addr_t tx_dma;
322 dma_addr_t rx_dma;
323
324 unsigned cs_change:1;
325 u16 delay_usecs;
326
327 struct list_head transfer_list;
328};
329
330/**
331 * struct spi_message - one multi-segment SPI transaction
332 * @transfers: list of transfer segments in this transaction
333 * @spi: SPI device to which the transaction is queued
334 * @is_dma_mapped: if true, the caller provided both dma and cpu virtual
335 * addresses for each transfer buffer
336 * @complete: called to report transaction completions
337 * @context: the argument to complete() when it's called
338 * @actual_length: the total number of bytes that were transferred in all
339 * successful segments
340 * @status: zero for success, else negative errno
341 * @queue: for use by whichever driver currently owns the message
342 * @state: for use by whichever driver currently owns the message
343 *
344 * An spi_message is used to execute an atomic sequence of data transfers,
345 * each represented by a struct spi_transfer. The sequence is "atomic"
346 * in the sense that no other spi_message may use that SPI bus until that
347 * sequence completes. On some systems, many such sequences can execute as
348 * as single programmed DMA transfer. On all systems, these messages are
349 * queued, and might complete after transactions to other devices. Messages
350 * sent to a given spi_device are alway executed in FIFO order.
351 *
352 * The code that submits an spi_message (and its spi_transfers)
353 * to the lower layers is responsible for managing its memory.
354 * Zero-initialize every field you don't set up explicitly, to
355 * insulate against future API updates. After you submit a message
356 * and its transfers, ignore them until its completion callback.
357 */
358struct spi_message {
359 struct list_head transfers;
360
361 struct spi_device *spi;
362
363 unsigned is_dma_mapped:1;
364
365 /* REVISIT: we might want a flag affecting the behavior of the
366 * last transfer ... allowing things like "read 16 bit length L"
367 * immediately followed by "read L bytes". Basically imposing
368 * a specific message scheduling algorithm.
369 *
370 * Some controller drivers (message-at-a-time queue processing)
371 * could provide that as their default scheduling algorithm. But
372 * others (with multi-message pipelines) could need a flag to
373 * tell them about such special cases.
374 */
375
376 /* completion is reported through a callback */
377 void (*complete)(void *context);
378 void *context;
379 unsigned actual_length;
380 int status;
381
382 /* for optional use by whatever driver currently owns the
383 * spi_message ... between calls to spi_async and then later
384 * complete(), that's the spi_master controller driver.
385 */
386 struct list_head queue;
387 void *state;
388};
389
390static inline void spi_message_init(struct spi_message *m)
391{
392 memset(m, 0, sizeof *m);
393 INIT_LIST_HEAD(&m->transfers);
394}
395
396static inline void
397spi_message_add_tail(struct spi_transfer *t, struct spi_message *m)
398{
399 list_add_tail(&t->transfer_list, &m->transfers);
400}
401
402static inline void
403spi_transfer_del(struct spi_transfer *t)
404{
405 list_del(&t->transfer_list);
406}
407
408/* It's fine to embed message and transaction structures in other data
409 * structures so long as you don't free them while they're in use.
410 */
411
412static inline struct spi_message *spi_message_alloc(unsigned ntrans, gfp_t flags)
413{
414 struct spi_message *m;
415
416 m = kzalloc(sizeof(struct spi_message)
417 + ntrans * sizeof(struct spi_transfer),
418 flags);
419 if (m) {
420 int i;
421 struct spi_transfer *t = (struct spi_transfer *)(m + 1);
422
423 INIT_LIST_HEAD(&m->transfers);
424 for (i = 0; i < ntrans; i++, t++)
425 spi_message_add_tail(t, m);
426 }
427 return m;
428}
429
430static inline void spi_message_free(struct spi_message *m)
431{
432 kfree(m);
433}
434
435/**
436 * spi_setup -- setup SPI mode and clock rate
437 * @spi: the device whose settings are being modified
438 *
439 * SPI protocol drivers may need to update the transfer mode if the
440 * device doesn't work with the mode 0 default. They may likewise need
441 * to update clock rates or word sizes from initial values. This function
442 * changes those settings, and must be called from a context that can sleep.
443 * The changes take effect the next time the device is selected and data
444 * is transferred to or from it.
445 */
446static inline int
447spi_setup(struct spi_device *spi)
448{
449 return spi->master->setup(spi);
450}
451
452
453/**
454 * spi_async -- asynchronous SPI transfer
455 * @spi: device with which data will be exchanged
456 * @message: describes the data transfers, including completion callback
457 *
458 * This call may be used in_irq and other contexts which can't sleep,
459 * as well as from task contexts which can sleep.
460 *
461 * The completion callback is invoked in a context which can't sleep.
462 * Before that invocation, the value of message->status is undefined.
463 * When the callback is issued, message->status holds either zero (to
464 * indicate complete success) or a negative error code. After that
465 * callback returns, the driver which issued the transfer request may
466 * deallocate the associated memory; it's no longer in use by any SPI
467 * core or controller driver code.
468 *
469 * Note that although all messages to a spi_device are handled in
470 * FIFO order, messages may go to different devices in other orders.
471 * Some device might be higher priority, or have various "hard" access
472 * time requirements, for example.
473 *
474 * On detection of any fault during the transfer, processing of
475 * the entire message is aborted, and the device is deselected.
476 * Until returning from the associated message completion callback,
477 * no other spi_message queued to that device will be processed.
478 * (This rule applies equally to all the synchronous transfer calls,
479 * which are wrappers around this core asynchronous primitive.)
480 */
481static inline int
482spi_async(struct spi_device *spi, struct spi_message *message)
483{
484 message->spi = spi;
485 return spi->master->transfer(spi, message);
486}
487
488/*---------------------------------------------------------------------------*/
489
490/* All these synchronous SPI transfer routines are utilities layered
491 * over the core async transfer primitive. Here, "synchronous" means
492 * they will sleep uninterruptibly until the async transfer completes.
493 */
494
495extern int spi_sync(struct spi_device *spi, struct spi_message *message);
496
497/**
498 * spi_write - SPI synchronous write
499 * @spi: device to which data will be written
500 * @buf: data buffer
501 * @len: data buffer size
502 *
503 * This writes the buffer and returns zero or a negative error code.
504 * Callable only from contexts that can sleep.
505 */
506static inline int
507spi_write(struct spi_device *spi, const u8 *buf, size_t len)
508{
509 struct spi_transfer t = {
510 .tx_buf = buf,
511 .len = len,
512 };
513 struct spi_message m;
514
515 spi_message_init(&m);
516 spi_message_add_tail(&t, &m);
517 return spi_sync(spi, &m);
518}
519
520/**
521 * spi_read - SPI synchronous read
522 * @spi: device from which data will be read
523 * @buf: data buffer
524 * @len: data buffer size
525 *
526 * This writes the buffer and returns zero or a negative error code.
527 * Callable only from contexts that can sleep.
528 */
529static inline int
530spi_read(struct spi_device *spi, u8 *buf, size_t len)
531{
532 struct spi_transfer t = {
533 .rx_buf = buf,
534 .len = len,
535 };
536 struct spi_message m;
537
538 spi_message_init(&m);
539 spi_message_add_tail(&t, &m);
540 return spi_sync(spi, &m);
541}
542
543/* this copies txbuf and rxbuf data; for small transfers only! */
544extern int spi_write_then_read(struct spi_device *spi,
545 const u8 *txbuf, unsigned n_tx,
546 u8 *rxbuf, unsigned n_rx);
547
548/**
549 * spi_w8r8 - SPI synchronous 8 bit write followed by 8 bit read
550 * @spi: device with which data will be exchanged
551 * @cmd: command to be written before data is read back
552 *
553 * This returns the (unsigned) eight bit number returned by the
554 * device, or else a negative error code. Callable only from
555 * contexts that can sleep.
556 */
557static inline ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)
558{
559 ssize_t status;
560 u8 result;
561
562 status = spi_write_then_read(spi, &cmd, 1, &result, 1);
563
564 /* return negative errno or unsigned value */
565 return (status < 0) ? status : result;
566}
567
568/**
569 * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read
570 * @spi: device with which data will be exchanged
571 * @cmd: command to be written before data is read back
572 *
573 * This returns the (unsigned) sixteen bit number returned by the
574 * device, or else a negative error code. Callable only from
575 * contexts that can sleep.
576 *
577 * The number is returned in wire-order, which is at least sometimes
578 * big-endian.
579 */
580static inline ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)
581{
582 ssize_t status;
583 u16 result;
584
585 status = spi_write_then_read(spi, &cmd, 1, (u8 *) &result, 2);
586
587 /* return negative errno or unsigned value */
588 return (status < 0) ? status : result;
589}
590
591/*---------------------------------------------------------------------------*/
592
593/*
594 * INTERFACE between board init code and SPI infrastructure.
595 *
596 * No SPI driver ever sees these SPI device table segments, but
597 * it's how the SPI core (or adapters that get hotplugged) grows
598 * the driver model tree.
599 *
600 * As a rule, SPI devices can't be probed. Instead, board init code
601 * provides a table listing the devices which are present, with enough
602 * information to bind and set up the device's driver. There's basic
603 * support for nonstatic configurations too; enough to handle adding
604 * parport adapters, or microcontrollers acting as USB-to-SPI bridges.
605 */
606
607/* board-specific information about each SPI device */
608struct spi_board_info {
609 /* the device name and module name are coupled, like platform_bus;
610 * "modalias" is normally the driver name.
611 *
612 * platform_data goes to spi_device.dev.platform_data,
613 * controller_data goes to spi_device.controller_data,
614 * irq is copied too
615 */
616 char modalias[KOBJ_NAME_LEN];
617 const void *platform_data;
618 void *controller_data;
619 int irq;
620
621 /* slower signaling on noisy or low voltage boards */
622 u32 max_speed_hz;
623
624
625 /* bus_num is board specific and matches the bus_num of some
626 * spi_master that will probably be registered later.
627 *
628 * chip_select reflects how this chip is wired to that master;
629 * it's less than num_chipselect.
630 */
631 u16 bus_num;
632 u16 chip_select;
633
634 /* ... may need additional spi_device chip config data here.
635 * avoid stuff protocol drivers can set; but include stuff
636 * needed to behave without being bound to a driver:
637 * - chipselect polarity
638 * - quirks like clock rate mattering when not selected
639 */
640};
641
642#ifdef CONFIG_SPI
643extern int
644spi_register_board_info(struct spi_board_info const *info, unsigned n);
645#else
646/* board init code may ignore whether SPI is configured or not */
647static inline int
648spi_register_board_info(struct spi_board_info const *info, unsigned n)
649 { return 0; }
650#endif
651
652
653/* If you're hotplugging an adapter with devices (parport, usb, etc)
654 * use spi_new_device() to describe each device. You can also call
655 * spi_unregister_device() to start making that device vanish, but
656 * normally that would be handled by spi_unregister_master().
657 */
658extern struct spi_device *
659spi_new_device(struct spi_master *, struct spi_board_info *);
660
661static inline void
662spi_unregister_device(struct spi_device *spi)
663{
664 if (spi)
665 device_unregister(&spi->dev);
666}
667
668#endif /* __LINUX_SPI_H */
diff --git a/include/linux/spi/spi_bitbang.h b/include/linux/spi/spi_bitbang.h
new file mode 100644
index 000000000000..c961fe9bf3eb
--- /dev/null
+++ b/include/linux/spi/spi_bitbang.h
@@ -0,0 +1,135 @@
1#ifndef __SPI_BITBANG_H
2#define __SPI_BITBANG_H
3
4/*
5 * Mix this utility code with some glue code to get one of several types of
6 * simple SPI master driver. Two do polled word-at-a-time I/O:
7 *
8 * - GPIO/parport bitbangers. Provide chipselect() and txrx_word[](),
9 * expanding the per-word routines from the inline templates below.
10 *
11 * - Drivers for controllers resembling bare shift registers. Provide
12 * chipselect() and txrx_word[](), with custom setup()/cleanup() methods
13 * that use your controller's clock and chipselect registers.
14 *
15 * Some hardware works well with requests at spi_transfer scope:
16 *
17 * - Drivers leveraging smarter hardware, with fifos or DMA; or for half
18 * duplex (MicroWire) controllers. Provide chipslect() and txrx_bufs(),
19 * and custom setup()/cleanup() methods.
20 */
21struct spi_bitbang {
22 struct workqueue_struct *workqueue;
23 struct work_struct work;
24
25 spinlock_t lock;
26 struct list_head queue;
27 u8 busy;
28 u8 shutdown;
29 u8 use_dma;
30
31 struct spi_master *master;
32
33 void (*chipselect)(struct spi_device *spi, int is_on);
34#define BITBANG_CS_ACTIVE 1 /* normally nCS, active low */
35#define BITBANG_CS_INACTIVE 0
36
37 /* txrx_bufs() may handle dma mapping for transfers that don't
38 * already have one (transfer.{tx,rx}_dma is zero), or use PIO
39 */
40 int (*txrx_bufs)(struct spi_device *spi, struct spi_transfer *t);
41
42 /* txrx_word[SPI_MODE_*]() just looks like a shift register */
43 u32 (*txrx_word[4])(struct spi_device *spi,
44 unsigned nsecs,
45 u32 word, u8 bits);
46};
47
48/* you can call these default bitbang->master methods from your custom
49 * methods, if you like.
50 */
51extern int spi_bitbang_setup(struct spi_device *spi);
52extern void spi_bitbang_cleanup(const struct spi_device *spi);
53extern int spi_bitbang_transfer(struct spi_device *spi, struct spi_message *m);
54
55/* start or stop queue processing */
56extern int spi_bitbang_start(struct spi_bitbang *spi);
57extern int spi_bitbang_stop(struct spi_bitbang *spi);
58
59#endif /* __SPI_BITBANG_H */
60
61/*-------------------------------------------------------------------------*/
62
63#ifdef EXPAND_BITBANG_TXRX
64
65/*
66 * The code that knows what GPIO pins do what should have declared four
67 * functions, ideally as inlines, before #defining EXPAND_BITBANG_TXRX
68 * and including this header:
69 *
70 * void setsck(struct spi_device *, int is_on);
71 * void setmosi(struct spi_device *, int is_on);
72 * int getmiso(struct spi_device *);
73 * void spidelay(unsigned);
74 *
75 * A non-inlined routine would call bitbang_txrx_*() routines. The
76 * main loop could easily compile down to a handful of instructions,
77 * especially if the delay is a NOP (to run at peak speed).
78 *
79 * Since this is software, the timings may not be exactly what your board's
80 * chips need ... there may be several reasons you'd need to tweak timings
81 * in these routines, not just make to make it faster or slower to match a
82 * particular CPU clock rate.
83 */
84
85static inline u32
86bitbang_txrx_be_cpha0(struct spi_device *spi,
87 unsigned nsecs, unsigned cpol,
88 u32 word, u8 bits)
89{
90 /* if (cpol == 0) this is SPI_MODE_0; else this is SPI_MODE_2 */
91
92 /* clock starts at inactive polarity */
93 for (word <<= (32 - bits); likely(bits); bits--) {
94
95 /* setup MSB (to slave) on trailing edge */
96 setmosi(spi, word & (1 << 31));
97 spidelay(nsecs); /* T(setup) */
98
99 setsck(spi, !cpol);
100 spidelay(nsecs);
101
102 /* sample MSB (from slave) on leading edge */
103 word <<= 1;
104 word |= getmiso(spi);
105 setsck(spi, cpol);
106 }
107 return word;
108}
109
110static inline u32
111bitbang_txrx_be_cpha1(struct spi_device *spi,
112 unsigned nsecs, unsigned cpol,
113 u32 word, u8 bits)
114{
115 /* if (cpol == 0) this is SPI_MODE_1; else this is SPI_MODE_3 */
116
117 /* clock starts at inactive polarity */
118 for (word <<= (32 - bits); likely(bits); bits--) {
119
120 /* setup MSB (to slave) on leading edge */
121 setsck(spi, !cpol);
122 setmosi(spi, word & (1 << 31));
123 spidelay(nsecs); /* T(setup) */
124
125 setsck(spi, cpol);
126 spidelay(nsecs);
127
128 /* sample MSB (from slave) on trailing edge */
129 word <<= 1;
130 word |= getmiso(spi);
131 }
132 return word;
133}
134
135#endif /* EXPAND_BITBANG_TXRX */