···1+spi_butterfly - parport-to-butterfly adapter driver2+===================================================3+4+This is a hardware and software project that includes building and using5+a parallel port adapter cable, together with an "AVR Butterfly" to run6+firmware for user interfacing and/or sensors. A Butterfly is a $US207+battery powered card with an AVR microcontroller and lots of goodies:8+sensors, LCD, flash, toggle stick, and more. You can use AVR-GCC to9+develop firmware for this, and flash it using this adapter cable.10+11+You can make this adapter from an old printer cable and solder things12+directly to the Butterfly. Or (if you have the parts and skills) you13+can come up with something fancier, providing ciruit protection to the14+Butterfly and the printer port, or with a better power supply than two15+signal pins from the printer port.16+17+18+The first cable connections will hook Linux up to one SPI bus, with the19+AVR and a DataFlash chip; and to the AVR reset line. This is all you20+need to reflash the firmware, and the pins are the standard Atmel "ISP"21+connector pins (used also on non-Butterfly AVR boards).22+23+ Signal Butterfly Parport (DB-25)24+ ------ --------- ---------------25+ SCK = J403.PB1/SCK = pin 2/D026+ RESET = J403.nRST = pin 3/D127+ VCC = J403.VCC_EXT = pin 8/D628+ MOSI = J403.PB2/MOSI = pin 9/D729+ MISO = J403.PB3/MISO = pin 11/S7,nBUSY30+ GND = J403.GND = pin 23/GND31+32+Then to let Linux master that bus to talk to the DataFlash chip, you must33+(a) flash new firmware that disables SPI (set PRR.2, and disable pullups34+by clearing PORTB.[0-3]); (b) configure the mtd_dataflash driver; and35+(c) cable in the chipselect.36+37+ Signal Butterfly Parport (DB-25)38+ ------ --------- ---------------39+ VCC = J400.VCC_EXT = pin 7/D540+ SELECT = J400.PB0/nSS = pin 17/C3,nSELECT41+ GND = J400.GND = pin 24/GND42+43+The "USI" controller, using J405, can be used for a second SPI bus. That44+would let you talk to the AVR over SPI, running firmware that makes it act45+as an SPI slave, while letting either Linux or the AVR use the DataFlash.46+There 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/D351+ MOSI = J403.PE5/DI = pin 6/D452+ MISO = J403.PE6/DO = pin 12/S5,nPAPEROUT53+ GND = J403.GND = pin 22/GND54+55+ IRQ = J402.PF4 = pin 10/S6,ACK56+ GND = J402.GND(P2) = pin 25/GND57+
···1+Overview of Linux kernel SPI support2+====================================3+4+02-Dec-20055+6+What is SPI?7+------------8+The "Serial Peripheral Interface" (SPI) is a synchronous four wire serial9+link used to connect microcontrollers to sensors, memory, and peripherals.10+11+The three signal wires hold a clock (SCLK, often on the order of 10 MHz),12+and parallel data lines with "Master Out, Slave In" (MOSI) or "Master In,13+Slave Out" (MISO) signals. (Other names are also used.) There are four14+clocking modes through which data is exchanged; mode-0 and mode-3 are most15+commonly used. Each clock cycle shifts data out and data in; the clock16+doesn't cycle except when there is data to shift.17+18+SPI masters may use a "chip select" line to activate a given SPI slave19+device, so those three signal wires may be connected to several chips20+in parallel. All SPI slaves support chipselects. Some devices have21+other signals, often including an interrupt to the master.22+23+Unlike serial busses like USB or SMBUS, even low level protocols for24+SPI slave functions are usually not interoperable between vendors25+(except for cases like SPI memory chips).26+27+ - SPI may be used for request/response style device protocols, as with28+ 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 word34+ lengths, such as streams of 12-bit or 20-bit digital samples.35+36+In the same way, SPI slaves will only rarely support any kind of automatic37+discovery/enumeration protocol. The tree of slave devices accessible from38+a given SPI master will normally be set up manually, with configuration39+tables.40+41+SPI is only one of the names used by such four-wire protocols, and42+most controllers have no problem handling "MicroWire" (think of it as43+half-duplex SPI, for request/response protocols), SSP ("Synchronous44+Serial Protocol"), PSP ("Programmable Serial Protocol"), and other45+related protocols.46+47+Microcontrollers often support both master and slave sides of the SPI48+protocol. This document (and Linux) currently only supports the master49+side of SPI interactions.50+51+52+Who uses it? On what kinds of systems?53+---------------------------------------54+Linux developers using SPI are probably writing device drivers for embedded55+systems boards. SPI is used to control external chips, and it is also a56+protocol supported by every MMC or SD memory card. (The older "DataFlash"57+cards, predating MMC cards but using the same connectors and card shape,58+support only SPI.) Some PC hardware uses SPI flash for BIOS code.59+60+SPI slave chips range from digital/analog converters used for analog61+sensors and codecs, to memory, to peripherals like USB controllers62+or Ethernet adapters; and more.63+64+Most systems using SPI will integrate a few devices on a mainboard.65+Some provide SPI links on expansion connectors; in cases where no66+dedicated SPI controller exists, GPIO pins can be used to create a67+low speed "bitbanging" adapter. Very few systems will "hotplug" an SPI68+controller; the reasons to use SPI focus on low cost and simple operation,69+and if dynamic reconfiguration is important, USB will often be a more70+appropriate low-pincount peripheral bus.71+72+Many microcontrollers that can run Linux integrate one or more I/O73+interfaces with SPI modes. Given SPI support, they could use MMC or SD74+cards without needing a special purpose MMC/SD/SDIO controller.75+76+77+How do these driver programming interfaces work?78+------------------------------------------------79+The <linux/spi/spi.h> header file includes kerneldoc, as does the80+main source code, and you should certainly read that. This is just81+an overview, so you get the big picture before the details.82+83+SPI requests always go into I/O queues. Requests for a given SPI device84+are always executed in FIFO order, and complete asynchronously through85+completion callbacks. There are also some simple synchronous wrappers86+for those calls, including ones for common transaction types like writing87+a command and then reading its response.88+89+There are two types of SPI driver, here called:90+91+ Controller drivers ... these are often built in to System-On-Chip92+ 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 controller97+ driver to communicate with a Slave or Master device on the98+ other side of an SPI link.99+100+So for example one protocol driver might talk to the MTD layer to export101+data to filesystems stored on SPI flash like DataFlash; and others might102+control audio interfaces, present touchscreen sensors as input interfaces,103+or monitor temperature and voltage levels during industrial processing.104+And those might all be sharing the same controller driver.105+106+A "struct spi_device" encapsulates the master-side interface between107+those two types of driver. At this writing, Linux has no slave side108+programming interface.109+110+There is a minimal core of SPI programming interfaces, focussing on111+using driver model to connect controller and protocol drivers using112+device tables provided by board specific initialization code. SPI113+shows 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 driver119+ that should be used with this device (for hotplug/coldplug)120+121+ /sys/bus/spi/devices/spiB.C ... symlink to the physical122+ spiB-C device123+124+ /sys/bus/spi/drivers/D ... driver for one or more spi*.* devices125+126+ /sys/class/spi_master/spiB ... class device for the controller127+ managing bus "B". All the spiB.* devices share the same128+ physical SPI bus segment, with SCLK, MOSI, and MISO.129+130+131+How does board-specific init code declare SPI devices?132+------------------------------------------------------133+Linux needs several kinds of information to properly configure SPI devices.134+That information is normally provided by board-specific code, even for135+chips that do support some of automated discovery/enumeration.136+137+DECLARE CONTROLLERS138+139+The first kind of information is a list of what SPI controllers exist.140+For System-on-Chip (SOC) based boards, these will usually be platform141+devices, and the controller may need some platform_data in order to142+operate properly. The "struct platform_device" will include resources143+like the physical address of the controller's first register and its IRQ.144+145+Platforms will often abstract the "register SPI controller" operation,146+maybe coupling it with code to initialize pin configurations, so that147+the arch/.../mach-*/board-*.c files for several boards can all share the148+same basic controller setup code. This is because most SOCs have several149+SPI-capable controllers, and only the ones actually usable on a given150+board should normally be set up and registered.151+152+So 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 can157+ * 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+169+And 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 are187+ * visible on the relevant pins ... bootloaders on188+ * production boards may already have done this, but189+ * developer boards will often need Linux to do it.190+ */191+ }192+ ...193+ }194+195+Notice how the platform_data for boards may be different, even if the196+same SOC controller is used. For example, on one board SPI might use197+an external clock, where another derives the SPI clock from current198+settings of some master clock.199+200+201+DECLARE SLAVE DEVICES202+203+The second kind of information is a list of what SPI slave devices exist204+on the target board, often with some board-specific data needed for the205+driver to work correctly.206+207+Normally your arch/.../mach-*/board-*.c files would provide a small table208+listing the SPI devices on each board. (This would typically be only a209+small 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+229+Again, notice how board-specific information is provided; each chip may need230+several types. This example shows generic constraints like the fastest SPI231+clock to allow (a function of board voltage in this case) or how an IRQ pin232+is wired, plus chip-specific constraints like an important delay that's233+changed by the capacitance at one pin.234+235+(There's also "controller_data", information that may be useful to the236+controller driver. An example would be peripheral-specific DMA tuning237+data or chipselect callbacks. This is stored in spi_device later.)238+239+The board_info should provide enough information to let the system work240+without the chip's driver being loaded. The most troublesome aspect of241+that is likely the SPI_CS_HIGH bit in the spi_device.mode field, since242+sharing a bus with a device that interprets chipselect "backwards" is243+not possible.244+245+Then your board initialization code would register that table with the SPI246+infrastructure, so that it's available later when the SPI master controller247+driver is registered:248+249+ spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info));250+251+Like with other static board-specific setup, you won't unregister those.252+253+The widely used "card" style computers bundle memory, cpu, and little else254+onto a card that's maybe just thirty square centimeters. On such systems,255+your arch/.../mach-.../board-*.c file would primarily provide information256+about the devices on the mainboard into which such a card is plugged. That257+certainly includes SPI devices hooked up through the card connectors!258+259+260+NON-STATIC CONFIGURATIONS261+262+Developer boards often play by different rules than product boards, and one263+example is the potential need to hotplug SPI devices and/or controllers.264+265+For those cases you might need to use use spi_busnum_to_master() to look266+up the spi bus master, and will likely need spi_new_device() to provide the267+board info based on the board that was hotplugged. Of course, you'd later268+call at least spi_unregister_device() when that board is removed.269+270+When Linux includes support for MMC/SD/SDIO/DataFlash cards through SPI, those271+configurations will also be dynamic. Fortunately, those devices all support272+basic device identification probes, so that support should hotplug normally.273+274+275+How do I write an "SPI Protocol Driver"?276+----------------------------------------277+All SPI drivers are currently kernel drivers. A userspace driver API278+would just be another kernel driver, probably offering some lowlevel279+access through aio_read(), aio_write(), and ioctl() calls and using the280+standard userspace sysfs mechanisms to bind to a given SPI device.281+282+SPI 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+297+The driver core will autmatically attempt to bind this driver to any SPI298+device whose board_info gave a modalias of "CHIP". Your probe() code299+might 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+ ... etc318+ return 0;319+ }320+321+As soon as it enters probe(), the driver may issue I/O requests to322+the SPI device using "struct spi_message". When remove() returns,323+the driver guarantees that it won't submit any more such messages.324+325+ - An spi_message is a sequence of of protocol operations, executed326+ as one atomic sequence. SPI driver controls include:327+328+ + when bidirectional reads and writes start ... by how its329+ sequence of spi_transfer requests is arranged;330+331+ + optionally defining short delays after transfers ... using332+ the spi_transfer.delay_usecs setting;333+334+ + whether the chipselect becomes inactive after a transfer and335+ any delay ... by using the spi_transfer.cs_change flag;336+337+ + hinting whether the next message is likely to go to this same338+ device ... using the spi_transfer.cs_change flag on the last339+ transfer in that atomic group, and potentially saving costs340+ for chip deselect and select operations.341+342+ - Follow standard kernel rules, and provide DMA-safe buffers in343+ your messages. That way controller drivers using DMA aren't forced344+ to make extra copies unless the hardware requires it (e.g. working345+ 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 driver349+ that you've already provided the relevant DMA addresses.350+351+ - The basic I/O primitive is spi_async(). Async requests may be352+ issued in any context (irq handler, task, etc) and completion353+ is reported using a callback provided with the message.354+ After any detected error, the chip is deselected and processing355+ of that spi_message is aborted.356+357+ - There are also synchronous wrappers like spi_sync(), and wrappers358+ like spi_read(), spi_write(), and spi_write_then_read(). These359+ may be issued only in contexts that may sleep, and they're all360+ clean (and small, and "optional") layers over spi_async().361+362+ - The spi_write_then_read() call, and convenience wrappers around363+ it, should only be used with small amounts of data where the364+ cost of an extra copy may be ignored. It's designed to support365+ common RPC-style requests, such as writing an eight bit command366+ and reading a sixteen bit response -- spi_w8r16() being one its367+ wrappers, doing exactly that.368+369+Some drivers may need to modify spi_device characteristics like the370+transfer mode, wordsize, or clock rate. This is done with spi_setup(),371+which would normally be called from probe() before the first I/O is372+done to the device.373+374+While "spi_device" would be the bottom boundary of the driver, the375+upper boundaries might include sysfs (especially for sensor readings),376+the input layer, ALSA, networking, MTD, the character device framework,377+or other Linux subsystems.378+379+Note that there are two types of memory your driver must manage as part380+of 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 those387+ I/O buffers into a group of protocol transactions. These can388+ be allocated anywhere it's convenient, including as part of389+ other allocate-once driver data structures. Zero-init these.390+391+If you like, spi_message_alloc() and spi_message_free() convenience392+routines are available to allocate and zero-initialize an spi_message393+with several transfers.394+395+396+How do I write an "SPI Master Controller Driver"?397+-------------------------------------------------398+An SPI controller will probably be registered on the platform_bus; write399+a driver to bind to the device, whichever bus is involved.400+401+The main task of this type of driver is to provide an "spi_master".402+Use spi_alloc_master() to allocate the master, and class_get_devdata()403+to 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+414+The driver will initialize the fields of that spi_master, including the415+bus number (maybe the same as the platform device ID) and three methods416+used to interact with the SPI core and SPI protocol drivers. It will417+also 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 then422+ 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 the426+ transfer happens and its complete() callback is issued; the two427+ 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 hold431+ state it dynamically associates with that device. If you do that,432+ be sure to provide the cleanup() method to free that state.433+434+The bulk of the driver will be managing the I/O queue fed by transfer().435+436+That queue could be purely conceptual. For example, a driver used only437+for low-frequency sensor acess might be fine using synchronous PIO.438+439+But the queue will probably be very real, using message->queue, PIO,440+often DMA (especially if the root filesystem is in SPI flash), and441+execution contexts like IRQ handlers, tasklets, or workqueues (such442+as keventd). Your driver can be as fancy, or as simple, as you need.443+444+445+THANKS TO446+---------447+Contributors to Linux-SPI discussions include (in alphabetical order,448+by last name):449+450+David Brownell451+Russell King452+Dmitry Pervushin453+Stephen Street454+Mark Underwood455+Andrew Victor456+Vitaly Wool457+
···1112if INPUT_TOUCHSCREEN1314+config TOUCHSCREEN_ADS784615+ tristate "ADS 7846 based touchscreens"16+ depends on SPI_MASTER17+ help18+ Say Y here if you have a touchscreen interface using the19+ ADS7846 controller, and your board-specific initialization20+ 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: the25+ module will be called ads7846.26+27config TOUCHSCREEN_BITSY28 tristate "Compaq iPAQ H3600 (Bitsy) touchscreen"29 depends on SA1100_BITSY
+1
drivers/input/touchscreen/Makefile
···45# Each configuration option enables a list of files.607obj-$(CONFIG_TOUCHSCREEN_BITSY) += h3600_ts_input.o8obj-$(CONFIG_TOUCHSCREEN_CORGI) += corgi_ts.o9obj-$(CONFIG_TOUCHSCREEN_GUNZE) += gunze.o
···45# Each configuration option enables a list of files.67+obj-$(CONFIG_TOUCHSCREEN_ADS7846) += ads7846.o8obj-$(CONFIG_TOUCHSCREEN_BITSY) += h3600_ts_input.o9obj-$(CONFIG_TOUCHSCREEN_CORGI) += corgi_ts.o10obj-$(CONFIG_TOUCHSCREEN_GUNZE) += gunze.o
···1+/*2+ * ADS7846 based touchscreen and sensor driver3+ *4+ * Copyright (c) 2005 David Brownell5+ *6+ * Using code from:7+ * - corgi_ts.c8+ * Copyright (C) 2004-2005 Richard Purdie9+ * - omap_ts.[hc], ads7846.h, ts_osk.c10+ * Copyright (C) 2002 MontaVista Software11+ * Copyright (C) 2004 Texas Instruments12+ * Copyright (C) 2005 Dirk Behme13+ *14+ * This program is free software; you can redistribute it and/or modify15+ * it under the terms of the GNU General Public License version 2 as16+ * 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_ARM28+#include <asm/mach-types.h>29+#ifdef CONFIG_ARCH_OMAP30+#include <asm/arch/gpio.h>31+#endif32+33+#else34+#define set_irq_type(irq,type) do{}while(0)35+#endif36+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/pressure43+ * event values sane enough for X11? How accurate are the temperature44+ * and voltage readings? (System-specific calibration should support45+ * 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 (which49+ * can also be helped by using synch signals) and more generally.50+ */51+52+#define TS_POLL_PERIOD msecs_to_jiffies(10)53+54+struct ts_event {55+ /* For portability, we can't read 12 bit values using SPI (which56+ * would make the controller deliver them as native byteorder u1657+ * 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+65+struct 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 089+#define CS_CHANGE(xfer) ((xfer).cs_change = 1)90+#else91+#define CS_CHANGE(xfer) ((xfer).cs_change = 0)92+#endif93+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+123+static const u8 read_y = READ_12BIT_DFR(y) | ADS_PD10_ADC_ON;124+static const u8 read_z1 = READ_12BIT_DFR(z1) | ADS_PD10_ADC_ON;125+static const u8 read_z2 = READ_12BIT_DFR(z2) | ADS_PD10_ADC_ON;126+static 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 powered130+ */131+#define READ_12BIT_SER(x) (ADS_START | ADS_A2A1A0_ ## x \132+ | ADS_12_BIT | ADS_SER)133+134+static const u8 ref_on = READ_12BIT_DFR(x) | ADS_PD10_ALL_ON;135+static 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+143+struct ser_req {144+ u8 command;145+ u16 scratch;146+ __be16 sample;147+ struct spi_message msg;148+ struct spi_transfer xfer[6];149+};150+151+static 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 with196+ * reading touchscreen state; disable penirq while sampling197+ */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 \215+name ## _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+} \223+static DEVICE_ATTR(name, S_IRUGO, name ## _show, NULL);224+225+SHOW(temp0)226+SHOW(temp1)227+SHOW(vaux)228+SHOW(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 reports237+ * touchscreen events and reactivates the timer (or IRQ) as appropriate.238+ */239+240+static 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 from249+ * 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+ } else269+ Rt = 0;270+271+ /* NOTE: "pendown" is inferred from pressure; we don't rely on272+ * being able to check nPENIRQ status, or "friendly" trigger modes273+ * (both-edges is much better than just-falling or low-level).274+ *275+ * REVISIT: some boards may require reading nPENIRQ; it's276+ * needed on 7843. and 7845 reads pressure differently...277+ *278+ * REVISIT: the touchscreen might not be connected; this code279+ * 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 VERBOSE299+ 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+#endif303+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+322+static 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+343+static 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+351+static int352+ads7846_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 neatly370+ */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 always382+ * leave it that way after every request383+ */384+385+ spin_unlock_irqrestore(&ts->lock, flags);386+ return 0;387+}388+389+static 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+399+static 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 controllers424+ * will then treat the 8 bit command words as 12 bits (and drop the425+ * four MSBs of the 12 bit result). Result: inputs must be shifted426+ * 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 we468+ * 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; avoid524+ * 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, and530+ * use the other sensors a bit differently too531+ */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+543+static 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+567+static 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+579+static int __init ads7846_init(void)580+{581+ /* grr, board-specific init should stay out of drivers!! */582+583+#ifdef CONFIG_ARCH_OMAP584+ 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 FPGA592+ // also Nokia 770593+ // also Palm Tungsten T2594+#endif595+596+ // PXA:597+ // also Dell Axim X50598+ // also HP iPaq H191x/H192x/H415x/H435x599+ // also Intel Lubbock (additional to UCB1400; as temperature sensor)600+ // also Sharp Zaurus C7xx, C8xx (corgi/sheperd/husky)601+602+ // Atmel at91sam9261-EK uses ads7843603+604+ // also various AMD Au1x00 devel boards605+606+ return spi_register_driver(&ads7846_driver);607+}608+module_init(ads7846_init);609+610+static void __exit ads7846_exit(void)611+{612+ spi_unregister_driver(&ads7846_driver);613+614+#ifdef CONFIG_ARCH_OMAP615+ if (machine_is_omap_osk()) {616+ omap_free_gpio(4);617+ omap_free_gpio(6);618+ }619+#endif620+621+}622+module_exit(ads7846_exit);623+624+MODULE_DESCRIPTION("ADS7846 TouchScreen Driver");625+MODULE_LICENSE("GPL");
+16
drivers/mtd/devices/Kconfig
···47 accelerator. Say Y here if you have a DECstation 5000/2x0 or a48 DECsystem 5900 equipped with such a module.49000000000000000050config MTD_SLRAM51 tristate "Uncached system RAM"52 depends on MTD
···47 accelerator. Say Y here if you have a DECstation 5000/2x0 or a48 DECsystem 5900 equipped with such a module.4950+config MTD_DATAFLASH51+ tristate "Support for AT45xxx DataFlash"52+ depends on MTD && SPI_MASTER && EXPERIMENTAL53+ help54+ This enables access to AT45xxx DataFlash chips, using SPI.55+ Sometimes DataFlash chips are packaged inside MMC-format56+ cards; at this writing, the MMC stack won't handle those.57+58+config MTD_M25P8059+ tristate "Support for M25 SPI Flash"60+ depends on MTD && SPI_MASTER && EXPERIMENTAL61+ help62+ This enables access to ST M25P80 and similar SPI flash chips,63+ used for program and data storage. Set up your spi devices64+ with the right board-specific platform data.65+66config MTD_SLRAM67 tristate "Uncached system RAM"68 depends on MTD
···1+#2+# SPI driver configuration3+#4+# NOTE: the reason this doesn't show SPI slave support is mostly that5+# nobody's needed a slave side API yet. The master-role API is not6+# fully appropriate there, so it'd need some thought to do well.7+#8+menu "SPI support"9+10+config SPI11+ bool "SPI support"12+ help13+ The "Serial Peripheral Interface" is a low level synchronous14+ protocol. Chips that support SPI can have data transfer rates15+ up to several tens of Mbit/sec. Chips are addressed with a16+ controller and a chipselect. Most SPI slaves don't support17+ 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 controller21+ chips, analog to digital (and d-to-a) converters, and more.22+ MMC and SD cards can be accessed using SPI protocol; and for23+ 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 wire26+ interface (select, clock, data in, data out) including Microwire27+ (half duplex), SSP, SSI, and PSP. This driver framework should28+ work with most such devices and controllers.29+30+config SPI_DEBUG31+ boolean "Debug support for SPI drivers"32+ depends on SPI && DEBUG_KERNEL33+ help34+ 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 microcontrollers39+#40+41+config SPI_MASTER42+# boolean "SPI Master Support"43+ boolean44+ default SPI45+ help46+ If your system has an master-capable SPI controller (which47+ provides the clock and chipselect), you can enable that48+ controller and the protocol drivers for the SPI slave chips49+ that are connected.50+51+comment "SPI Master Controller Drivers"52+ depends on SPI_MASTER53+54+config SPI_BITBANG55+ tristate "Bitbanging SPI master"56+ depends on SPI_MASTER && EXPERIMENTAL57+ help58+ With a few GPIO pins, your system can bitbang the SPI protocol.59+ Select this to get SPI support through I/O pins (GPIO, parallel60+ port, etc). Or, some systems' SPI master controller drivers use61+ this code to manage the per-word or per-transfer accesses to the62+ hardware shift registers.63+64+ This is library code, and is automatically selected by drivers that65+ need it. You only need to select this explicitly to support driver66+ modules that aren't part of this kernel tree.67+68+config SPI_BUTTERFLY69+ tristate "Parallel port adapter for AVR Butterfly (DEVELOPMENT)"70+ depends on SPI_MASTER && PARPORT && EXPERIMENTAL71+ select SPI_BITBANG72+ help73+ This uses a custom parallel port cable to connect to an AVR74+ Butterfly <http://www.atmel.com/products/avr/butterfly>, an75+ inexpensive battery powered microcontroller evaluation board.76+ This same cable can be used to flash new firmware.77+78+config SPI_BUTTERFLY79+ tristate "Parallel port adapter for AVR Butterfly (DEVELOPMENT)"80+ depends on SPI_MASTER && PARPORT && EXPERIMENTAL81+ select SPI_BITBANG82+ help83+ This uses a custom parallel port cable to connect to an AVR84+ Butterfly <http://www.atmel.com/products/avr/butterfly>, an85+ 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 line90+#91+92+93+#94+# There are lots of SPI device types, with sensors and memory95+# being probably the most widely used ones.96+#97+comment "SPI Protocol Masters"98+ depends on SPI_MASTER99+100+101+#102+# Add new SPI protocol masters in alphabetical order above this line103+#104+105+106+# (slave support would go here)107+108+endmenu # "SPI support"109+
+25
drivers/spi/Makefile
···0000000000000000000000000
···1+#2+# Makefile for kernel SPI drivers.3+#4+5+ifeq ($(CONFIG_SPI_DEBUG),y)6+EXTRA_CFLAGS += -DDEBUG7+endif8+9+# small core, mostly translating board-specific10+# config declarations into driver model code11+obj-$(CONFIG_SPI_MASTER) += spi.o12+13+# SPI master controller drivers (bus)14+obj-$(CONFIG_SPI_BITBANG) += spi_bitbang.o15+obj-$(CONFIG_SPI_BUTTERFLY) += spi_butterfly.o16+# ... 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 ...
···1+/*2+ * spi.c - SPI init/core code3+ *4+ * Copyright (C) 2005 David Brownell5+ *6+ * This program is free software; you can redistribute it and/or modify7+ * it under the terms of the GNU General Public License as published by8+ * the Free Software Foundation; either version 2 of the License, or9+ * (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 of13+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14+ * GNU General Public License for more details.15+ *16+ * You should have received a copy of the GNU General Public License17+ * along with this program; if not, write to the Free Software18+ * 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 code30+ * provides the SPI device tables, ensuring that both are present by the31+ * time controller driver registration causes spi_devices to "enumerate".32+ */33+static 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+45+static ssize_t46+modalias_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+53+static 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+62+static 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+69+static 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_PM81+82+/*83+ * NOTE: the suspend() method for an spi_master controller driver84+ * should verify that all its child devices are marked as suspended;85+ * suspend requests delivered through sysfs power/state files don't86+ * enforce such constraints.87+ */88+static 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+103+static 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+#else119+#define spi_suspend NULL120+#define spi_resume NULL121+#endif122+123+struct 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+};131+EXPORT_SYMBOL_GPL(spi_bus_type);132+133+134+static 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+141+static 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+148+static 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+155+int 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+}166+EXPORT_SYMBOL_GPL(spi_register_driver);167+168+/*-------------------------------------------------------------------------*/169+170+/* SPI devices should normally not be created by SPI device drivers; that171+ * would make them board-specific. Similarly with SPI master drivers.172+ * Device registration normally goes into like arch/.../mach.../board-YYY.c173+ * with other readonly (flashable) information about mainboard devices.174+ */175+176+struct boardinfo {177+ struct list_head list;178+ unsigned n_board_info;179+ struct spi_board_info board_info[0];180+};181+182+static LIST_HEAD(board_list);183+static DECLARE_MUTEX(board_lock);184+185+186+/* On typical mainboards, this is purely internal; and it's not needed187+ * after board init creates the hard-wired devices. Some development188+ * platforms may not be able to use spi_register_board_info though, and189+ * this is exported so that for example a USB or parport based adapter190+ * driver could add devices (which it would learn about out-of-band).191+ */192+struct spi_device *__init_or_module193+spi_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 defining235+ * 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+246+fail:247+ spi_master_put(master);248+ kfree(proxy);249+ return NULL;250+}251+EXPORT_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 keep257+ * this table of devices forever, so that reloading a controller driver will258+ * 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 provide261+ * SPI devices through its expansion connector, so code initializing that board262+ * would naturally declare its SPI devices.263+ *264+ * The board info passed can safely be __initdata ... but be careful of265+ * any embedded pointers (platform_data, etc), they're copied as-is.266+ */267+int __init268+spi_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+}283+EXPORT_SYMBOL_GPL(spi_register_board_info);284+285+/* FIXME someone should add support for a __setup("spi", ...) that286+ * creates board info from kernel command lines287+ */288+289+static void __init_or_module290+scan_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 they304+ * might not use chipselects. otherwise, the305+ * chipselects are numbered 0..max.306+ */307+ if (chip->chip_select >= master->num_chipselect308+ && 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+322+static 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+330+static 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 controller339+ * @dev: the controller, possibly using the platform_bus340+ * @size: how much driver-private data to preallocate; the pointer to this341+ * 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 the345+ * only ones directly touching chip registers. It's how they allocate346+ * an spi_master structure, prior to calling spi_add_master().347+ *348+ * This must be called from context that can sleep. It returns the SPI349+ * master structure on success, else NULL.350+ *351+ * The caller is responsible for assigning the bus number and initializing352+ * the master's methods before calling spi_add_master(); and (after errors353+ * adding the device) calling spi_master_put() to prevent a memory leak.354+ */355+struct spi_master * __init_or_module356+spi_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+}374+EXPORT_SYMBOL_GPL(spi_alloc_master);375+376+/**377+ * spi_register_master - register SPI master controller378+ * @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 code382+ * 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 numbers386+ * with chip select numbers. Since SPI does not directly support dynamic387+ * device identification, boards need configuration tables telling which388+ * chip is at which address.389+ *390+ * This must be called from context that can sleep. It returns zero on391+ * success, else a negative error code (dropping the master's refcount).392+ * After a successful return, the caller is responsible for calling393+ * spi_unregister_master().394+ */395+int __init_or_module396+spi_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;426+done:427+ return status;428+}429+EXPORT_SYMBOL_GPL(spi_register_master);430+431+432+static 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 controller441+ * @master: the master being unregistered442+ *443+ * This call is used only by SPI master controller drivers, which are the444+ * only ones directly touching chip registers.445+ *446+ * This must be called from context that can sleep.447+ */448+void 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+}454+EXPORT_SYMBOL_GPL(spi_unregister_master);455+456+/**457+ * spi_busnum_to_master - look up master associated with bus_num458+ * @bus_num: the master's bus number459+ *460+ * This call may be used with devices that are registered after461+ * arch init time. It returns a refcounted pointer to the relevant462+ * spi_master (which the caller must release), or NULL if there is463+ * no such master registered.464+ */465+struct 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+}478+EXPORT_SYMBOL_GPL(spi_busnum_to_master);479+480+481+/*-------------------------------------------------------------------------*/482+483+static void spi_complete(void *arg)484+{485+ complete(arg);486+}487+488+/**489+ * spi_sync - blocking/synchronous SPI data transfers490+ * @spi: device with which data will be exchanged491+ * @message: describes the data transfers492+ *493+ * This call may only be used from a context that may sleep. The sleep494+ * is non-interruptible, and has no timeout. Low-overhead controller495+ * 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 some499+ * frequently-used devices may want to minimize costs of selecting a chip,500+ * by leaving it selected in anticipation that the next message will go501+ * to the same chip. (That may increase power usage.)502+ *503+ * Also, the caller is guaranteeing that the memory associated with the504+ * message will not be freed before this call returns.505+ *506+ * The return value is a negative error code if the message could not be507+ * submitted, else zero. When the value is zero, then message->status is508+ * also defined: it's the completion code for the transfer, either zero509+ * or a negative error code from the controller driver.510+ */511+int 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+}524+EXPORT_SYMBOL_GPL(spi_sync);525+526+#define SPI_BUFSIZ (SMP_CACHE_BYTES)527+528+static u8 *buf;529+530+/**531+ * spi_write_then_read - SPI synchronous write followed by read532+ * @spi: device with which data will be exchanged533+ * @txbuf: data to be written (need not be dma-safe)534+ * @n_tx: size of txbuf, in bytes535+ * @rxbuf: buffer into which data will be read536+ * @n_rx: size of rxbuf, in bytes (need not be dma-safe)537+ *538+ * This performs a half duplex MicroWire style transaction with the539+ * device, sending txbuf and then reading rxbuf. The return value540+ * 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 use545+ * spi_{async,sync}() calls with dma-safe buffers.546+ */547+int 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 costs560+ * 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+ } else582+ 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+ else598+ kfree(local_buf);599+600+ return status;601+}602+EXPORT_SYMBOL_GPL(spi_write_then_read);603+604+/*-------------------------------------------------------------------------*/605+606+static 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+625+err2:626+ bus_unregister(&spi_bus_type);627+err1:628+ kfree(buf);629+ buf = NULL;630+err0:631+ return status;632+}633+634+/* board_info is normally registered in arch_initcall(),635+ * but even essential drivers wait till later636+ *637+ * REVISIT only boardinfo really needs static linking. the rest (device and638+ * driver registration) _could_ be dynamically linked (modular) ... costs639+ * include needing to have boardinfo data structures be much more public.640+ */641+subsys_initcall(spi_init);642+
···1+/*2+ * spi_bitbang.c - polling/bitbanging SPI master controller driver utilities3+ *4+ * This program is free software; you can redistribute it and/or modify5+ * it under the terms of the GNU General Public License as published by6+ * the Free Software Foundation; either version 2 of the License, or7+ * (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 of11+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12+ * GNU General Public License for more details.13+ *14+ * You should have received a copy of the GNU General Public License15+ * along with this program; if not, write to the Free Software16+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA17+ */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 unavailable39+ * to glue code. These bitbang setup() and cleanup() routines are always40+ * used, though maybe they're called from controller-aware code.41+ *42+ * chipselect() and friends may use use spi_device->controller_data and43+ * 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 hardware48+ * working quickly, or testing for differences that aren't speed related.49+ */50+51+struct 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+63+static 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 *t70+) {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+89+static 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 *t96+) {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+115+static 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 *t122+) {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 loops143+ */144+int 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+ else171+ 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 adapter188+ * setup, unless the hardware defaults cooperate to avoid confusion189+ * 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+}202+EXPORT_SYMBOL_GPL(spi_bitbang_setup);203+204+/**205+ * spi_bitbang_cleanup - default cleanup for per-word I/O loops206+ */207+void spi_bitbang_cleanup(const struct spi_device *spi)208+{209+ kfree(spi->controller_state);210+}211+EXPORT_SYMBOL_GPL(spi_bitbang_cleanup);212+213+static 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 by227+ * performing each transfer in sequence. Smarter hardware can queue228+ * several DMA transfers at once, and process several controller queues229+ * in parallel; this driver doesn't match such hardware very well.230+ *231+ * Drivers can provide word-at-a-time i/o primitives, or provide232+ * transfer-at-a-time ones to leverage dma or fifo hardware.233+ */234+static 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 to256+ * 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 as274+ * previously recorded for this device via setup().275+ * (and also deselects any other chip that might be276+ * 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 any289+ * new dma mappings it needs. our caller always gave290+ * us dma-safe buffers.291+ */292+ if (t->len) {293+ /* REVISIT dma API still needs a designated294+ * 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 chip318+ * may be needed to terminate a mode or command319+ */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 and329+ * cs_change has hinted that the next message will probably330+ * 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 queue346+ */347+int 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+}366+EXPORT_SYMBOL_GPL(spi_bitbang_transfer);367+368+/*----------------------------------------------------------------------*/369+370+/**371+ * spi_bitbang_start - start up a polled/bitbanging SPI master driver372+ * @bitbang: driver handle373+ *374+ * Caller should have zero-initialized all parts of the structure, and then375+ * provided callbacks for chip selection and I/O loops. If the master has376+ * 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 should378+ * also set up the bus number and number of chipselects.379+ *380+ * For i/o loops, provide callbacks either per-word (for bitbanging, or for381+ * hardware that basically exposes a shift register) or per-spi_transfer382+ * (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 and385+ * spi_bitbang_cleanup to handle those spi master methods. Those methods are386+ * the defaults if the bitbang->txrx_bufs routine isn't initialized.387+ *388+ * This routine registers the spi_master, which will process requests in a389+ * dedicated task, keeping IRQs unblocked most of the time. To stop390+ * processing those requests, call spi_bitbang_stop().391+ */392+int 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, especially425+ * if someone registered boardinfo for devices426+ */427+ status = spi_register_master(bitbang->master);428+ if (status < 0)429+ goto err2;430+431+ return status;432+433+err2:434+ destroy_workqueue(bitbang->workqueue);435+err1:436+ return status;437+}438+EXPORT_SYMBOL_GPL(spi_bitbang_start);439+440+/**441+ * spi_bitbang_stop - stops the task providing spi communication442+ */443+int 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+}469+EXPORT_SYMBOL_GPL(spi_bitbang_stop);470+471+MODULE_LICENSE("GPL");472+
···1+/*2+ * spi_butterfly.c - parport-to-butterfly adapter3+ *4+ * Copyright (C) 2005 David Brownell5+ *6+ * This program is free software; you can redistribute it and/or modify7+ * it under the terms of the GNU General Public License as published by8+ * the Free Software Foundation; either version 2 of the License, or9+ * (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 of13+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14+ * GNU General Public License for more details.15+ *16+ * You should have received a copy of the GNU General Public License17+ * along with this program; if not, write to the Free Software18+ * 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 card36+ * with a battery powered AVR microcontroller and lots of goodies. You37+ * can use GCC to develop firmware for this.38+ *39+ * See Documentation/spi/butterfly for information about how to build40+ * 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+68+static inline struct butterfly *spidev_to_pp(struct spi_device *spi)69+{70+ return spi->controller_data;71+}72+73+static inline int is_usidev(struct spi_device *spi)74+{75+#ifdef HAVE_USI76+ return spi->chip_select != 1;77+#else78+ return 0;79+#endif80+}81+82+83+struct 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 hiding102+ * the fact that there are two different SPI busses on this cable: one103+ * to the DataFlash chip (or AVR SPI controller), the other to the104+ * AVR USI controller.105+ */106+107+static inline void108+setsck(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+ else116+ bit = spi_sck_bit;117+118+ if (is_on)119+ byte |= bit;120+ else121+ byte &= ~bit;122+ parport_write_data(pp->port, byte);123+ pp->lastbyte = byte;124+}125+126+static inline void127+setmosi(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+ else135+ bit = spi_mosi_bit;136+137+ if (is_on)138+ byte |= bit;139+ else140+ byte &= ~bit;141+ parport_write_data(pp->port, byte);142+ pp->lastbyte = byte;143+}144+145+static 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+ else154+ 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+161+static 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 ndelay189+190+#define EXPAND_BITBANG_TXRX191+#include <linux/spi/spi_bitbang.h>192+193+static u32194+butterfly_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 */204+static 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/page209+ */210+ .name = "bookkeeping", // 66 KB211+ .offset = 0,212+ .size = (8 + 248) * 264,213+// .mask_flags = MTD_WRITEABLE,214+}, {215+ /* sector 2 = 256 pages * 264 bytes/page216+ * sectors 3-5 = 512 pages * 264 bytes/page217+ */218+ .name = "filesystem", // 462 KB219+ .offset = MTDPART_OFS_APPEND,220+ .size = MTDPART_SIZ_FULL,221+} };222+223+static 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 */231+static struct butterfly *butterfly;232+233+static 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, etc250+ * 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 hookup263+ *264+ * use default setup(), cleanup(), and transfer() methods; and265+ * 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 hookup276+ */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 firmware293+ */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), and300+ * 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_USI333+ /* 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+#endif346+347+ // dev_info(_what?_, ...)348+ pr_info("%s: AVR Butterfly\n", p->name);349+ butterfly = pp;350+ return;351+352+clean2:353+ /* turn off VCC */354+ parport_write_data(pp->port, 0);355+356+ parport_release(pp->pd);357+clean1:358+ parport_unregister_device(pd);359+clean0:360+ (void) spi_master_put(pp->bitbang.master);361+done:362+ platform_device_unregister(pdev);363+ pr_debug("%s: butterfly probe, fail %d\n", p->name, status);364+}365+366+static 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 from373+ * 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_USI382+ spi_unregister_device(pp->butterfly);383+ pp->butterfly = NULL;384+#endif385+ 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+404+static struct parport_driver butterfly_driver = {405+ .name = "spi_butterfly",406+ .attach = butterfly_attach,407+ .detach = butterfly_detach,408+};409+410+411+static int __init butterfly_init(void)412+{413+ return parport_register_driver(&butterfly_driver);414+}415+device_initcall(butterfly_init);416+417+static void __exit butterfly_exit(void)418+{419+ parport_unregister_driver(&butterfly_driver);420+}421+module_exit(butterfly_exit);422+423+MODULE_LICENSE("GPL");
+18
include/linux/spi/ads7846.h
···000000000000000000
···1+/* linux/spi/ads7846.h */2+3+/* Touchscreen characteristics vary between boards and models. The4+ * platform_data for the device's "struct device" holds this information.5+ *6+ * It's OK if the min/max values are zero.7+ */8+struct 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+
+31
include/linux/spi/flash.h
···0000000000000000000000000000000
···1+#ifndef LINUX_SPI_FLASH_H2+#define LINUX_SPI_FLASH_H3+4+struct mtd_partition;5+6+/**7+ * struct flash_platform_data: board-specific flash data8+ * @name: optional flash device name (eg, as used with mtdparts=)9+ * @parts: optional array of mtd_partitions for static partitioning10+ * @nr_parts: number of mtd_partitions for static partitoning11+ * @type: optional flash device type (e.g. m25p80 vs m25p64), for use12+ * with chips that can't be queried for JEDEC or other IDs13+ *14+ * Board init code (in arch/.../mach-xxx/board-yyy.c files) can15+ * provide information about SPI flash parts (such as DataFlash) to16+ * help set up the device and its appropriate default partitioning.17+ *18+ * Note that for DataFlash, sizes for pages, blocks, and sectors are19+ * rarely powers of two; and partitions should be sector-aligned.20+ */21+struct 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
···1+/*2+ * Copyright (C) 2005 David Brownell3+ *4+ * This program is free software; you can redistribute it and/or modify5+ * it under the terms of the GNU General Public License as published by6+ * the Free Software Foundation; either version 2 of the License, or7+ * (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 of11+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12+ * GNU General Public License for more details.13+ *14+ * You should have received a copy of the GNU General Public License15+ * along with this program; if not, write to the Free Software16+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.17+ */18+19+#ifndef __LINUX_SPI_H20+#define __LINUX_SPI_H21+22+/*23+ * INTERFACES between SPI master-side drivers and SPI infrastructure.24+ * (There's no SPI slave support for Linux yet...)25+ */26+extern struct bus_type spi_bus_type;27+28+/**29+ * struct spi_device - Master side proxy for an SPI slave device30+ * @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 chip33+ * (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 sizes38+ * like eight or 12 bits are common. In-memory wordsizes are39+ * 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 receive42+ * interrupts from this device.43+ * @controller_state: Controller's runtime state44+ * @controller_data: Board-specific definitions for controller, such as45+ * FIFO initialization parameters; from board_info.controller_data46+ *47+ * An spi_device is used to interchange data between an SPI slave48+ * (usually a discrete chip) and CPU memory.49+ *50+ * In "dev", the platform_data is used to hold information about this51+ * device that's meaningful to the device's protocol driver, but not52+ * to its controller. One example might be an identifier for a chip53+ * variant with slightly different functionality.54+ */55+struct 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 how75+ // 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+ // - priority79+ // - drop chipselect after each word80+ // - chipselect delays81+ // - ...82+};83+84+static 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 */90+static inline struct spi_device *spi_dev_get(struct spi_device *spi)91+{92+ return (spi && get_device(&spi->dev)) ? spi : NULL;93+}94+95+static 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 */102+static inline void *spi_get_ctldata(struct spi_device *spi)103+{104+ return spi->controller_state;105+}106+107+static inline void spi_set_ctldata(struct spi_device *spi, void *state)108+{109+ spi->controller_state = state;110+}111+112+113+struct spi_message;114+115+116+117+struct 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+126+static 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+131+extern int spi_register_driver(struct spi_driver *sdrv);132+133+static 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 controller144+ * @cdev: class interface to this driver145+ * @bus_num: board-specific (and often SOC-specific) identifier for a146+ * given SPI controller.147+ * @num_chipselect: chipselects are used to distinguish individual148+ * SPI slaves, and are numbered from zero to num_chipselects.149+ * each slave has a chipselect signal, but it's common that not150+ * every chipselect is connected to a slave.151+ * @setup: updates the device mode and clocking records used by a152+ * 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 state155+ *156+ * Each SPI master controller can communicate with one or more spi_device157+ * children. These make a small bus, sharing MOSI, MISO and SCK signals158+ * but not chip select signals. Each device may be configured to use a159+ * different clock rate, since those shared signals are ignored unless160+ * the chip is selected.161+ *162+ * The driver for an SPI controller manages access to those devices through163+ * a queue of spi_message transactions, copyin data between CPU memory and164+ * an SPI slave device). For each such message it queues, it calls the165+ * message's completion function when the transaction completes.166+ */167+struct spi_master {168+ struct class_device cdev;169+170+ /* other than zero (== assign one dynamically), bus_num is fully171+ * 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. software174+ * would normally use bus_num=2 for that controller.175+ */176+ u16 bus_num;177+178+ /* chipselects will be integral to many controllers; some others179+ * 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 transfers187+ *188+ * + The transfer() method may not sleep; its main role is189+ * just to add the message to the queue.190+ * + For now there's no remove-from-queue operation, or191+ * any other request management192+ * + To a given spi_device, message queueing is pure fifo193+ *194+ * + The master's main job is to process its message queue,195+ * selecting a chip then transferring data196+ * + If there are multiple spi_device children, the i/o queue197+ * arbitration algorithm is unspecified (round robin, fifo,198+ * priority, reservations, preemption, etc)199+ *200+ * + Chipselect stays active during the entire message201+ * (unless modified by spi_transfer.cs_change != 0).202+ * + The message transfers use clock and SPI mode parameters203+ * previously established by setup() for this device204+ */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+212+static inline void *spi_master_get_devdata(struct spi_master *master)213+{214+ return class_get_devdata(&master->cdev);215+}216+217+static inline void spi_master_set_devdata(struct spi_master *master, void *data)218+{219+ class_set_devdata(&master->cdev, data);220+}221+222+static 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+229+static 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 */237+extern struct spi_master *238+spi_alloc_master(struct device *host, unsigned size);239+240+extern int spi_register_master(struct spi_master *master);241+extern void spi_unregister_master(struct spi_master *master);242+243+extern struct spi_master *spi_busnum_to_master(u16 busnum);244+245+/*---------------------------------------------------------------------------*/246+247+/*248+ * I/O INTERFACE between SPI controller and protocol drivers249+ *250+ * Protocol drivers use a queue of spi_messages, each transferring data251+ * between the controller and memory buffers.252+ *253+ * The spi_messages themselves consist of a series of read+write transfer254+ * segments. Those segments always read the same number of bits as they255+ * write; but one or the other is easily ignored by passing a null buffer256+ * pointer. (This is unlike most types of I/O API, because SPI hardware257+ * is full duplex.)258+ *259+ * NOTE: Allocation of spi_transfer and spi_message memory is entirely260+ * up to the protocol driver, which guarantees the integrity of both (as261+ * well as the data buffers) for as long as the message is queued.262+ */263+264+/**265+ * struct spi_transfer - a read/write buffer pair266+ * @tx_buf: data to be written (dma-safe memory), or NULL267+ * @rx_buf: data to be read (dma-safe memory), or NULL268+ * @tx_dma: DMA address of tx_buf, if spi_message.is_dma_mapped269+ * @rx_dma: DMA address of rx_buf, if spi_message.is_dma_mapped270+ * @len: size of rx and tx buffers (in bytes)271+ * @cs_change: affects chipselect after this transfer completes272+ * @delay_usecs: microseconds to delay after this transfer before273+ * (optionally) changing the chipselect status, then starting274+ * the next transfer or completing this spi_message.275+ * @transfer_list: transfers are sequenced through spi_message.transfers276+ *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 for280+ * the data being transferred; that may reduce overhead, when the281+ * underlying driver uses dma.282+ *283+ * If the transmit buffer is null, undefined data will be shifted out284+ * while filling rx_buf. If the receive buffer is null, the data285+ * 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, by287+ * 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. Normally291+ * it stays selected until after the last transfer in a message. Drivers292+ * can affect the chipselect signal using cs_change:293+ *294+ * (i) If the transfer isn't the last one in the message, this flag is295+ * used to make the chipselect briefly go inactive in the middle of the296+ * message. Toggling chipselect in this way may be needed to terminate297+ * a chip command, letting a single spi_message perform all of group of298+ * chip transactions together.299+ *300+ * (ii) When the transfer is the last one in the message, the chip may301+ * stay selected until the next transfer. This is purely a performance302+ * hint; the controller driver may need to select a different device303+ * 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, to308+ * insulate against future API updates. After you submit a message309+ * and its transfers, ignore them until its completion callback.310+ */311+struct spi_transfer {312+ /* it's ok if tx_buf == rx_buf (right?)313+ * for MicroWire, one buffer must be null314+ * buffers must work with dma_*map_single() calls, unless315+ * spi_message.is_dma_mapped reports a pre-existing mapping316+ */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 transaction332+ * @transfers: list of transfer segments in this transaction333+ * @spi: SPI device to which the transaction is queued334+ * @is_dma_mapped: if true, the caller provided both dma and cpu virtual335+ * addresses for each transfer buffer336+ * @complete: called to report transaction completions337+ * @context: the argument to complete() when it's called338+ * @actual_length: the total number of bytes that were transferred in all339+ * successful segments340+ * @status: zero for success, else negative errno341+ * @queue: for use by whichever driver currently owns the message342+ * @state: for use by whichever driver currently owns the message343+ *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 that347+ * sequence completes. On some systems, many such sequences can execute as348+ * as single programmed DMA transfer. On all systems, these messages are349+ * queued, and might complete after transactions to other devices. Messages350+ * 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, to355+ * insulate against future API updates. After you submit a message356+ * and its transfers, ignore them until its completion callback.357+ */358+struct 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 the366+ * last transfer ... allowing things like "read 16 bit length L"367+ * immediately followed by "read L bytes". Basically imposing368+ * 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. But372+ * others (with multi-message pipelines) could need a flag to373+ * 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 the383+ * spi_message ... between calls to spi_async and then later384+ * complete(), that's the spi_master controller driver.385+ */386+ struct list_head queue;387+ void *state;388+};389+390+static inline void spi_message_init(struct spi_message *m)391+{392+ memset(m, 0, sizeof *m);393+ INIT_LIST_HEAD(&m->transfers);394+}395+396+static inline void397+spi_message_add_tail(struct spi_transfer *t, struct spi_message *m)398+{399+ list_add_tail(&t->transfer_list, &m->transfers);400+}401+402+static inline void403+spi_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 data409+ * structures so long as you don't free them while they're in use.410+ */411+412+static 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+430+static inline void spi_message_free(struct spi_message *m)431+{432+ kfree(m);433+}434+435+/**436+ * spi_setup -- setup SPI mode and clock rate437+ * @spi: the device whose settings are being modified438+ *439+ * SPI protocol drivers may need to update the transfer mode if the440+ * device doesn't work with the mode 0 default. They may likewise need441+ * to update clock rates or word sizes from initial values. This function442+ * 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 data444+ * is transferred to or from it.445+ */446+static inline int447+spi_setup(struct spi_device *spi)448+{449+ return spi->master->setup(spi);450+}451+452+453+/**454+ * spi_async -- asynchronous SPI transfer455+ * @spi: device with which data will be exchanged456+ * @message: describes the data transfers, including completion callback457+ *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 (to464+ * indicate complete success) or a negative error code. After that465+ * callback returns, the driver which issued the transfer request may466+ * deallocate the associated memory; it's no longer in use by any SPI467+ * core or controller driver code.468+ *469+ * Note that although all messages to a spi_device are handled in470+ * FIFO order, messages may go to different devices in other orders.471+ * Some device might be higher priority, or have various "hard" access472+ * time requirements, for example.473+ *474+ * On detection of any fault during the transfer, processing of475+ * 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+ */481+static inline int482+spi_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 layered491+ * over the core async transfer primitive. Here, "synchronous" means492+ * they will sleep uninterruptibly until the async transfer completes.493+ */494+495+extern int spi_sync(struct spi_device *spi, struct spi_message *message);496+497+/**498+ * spi_write - SPI synchronous write499+ * @spi: device to which data will be written500+ * @buf: data buffer501+ * @len: data buffer size502+ *503+ * This writes the buffer and returns zero or a negative error code.504+ * Callable only from contexts that can sleep.505+ */506+static inline int507+spi_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 read522+ * @spi: device from which data will be read523+ * @buf: data buffer524+ * @len: data buffer size525+ *526+ * This writes the buffer and returns zero or a negative error code.527+ * Callable only from contexts that can sleep.528+ */529+static inline int530+spi_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! */544+extern 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 read550+ * @spi: device with which data will be exchanged551+ * @cmd: command to be written before data is read back552+ *553+ * This returns the (unsigned) eight bit number returned by the554+ * device, or else a negative error code. Callable only from555+ * contexts that can sleep.556+ */557+static 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 read570+ * @spi: device with which data will be exchanged571+ * @cmd: command to be written before data is read back572+ *573+ * This returns the (unsigned) sixteen bit number returned by the574+ * device, or else a negative error code. Callable only from575+ * contexts that can sleep.576+ *577+ * The number is returned in wire-order, which is at least sometimes578+ * big-endian.579+ */580+static 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, but597+ * it's how the SPI core (or adapters that get hotplugged) grows598+ * the driver model tree.599+ *600+ * As a rule, SPI devices can't be probed. Instead, board init code601+ * provides a table listing the devices which are present, with enough602+ * information to bind and set up the device's driver. There's basic603+ * support for nonstatic configurations too; enough to handle adding604+ * parport adapters, or microcontrollers acting as USB-to-SPI bridges.605+ */606+607+/* board-specific information about each SPI device */608+struct 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 too615+ */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 some626+ * 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 stuff636+ * needed to behave without being bound to a driver:637+ * - chipselect polarity638+ * - quirks like clock rate mattering when not selected639+ */640+};641+642+#ifdef CONFIG_SPI643+extern int644+spi_register_board_info(struct spi_board_info const *info, unsigned n);645+#else646+/* board init code may ignore whether SPI is configured or not */647+static inline int648+spi_register_board_info(struct spi_board_info const *info, unsigned n)649+ { return 0; }650+#endif651+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 call655+ * spi_unregister_device() to start making that device vanish, but656+ * normally that would be handled by spi_unregister_master().657+ */658+extern struct spi_device *659+spi_new_device(struct spi_master *, struct spi_board_info *);660+661+static inline void662+spi_unregister_device(struct spi_device *spi)663+{664+ if (spi)665+ device_unregister(&spi->dev);666+}667+668+#endif /* __LINUX_SPI_H */
···1+#ifndef __SPI_BITBANG_H2+#define __SPI_BITBANG_H3+4+/*5+ * Mix this utility code with some glue code to get one of several types of6+ * 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. Provide12+ * chipselect() and txrx_word[](), with custom setup()/cleanup() methods13+ * 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 half18+ * duplex (MicroWire) controllers. Provide chipslect() and txrx_bufs(),19+ * and custom setup()/cleanup() methods.20+ */21+struct 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 036+37+ /* txrx_bufs() may handle dma mapping for transfers that don't38+ * already have one (transfer.{tx,rx}_dma is zero), or use PIO39+ */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 custom49+ * methods, if you like.50+ */51+extern int spi_bitbang_setup(struct spi_device *spi);52+extern void spi_bitbang_cleanup(const struct spi_device *spi);53+extern int spi_bitbang_transfer(struct spi_device *spi, struct spi_message *m);54+55+/* start or stop queue processing */56+extern int spi_bitbang_start(struct spi_bitbang *spi);57+extern int spi_bitbang_stop(struct spi_bitbang *spi);58+59+#endif /* __SPI_BITBANG_H */60+61+/*-------------------------------------------------------------------------*/62+63+#ifdef EXPAND_BITBANG_TXRX64+65+/*66+ * The code that knows what GPIO pins do what should have declared four67+ * functions, ideally as inlines, before #defining EXPAND_BITBANG_TXRX68+ * 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. The76+ * 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's80+ * chips need ... there may be several reasons you'd need to tweak timings81+ * in these routines, not just make to make it faster or slower to match a82+ * particular CPU clock rate.83+ */84+85+static inline u3286+bitbang_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+110+static inline u32111+bitbang_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 */