···11+spi_butterfly - parport-to-butterfly adapter driver22+===================================================33+44+This is a hardware and software project that includes building and using55+a parallel port adapter cable, together with an "AVR Butterfly" to run66+firmware for user interfacing and/or sensors. A Butterfly is a $US2077+battery powered card with an AVR microcontroller and lots of goodies:88+sensors, LCD, flash, toggle stick, and more. You can use AVR-GCC to99+develop firmware for this, and flash it using this adapter cable.1010+1111+You can make this adapter from an old printer cable and solder things1212+directly to the Butterfly. Or (if you have the parts and skills) you1313+can come up with something fancier, providing ciruit protection to the1414+Butterfly and the printer port, or with a better power supply than two1515+signal pins from the printer port.1616+1717+1818+The first cable connections will hook Linux up to one SPI bus, with the1919+AVR and a DataFlash chip; and to the AVR reset line. This is all you2020+need to reflash the firmware, and the pins are the standard Atmel "ISP"2121+connector pins (used also on non-Butterfly AVR boards).2222+2323+ Signal Butterfly Parport (DB-25)2424+ ------ --------- ---------------2525+ SCK = J403.PB1/SCK = pin 2/D02626+ RESET = J403.nRST = pin 3/D12727+ VCC = J403.VCC_EXT = pin 8/D62828+ MOSI = J403.PB2/MOSI = pin 9/D72929+ MISO = J403.PB3/MISO = pin 11/S7,nBUSY3030+ GND = J403.GND = pin 23/GND3131+3232+Then to let Linux master that bus to talk to the DataFlash chip, you must3333+(a) flash new firmware that disables SPI (set PRR.2, and disable pullups3434+by clearing PORTB.[0-3]); (b) configure the mtd_dataflash driver; and3535+(c) cable in the chipselect.3636+3737+ Signal Butterfly Parport (DB-25)3838+ ------ --------- ---------------3939+ VCC = J400.VCC_EXT = pin 7/D54040+ SELECT = J400.PB0/nSS = pin 17/C3,nSELECT4141+ GND = J400.GND = pin 24/GND4242+4343+The "USI" controller, using J405, can be used for a second SPI bus. That4444+would let you talk to the AVR over SPI, running firmware that makes it act4545+as an SPI slave, while letting either Linux or the AVR use the DataFlash.4646+There are plenty of spare parport pins to wire this one up, such as:4747+4848+ Signal Butterfly Parport (DB-25)4949+ ------ --------- ---------------5050+ SCK = J403.PE4/USCK = pin 5/D35151+ MOSI = J403.PE5/DI = pin 6/D45252+ MISO = J403.PE6/DO = pin 12/S5,nPAPEROUT5353+ GND = J403.GND = pin 22/GND5454+5555+ IRQ = J402.PF4 = pin 10/S6,ACK5656+ GND = J402.GND(P2) = pin 25/GND5757+
+457
Documentation/spi/spi-summary
···11+Overview of Linux kernel SPI support22+====================================33+44+02-Dec-200555+66+What is SPI?77+------------88+The "Serial Peripheral Interface" (SPI) is a synchronous four wire serial99+link used to connect microcontrollers to sensors, memory, and peripherals.1010+1111+The three signal wires hold a clock (SCLK, often on the order of 10 MHz),1212+and parallel data lines with "Master Out, Slave In" (MOSI) or "Master In,1313+Slave Out" (MISO) signals. (Other names are also used.) There are four1414+clocking modes through which data is exchanged; mode-0 and mode-3 are most1515+commonly used. Each clock cycle shifts data out and data in; the clock1616+doesn't cycle except when there is data to shift.1717+1818+SPI masters may use a "chip select" line to activate a given SPI slave1919+device, so those three signal wires may be connected to several chips2020+in parallel. All SPI slaves support chipselects. Some devices have2121+other signals, often including an interrupt to the master.2222+2323+Unlike serial busses like USB or SMBUS, even low level protocols for2424+SPI slave functions are usually not interoperable between vendors2525+(except for cases like SPI memory chips).2626+2727+ - SPI may be used for request/response style device protocols, as with2828+ touchscreen sensors and memory chips.2929+3030+ - It may also be used to stream data in either direction (half duplex),3131+ or both of them at the same time (full duplex).3232+3333+ - Some devices may use eight bit words. Others may different word3434+ lengths, such as streams of 12-bit or 20-bit digital samples.3535+3636+In the same way, SPI slaves will only rarely support any kind of automatic3737+discovery/enumeration protocol. The tree of slave devices accessible from3838+a given SPI master will normally be set up manually, with configuration3939+tables.4040+4141+SPI is only one of the names used by such four-wire protocols, and4242+most controllers have no problem handling "MicroWire" (think of it as4343+half-duplex SPI, for request/response protocols), SSP ("Synchronous4444+Serial Protocol"), PSP ("Programmable Serial Protocol"), and other4545+related protocols.4646+4747+Microcontrollers often support both master and slave sides of the SPI4848+protocol. This document (and Linux) currently only supports the master4949+side of SPI interactions.5050+5151+5252+Who uses it? On what kinds of systems?5353+---------------------------------------5454+Linux developers using SPI are probably writing device drivers for embedded5555+systems boards. SPI is used to control external chips, and it is also a5656+protocol supported by every MMC or SD memory card. (The older "DataFlash"5757+cards, predating MMC cards but using the same connectors and card shape,5858+support only SPI.) Some PC hardware uses SPI flash for BIOS code.5959+6060+SPI slave chips range from digital/analog converters used for analog6161+sensors and codecs, to memory, to peripherals like USB controllers6262+or Ethernet adapters; and more.6363+6464+Most systems using SPI will integrate a few devices on a mainboard.6565+Some provide SPI links on expansion connectors; in cases where no6666+dedicated SPI controller exists, GPIO pins can be used to create a6767+low speed "bitbanging" adapter. Very few systems will "hotplug" an SPI6868+controller; the reasons to use SPI focus on low cost and simple operation,6969+and if dynamic reconfiguration is important, USB will often be a more7070+appropriate low-pincount peripheral bus.7171+7272+Many microcontrollers that can run Linux integrate one or more I/O7373+interfaces with SPI modes. Given SPI support, they could use MMC or SD7474+cards without needing a special purpose MMC/SD/SDIO controller.7575+7676+7777+How do these driver programming interfaces work?7878+------------------------------------------------7979+The <linux/spi/spi.h> header file includes kerneldoc, as does the8080+main source code, and you should certainly read that. This is just8181+an overview, so you get the big picture before the details.8282+8383+SPI requests always go into I/O queues. Requests for a given SPI device8484+are always executed in FIFO order, and complete asynchronously through8585+completion callbacks. There are also some simple synchronous wrappers8686+for those calls, including ones for common transaction types like writing8787+a command and then reading its response.8888+8989+There are two types of SPI driver, here called:9090+9191+ Controller drivers ... these are often built in to System-On-Chip9292+ processors, and often support both Master and Slave roles.9393+ These drivers touch hardware registers and may use DMA.9494+ Or they can be PIO bitbangers, needing just GPIO pins.9595+9696+ Protocol drivers ... these pass messages through the controller9797+ driver to communicate with a Slave or Master device on the9898+ other side of an SPI link.9999+100100+So for example one protocol driver might talk to the MTD layer to export101101+data to filesystems stored on SPI flash like DataFlash; and others might102102+control audio interfaces, present touchscreen sensors as input interfaces,103103+or monitor temperature and voltage levels during industrial processing.104104+And those might all be sharing the same controller driver.105105+106106+A "struct spi_device" encapsulates the master-side interface between107107+those two types of driver. At this writing, Linux has no slave side108108+programming interface.109109+110110+There is a minimal core of SPI programming interfaces, focussing on111111+using driver model to connect controller and protocol drivers using112112+device tables provided by board specific initialization code. SPI113113+shows up in sysfs in several locations:114114+115115+ /sys/devices/.../CTLR/spiB.C ... spi_device for on bus "B",116116+ chipselect C, accessed through CTLR.117117+118118+ /sys/devices/.../CTLR/spiB.C/modalias ... identifies the driver119119+ that should be used with this device (for hotplug/coldplug)120120+121121+ /sys/bus/spi/devices/spiB.C ... symlink to the physical122122+ spiB-C device123123+124124+ /sys/bus/spi/drivers/D ... driver for one or more spi*.* devices125125+126126+ /sys/class/spi_master/spiB ... class device for the controller127127+ managing bus "B". All the spiB.* devices share the same128128+ physical SPI bus segment, with SCLK, MOSI, and MISO.129129+130130+131131+How does board-specific init code declare SPI devices?132132+------------------------------------------------------133133+Linux needs several kinds of information to properly configure SPI devices.134134+That information is normally provided by board-specific code, even for135135+chips that do support some of automated discovery/enumeration.136136+137137+DECLARE CONTROLLERS138138+139139+The first kind of information is a list of what SPI controllers exist.140140+For System-on-Chip (SOC) based boards, these will usually be platform141141+devices, and the controller may need some platform_data in order to142142+operate properly. The "struct platform_device" will include resources143143+like the physical address of the controller's first register and its IRQ.144144+145145+Platforms will often abstract the "register SPI controller" operation,146146+maybe coupling it with code to initialize pin configurations, so that147147+the arch/.../mach-*/board-*.c files for several boards can all share the148148+same basic controller setup code. This is because most SOCs have several149149+SPI-capable controllers, and only the ones actually usable on a given150150+board should normally be set up and registered.151151+152152+So for example arch/.../mach-*/board-*.c files might have code like:153153+154154+ #include <asm/arch/spi.h> /* for mysoc_spi_data */155155+156156+ /* if your mach-* infrastructure doesn't support kernels that can157157+ * run on multiple boards, pdata wouldn't benefit from "__init".158158+ */159159+ static struct mysoc_spi_data __init pdata = { ... };160160+161161+ static __init board_init(void)162162+ {163163+ ...164164+ /* this board only uses SPI controller #2 */165165+ mysoc_register_spi(2, &pdata);166166+ ...167167+ }168168+169169+And SOC-specific utility code might look something like:170170+171171+ #include <asm/arch/spi.h>172172+173173+ static struct platform_device spi2 = { ... };174174+175175+ void mysoc_register_spi(unsigned n, struct mysoc_spi_data *pdata)176176+ {177177+ struct mysoc_spi_data *pdata2;178178+179179+ pdata2 = kmalloc(sizeof *pdata2, GFP_KERNEL);180180+ *pdata2 = pdata;181181+ ...182182+ if (n == 2) {183183+ spi2->dev.platform_data = pdata2;184184+ register_platform_device(&spi2);185185+186186+ /* also: set up pin modes so the spi2 signals are187187+ * visible on the relevant pins ... bootloaders on188188+ * production boards may already have done this, but189189+ * developer boards will often need Linux to do it.190190+ */191191+ }192192+ ...193193+ }194194+195195+Notice how the platform_data for boards may be different, even if the196196+same SOC controller is used. For example, on one board SPI might use197197+an external clock, where another derives the SPI clock from current198198+settings of some master clock.199199+200200+201201+DECLARE SLAVE DEVICES202202+203203+The second kind of information is a list of what SPI slave devices exist204204+on the target board, often with some board-specific data needed for the205205+driver to work correctly.206206+207207+Normally your arch/.../mach-*/board-*.c files would provide a small table208208+listing the SPI devices on each board. (This would typically be only a209209+small handful.) That might look like:210210+211211+ static struct ads7846_platform_data ads_info = {212212+ .vref_delay_usecs = 100,213213+ .x_plate_ohms = 580,214214+ .y_plate_ohms = 410,215215+ };216216+217217+ static struct spi_board_info spi_board_info[] __initdata = {218218+ {219219+ .modalias = "ads7846",220220+ .platform_data = &ads_info,221221+ .mode = SPI_MODE_0,222222+ .irq = GPIO_IRQ(31),223223+ .max_speed_hz = 120000 /* max sample rate at 3V */ * 16,224224+ .bus_num = 1,225225+ .chip_select = 0,226226+ },227227+ };228228+229229+Again, notice how board-specific information is provided; each chip may need230230+several types. This example shows generic constraints like the fastest SPI231231+clock to allow (a function of board voltage in this case) or how an IRQ pin232232+is wired, plus chip-specific constraints like an important delay that's233233+changed by the capacitance at one pin.234234+235235+(There's also "controller_data", information that may be useful to the236236+controller driver. An example would be peripheral-specific DMA tuning237237+data or chipselect callbacks. This is stored in spi_device later.)238238+239239+The board_info should provide enough information to let the system work240240+without the chip's driver being loaded. The most troublesome aspect of241241+that is likely the SPI_CS_HIGH bit in the spi_device.mode field, since242242+sharing a bus with a device that interprets chipselect "backwards" is243243+not possible.244244+245245+Then your board initialization code would register that table with the SPI246246+infrastructure, so that it's available later when the SPI master controller247247+driver is registered:248248+249249+ spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info));250250+251251+Like with other static board-specific setup, you won't unregister those.252252+253253+The widely used "card" style computers bundle memory, cpu, and little else254254+onto a card that's maybe just thirty square centimeters. On such systems,255255+your arch/.../mach-.../board-*.c file would primarily provide information256256+about the devices on the mainboard into which such a card is plugged. That257257+certainly includes SPI devices hooked up through the card connectors!258258+259259+260260+NON-STATIC CONFIGURATIONS261261+262262+Developer boards often play by different rules than product boards, and one263263+example is the potential need to hotplug SPI devices and/or controllers.264264+265265+For those cases you might need to use use spi_busnum_to_master() to look266266+up the spi bus master, and will likely need spi_new_device() to provide the267267+board info based on the board that was hotplugged. Of course, you'd later268268+call at least spi_unregister_device() when that board is removed.269269+270270+When Linux includes support for MMC/SD/SDIO/DataFlash cards through SPI, those271271+configurations will also be dynamic. Fortunately, those devices all support272272+basic device identification probes, so that support should hotplug normally.273273+274274+275275+How do I write an "SPI Protocol Driver"?276276+----------------------------------------277277+All SPI drivers are currently kernel drivers. A userspace driver API278278+would just be another kernel driver, probably offering some lowlevel279279+access through aio_read(), aio_write(), and ioctl() calls and using the280280+standard userspace sysfs mechanisms to bind to a given SPI device.281281+282282+SPI protocol drivers somewhat resemble platform device drivers:283283+284284+ static struct spi_driver CHIP_driver = {285285+ .driver = {286286+ .name = "CHIP",287287+ .bus = &spi_bus_type,288288+ .owner = THIS_MODULE,289289+ },290290+291291+ .probe = CHIP_probe,292292+ .remove = __devexit_p(CHIP_remove),293293+ .suspend = CHIP_suspend,294294+ .resume = CHIP_resume,295295+ };296296+297297+The driver core will autmatically attempt to bind this driver to any SPI298298+device whose board_info gave a modalias of "CHIP". Your probe() code299299+might look like this unless you're creating a class_device:300300+301301+ static int __devinit CHIP_probe(struct spi_device *spi)302302+ {303303+ struct CHIP *chip;304304+ struct CHIP_platform_data *pdata;305305+306306+ /* assuming the driver requires board-specific data: */307307+ pdata = &spi->dev.platform_data;308308+ if (!pdata)309309+ return -ENODEV;310310+311311+ /* get memory for driver's per-chip state */312312+ chip = kzalloc(sizeof *chip, GFP_KERNEL);313313+ if (!chip)314314+ return -ENOMEM;315315+ dev_set_drvdata(&spi->dev, chip);316316+317317+ ... etc318318+ return 0;319319+ }320320+321321+As soon as it enters probe(), the driver may issue I/O requests to322322+the SPI device using "struct spi_message". When remove() returns,323323+the driver guarantees that it won't submit any more such messages.324324+325325+ - An spi_message is a sequence of of protocol operations, executed326326+ as one atomic sequence. SPI driver controls include:327327+328328+ + when bidirectional reads and writes start ... by how its329329+ sequence of spi_transfer requests is arranged;330330+331331+ + optionally defining short delays after transfers ... using332332+ the spi_transfer.delay_usecs setting;333333+334334+ + whether the chipselect becomes inactive after a transfer and335335+ any delay ... by using the spi_transfer.cs_change flag;336336+337337+ + hinting whether the next message is likely to go to this same338338+ device ... using the spi_transfer.cs_change flag on the last339339+ transfer in that atomic group, and potentially saving costs340340+ for chip deselect and select operations.341341+342342+ - Follow standard kernel rules, and provide DMA-safe buffers in343343+ your messages. That way controller drivers using DMA aren't forced344344+ to make extra copies unless the hardware requires it (e.g. working345345+ around hardware errata that force the use of bounce buffering).346346+347347+ If standard dma_map_single() handling of these buffers is inappropriate,348348+ you can use spi_message.is_dma_mapped to tell the controller driver349349+ that you've already provided the relevant DMA addresses.350350+351351+ - The basic I/O primitive is spi_async(). Async requests may be352352+ issued in any context (irq handler, task, etc) and completion353353+ is reported using a callback provided with the message.354354+ After any detected error, the chip is deselected and processing355355+ of that spi_message is aborted.356356+357357+ - There are also synchronous wrappers like spi_sync(), and wrappers358358+ like spi_read(), spi_write(), and spi_write_then_read(). These359359+ may be issued only in contexts that may sleep, and they're all360360+ clean (and small, and "optional") layers over spi_async().361361+362362+ - The spi_write_then_read() call, and convenience wrappers around363363+ it, should only be used with small amounts of data where the364364+ cost of an extra copy may be ignored. It's designed to support365365+ common RPC-style requests, such as writing an eight bit command366366+ and reading a sixteen bit response -- spi_w8r16() being one its367367+ wrappers, doing exactly that.368368+369369+Some drivers may need to modify spi_device characteristics like the370370+transfer mode, wordsize, or clock rate. This is done with spi_setup(),371371+which would normally be called from probe() before the first I/O is372372+done to the device.373373+374374+While "spi_device" would be the bottom boundary of the driver, the375375+upper boundaries might include sysfs (especially for sensor readings),376376+the input layer, ALSA, networking, MTD, the character device framework,377377+or other Linux subsystems.378378+379379+Note that there are two types of memory your driver must manage as part380380+of interacting with SPI devices.381381+382382+ - I/O buffers use the usual Linux rules, and must be DMA-safe.383383+ You'd normally allocate them from the heap or free page pool.384384+ Don't use the stack, or anything that's declared "static".385385+386386+ - The spi_message and spi_transfer metadata used to glue those387387+ I/O buffers into a group of protocol transactions. These can388388+ be allocated anywhere it's convenient, including as part of389389+ other allocate-once driver data structures. Zero-init these.390390+391391+If you like, spi_message_alloc() and spi_message_free() convenience392392+routines are available to allocate and zero-initialize an spi_message393393+with several transfers.394394+395395+396396+How do I write an "SPI Master Controller Driver"?397397+-------------------------------------------------398398+An SPI controller will probably be registered on the platform_bus; write399399+a driver to bind to the device, whichever bus is involved.400400+401401+The main task of this type of driver is to provide an "spi_master".402402+Use spi_alloc_master() to allocate the master, and class_get_devdata()403403+to get the driver-private data allocated for that device.404404+405405+ struct spi_master *master;406406+ struct CONTROLLER *c;407407+408408+ master = spi_alloc_master(dev, sizeof *c);409409+ if (!master)410410+ return -ENODEV;411411+412412+ c = class_get_devdata(&master->cdev);413413+414414+The driver will initialize the fields of that spi_master, including the415415+bus number (maybe the same as the platform device ID) and three methods416416+used to interact with the SPI core and SPI protocol drivers. It will417417+also initialize its own internal state.418418+419419+ master->setup(struct spi_device *spi)420420+ This sets up the device clock rate, SPI mode, and word sizes.421421+ Drivers may change the defaults provided by board_info, and then422422+ call spi_setup(spi) to invoke this routine. It may sleep.423423+424424+ master->transfer(struct spi_device *spi, struct spi_message *message)425425+ This must not sleep. Its responsibility is arrange that the426426+ transfer happens and its complete() callback is issued; the two427427+ will normally happen later, after other transfers complete.428428+429429+ master->cleanup(struct spi_device *spi)430430+ Your controller driver may use spi_device.controller_state to hold431431+ state it dynamically associates with that device. If you do that,432432+ be sure to provide the cleanup() method to free that state.433433+434434+The bulk of the driver will be managing the I/O queue fed by transfer().435435+436436+That queue could be purely conceptual. For example, a driver used only437437+for low-frequency sensor acess might be fine using synchronous PIO.438438+439439+But the queue will probably be very real, using message->queue, PIO,440440+often DMA (especially if the root filesystem is in SPI flash), and441441+execution contexts like IRQ handlers, tasklets, or workqueues (such442442+as keventd). Your driver can be as fancy, or as simple, as you need.443443+444444+445445+THANKS TO446446+---------447447+Contributors to Linux-SPI discussions include (in alphabetical order,448448+by last name):449449+450450+David Brownell451451+Russell King452452+Dmitry Pervushin453453+Stephen Street454454+Mark Underwood455455+Andrew Victor456456+Vitaly Wool457457+
···11111212if INPUT_TOUCHSCREEN13131414+config TOUCHSCREEN_ADS78461515+ tristate "ADS 7846 based touchscreens"1616+ depends on SPI_MASTER1717+ help1818+ Say Y here if you have a touchscreen interface using the1919+ ADS7846 controller, and your board-specific initialization2020+ code includes that in its table of SPI devices.2121+2222+ If unsure, say N (but it's safe to say "Y").2323+2424+ To compile this driver as a module, choose M here: the2525+ module will be called ads7846.2626+1427config TOUCHSCREEN_BITSY1528 tristate "Compaq iPAQ H3600 (Bitsy) touchscreen"1629 depends on SA1100_BITSY
+1
drivers/input/touchscreen/Makefile
···4455# Each configuration option enables a list of files.6677+obj-$(CONFIG_TOUCHSCREEN_ADS7846) += ads7846.o78obj-$(CONFIG_TOUCHSCREEN_BITSY) += h3600_ts_input.o89obj-$(CONFIG_TOUCHSCREEN_CORGI) += corgi_ts.o910obj-$(CONFIG_TOUCHSCREEN_GUNZE) += gunze.o
+625
drivers/input/touchscreen/ads7846.c
···11+/*22+ * ADS7846 based touchscreen and sensor driver33+ *44+ * Copyright (c) 2005 David Brownell55+ *66+ * Using code from:77+ * - corgi_ts.c88+ * Copyright (C) 2004-2005 Richard Purdie99+ * - omap_ts.[hc], ads7846.h, ts_osk.c1010+ * Copyright (C) 2002 MontaVista Software1111+ * Copyright (C) 2004 Texas Instruments1212+ * Copyright (C) 2005 Dirk Behme1313+ *1414+ * This program is free software; you can redistribute it and/or modify1515+ * it under the terms of the GNU General Public License version 2 as1616+ * published by the Free Software Foundation.1717+ */1818+#include <linux/device.h>1919+#include <linux/init.h>2020+#include <linux/delay.h>2121+#include <linux/input.h>2222+#include <linux/interrupt.h>2323+#include <linux/slab.h>2424+#include <linux/spi/spi.h>2525+#include <linux/spi/ads7846.h>2626+2727+#ifdef CONFIG_ARM2828+#include <asm/mach-types.h>2929+#ifdef CONFIG_ARCH_OMAP3030+#include <asm/arch/gpio.h>3131+#endif3232+3333+#else3434+#define set_irq_type(irq,type) do{}while(0)3535+#endif3636+3737+3838+/*3939+ * This code has been lightly tested on an ads7846.4040+ * Support for ads7843 and ads7845 has only been stubbed in.4141+ *4242+ * Not yet done: investigate the values reported. Are x/y/pressure4343+ * event values sane enough for X11? How accurate are the temperature4444+ * and voltage readings? (System-specific calibration should support4545+ * accuracy of 0.3 degrees C; otherwise it's 2.0 degrees.)4646+ *4747+ * app note sbaa036 talks in more detail about accurate sampling...4848+ * that ought to help in situations like LCDs inducing noise (which4949+ * can also be helped by using synch signals) and more generally.5050+ */5151+5252+#define TS_POLL_PERIOD msecs_to_jiffies(10)5353+5454+struct ts_event {5555+ /* For portability, we can't read 12 bit values using SPI (which5656+ * would make the controller deliver them as native byteorder u165757+ * with msbs zeroed). Instead, we read them as two 8-byte values,5858+ * which need byteswapping then range adjustment.5959+ */6060+ __be16 x;6161+ __be16 y;6262+ __be16 z1, z2;6363+};6464+6565+struct ads7846 {6666+ struct input_dev input;6767+ char phys[32];6868+6969+ struct spi_device *spi;7070+ u16 model;7171+ u16 vref_delay_usecs;7272+ u16 x_plate_ohms;7373+7474+ struct ts_event tc;7575+7676+ struct spi_transfer xfer[8];7777+ struct spi_message msg;7878+7979+ spinlock_t lock;8080+ struct timer_list timer; /* P: lock */8181+ unsigned pendown:1; /* P: lock */8282+ unsigned pending:1; /* P: lock */8383+// FIXME remove "irq_disabled"8484+ unsigned irq_disabled:1; /* P: lock */8585+};8686+8787+/* leave chip selected when we're done, for quicker re-select? */8888+#if 08989+#define CS_CHANGE(xfer) ((xfer).cs_change = 1)9090+#else9191+#define CS_CHANGE(xfer) ((xfer).cs_change = 0)9292+#endif9393+9494+/*--------------------------------------------------------------------------*/9595+9696+/* The ADS7846 has touchscreen and other sensors.9797+ * Earlier ads784x chips are somewhat compatible.9898+ */9999+#define ADS_START (1 << 7)100100+#define ADS_A2A1A0_d_y (1 << 4) /* differential */101101+#define ADS_A2A1A0_d_z1 (3 << 4) /* differential */102102+#define ADS_A2A1A0_d_z2 (4 << 4) /* differential */103103+#define ADS_A2A1A0_d_x (5 << 4) /* differential */104104+#define ADS_A2A1A0_temp0 (0 << 4) /* non-differential */105105+#define ADS_A2A1A0_vbatt (2 << 4) /* non-differential */106106+#define ADS_A2A1A0_vaux (6 << 4) /* non-differential */107107+#define ADS_A2A1A0_temp1 (7 << 4) /* non-differential */108108+#define ADS_8_BIT (1 << 3)109109+#define ADS_12_BIT (0 << 3)110110+#define ADS_SER (1 << 2) /* non-differential */111111+#define ADS_DFR (0 << 2) /* differential */112112+#define ADS_PD10_PDOWN (0 << 0) /* lowpower mode + penirq */113113+#define ADS_PD10_ADC_ON (1 << 0) /* ADC on */114114+#define ADS_PD10_REF_ON (2 << 0) /* vREF on + penirq */115115+#define ADS_PD10_ALL_ON (3 << 0) /* ADC + vREF on */116116+117117+#define MAX_12BIT ((1<<12)-1)118118+119119+/* leave ADC powered up (disables penirq) between differential samples */120120+#define READ_12BIT_DFR(x) (ADS_START | ADS_A2A1A0_d_ ## x \121121+ | ADS_12_BIT | ADS_DFR)122122+123123+static const u8 read_y = READ_12BIT_DFR(y) | ADS_PD10_ADC_ON;124124+static const u8 read_z1 = READ_12BIT_DFR(z1) | ADS_PD10_ADC_ON;125125+static const u8 read_z2 = READ_12BIT_DFR(z2) | ADS_PD10_ADC_ON;126126+static const u8 read_x = READ_12BIT_DFR(x) | ADS_PD10_PDOWN; /* LAST */127127+128128+/* single-ended samples need to first power up reference voltage;129129+ * we leave both ADC and VREF powered130130+ */131131+#define READ_12BIT_SER(x) (ADS_START | ADS_A2A1A0_ ## x \132132+ | ADS_12_BIT | ADS_SER)133133+134134+static const u8 ref_on = READ_12BIT_DFR(x) | ADS_PD10_ALL_ON;135135+static const u8 ref_off = READ_12BIT_DFR(y) | ADS_PD10_PDOWN;136136+137137+/*--------------------------------------------------------------------------*/138138+139139+/*140140+ * Non-touchscreen sensors only use single-ended conversions.141141+ */142142+143143+struct ser_req {144144+ u8 command;145145+ u16 scratch;146146+ __be16 sample;147147+ struct spi_message msg;148148+ struct spi_transfer xfer[6];149149+};150150+151151+static int ads7846_read12_ser(struct device *dev, unsigned command)152152+{153153+ struct spi_device *spi = to_spi_device(dev);154154+ struct ads7846 *ts = dev_get_drvdata(dev);155155+ struct ser_req *req = kzalloc(sizeof *req, SLAB_KERNEL);156156+ int status;157157+ int sample;158158+ int i;159159+160160+ if (!req)161161+ return -ENOMEM;162162+163163+ INIT_LIST_HEAD(&req->msg.transfers);164164+165165+ /* activate reference, so it has time to settle; */166166+ req->xfer[0].tx_buf = &ref_on;167167+ req->xfer[0].len = 1;168168+ req->xfer[1].rx_buf = &req->scratch;169169+ req->xfer[1].len = 2;170170+171171+ /*172172+ * for external VREF, 0 usec (and assume it's always on);173173+ * for 1uF, use 800 usec;174174+ * no cap, 100 usec.175175+ */176176+ req->xfer[1].delay_usecs = ts->vref_delay_usecs;177177+178178+ /* take sample */179179+ req->command = (u8) command;180180+ req->xfer[2].tx_buf = &req->command;181181+ req->xfer[2].len = 1;182182+ req->xfer[3].rx_buf = &req->sample;183183+ req->xfer[3].len = 2;184184+185185+ /* REVISIT: take a few more samples, and compare ... */186186+187187+ /* turn off reference */188188+ req->xfer[4].tx_buf = &ref_off;189189+ req->xfer[4].len = 1;190190+ req->xfer[5].rx_buf = &req->scratch;191191+ req->xfer[5].len = 2;192192+193193+ CS_CHANGE(req->xfer[5]);194194+195195+ /* group all the transfers together, so we can't interfere with196196+ * reading touchscreen state; disable penirq while sampling197197+ */198198+ for (i = 0; i < 6; i++)199199+ spi_message_add_tail(&req->xfer[i], &req->msg);200200+201201+ disable_irq(spi->irq);202202+ status = spi_sync(spi, &req->msg);203203+ enable_irq(spi->irq);204204+205205+ if (req->msg.status)206206+ status = req->msg.status;207207+ sample = be16_to_cpu(req->sample);208208+ sample = sample >> 4;209209+ kfree(req);210210+211211+ return status ? status : sample;212212+}213213+214214+#define SHOW(name) static ssize_t \215215+name ## _show(struct device *dev, struct device_attribute *attr, char *buf) \216216+{ \217217+ ssize_t v = ads7846_read12_ser(dev, \218218+ READ_12BIT_SER(name) | ADS_PD10_ALL_ON); \219219+ if (v < 0) \220220+ return v; \221221+ return sprintf(buf, "%u\n", (unsigned) v); \222222+} \223223+static DEVICE_ATTR(name, S_IRUGO, name ## _show, NULL);224224+225225+SHOW(temp0)226226+SHOW(temp1)227227+SHOW(vaux)228228+SHOW(vbatt)229229+230230+/*--------------------------------------------------------------------------*/231231+232232+/*233233+ * PENIRQ only kicks the timer. The timer only reissues the SPI transfer,234234+ * to retrieve touchscreen status.235235+ *236236+ * The SPI transfer completion callback does the real work. It reports237237+ * touchscreen events and reactivates the timer (or IRQ) as appropriate.238238+ */239239+240240+static void ads7846_rx(void *ads)241241+{242242+ struct ads7846 *ts = ads;243243+ unsigned Rt;244244+ unsigned sync = 0;245245+ u16 x, y, z1, z2;246246+ unsigned long flags;247247+248248+ /* adjust: 12 bit samples (left aligned), built from249249+ * two 8 bit values writen msb-first.250250+ */251251+ x = be16_to_cpu(ts->tc.x) >> 4;252252+ y = be16_to_cpu(ts->tc.y) >> 4;253253+ z1 = be16_to_cpu(ts->tc.z1) >> 4;254254+ z2 = be16_to_cpu(ts->tc.z2) >> 4;255255+256256+ /* range filtering */257257+ if (x == MAX_12BIT)258258+ x = 0;259259+260260+ if (x && z1 && ts->spi->dev.power.power_state.event == PM_EVENT_ON) {261261+ /* compute touch pressure resistance using equation #2 */262262+ Rt = z2;263263+ Rt -= z1;264264+ Rt *= x;265265+ Rt *= ts->x_plate_ohms;266266+ Rt /= z1;267267+ Rt = (Rt + 2047) >> 12;268268+ } else269269+ Rt = 0;270270+271271+ /* NOTE: "pendown" is inferred from pressure; we don't rely on272272+ * being able to check nPENIRQ status, or "friendly" trigger modes273273+ * (both-edges is much better than just-falling or low-level).274274+ *275275+ * REVISIT: some boards may require reading nPENIRQ; it's276276+ * needed on 7843. and 7845 reads pressure differently...277277+ *278278+ * REVISIT: the touchscreen might not be connected; this code279279+ * won't notice that, even if nPENIRQ never fires ...280280+ */281281+ if (!ts->pendown && Rt != 0) {282282+ input_report_key(&ts->input, BTN_TOUCH, 1);283283+ sync = 1;284284+ } else if (ts->pendown && Rt == 0) {285285+ input_report_key(&ts->input, BTN_TOUCH, 0);286286+ sync = 1;287287+ }288288+289289+ if (Rt) {290290+ input_report_abs(&ts->input, ABS_X, x);291291+ input_report_abs(&ts->input, ABS_Y, y);292292+ input_report_abs(&ts->input, ABS_PRESSURE, Rt);293293+ sync = 1;294294+ }295295+ if (sync)296296+ input_sync(&ts->input);297297+298298+#ifdef VERBOSE299299+ if (Rt || ts->pendown)300300+ pr_debug("%s: %d/%d/%d%s\n", ts->spi->dev.bus_id,301301+ x, y, Rt, Rt ? "" : " UP");302302+#endif303303+304304+ /* don't retrigger while we're suspended */305305+ spin_lock_irqsave(&ts->lock, flags);306306+307307+ ts->pendown = (Rt != 0);308308+ ts->pending = 0;309309+310310+ if (ts->spi->dev.power.power_state.event == PM_EVENT_ON) {311311+ if (ts->pendown)312312+ mod_timer(&ts->timer, jiffies + TS_POLL_PERIOD);313313+ else if (ts->irq_disabled) {314314+ ts->irq_disabled = 0;315315+ enable_irq(ts->spi->irq);316316+ }317317+ }318318+319319+ spin_unlock_irqrestore(&ts->lock, flags);320320+}321321+322322+static void ads7846_timer(unsigned long handle)323323+{324324+ struct ads7846 *ts = (void *)handle;325325+ int status = 0;326326+ unsigned long flags;327327+328328+ spin_lock_irqsave(&ts->lock, flags);329329+ if (!ts->pending) {330330+ ts->pending = 1;331331+ if (!ts->irq_disabled) {332332+ ts->irq_disabled = 1;333333+ disable_irq(ts->spi->irq);334334+ }335335+ status = spi_async(ts->spi, &ts->msg);336336+ if (status)337337+ dev_err(&ts->spi->dev, "spi_async --> %d\n",338338+ status);339339+ }340340+ spin_unlock_irqrestore(&ts->lock, flags);341341+}342342+343343+static irqreturn_t ads7846_irq(int irq, void *handle, struct pt_regs *regs)344344+{345345+ ads7846_timer((unsigned long) handle);346346+ return IRQ_HANDLED;347347+}348348+349349+/*--------------------------------------------------------------------------*/350350+351351+static int352352+ads7846_suspend(struct spi_device *spi, pm_message_t message)353353+{354354+ struct ads7846 *ts = dev_get_drvdata(&spi->dev);355355+ unsigned long flags;356356+357357+ spin_lock_irqsave(&ts->lock, flags);358358+359359+ spi->dev.power.power_state = message;360360+361361+ /* are we waiting for IRQ, or polling? */362362+ if (!ts->pendown) {363363+ if (!ts->irq_disabled) {364364+ ts->irq_disabled = 1;365365+ disable_irq(ts->spi->irq);366366+ }367367+ } else {368368+ /* polling; force a final SPI completion;369369+ * that will clean things up neatly370370+ */371371+ if (!ts->pending)372372+ mod_timer(&ts->timer, jiffies);373373+374374+ while (ts->pendown || ts->pending) {375375+ spin_unlock_irqrestore(&ts->lock, flags);376376+ udelay(10);377377+ spin_lock_irqsave(&ts->lock, flags);378378+ }379379+ }380380+381381+ /* we know the chip's in lowpower mode since we always382382+ * leave it that way after every request383383+ */384384+385385+ spin_unlock_irqrestore(&ts->lock, flags);386386+ return 0;387387+}388388+389389+static int ads7846_resume(struct spi_device *spi)390390+{391391+ struct ads7846 *ts = dev_get_drvdata(&spi->dev);392392+393393+ ts->irq_disabled = 0;394394+ enable_irq(ts->spi->irq);395395+ spi->dev.power.power_state = PMSG_ON;396396+ return 0;397397+}398398+399399+static int __devinit ads7846_probe(struct spi_device *spi)400400+{401401+ struct ads7846 *ts;402402+ struct ads7846_platform_data *pdata = spi->dev.platform_data;403403+ struct spi_transfer *x;404404+ int i;405405+406406+ if (!spi->irq) {407407+ dev_dbg(&spi->dev, "no IRQ?\n");408408+ return -ENODEV;409409+ }410410+411411+ if (!pdata) {412412+ dev_dbg(&spi->dev, "no platform data?\n");413413+ return -ENODEV;414414+ }415415+416416+ /* don't exceed max specified sample rate */417417+ if (spi->max_speed_hz > (125000 * 16)) {418418+ dev_dbg(&spi->dev, "f(sample) %d KHz?\n",419419+ (spi->max_speed_hz/16)/1000);420420+ return -EINVAL;421421+ }422422+423423+ /* We'd set the wordsize to 12 bits ... except that some controllers424424+ * will then treat the 8 bit command words as 12 bits (and drop the425425+ * four MSBs of the 12 bit result). Result: inputs must be shifted426426+ * to discard the four garbage LSBs.427427+ */428428+429429+ if (!(ts = kzalloc(sizeof(struct ads7846), GFP_KERNEL)))430430+ return -ENOMEM;431431+432432+ dev_set_drvdata(&spi->dev, ts);433433+434434+ ts->spi = spi;435435+ spi->dev.power.power_state = PMSG_ON;436436+437437+ init_timer(&ts->timer);438438+ ts->timer.data = (unsigned long) ts;439439+ ts->timer.function = ads7846_timer;440440+441441+ ts->model = pdata->model ? : 7846;442442+ ts->vref_delay_usecs = pdata->vref_delay_usecs ? : 100;443443+ ts->x_plate_ohms = pdata->x_plate_ohms ? : 400;444444+445445+ init_input_dev(&ts->input);446446+447447+ ts->input.dev = &spi->dev;448448+ ts->input.name = "ADS784x Touchscreen";449449+ snprintf(ts->phys, sizeof ts->phys, "%s/input0", spi->dev.bus_id);450450+ ts->input.phys = ts->phys;451451+452452+ ts->input.evbit[0] = BIT(EV_KEY) | BIT(EV_ABS);453453+ ts->input.keybit[LONG(BTN_TOUCH)] = BIT(BTN_TOUCH);454454+ input_set_abs_params(&ts->input, ABS_X,455455+ pdata->x_min ? : 0,456456+ pdata->x_max ? : MAX_12BIT,457457+ 0, 0);458458+ input_set_abs_params(&ts->input, ABS_Y,459459+ pdata->y_min ? : 0,460460+ pdata->y_max ? : MAX_12BIT,461461+ 0, 0);462462+ input_set_abs_params(&ts->input, ABS_PRESSURE,463463+ pdata->pressure_min, pdata->pressure_max, 0, 0);464464+465465+ input_register_device(&ts->input);466466+467467+ /* set up the transfers to read touchscreen state; this assumes we468468+ * use formula #2 for pressure, not #3.469469+ */470470+ x = ts->xfer;471471+472472+ /* y- still on; turn on only y+ (and ADC) */473473+ x->tx_buf = &read_y;474474+ x->len = 1;475475+ x++;476476+ x->rx_buf = &ts->tc.y;477477+ x->len = 2;478478+ x++;479479+480480+ /* turn y+ off, x- on; we'll use formula #2 */481481+ if (ts->model == 7846) {482482+ x->tx_buf = &read_z1;483483+ x->len = 1;484484+ x++;485485+ x->rx_buf = &ts->tc.z1;486486+ x->len = 2;487487+ x++;488488+489489+ x->tx_buf = &read_z2;490490+ x->len = 1;491491+ x++;492492+ x->rx_buf = &ts->tc.z2;493493+ x->len = 2;494494+ x++;495495+ }496496+497497+ /* turn y- off, x+ on, then leave in lowpower */498498+ x->tx_buf = &read_x;499499+ x->len = 1;500500+ x++;501501+ x->rx_buf = &ts->tc.x;502502+ x->len = 2;503503+ x++;504504+505505+ CS_CHANGE(x[-1]);506506+507507+ for (i = 0; i < x - ts->xfer; i++)508508+ spi_message_add_tail(&ts->xfer[i], &ts->msg);509509+ ts->msg.complete = ads7846_rx;510510+ ts->msg.context = ts;511511+512512+ if (request_irq(spi->irq, ads7846_irq, SA_SAMPLE_RANDOM,513513+ spi->dev.bus_id, ts)) {514514+ dev_dbg(&spi->dev, "irq %d busy?\n", spi->irq);515515+ input_unregister_device(&ts->input);516516+ kfree(ts);517517+ return -EBUSY;518518+ }519519+ set_irq_type(spi->irq, IRQT_FALLING);520520+521521+ dev_info(&spi->dev, "touchscreen, irq %d\n", spi->irq);522522+523523+ /* take a first sample, leaving nPENIRQ active; avoid524524+ * the touchscreen, in case it's not connected.525525+ */526526+ (void) ads7846_read12_ser(&spi->dev,527527+ READ_12BIT_SER(vaux) | ADS_PD10_ALL_ON);528528+529529+ /* ads7843/7845 don't have temperature sensors, and530530+ * use the other sensors a bit differently too531531+ */532532+ if (ts->model == 7846) {533533+ device_create_file(&spi->dev, &dev_attr_temp0);534534+ device_create_file(&spi->dev, &dev_attr_temp1);535535+ }536536+ if (ts->model != 7845)537537+ device_create_file(&spi->dev, &dev_attr_vbatt);538538+ device_create_file(&spi->dev, &dev_attr_vaux);539539+540540+ return 0;541541+}542542+543543+static int __devexit ads7846_remove(struct spi_device *spi)544544+{545545+ struct ads7846 *ts = dev_get_drvdata(&spi->dev);546546+547547+ ads7846_suspend(spi, PMSG_SUSPEND);548548+ free_irq(ts->spi->irq, ts);549549+ if (ts->irq_disabled)550550+ enable_irq(ts->spi->irq);551551+552552+ if (ts->model == 7846) {553553+ device_remove_file(&spi->dev, &dev_attr_temp0);554554+ device_remove_file(&spi->dev, &dev_attr_temp1);555555+ }556556+ if (ts->model != 7845)557557+ device_remove_file(&spi->dev, &dev_attr_vbatt);558558+ device_remove_file(&spi->dev, &dev_attr_vaux);559559+560560+ input_unregister_device(&ts->input);561561+ kfree(ts);562562+563563+ dev_dbg(&spi->dev, "unregistered touchscreen\n");564564+ return 0;565565+}566566+567567+static struct spi_driver ads7846_driver = {568568+ .driver = {569569+ .name = "ads7846",570570+ .bus = &spi_bus_type,571571+ .owner = THIS_MODULE,572572+ },573573+ .probe = ads7846_probe,574574+ .remove = __devexit_p(ads7846_remove),575575+ .suspend = ads7846_suspend,576576+ .resume = ads7846_resume,577577+};578578+579579+static int __init ads7846_init(void)580580+{581581+ /* grr, board-specific init should stay out of drivers!! */582582+583583+#ifdef CONFIG_ARCH_OMAP584584+ if (machine_is_omap_osk()) {585585+ /* GPIO4 = PENIRQ; GPIO6 = BUSY */586586+ omap_request_gpio(4);587587+ omap_set_gpio_direction(4, 1);588588+ omap_request_gpio(6);589589+ omap_set_gpio_direction(6, 1);590590+ }591591+ // also TI 1510 Innovator, bitbanging through FPGA592592+ // also Nokia 770593593+ // also Palm Tungsten T2594594+#endif595595+596596+ // PXA:597597+ // also Dell Axim X50598598+ // also HP iPaq H191x/H192x/H415x/H435x599599+ // also Intel Lubbock (additional to UCB1400; as temperature sensor)600600+ // also Sharp Zaurus C7xx, C8xx (corgi/sheperd/husky)601601+602602+ // Atmel at91sam9261-EK uses ads7843603603+604604+ // also various AMD Au1x00 devel boards605605+606606+ return spi_register_driver(&ads7846_driver);607607+}608608+module_init(ads7846_init);609609+610610+static void __exit ads7846_exit(void)611611+{612612+ spi_unregister_driver(&ads7846_driver);613613+614614+#ifdef CONFIG_ARCH_OMAP615615+ if (machine_is_omap_osk()) {616616+ omap_free_gpio(4);617617+ omap_free_gpio(6);618618+ }619619+#endif620620+621621+}622622+module_exit(ads7846_exit);623623+624624+MODULE_DESCRIPTION("ADS7846 TouchScreen Driver");625625+MODULE_LICENSE("GPL");
+16
drivers/mtd/devices/Kconfig
···4747 accelerator. Say Y here if you have a DECstation 5000/2x0 or a4848 DECsystem 5900 equipped with such a module.49495050+config MTD_DATAFLASH5151+ tristate "Support for AT45xxx DataFlash"5252+ depends on MTD && SPI_MASTER && EXPERIMENTAL5353+ help5454+ This enables access to AT45xxx DataFlash chips, using SPI.5555+ Sometimes DataFlash chips are packaged inside MMC-format5656+ cards; at this writing, the MMC stack won't handle those.5757+5858+config MTD_M25P805959+ tristate "Support for M25 SPI Flash"6060+ depends on MTD && SPI_MASTER && EXPERIMENTAL6161+ help6262+ This enables access to ST M25P80 and similar SPI flash chips,6363+ used for program and data storage. Set up your spi devices6464+ with the right board-specific platform data.6565+5066config MTD_SLRAM5167 tristate "Uncached system RAM"5268 depends on MTD
···11+/*22+ * MTD SPI driver for ST M25Pxx flash chips33+ *44+ * Author: Mike Lavender, mike@steroidmicros.com55+ *66+ * Copyright (c) 2005, Intec Automation Inc.77+ *88+ * Some parts are based on lart.c by Abraham Van Der Merwe99+ *1010+ * Cleaned up and generalized based on mtd_dataflash.c1111+ *1212+ * This code is free software; you can redistribute it and/or modify1313+ * it under the terms of the GNU General Public License version 2 as1414+ * published by the Free Software Foundation.1515+ *1616+ */1717+1818+#include <linux/init.h>1919+#include <linux/module.h>2020+#include <linux/device.h>2121+#include <linux/interrupt.h>2222+#include <linux/interrupt.h>2323+#include <linux/mtd/mtd.h>2424+#include <linux/mtd/partitions.h>2525+#include <linux/spi/spi.h>2626+#include <linux/spi/flash.h>2727+2828+#include <asm/semaphore.h>2929+3030+3131+/* NOTE: AT 25F and SST 25LF series are very similar,3232+ * but commands for sector erase and chip id differ...3333+ */3434+3535+#define FLASH_PAGESIZE 2563636+3737+/* Flash opcodes. */3838+#define OPCODE_WREN 6 /* Write enable */3939+#define OPCODE_RDSR 5 /* Read status register */4040+#define OPCODE_READ 3 /* Read data bytes */4141+#define OPCODE_PP 2 /* Page program */4242+#define OPCODE_SE 0xd8 /* Sector erase */4343+#define OPCODE_RES 0xab /* Read Electronic Signature */4444+#define OPCODE_RDID 0x9f /* Read JEDEC ID */4545+4646+/* Status Register bits. */4747+#define SR_WIP 1 /* Write in progress */4848+#define SR_WEL 2 /* Write enable latch */4949+#define SR_BP0 4 /* Block protect 0 */5050+#define SR_BP1 8 /* Block protect 1 */5151+#define SR_BP2 0x10 /* Block protect 2 */5252+#define SR_SRWD 0x80 /* SR write protect */5353+5454+/* Define max times to check status register before we give up. */5555+#define MAX_READY_WAIT_COUNT 1000005656+5757+5858+#ifdef CONFIG_MTD_PARTITIONS5959+#define mtd_has_partitions() (1)6060+#else6161+#define mtd_has_partitions() (0)6262+#endif6363+6464+/****************************************************************************/6565+6666+struct m25p {6767+ struct spi_device *spi;6868+ struct semaphore lock;6969+ struct mtd_info mtd;7070+ unsigned partitioned;7171+ u8 command[4];7272+};7373+7474+static inline struct m25p *mtd_to_m25p(struct mtd_info *mtd)7575+{7676+ return container_of(mtd, struct m25p, mtd);7777+}7878+7979+/****************************************************************************/8080+8181+/*8282+ * Internal helper functions8383+ */8484+8585+/*8686+ * Read the status register, returning its value in the location8787+ * Return the status register value.8888+ * Returns negative if error occurred.8989+ */9090+static int read_sr(struct m25p *flash)9191+{9292+ ssize_t retval;9393+ u8 code = OPCODE_RDSR;9494+ u8 val;9595+9696+ retval = spi_write_then_read(flash->spi, &code, 1, &val, 1);9797+9898+ if (retval < 0) {9999+ dev_err(&flash->spi->dev, "error %d reading SR\n",100100+ (int) retval);101101+ return retval;102102+ }103103+104104+ return val;105105+}106106+107107+108108+/*109109+ * Set write enable latch with Write Enable command.110110+ * Returns negative if error occurred.111111+ */112112+static inline int write_enable(struct m25p *flash)113113+{114114+ u8 code = OPCODE_WREN;115115+116116+ return spi_write_then_read(flash->spi, &code, 1, NULL, 0);117117+}118118+119119+120120+/*121121+ * Service routine to read status register until ready, or timeout occurs.122122+ * Returns non-zero if error.123123+ */124124+static int wait_till_ready(struct m25p *flash)125125+{126126+ int count;127127+ int sr;128128+129129+ /* one chip guarantees max 5 msec wait here after page writes,130130+ * but potentially three seconds (!) after page erase.131131+ */132132+ for (count = 0; count < MAX_READY_WAIT_COUNT; count++) {133133+ if ((sr = read_sr(flash)) < 0)134134+ break;135135+ else if (!(sr & SR_WIP))136136+ return 0;137137+138138+ /* REVISIT sometimes sleeping would be best */139139+ }140140+141141+ return 1;142142+}143143+144144+145145+/*146146+ * Erase one sector of flash memory at offset ``offset'' which is any147147+ * address within the sector which should be erased.148148+ *149149+ * Returns 0 if successful, non-zero otherwise.150150+ */151151+static int erase_sector(struct m25p *flash, u32 offset)152152+{153153+ DEBUG(MTD_DEBUG_LEVEL3, "%s: %s at 0x%08x\n", flash->spi->dev.bus_id,154154+ __FUNCTION__, offset);155155+156156+ /* Wait until finished previous write command. */157157+ if (wait_till_ready(flash))158158+ return 1;159159+160160+ /* Send write enable, then erase commands. */161161+ write_enable(flash);162162+163163+ /* Set up command buffer. */164164+ flash->command[0] = OPCODE_SE;165165+ flash->command[1] = offset >> 16;166166+ flash->command[2] = offset >> 8;167167+ flash->command[3] = offset;168168+169169+ spi_write(flash->spi, flash->command, sizeof(flash->command));170170+171171+ return 0;172172+}173173+174174+/****************************************************************************/175175+176176+/*177177+ * MTD implementation178178+ */179179+180180+/*181181+ * Erase an address range on the flash chip. The address range may extend182182+ * one or more erase sectors. Return an error is there is a problem erasing.183183+ */184184+static int m25p80_erase(struct mtd_info *mtd, struct erase_info *instr)185185+{186186+ struct m25p *flash = mtd_to_m25p(mtd);187187+ u32 addr,len;188188+189189+ DEBUG(MTD_DEBUG_LEVEL2, "%s: %s %s 0x%08x, len %zd\n",190190+ flash->spi->dev.bus_id, __FUNCTION__, "at",191191+ (u32)instr->addr, instr->len);192192+193193+ /* sanity checks */194194+ if (instr->addr + instr->len > flash->mtd.size)195195+ return -EINVAL;196196+ if ((instr->addr % mtd->erasesize) != 0197197+ || (instr->len % mtd->erasesize) != 0) {198198+ return -EINVAL;199199+ }200200+201201+ addr = instr->addr;202202+ len = instr->len;203203+204204+ down(&flash->lock);205205+206206+ /* now erase those sectors */207207+ while (len) {208208+ if (erase_sector(flash, addr)) {209209+ instr->state = MTD_ERASE_FAILED;210210+ up(&flash->lock);211211+ return -EIO;212212+ }213213+214214+ addr += mtd->erasesize;215215+ len -= mtd->erasesize;216216+ }217217+218218+ up(&flash->lock);219219+220220+ instr->state = MTD_ERASE_DONE;221221+ mtd_erase_callback(instr);222222+223223+ return 0;224224+}225225+226226+/*227227+ * Read an address range from the flash chip. The address range228228+ * may be any size provided it is within the physical boundaries.229229+ */230230+static int m25p80_read(struct mtd_info *mtd, loff_t from, size_t len,231231+ size_t *retlen, u_char *buf)232232+{233233+ struct m25p *flash = mtd_to_m25p(mtd);234234+ struct spi_transfer t[2];235235+ struct spi_message m;236236+237237+ DEBUG(MTD_DEBUG_LEVEL2, "%s: %s %s 0x%08x, len %zd\n",238238+ flash->spi->dev.bus_id, __FUNCTION__, "from",239239+ (u32)from, len);240240+241241+ /* sanity checks */242242+ if (!len)243243+ return 0;244244+245245+ if (from + len > flash->mtd.size)246246+ return -EINVAL;247247+248248+ spi_message_init(&m);249249+ memset(t, 0, (sizeof t));250250+251251+ t[0].tx_buf = flash->command;252252+ t[0].len = sizeof(flash->command);253253+ spi_message_add_tail(&t[0], &m);254254+255255+ t[1].rx_buf = buf;256256+ t[1].len = len;257257+ spi_message_add_tail(&t[1], &m);258258+259259+ /* Byte count starts at zero. */260260+ if (retlen)261261+ *retlen = 0;262262+263263+ down(&flash->lock);264264+265265+ /* Wait till previous write/erase is done. */266266+ if (wait_till_ready(flash)) {267267+ /* REVISIT status return?? */268268+ up(&flash->lock);269269+ return 1;270270+ }271271+272272+ /* NOTE: OPCODE_FAST_READ (if available) is faster... */273273+274274+ /* Set up the write data buffer. */275275+ flash->command[0] = OPCODE_READ;276276+ flash->command[1] = from >> 16;277277+ flash->command[2] = from >> 8;278278+ flash->command[3] = from;279279+280280+ spi_sync(flash->spi, &m);281281+282282+ *retlen = m.actual_length - sizeof(flash->command);283283+284284+ up(&flash->lock);285285+286286+ return 0;287287+}288288+289289+/*290290+ * Write an address range to the flash chip. Data must be written in291291+ * FLASH_PAGESIZE chunks. The address range may be any size provided292292+ * it is within the physical boundaries.293293+ */294294+static int m25p80_write(struct mtd_info *mtd, loff_t to, size_t len,295295+ size_t *retlen, const u_char *buf)296296+{297297+ struct m25p *flash = mtd_to_m25p(mtd);298298+ u32 page_offset, page_size;299299+ struct spi_transfer t[2];300300+ struct spi_message m;301301+302302+ DEBUG(MTD_DEBUG_LEVEL2, "%s: %s %s 0x%08x, len %zd\n",303303+ flash->spi->dev.bus_id, __FUNCTION__, "to",304304+ (u32)to, len);305305+306306+ if (retlen)307307+ *retlen = 0;308308+309309+ /* sanity checks */310310+ if (!len)311311+ return(0);312312+313313+ if (to + len > flash->mtd.size)314314+ return -EINVAL;315315+316316+ spi_message_init(&m);317317+ memset(t, 0, (sizeof t));318318+319319+ t[0].tx_buf = flash->command;320320+ t[0].len = sizeof(flash->command);321321+ spi_message_add_tail(&t[0], &m);322322+323323+ t[1].tx_buf = buf;324324+ spi_message_add_tail(&t[1], &m);325325+326326+ down(&flash->lock);327327+328328+ /* Wait until finished previous write command. */329329+ if (wait_till_ready(flash))330330+ return 1;331331+332332+ write_enable(flash);333333+334334+ /* Set up the opcode in the write buffer. */335335+ flash->command[0] = OPCODE_PP;336336+ flash->command[1] = to >> 16;337337+ flash->command[2] = to >> 8;338338+ flash->command[3] = to;339339+340340+ /* what page do we start with? */341341+ page_offset = to % FLASH_PAGESIZE;342342+343343+ /* do all the bytes fit onto one page? */344344+ if (page_offset + len <= FLASH_PAGESIZE) {345345+ t[1].len = len;346346+347347+ spi_sync(flash->spi, &m);348348+349349+ *retlen = m.actual_length - sizeof(flash->command);350350+ } else {351351+ u32 i;352352+353353+ /* the size of data remaining on the first page */354354+ page_size = FLASH_PAGESIZE - page_offset;355355+356356+ t[1].len = page_size;357357+ spi_sync(flash->spi, &m);358358+359359+ *retlen = m.actual_length - sizeof(flash->command);360360+361361+ /* write everything in PAGESIZE chunks */362362+ for (i = page_size; i < len; i += page_size) {363363+ page_size = len - i;364364+ if (page_size > FLASH_PAGESIZE)365365+ page_size = FLASH_PAGESIZE;366366+367367+ /* write the next page to flash */368368+ flash->command[1] = (to + i) >> 16;369369+ flash->command[2] = (to + i) >> 8;370370+ flash->command[3] = (to + i);371371+372372+ t[1].tx_buf = buf + i;373373+ t[1].len = page_size;374374+375375+ wait_till_ready(flash);376376+377377+ write_enable(flash);378378+379379+ spi_sync(flash->spi, &m);380380+381381+ if (retlen)382382+ *retlen += m.actual_length383383+ - sizeof(flash->command);384384+ }385385+ }386386+387387+ up(&flash->lock);388388+389389+ return 0;390390+}391391+392392+393393+/****************************************************************************/394394+395395+/*396396+ * SPI device driver setup and teardown397397+ */398398+399399+struct flash_info {400400+ char *name;401401+ u8 id;402402+ u16 jedec_id;403403+ unsigned sector_size;404404+ unsigned n_sectors;405405+};406406+407407+static struct flash_info __devinitdata m25p_data [] = {408408+ /* REVISIT: fill in JEDEC ids, for parts that have them */409409+ { "m25p05", 0x05, 0x0000, 32 * 1024, 2 },410410+ { "m25p10", 0x10, 0x0000, 32 * 1024, 4 },411411+ { "m25p20", 0x11, 0x0000, 64 * 1024, 4 },412412+ { "m25p40", 0x12, 0x0000, 64 * 1024, 8 },413413+ { "m25p80", 0x13, 0x0000, 64 * 1024, 16 },414414+ { "m25p16", 0x14, 0x0000, 64 * 1024, 32 },415415+ { "m25p32", 0x15, 0x0000, 64 * 1024, 64 },416416+ { "m25p64", 0x16, 0x2017, 64 * 1024, 128 },417417+};418418+419419+/*420420+ * board specific setup should have ensured the SPI clock used here421421+ * matches what the READ command supports, at least until this driver422422+ * understands FAST_READ (for clocks over 25 MHz).423423+ */424424+static int __devinit m25p_probe(struct spi_device *spi)425425+{426426+ struct flash_platform_data *data;427427+ struct m25p *flash;428428+ struct flash_info *info;429429+ unsigned i;430430+431431+ /* Platform data helps sort out which chip type we have, as432432+ * well as how this board partitions it.433433+ */434434+ data = spi->dev.platform_data;435435+ if (!data || !data->type) {436436+ /* FIXME some chips can identify themselves with RES437437+ * or JEDEC get-id commands. Try them ...438438+ */439439+ DEBUG(MTD_DEBUG_LEVEL1, "%s: no chip id\n",440440+ flash->spi->dev.bus_id);441441+ return -ENODEV;442442+ }443443+444444+ for (i = 0, info = m25p_data; i < ARRAY_SIZE(m25p_data); i++, info++) {445445+ if (strcmp(data->type, info->name) == 0)446446+ break;447447+ }448448+ if (i == ARRAY_SIZE(m25p_data)) {449449+ DEBUG(MTD_DEBUG_LEVEL1, "%s: unrecognized id %s\n",450450+ flash->spi->dev.bus_id, data->type);451451+ return -ENODEV;452452+ }453453+454454+ flash = kzalloc(sizeof *flash, SLAB_KERNEL);455455+ if (!flash)456456+ return -ENOMEM;457457+458458+ flash->spi = spi;459459+ init_MUTEX(&flash->lock);460460+ dev_set_drvdata(&spi->dev, flash);461461+462462+ if (data->name)463463+ flash->mtd.name = data->name;464464+ else465465+ flash->mtd.name = spi->dev.bus_id;466466+467467+ flash->mtd.type = MTD_NORFLASH;468468+ flash->mtd.flags = MTD_CAP_NORFLASH;469469+ flash->mtd.size = info->sector_size * info->n_sectors;470470+ flash->mtd.erasesize = info->sector_size;471471+ flash->mtd.erase = m25p80_erase;472472+ flash->mtd.read = m25p80_read;473473+ flash->mtd.write = m25p80_write;474474+475475+ dev_info(&spi->dev, "%s (%d Kbytes)\n", info->name,476476+ flash->mtd.size / 1024);477477+478478+ DEBUG(MTD_DEBUG_LEVEL2,479479+ "mtd .name = %s, .size = 0x%.8x (%uM) "480480+ ".erasesize = 0x%.8x (%uK) .numeraseregions = %d\n",481481+ flash->mtd.name,482482+ flash->mtd.size, flash->mtd.size / (1024*1024),483483+ flash->mtd.erasesize, flash->mtd.erasesize / 1024,484484+ flash->mtd.numeraseregions);485485+486486+ if (flash->mtd.numeraseregions)487487+ for (i = 0; i < flash->mtd.numeraseregions; i++)488488+ DEBUG(MTD_DEBUG_LEVEL2,489489+ "mtd.eraseregions[%d] = { .offset = 0x%.8x, "490490+ ".erasesize = 0x%.8x (%uK), "491491+ ".numblocks = %d }\n",492492+ i, flash->mtd.eraseregions[i].offset,493493+ flash->mtd.eraseregions[i].erasesize,494494+ flash->mtd.eraseregions[i].erasesize / 1024,495495+ flash->mtd.eraseregions[i].numblocks);496496+497497+498498+ /* partitions should match sector boundaries; and it may be good to499499+ * use readonly partitions for writeprotected sectors (BP2..BP0).500500+ */501501+ if (mtd_has_partitions()) {502502+ struct mtd_partition *parts = NULL;503503+ int nr_parts = 0;504504+505505+#ifdef CONFIG_MTD_CMDLINE_PARTS506506+ static const char *part_probes[] = { "cmdlinepart", NULL, };507507+508508+ nr_parts = parse_mtd_partitions(&flash->mtd,509509+ part_probes, &parts, 0);510510+#endif511511+512512+ if (nr_parts <= 0 && data && data->parts) {513513+ parts = data->parts;514514+ nr_parts = data->nr_parts;515515+ }516516+517517+ if (nr_parts > 0) {518518+ for (i = 0; i < data->nr_parts; i++) {519519+ DEBUG(MTD_DEBUG_LEVEL2, "partitions[%d] = "520520+ "{.name = %s, .offset = 0x%.8x, "521521+ ".size = 0x%.8x (%uK) }\n",522522+ i, data->parts[i].name,523523+ data->parts[i].offset,524524+ data->parts[i].size,525525+ data->parts[i].size / 1024);526526+ }527527+ flash->partitioned = 1;528528+ return add_mtd_partitions(&flash->mtd, parts, nr_parts);529529+ }530530+ } else if (data->nr_parts)531531+ dev_warn(&spi->dev, "ignoring %d default partitions on %s\n",532532+ data->nr_parts, data->name);533533+534534+ return add_mtd_device(&flash->mtd) == 1 ? -ENODEV : 0;535535+}536536+537537+538538+static int __devexit m25p_remove(struct spi_device *spi)539539+{540540+ struct m25p *flash = dev_get_drvdata(&spi->dev);541541+ int status;542542+543543+ /* Clean up MTD stuff. */544544+ if (mtd_has_partitions() && flash->partitioned)545545+ status = del_mtd_partitions(&flash->mtd);546546+ else547547+ status = del_mtd_device(&flash->mtd);548548+ if (status == 0)549549+ kfree(flash);550550+ return 0;551551+}552552+553553+554554+static struct spi_driver m25p80_driver = {555555+ .driver = {556556+ .name = "m25p80",557557+ .bus = &spi_bus_type,558558+ .owner = THIS_MODULE,559559+ },560560+ .probe = m25p_probe,561561+ .remove = __devexit_p(m25p_remove),562562+};563563+564564+565565+static int m25p80_init(void)566566+{567567+ return spi_register_driver(&m25p80_driver);568568+}569569+570570+571571+static void m25p80_exit(void)572572+{573573+ spi_unregister_driver(&m25p80_driver);574574+}575575+576576+577577+module_init(m25p80_init);578578+module_exit(m25p80_exit);579579+580580+MODULE_LICENSE("GPL");581581+MODULE_AUTHOR("Mike Lavender");582582+MODULE_DESCRIPTION("MTD SPI driver for ST M25Pxx flash chips");
+629
drivers/mtd/devices/mtd_dataflash.c
···11+/*22+ * Atmel AT45xxx DataFlash MTD driver for lightweight SPI framework33+ *44+ * Largely derived from at91_dataflash.c:55+ * Copyright (C) 2003-2005 SAN People (Pty) Ltd66+ *77+ * This program is free software; you can redistribute it and/or88+ * modify it under the terms of the GNU General Public License99+ * as published by the Free Software Foundation; either version1010+ * 2 of the License, or (at your option) any later version.1111+*/1212+#include <linux/config.h>1313+#include <linux/module.h>1414+#include <linux/init.h>1515+#include <linux/slab.h>1616+#include <linux/delay.h>1717+#include <linux/device.h>1818+#include <linux/spi/spi.h>1919+#include <linux/spi/flash.h>2020+2121+#include <linux/mtd/mtd.h>2222+#include <linux/mtd/partitions.h>2323+2424+2525+/*2626+ * DataFlash is a kind of SPI flash. Most AT45 chips have two buffers in2727+ * each chip, which may be used for double buffered I/O; but this driver2828+ * doesn't (yet) use these for any kind of i/o overlap or prefetching.2929+ *3030+ * Sometimes DataFlash is packaged in MMC-format cards, although the3131+ * MMC stack can't use SPI (yet), or distinguish between MMC and DataFlash3232+ * protocols during enumeration.3333+ */3434+3535+#define CONFIG_DATAFLASH_WRITE_VERIFY3636+3737+/* reads can bypass the buffers */3838+#define OP_READ_CONTINUOUS 0xE83939+#define OP_READ_PAGE 0xD24040+4141+/* group B requests can run even while status reports "busy" */4242+#define OP_READ_STATUS 0xD7 /* group B */4343+4444+/* move data between host and buffer */4545+#define OP_READ_BUFFER1 0xD4 /* group B */4646+#define OP_READ_BUFFER2 0xD6 /* group B */4747+#define OP_WRITE_BUFFER1 0x84 /* group B */4848+#define OP_WRITE_BUFFER2 0x87 /* group B */4949+5050+/* erasing flash */5151+#define OP_ERASE_PAGE 0x815252+#define OP_ERASE_BLOCK 0x505353+5454+/* move data between buffer and flash */5555+#define OP_TRANSFER_BUF1 0x535656+#define OP_TRANSFER_BUF2 0x555757+#define OP_MREAD_BUFFER1 0xD45858+#define OP_MREAD_BUFFER2 0xD65959+#define OP_MWERASE_BUFFER1 0x836060+#define OP_MWERASE_BUFFER2 0x866161+#define OP_MWRITE_BUFFER1 0x88 /* sector must be pre-erased */6262+#define OP_MWRITE_BUFFER2 0x89 /* sector must be pre-erased */6363+6464+/* write to buffer, then write-erase to flash */6565+#define OP_PROGRAM_VIA_BUF1 0x826666+#define OP_PROGRAM_VIA_BUF2 0x856767+6868+/* compare buffer to flash */6969+#define OP_COMPARE_BUF1 0x607070+#define OP_COMPARE_BUF2 0x617171+7272+/* read flash to buffer, then write-erase to flash */7373+#define OP_REWRITE_VIA_BUF1 0x587474+#define OP_REWRITE_VIA_BUF2 0x597575+7676+/* newer chips report JEDEC manufacturer and device IDs; chip7777+ * serial number and OTP bits; and per-sector writeprotect.7878+ */7979+#define OP_READ_ID 0x9F8080+#define OP_READ_SECURITY 0x778181+#define OP_WRITE_SECURITY 0x9A /* OTP bits */8282+8383+8484+struct dataflash {8585+ u8 command[4];8686+ char name[24];8787+8888+ unsigned partitioned:1;8989+9090+ unsigned short page_offset; /* offset in flash address */9191+ unsigned int page_size; /* of bytes per page */9292+9393+ struct semaphore lock;9494+ struct spi_device *spi;9595+9696+ struct mtd_info mtd;9797+};9898+9999+#ifdef CONFIG_MTD_PARTITIONS100100+#define mtd_has_partitions() (1)101101+#else102102+#define mtd_has_partitions() (0)103103+#endif104104+105105+/* ......................................................................... */106106+107107+/*108108+ * Return the status of the DataFlash device.109109+ */110110+static inline int dataflash_status(struct spi_device *spi)111111+{112112+ /* NOTE: at45db321c over 25 MHz wants to write113113+ * a dummy byte after the opcode...114114+ */115115+ return spi_w8r8(spi, OP_READ_STATUS);116116+}117117+118118+/*119119+ * Poll the DataFlash device until it is READY.120120+ * This usually takes 5-20 msec or so; more for sector erase.121121+ */122122+static int dataflash_waitready(struct spi_device *spi)123123+{124124+ int status;125125+126126+ for (;;) {127127+ status = dataflash_status(spi);128128+ if (status < 0) {129129+ DEBUG(MTD_DEBUG_LEVEL1, "%s: status %d?\n",130130+ spi->dev.bus_id, status);131131+ status = 0;132132+ }133133+134134+ if (status & (1 << 7)) /* RDY/nBSY */135135+ return status;136136+137137+ msleep(3);138138+ }139139+}140140+141141+/* ......................................................................... */142142+143143+/*144144+ * Erase pages of flash.145145+ */146146+static int dataflash_erase(struct mtd_info *mtd, struct erase_info *instr)147147+{148148+ struct dataflash *priv = (struct dataflash *)mtd->priv;149149+ struct spi_device *spi = priv->spi;150150+ struct spi_transfer x = { .tx_dma = 0, };151151+ struct spi_message msg;152152+ unsigned blocksize = priv->page_size << 3;153153+ u8 *command;154154+155155+ DEBUG(MTD_DEBUG_LEVEL2, "%s: erase addr=0x%x len 0x%x\n",156156+ spi->dev.bus_id,157157+ instr->addr, instr->len);158158+159159+ /* Sanity checks */160160+ if ((instr->addr + instr->len) > mtd->size161161+ || (instr->len % priv->page_size) != 0162162+ || (instr->addr % priv->page_size) != 0)163163+ return -EINVAL;164164+165165+ spi_message_init(&msg);166166+167167+ x.tx_buf = command = priv->command;168168+ x.len = 4;169169+ spi_message_add_tail(&x, &msg);170170+171171+ down(&priv->lock);172172+ while (instr->len > 0) {173173+ unsigned int pageaddr;174174+ int status;175175+ int do_block;176176+177177+ /* Calculate flash page address; use block erase (for speed) if178178+ * we're at a block boundary and need to erase the whole block.179179+ */180180+ pageaddr = instr->addr / priv->page_size;181181+ do_block = (pageaddr & 0x7) == 0 && instr->len <= blocksize;182182+ pageaddr = pageaddr << priv->page_offset;183183+184184+ command[0] = do_block ? OP_ERASE_BLOCK : OP_ERASE_PAGE;185185+ command[1] = (u8)(pageaddr >> 16);186186+ command[2] = (u8)(pageaddr >> 8);187187+ command[3] = 0;188188+189189+ DEBUG(MTD_DEBUG_LEVEL3, "ERASE %s: (%x) %x %x %x [%i]\n",190190+ do_block ? "block" : "page",191191+ command[0], command[1], command[2], command[3],192192+ pageaddr);193193+194194+ status = spi_sync(spi, &msg);195195+ (void) dataflash_waitready(spi);196196+197197+ if (status < 0) {198198+ printk(KERN_ERR "%s: erase %x, err %d\n",199199+ spi->dev.bus_id, pageaddr, status);200200+ /* REVISIT: can retry instr->retries times; or201201+ * giveup and instr->fail_addr = instr->addr;202202+ */203203+ continue;204204+ }205205+206206+ if (do_block) {207207+ instr->addr += blocksize;208208+ instr->len -= blocksize;209209+ } else {210210+ instr->addr += priv->page_size;211211+ instr->len -= priv->page_size;212212+ }213213+ }214214+ up(&priv->lock);215215+216216+ /* Inform MTD subsystem that erase is complete */217217+ instr->state = MTD_ERASE_DONE;218218+ mtd_erase_callback(instr);219219+220220+ return 0;221221+}222222+223223+/*224224+ * Read from the DataFlash device.225225+ * from : Start offset in flash device226226+ * len : Amount to read227227+ * retlen : About of data actually read228228+ * buf : Buffer containing the data229229+ */230230+static int dataflash_read(struct mtd_info *mtd, loff_t from, size_t len,231231+ size_t *retlen, u_char *buf)232232+{233233+ struct dataflash *priv = (struct dataflash *)mtd->priv;234234+ struct spi_transfer x[2] = { { .tx_dma = 0, }, };235235+ struct spi_message msg;236236+ unsigned int addr;237237+ u8 *command;238238+ int status;239239+240240+ DEBUG(MTD_DEBUG_LEVEL2, "%s: read 0x%x..0x%x\n",241241+ priv->spi->dev.bus_id, (unsigned)from, (unsigned)(from + len));242242+243243+ *retlen = 0;244244+245245+ /* Sanity checks */246246+ if (!len)247247+ return 0;248248+ if (from + len > mtd->size)249249+ return -EINVAL;250250+251251+ /* Calculate flash page/byte address */252252+ addr = (((unsigned)from / priv->page_size) << priv->page_offset)253253+ + ((unsigned)from % priv->page_size);254254+255255+ command = priv->command;256256+257257+ DEBUG(MTD_DEBUG_LEVEL3, "READ: (%x) %x %x %x\n",258258+ command[0], command[1], command[2], command[3]);259259+260260+ spi_message_init(&msg);261261+262262+ x[0].tx_buf = command;263263+ x[0].len = 8;264264+ spi_message_add_tail(&x[0], &msg);265265+266266+ x[1].rx_buf = buf;267267+ x[1].len = len;268268+ spi_message_add_tail(&x[1], &msg);269269+270270+ down(&priv->lock);271271+272272+ /* Continuous read, max clock = f(car) which may be less than273273+ * the peak rate available. Some chips support commands with274274+ * fewer "don't care" bytes. Both buffers stay unchanged.275275+ */276276+ command[0] = OP_READ_CONTINUOUS;277277+ command[1] = (u8)(addr >> 16);278278+ command[2] = (u8)(addr >> 8);279279+ command[3] = (u8)(addr >> 0);280280+ /* plus 4 "don't care" bytes */281281+282282+ status = spi_sync(priv->spi, &msg);283283+ up(&priv->lock);284284+285285+ if (status >= 0) {286286+ *retlen = msg.actual_length - 8;287287+ status = 0;288288+ } else289289+ DEBUG(MTD_DEBUG_LEVEL1, "%s: read %x..%x --> %d\n",290290+ priv->spi->dev.bus_id,291291+ (unsigned)from, (unsigned)(from + len),292292+ status);293293+ return status;294294+}295295+296296+/*297297+ * Write to the DataFlash device.298298+ * to : Start offset in flash device299299+ * len : Amount to write300300+ * retlen : Amount of data actually written301301+ * buf : Buffer containing the data302302+ */303303+static int dataflash_write(struct mtd_info *mtd, loff_t to, size_t len,304304+ size_t * retlen, const u_char * buf)305305+{306306+ struct dataflash *priv = (struct dataflash *)mtd->priv;307307+ struct spi_device *spi = priv->spi;308308+ struct spi_transfer x[2] = { { .tx_dma = 0, }, };309309+ struct spi_message msg;310310+ unsigned int pageaddr, addr, offset, writelen;311311+ size_t remaining = len;312312+ u_char *writebuf = (u_char *) buf;313313+ int status = -EINVAL;314314+ u8 *command;315315+316316+ DEBUG(MTD_DEBUG_LEVEL2, "%s: write 0x%x..0x%x\n",317317+ spi->dev.bus_id, (unsigned)to, (unsigned)(to + len));318318+319319+ *retlen = 0;320320+321321+ /* Sanity checks */322322+ if (!len)323323+ return 0;324324+ if ((to + len) > mtd->size)325325+ return -EINVAL;326326+327327+ spi_message_init(&msg);328328+329329+ x[0].tx_buf = command = priv->command;330330+ x[0].len = 4;331331+ spi_message_add_tail(&x[0], &msg);332332+333333+ pageaddr = ((unsigned)to / priv->page_size);334334+ offset = ((unsigned)to % priv->page_size);335335+ if (offset + len > priv->page_size)336336+ writelen = priv->page_size - offset;337337+ else338338+ writelen = len;339339+340340+ down(&priv->lock);341341+ while (remaining > 0) {342342+ DEBUG(MTD_DEBUG_LEVEL3, "write @ %i:%i len=%i\n",343343+ pageaddr, offset, writelen);344344+345345+ /* REVISIT:346346+ * (a) each page in a sector must be rewritten at least347347+ * once every 10K sibling erase/program operations.348348+ * (b) for pages that are already erased, we could349349+ * use WRITE+MWRITE not PROGRAM for ~30% speedup.350350+ * (c) WRITE to buffer could be done while waiting for351351+ * a previous MWRITE/MWERASE to complete ...352352+ * (d) error handling here seems to be mostly missing.353353+ *354354+ * Two persistent bits per page, plus a per-sector counter,355355+ * could support (a) and (b) ... we might consider using356356+ * the second half of sector zero, which is just one block,357357+ * to track that state. (On AT91, that sector should also358358+ * support boot-from-DataFlash.)359359+ */360360+361361+ addr = pageaddr << priv->page_offset;362362+363363+ /* (1) Maybe transfer partial page to Buffer1 */364364+ if (writelen != priv->page_size) {365365+ command[0] = OP_TRANSFER_BUF1;366366+ command[1] = (addr & 0x00FF0000) >> 16;367367+ command[2] = (addr & 0x0000FF00) >> 8;368368+ command[3] = 0;369369+370370+ DEBUG(MTD_DEBUG_LEVEL3, "TRANSFER: (%x) %x %x %x\n",371371+ command[0], command[1], command[2], command[3]);372372+373373+ status = spi_sync(spi, &msg);374374+ if (status < 0)375375+ DEBUG(MTD_DEBUG_LEVEL1, "%s: xfer %u -> %d \n",376376+ spi->dev.bus_id, addr, status);377377+378378+ (void) dataflash_waitready(priv->spi);379379+ }380380+381381+ /* (2) Program full page via Buffer1 */382382+ addr += offset;383383+ command[0] = OP_PROGRAM_VIA_BUF1;384384+ command[1] = (addr & 0x00FF0000) >> 16;385385+ command[2] = (addr & 0x0000FF00) >> 8;386386+ command[3] = (addr & 0x000000FF);387387+388388+ DEBUG(MTD_DEBUG_LEVEL3, "PROGRAM: (%x) %x %x %x\n",389389+ command[0], command[1], command[2], command[3]);390390+391391+ x[1].tx_buf = writebuf;392392+ x[1].len = writelen;393393+ spi_message_add_tail(x + 1, &msg);394394+ status = spi_sync(spi, &msg);395395+ spi_transfer_del(x + 1);396396+ if (status < 0)397397+ DEBUG(MTD_DEBUG_LEVEL1, "%s: pgm %u/%u -> %d \n",398398+ spi->dev.bus_id, addr, writelen, status);399399+400400+ (void) dataflash_waitready(priv->spi);401401+402402+403403+#ifdef CONFIG_DATAFLASH_WRITE_VERIFY404404+405405+ /* (3) Compare to Buffer1 */406406+ addr = pageaddr << priv->page_offset;407407+ command[0] = OP_COMPARE_BUF1;408408+ command[1] = (addr & 0x00FF0000) >> 16;409409+ command[2] = (addr & 0x0000FF00) >> 8;410410+ command[3] = 0;411411+412412+ DEBUG(MTD_DEBUG_LEVEL3, "COMPARE: (%x) %x %x %x\n",413413+ command[0], command[1], command[2], command[3]);414414+415415+ status = spi_sync(spi, &msg);416416+ if (status < 0)417417+ DEBUG(MTD_DEBUG_LEVEL1, "%s: compare %u -> %d \n",418418+ spi->dev.bus_id, addr, status);419419+420420+ status = dataflash_waitready(priv->spi);421421+422422+ /* Check result of the compare operation */423423+ if ((status & (1 << 6)) == 1) {424424+ printk(KERN_ERR "%s: compare page %u, err %d\n",425425+ spi->dev.bus_id, pageaddr, status);426426+ remaining = 0;427427+ status = -EIO;428428+ break;429429+ } else430430+ status = 0;431431+432432+#endif /* CONFIG_DATAFLASH_WRITE_VERIFY */433433+434434+ remaining = remaining - writelen;435435+ pageaddr++;436436+ offset = 0;437437+ writebuf += writelen;438438+ *retlen += writelen;439439+440440+ if (remaining > priv->page_size)441441+ writelen = priv->page_size;442442+ else443443+ writelen = remaining;444444+ }445445+ up(&priv->lock);446446+447447+ return status;448448+}449449+450450+/* ......................................................................... */451451+452452+/*453453+ * Register DataFlash device with MTD subsystem.454454+ */455455+static int __devinit456456+add_dataflash(struct spi_device *spi, char *name,457457+ int nr_pages, int pagesize, int pageoffset)458458+{459459+ struct dataflash *priv;460460+ struct mtd_info *device;461461+ struct flash_platform_data *pdata = spi->dev.platform_data;462462+463463+ priv = (struct dataflash *) kzalloc(sizeof *priv, GFP_KERNEL);464464+ if (!priv)465465+ return -ENOMEM;466466+467467+ init_MUTEX(&priv->lock);468468+ priv->spi = spi;469469+ priv->page_size = pagesize;470470+ priv->page_offset = pageoffset;471471+472472+ /* name must be usable with cmdlinepart */473473+ sprintf(priv->name, "spi%d.%d-%s",474474+ spi->master->bus_num, spi->chip_select,475475+ name);476476+477477+ device = &priv->mtd;478478+ device->name = (pdata && pdata->name) ? pdata->name : priv->name;479479+ device->size = nr_pages * pagesize;480480+ device->erasesize = pagesize;481481+ device->owner = THIS_MODULE;482482+ device->type = MTD_DATAFLASH;483483+ device->flags = MTD_CAP_NORFLASH;484484+ device->erase = dataflash_erase;485485+ device->read = dataflash_read;486486+ device->write = dataflash_write;487487+ device->priv = priv;488488+489489+ dev_info(&spi->dev, "%s (%d KBytes)\n", name, device->size/1024);490490+ dev_set_drvdata(&spi->dev, priv);491491+492492+ if (mtd_has_partitions()) {493493+ struct mtd_partition *parts;494494+ int nr_parts = 0;495495+496496+#ifdef CONFIG_MTD_CMDLINE_PARTS497497+ static const char *part_probes[] = { "cmdlinepart", NULL, };498498+499499+ nr_parts = parse_mtd_partitions(device, part_probes, &parts, 0);500500+#endif501501+502502+ if (nr_parts <= 0 && pdata && pdata->parts) {503503+ parts = pdata->parts;504504+ nr_parts = pdata->nr_parts;505505+ }506506+507507+ if (nr_parts > 0) {508508+ priv->partitioned = 1;509509+ return add_mtd_partitions(device, parts, nr_parts);510510+ }511511+ } else if (pdata && pdata->nr_parts)512512+ dev_warn(&spi->dev, "ignoring %d default partitions on %s\n",513513+ pdata->nr_parts, device->name);514514+515515+ return add_mtd_device(device) == 1 ? -ENODEV : 0;516516+}517517+518518+/*519519+ * Detect and initialize DataFlash device:520520+ *521521+ * Device Density ID code #Pages PageSize Offset522522+ * AT45DB011B 1Mbit (128K) xx0011xx (0x0c) 512 264 9523523+ * AT45DB021B 2Mbit (256K) xx0101xx (0x14) 1025 264 9524524+ * AT45DB041B 4Mbit (512K) xx0111xx (0x1c) 2048 264 9525525+ * AT45DB081B 8Mbit (1M) xx1001xx (0x24) 4096 264 9526526+ * AT45DB0161B 16Mbit (2M) xx1011xx (0x2c) 4096 528 10527527+ * AT45DB0321B 32Mbit (4M) xx1101xx (0x34) 8192 528 10528528+ * AT45DB0642 64Mbit (8M) xx111xxx (0x3c) 8192 1056 11529529+ * AT45DB1282 128Mbit (16M) xx0100xx (0x10) 16384 1056 11530530+ */531531+static int __devinit dataflash_probe(struct spi_device *spi)532532+{533533+ int status;534534+535535+ status = dataflash_status(spi);536536+ if (status <= 0 || status == 0xff) {537537+ DEBUG(MTD_DEBUG_LEVEL1, "%s: status error %d\n",538538+ spi->dev.bus_id, status);539539+ if (status == 0xff)540540+ status = -ENODEV;541541+ return status;542542+ }543543+544544+ /* if there's a device there, assume it's dataflash.545545+ * board setup should have set spi->max_speed_max to546546+ * match f(car) for continuous reads, mode 0 or 3.547547+ */548548+ switch (status & 0x3c) {549549+ case 0x0c: /* 0 0 1 1 x x */550550+ status = add_dataflash(spi, "AT45DB011B", 512, 264, 9);551551+ break;552552+ case 0x14: /* 0 1 0 1 x x */553553+ status = add_dataflash(spi, "AT45DB021B", 1025, 264, 9);554554+ break;555555+ case 0x1c: /* 0 1 1 1 x x */556556+ status = add_dataflash(spi, "AT45DB041x", 2048, 264, 9);557557+ break;558558+ case 0x24: /* 1 0 0 1 x x */559559+ status = add_dataflash(spi, "AT45DB081B", 4096, 264, 9);560560+ break;561561+ case 0x2c: /* 1 0 1 1 x x */562562+ status = add_dataflash(spi, "AT45DB161x", 4096, 528, 10);563563+ break;564564+ case 0x34: /* 1 1 0 1 x x */565565+ status = add_dataflash(spi, "AT45DB321x", 8192, 528, 10);566566+ break;567567+ case 0x38: /* 1 1 1 x x x */568568+ case 0x3c:569569+ status = add_dataflash(spi, "AT45DB642x", 8192, 1056, 11);570570+ break;571571+ /* obsolete AT45DB1282 not (yet?) supported */572572+ default:573573+ DEBUG(MTD_DEBUG_LEVEL1, "%s: unsupported device (%x)\n",574574+ spi->dev.bus_id, status & 0x3c);575575+ status = -ENODEV;576576+ }577577+578578+ if (status < 0)579579+ DEBUG(MTD_DEBUG_LEVEL1, "%s: add_dataflash --> %d\n",580580+ spi->dev.bus_id, status);581581+582582+ return status;583583+}584584+585585+static int __devexit dataflash_remove(struct spi_device *spi)586586+{587587+ struct dataflash *flash = dev_get_drvdata(&spi->dev);588588+ int status;589589+590590+ DEBUG(MTD_DEBUG_LEVEL1, "%s: remove\n", spi->dev.bus_id);591591+592592+ if (mtd_has_partitions() && flash->partitioned)593593+ status = del_mtd_partitions(&flash->mtd);594594+ else595595+ status = del_mtd_device(&flash->mtd);596596+ if (status == 0)597597+ kfree(flash);598598+ return status;599599+}600600+601601+static struct spi_driver dataflash_driver = {602602+ .driver = {603603+ .name = "mtd_dataflash",604604+ .bus = &spi_bus_type,605605+ .owner = THIS_MODULE,606606+ },607607+608608+ .probe = dataflash_probe,609609+ .remove = __devexit_p(dataflash_remove),610610+611611+ /* FIXME: investigate suspend and resume... */612612+};613613+614614+static int __init dataflash_init(void)615615+{616616+ return spi_register_driver(&dataflash_driver);617617+}618618+module_init(dataflash_init);619619+620620+static void __exit dataflash_exit(void)621621+{622622+ spi_unregister_driver(&dataflash_driver);623623+}624624+module_exit(dataflash_exit);625625+626626+627627+MODULE_LICENSE("GPL");628628+MODULE_AUTHOR("Andrew Victor, David Brownell");629629+MODULE_DESCRIPTION("MTD DataFlash driver");
+109
drivers/spi/Kconfig
···11+#22+# SPI driver configuration33+#44+# NOTE: the reason this doesn't show SPI slave support is mostly that55+# nobody's needed a slave side API yet. The master-role API is not66+# fully appropriate there, so it'd need some thought to do well.77+#88+menu "SPI support"99+1010+config SPI1111+ bool "SPI support"1212+ help1313+ The "Serial Peripheral Interface" is a low level synchronous1414+ protocol. Chips that support SPI can have data transfer rates1515+ up to several tens of Mbit/sec. Chips are addressed with a1616+ controller and a chipselect. Most SPI slaves don't support1717+ dynamic device discovery; some are even write-only or read-only.1818+1919+ SPI is widely used by microcontollers to talk with sensors,2020+ eeprom and flash memory, codecs and various other controller2121+ chips, analog to digital (and d-to-a) converters, and more.2222+ MMC and SD cards can be accessed using SPI protocol; and for2323+ DataFlash cards used in MMC sockets, SPI must always be used.2424+2525+ SPI is one of a family of similar protocols using a four wire2626+ interface (select, clock, data in, data out) including Microwire2727+ (half duplex), SSP, SSI, and PSP. This driver framework should2828+ work with most such devices and controllers.2929+3030+config SPI_DEBUG3131+ boolean "Debug support for SPI drivers"3232+ depends on SPI && DEBUG_KERNEL3333+ help3434+ Say "yes" to enable debug messaging (like dev_dbg and pr_debug),3535+ sysfs, and debugfs support in SPI controller and protocol drivers.3636+3737+#3838+# MASTER side ... talking to discrete SPI slave chips including microcontrollers3939+#4040+4141+config SPI_MASTER4242+# boolean "SPI Master Support"4343+ boolean4444+ default SPI4545+ help4646+ If your system has an master-capable SPI controller (which4747+ provides the clock and chipselect), you can enable that4848+ controller and the protocol drivers for the SPI slave chips4949+ that are connected.5050+5151+comment "SPI Master Controller Drivers"5252+ depends on SPI_MASTER5353+5454+config SPI_BITBANG5555+ tristate "Bitbanging SPI master"5656+ depends on SPI_MASTER && EXPERIMENTAL5757+ help5858+ With a few GPIO pins, your system can bitbang the SPI protocol.5959+ Select this to get SPI support through I/O pins (GPIO, parallel6060+ port, etc). Or, some systems' SPI master controller drivers use6161+ this code to manage the per-word or per-transfer accesses to the6262+ hardware shift registers.6363+6464+ This is library code, and is automatically selected by drivers that6565+ need it. You only need to select this explicitly to support driver6666+ modules that aren't part of this kernel tree.6767+6868+config SPI_BUTTERFLY6969+ tristate "Parallel port adapter for AVR Butterfly (DEVELOPMENT)"7070+ depends on SPI_MASTER && PARPORT && EXPERIMENTAL7171+ select SPI_BITBANG7272+ help7373+ This uses a custom parallel port cable to connect to an AVR7474+ Butterfly <http://www.atmel.com/products/avr/butterfly>, an7575+ inexpensive battery powered microcontroller evaluation board.7676+ This same cable can be used to flash new firmware.7777+7878+config SPI_BUTTERFLY7979+ tristate "Parallel port adapter for AVR Butterfly (DEVELOPMENT)"8080+ depends on SPI_MASTER && PARPORT && EXPERIMENTAL8181+ select SPI_BITBANG8282+ help8383+ This uses a custom parallel port cable to connect to an AVR8484+ Butterfly <http://www.atmel.com/products/avr/butterfly>, an8585+ inexpensive battery powered microcontroller evaluation board.8686+ This same cable can be used to flash new firmware.8787+8888+#8989+# Add new SPI master controllers in alphabetical order above this line9090+#9191+9292+9393+#9494+# There are lots of SPI device types, with sensors and memory9595+# being probably the most widely used ones.9696+#9797+comment "SPI Protocol Masters"9898+ depends on SPI_MASTER9999+100100+101101+#102102+# Add new SPI protocol masters in alphabetical order above this line103103+#104104+105105+106106+# (slave support would go here)107107+108108+endmenu # "SPI support"109109+
+25
drivers/spi/Makefile
···11+#22+# Makefile for kernel SPI drivers.33+#44+55+ifeq ($(CONFIG_SPI_DEBUG),y)66+EXTRA_CFLAGS += -DDEBUG77+endif88+99+# small core, mostly translating board-specific1010+# config declarations into driver model code1111+obj-$(CONFIG_SPI_MASTER) += spi.o1212+1313+# SPI master controller drivers (bus)1414+obj-$(CONFIG_SPI_BITBANG) += spi_bitbang.o1515+obj-$(CONFIG_SPI_BUTTERFLY) += spi_butterfly.o1616+# ... add above this line ...1717+1818+# SPI protocol drivers (device/link on bus)1919+# ... add above this line ...2020+2121+# SPI slave controller drivers (upstream link)2222+# ... add above this line ...2323+2424+# SPI slave drivers (protocol for that link)2525+# ... add above this line ...
+642
drivers/spi/spi.c
···11+/*22+ * spi.c - SPI init/core code33+ *44+ * Copyright (C) 2005 David Brownell55+ *66+ * This program is free software; you can redistribute it and/or modify77+ * it under the terms of the GNU General Public License as published by88+ * the Free Software Foundation; either version 2 of the License, or99+ * (at your option) any later version.1010+ *1111+ * This program is distributed in the hope that it will be useful,1212+ * but WITHOUT ANY WARRANTY; without even the implied warranty of1313+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the1414+ * GNU General Public License for more details.1515+ *1616+ * You should have received a copy of the GNU General Public License1717+ * along with this program; if not, write to the Free Software1818+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.1919+ */2020+2121+#include <linux/autoconf.h>2222+#include <linux/kernel.h>2323+#include <linux/device.h>2424+#include <linux/init.h>2525+#include <linux/cache.h>2626+#include <linux/spi/spi.h>2727+2828+2929+/* SPI bustype and spi_master class are registered after board init code3030+ * provides the SPI device tables, ensuring that both are present by the3131+ * time controller driver registration causes spi_devices to "enumerate".3232+ */3333+static void spidev_release(struct device *dev)3434+{3535+ const struct spi_device *spi = to_spi_device(dev);3636+3737+ /* spi masters may cleanup for released devices */3838+ if (spi->master->cleanup)3939+ spi->master->cleanup(spi);4040+4141+ spi_master_put(spi->master);4242+ kfree(dev);4343+}4444+4545+static ssize_t4646+modalias_show(struct device *dev, struct device_attribute *a, char *buf)4747+{4848+ const struct spi_device *spi = to_spi_device(dev);4949+5050+ return snprintf(buf, BUS_ID_SIZE + 1, "%s\n", spi->modalias);5151+}5252+5353+static struct device_attribute spi_dev_attrs[] = {5454+ __ATTR_RO(modalias),5555+ __ATTR_NULL,5656+};5757+5858+/* modalias support makes "modprobe $MODALIAS" new-style hotplug work,5959+ * and the sysfs version makes coldplug work too.6060+ */6161+6262+static int spi_match_device(struct device *dev, struct device_driver *drv)6363+{6464+ const struct spi_device *spi = to_spi_device(dev);6565+6666+ return strncmp(spi->modalias, drv->name, BUS_ID_SIZE) == 0;6767+}6868+6969+static int spi_uevent(struct device *dev, char **envp, int num_envp,7070+ char *buffer, int buffer_size)7171+{7272+ const struct spi_device *spi = to_spi_device(dev);7373+7474+ envp[0] = buffer;7575+ snprintf(buffer, buffer_size, "MODALIAS=%s", spi->modalias);7676+ envp[1] = NULL;7777+ return 0;7878+}7979+8080+#ifdef CONFIG_PM8181+8282+/*8383+ * NOTE: the suspend() method for an spi_master controller driver8484+ * should verify that all its child devices are marked as suspended;8585+ * suspend requests delivered through sysfs power/state files don't8686+ * enforce such constraints.8787+ */8888+static int spi_suspend(struct device *dev, pm_message_t message)8989+{9090+ int value;9191+ struct spi_driver *drv = to_spi_driver(dev->driver);9292+9393+ if (!drv->suspend)9494+ return 0;9595+9696+ /* suspend will stop irqs and dma; no more i/o */9797+ value = drv->suspend(to_spi_device(dev), message);9898+ if (value == 0)9999+ dev->power.power_state = message;100100+ return value;101101+}102102+103103+static int spi_resume(struct device *dev)104104+{105105+ int value;106106+ struct spi_driver *drv = to_spi_driver(dev->driver);107107+108108+ if (!drv->resume)109109+ return 0;110110+111111+ /* resume may restart the i/o queue */112112+ value = drv->resume(to_spi_device(dev));113113+ if (value == 0)114114+ dev->power.power_state = PMSG_ON;115115+ return value;116116+}117117+118118+#else119119+#define spi_suspend NULL120120+#define spi_resume NULL121121+#endif122122+123123+struct bus_type spi_bus_type = {124124+ .name = "spi",125125+ .dev_attrs = spi_dev_attrs,126126+ .match = spi_match_device,127127+ .uevent = spi_uevent,128128+ .suspend = spi_suspend,129129+ .resume = spi_resume,130130+};131131+EXPORT_SYMBOL_GPL(spi_bus_type);132132+133133+134134+static int spi_drv_probe(struct device *dev)135135+{136136+ const struct spi_driver *sdrv = to_spi_driver(dev->driver);137137+138138+ return sdrv->probe(to_spi_device(dev));139139+}140140+141141+static int spi_drv_remove(struct device *dev)142142+{143143+ const struct spi_driver *sdrv = to_spi_driver(dev->driver);144144+145145+ return sdrv->remove(to_spi_device(dev));146146+}147147+148148+static void spi_drv_shutdown(struct device *dev)149149+{150150+ const struct spi_driver *sdrv = to_spi_driver(dev->driver);151151+152152+ sdrv->shutdown(to_spi_device(dev));153153+}154154+155155+int spi_register_driver(struct spi_driver *sdrv)156156+{157157+ sdrv->driver.bus = &spi_bus_type;158158+ if (sdrv->probe)159159+ sdrv->driver.probe = spi_drv_probe;160160+ if (sdrv->remove)161161+ sdrv->driver.remove = spi_drv_remove;162162+ if (sdrv->shutdown)163163+ sdrv->driver.shutdown = spi_drv_shutdown;164164+ return driver_register(&sdrv->driver);165165+}166166+EXPORT_SYMBOL_GPL(spi_register_driver);167167+168168+/*-------------------------------------------------------------------------*/169169+170170+/* SPI devices should normally not be created by SPI device drivers; that171171+ * would make them board-specific. Similarly with SPI master drivers.172172+ * Device registration normally goes into like arch/.../mach.../board-YYY.c173173+ * with other readonly (flashable) information about mainboard devices.174174+ */175175+176176+struct boardinfo {177177+ struct list_head list;178178+ unsigned n_board_info;179179+ struct spi_board_info board_info[0];180180+};181181+182182+static LIST_HEAD(board_list);183183+static DECLARE_MUTEX(board_lock);184184+185185+186186+/* On typical mainboards, this is purely internal; and it's not needed187187+ * after board init creates the hard-wired devices. Some development188188+ * platforms may not be able to use spi_register_board_info though, and189189+ * this is exported so that for example a USB or parport based adapter190190+ * driver could add devices (which it would learn about out-of-band).191191+ */192192+struct spi_device *__init_or_module193193+spi_new_device(struct spi_master *master, struct spi_board_info *chip)194194+{195195+ struct spi_device *proxy;196196+ struct device *dev = master->cdev.dev;197197+ int status;198198+199199+ /* NOTE: caller did any chip->bus_num checks necessary */200200+201201+ if (!spi_master_get(master))202202+ return NULL;203203+204204+ proxy = kzalloc(sizeof *proxy, GFP_KERNEL);205205+ if (!proxy) {206206+ dev_err(dev, "can't alloc dev for cs%d\n",207207+ chip->chip_select);208208+ goto fail;209209+ }210210+ proxy->master = master;211211+ proxy->chip_select = chip->chip_select;212212+ proxy->max_speed_hz = chip->max_speed_hz;213213+ proxy->irq = chip->irq;214214+ proxy->modalias = chip->modalias;215215+216216+ snprintf(proxy->dev.bus_id, sizeof proxy->dev.bus_id,217217+ "%s.%u", master->cdev.class_id,218218+ chip->chip_select);219219+ proxy->dev.parent = dev;220220+ proxy->dev.bus = &spi_bus_type;221221+ proxy->dev.platform_data = (void *) chip->platform_data;222222+ proxy->controller_data = chip->controller_data;223223+ proxy->controller_state = NULL;224224+ proxy->dev.release = spidev_release;225225+226226+ /* drivers may modify this default i/o setup */227227+ status = master->setup(proxy);228228+ if (status < 0) {229229+ dev_dbg(dev, "can't %s %s, status %d\n",230230+ "setup", proxy->dev.bus_id, status);231231+ goto fail;232232+ }233233+234234+ /* driver core catches callers that misbehave by defining235235+ * devices that already exist.236236+ */237237+ status = device_register(&proxy->dev);238238+ if (status < 0) {239239+ dev_dbg(dev, "can't %s %s, status %d\n",240240+ "add", proxy->dev.bus_id, status);241241+ goto fail;242242+ }243243+ dev_dbg(dev, "registered child %s\n", proxy->dev.bus_id);244244+ return proxy;245245+246246+fail:247247+ spi_master_put(master);248248+ kfree(proxy);249249+ return NULL;250250+}251251+EXPORT_SYMBOL_GPL(spi_new_device);252252+253253+/*254254+ * Board-specific early init code calls this (probably during arch_initcall)255255+ * with segments of the SPI device table. Any device nodes are created later,256256+ * after the relevant parent SPI controller (bus_num) is defined. We keep257257+ * this table of devices forever, so that reloading a controller driver will258258+ * not make Linux forget about these hard-wired devices.259259+ *260260+ * Other code can also call this, e.g. a particular add-on board might provide261261+ * SPI devices through its expansion connector, so code initializing that board262262+ * would naturally declare its SPI devices.263263+ *264264+ * The board info passed can safely be __initdata ... but be careful of265265+ * any embedded pointers (platform_data, etc), they're copied as-is.266266+ */267267+int __init268268+spi_register_board_info(struct spi_board_info const *info, unsigned n)269269+{270270+ struct boardinfo *bi;271271+272272+ bi = kmalloc(sizeof(*bi) + n * sizeof *info, GFP_KERNEL);273273+ if (!bi)274274+ return -ENOMEM;275275+ bi->n_board_info = n;276276+ memcpy(bi->board_info, info, n * sizeof *info);277277+278278+ down(&board_lock);279279+ list_add_tail(&bi->list, &board_list);280280+ up(&board_lock);281281+ return 0;282282+}283283+EXPORT_SYMBOL_GPL(spi_register_board_info);284284+285285+/* FIXME someone should add support for a __setup("spi", ...) that286286+ * creates board info from kernel command lines287287+ */288288+289289+static void __init_or_module290290+scan_boardinfo(struct spi_master *master)291291+{292292+ struct boardinfo *bi;293293+ struct device *dev = master->cdev.dev;294294+295295+ down(&board_lock);296296+ list_for_each_entry(bi, &board_list, list) {297297+ struct spi_board_info *chip = bi->board_info;298298+ unsigned n;299299+300300+ for (n = bi->n_board_info; n > 0; n--, chip++) {301301+ if (chip->bus_num != master->bus_num)302302+ continue;303303+ /* some controllers only have one chip, so they304304+ * might not use chipselects. otherwise, the305305+ * chipselects are numbered 0..max.306306+ */307307+ if (chip->chip_select >= master->num_chipselect308308+ && master->num_chipselect) {309309+ dev_dbg(dev, "cs%d > max %d\n",310310+ chip->chip_select,311311+ master->num_chipselect);312312+ continue;313313+ }314314+ (void) spi_new_device(master, chip);315315+ }316316+ }317317+ up(&board_lock);318318+}319319+320320+/*-------------------------------------------------------------------------*/321321+322322+static void spi_master_release(struct class_device *cdev)323323+{324324+ struct spi_master *master;325325+326326+ master = container_of(cdev, struct spi_master, cdev);327327+ kfree(master);328328+}329329+330330+static struct class spi_master_class = {331331+ .name = "spi_master",332332+ .owner = THIS_MODULE,333333+ .release = spi_master_release,334334+};335335+336336+337337+/**338338+ * spi_alloc_master - allocate SPI master controller339339+ * @dev: the controller, possibly using the platform_bus340340+ * @size: how much driver-private data to preallocate; the pointer to this341341+ * memory is in the class_data field of the returned class_device,342342+ * accessible with spi_master_get_devdata().343343+ *344344+ * This call is used only by SPI master controller drivers, which are the345345+ * only ones directly touching chip registers. It's how they allocate346346+ * an spi_master structure, prior to calling spi_add_master().347347+ *348348+ * This must be called from context that can sleep. It returns the SPI349349+ * master structure on success, else NULL.350350+ *351351+ * The caller is responsible for assigning the bus number and initializing352352+ * the master's methods before calling spi_add_master(); and (after errors353353+ * adding the device) calling spi_master_put() to prevent a memory leak.354354+ */355355+struct spi_master * __init_or_module356356+spi_alloc_master(struct device *dev, unsigned size)357357+{358358+ struct spi_master *master;359359+360360+ if (!dev)361361+ return NULL;362362+363363+ master = kzalloc(size + sizeof *master, SLAB_KERNEL);364364+ if (!master)365365+ return NULL;366366+367367+ class_device_initialize(&master->cdev);368368+ master->cdev.class = &spi_master_class;369369+ master->cdev.dev = get_device(dev);370370+ spi_master_set_devdata(master, &master[1]);371371+372372+ return master;373373+}374374+EXPORT_SYMBOL_GPL(spi_alloc_master);375375+376376+/**377377+ * spi_register_master - register SPI master controller378378+ * @master: initialized master, originally from spi_alloc_master()379379+ *380380+ * SPI master controllers connect to their drivers using some non-SPI bus,381381+ * such as the platform bus. The final stage of probe() in that code382382+ * includes calling spi_register_master() to hook up to this SPI bus glue.383383+ *384384+ * SPI controllers use board specific (often SOC specific) bus numbers,385385+ * and board-specific addressing for SPI devices combines those numbers386386+ * with chip select numbers. Since SPI does not directly support dynamic387387+ * device identification, boards need configuration tables telling which388388+ * chip is at which address.389389+ *390390+ * This must be called from context that can sleep. It returns zero on391391+ * success, else a negative error code (dropping the master's refcount).392392+ * After a successful return, the caller is responsible for calling393393+ * spi_unregister_master().394394+ */395395+int __init_or_module396396+spi_register_master(struct spi_master *master)397397+{398398+ static atomic_t dyn_bus_id = ATOMIC_INIT(0);399399+ struct device *dev = master->cdev.dev;400400+ int status = -ENODEV;401401+ int dynamic = 0;402402+403403+ if (!dev)404404+ return -ENODEV;405405+406406+ /* convention: dynamically assigned bus IDs count down from the max */407407+ if (master->bus_num == 0) {408408+ master->bus_num = atomic_dec_return(&dyn_bus_id);409409+ dynamic = 1;410410+ }411411+412412+ /* register the device, then userspace will see it.413413+ * registration fails if the bus ID is in use.414414+ */415415+ snprintf(master->cdev.class_id, sizeof master->cdev.class_id,416416+ "spi%u", master->bus_num);417417+ status = class_device_add(&master->cdev);418418+ if (status < 0)419419+ goto done;420420+ dev_dbg(dev, "registered master %s%s\n", master->cdev.class_id,421421+ dynamic ? " (dynamic)" : "");422422+423423+ /* populate children from any spi device tables */424424+ scan_boardinfo(master);425425+ status = 0;426426+done:427427+ return status;428428+}429429+EXPORT_SYMBOL_GPL(spi_register_master);430430+431431+432432+static int __unregister(struct device *dev, void *unused)433433+{434434+ /* note: before about 2.6.14-rc1 this would corrupt memory: */435435+ spi_unregister_device(to_spi_device(dev));436436+ return 0;437437+}438438+439439+/**440440+ * spi_unregister_master - unregister SPI master controller441441+ * @master: the master being unregistered442442+ *443443+ * This call is used only by SPI master controller drivers, which are the444444+ * only ones directly touching chip registers.445445+ *446446+ * This must be called from context that can sleep.447447+ */448448+void spi_unregister_master(struct spi_master *master)449449+{450450+ (void) device_for_each_child(master->cdev.dev, NULL, __unregister);451451+ class_device_unregister(&master->cdev);452452+ master->cdev.dev = NULL;453453+}454454+EXPORT_SYMBOL_GPL(spi_unregister_master);455455+456456+/**457457+ * spi_busnum_to_master - look up master associated with bus_num458458+ * @bus_num: the master's bus number459459+ *460460+ * This call may be used with devices that are registered after461461+ * arch init time. It returns a refcounted pointer to the relevant462462+ * spi_master (which the caller must release), or NULL if there is463463+ * no such master registered.464464+ */465465+struct spi_master *spi_busnum_to_master(u16 bus_num)466466+{467467+ if (bus_num) {468468+ char name[8];469469+ struct kobject *bus;470470+471471+ snprintf(name, sizeof name, "spi%u", bus_num);472472+ bus = kset_find_obj(&spi_master_class.subsys.kset, name);473473+ if (bus)474474+ return container_of(bus, struct spi_master, cdev.kobj);475475+ }476476+ return NULL;477477+}478478+EXPORT_SYMBOL_GPL(spi_busnum_to_master);479479+480480+481481+/*-------------------------------------------------------------------------*/482482+483483+static void spi_complete(void *arg)484484+{485485+ complete(arg);486486+}487487+488488+/**489489+ * spi_sync - blocking/synchronous SPI data transfers490490+ * @spi: device with which data will be exchanged491491+ * @message: describes the data transfers492492+ *493493+ * This call may only be used from a context that may sleep. The sleep494494+ * is non-interruptible, and has no timeout. Low-overhead controller495495+ * drivers may DMA directly into and out of the message buffers.496496+ *497497+ * Note that the SPI device's chip select is active during the message,498498+ * and then is normally disabled between messages. Drivers for some499499+ * frequently-used devices may want to minimize costs of selecting a chip,500500+ * by leaving it selected in anticipation that the next message will go501501+ * to the same chip. (That may increase power usage.)502502+ *503503+ * Also, the caller is guaranteeing that the memory associated with the504504+ * message will not be freed before this call returns.505505+ *506506+ * The return value is a negative error code if the message could not be507507+ * submitted, else zero. When the value is zero, then message->status is508508+ * also defined: it's the completion code for the transfer, either zero509509+ * or a negative error code from the controller driver.510510+ */511511+int spi_sync(struct spi_device *spi, struct spi_message *message)512512+{513513+ DECLARE_COMPLETION(done);514514+ int status;515515+516516+ message->complete = spi_complete;517517+ message->context = &done;518518+ status = spi_async(spi, message);519519+ if (status == 0)520520+ wait_for_completion(&done);521521+ message->context = NULL;522522+ return status;523523+}524524+EXPORT_SYMBOL_GPL(spi_sync);525525+526526+#define SPI_BUFSIZ (SMP_CACHE_BYTES)527527+528528+static u8 *buf;529529+530530+/**531531+ * spi_write_then_read - SPI synchronous write followed by read532532+ * @spi: device with which data will be exchanged533533+ * @txbuf: data to be written (need not be dma-safe)534534+ * @n_tx: size of txbuf, in bytes535535+ * @rxbuf: buffer into which data will be read536536+ * @n_rx: size of rxbuf, in bytes (need not be dma-safe)537537+ *538538+ * This performs a half duplex MicroWire style transaction with the539539+ * device, sending txbuf and then reading rxbuf. The return value540540+ * is zero for success, else a negative errno status code.541541+ * This call may only be used from a context that may sleep.542542+ *543543+ * Parameters to this routine are always copied using a small buffer;544544+ * performance-sensitive or bulk transfer code should instead use545545+ * spi_{async,sync}() calls with dma-safe buffers.546546+ */547547+int spi_write_then_read(struct spi_device *spi,548548+ const u8 *txbuf, unsigned n_tx,549549+ u8 *rxbuf, unsigned n_rx)550550+{551551+ static DECLARE_MUTEX(lock);552552+553553+ int status;554554+ struct spi_message message;555555+ struct spi_transfer x[2];556556+ u8 *local_buf;557557+558558+ /* Use preallocated DMA-safe buffer. We can't avoid copying here,559559+ * (as a pure convenience thing), but we can keep heap costs560560+ * out of the hot path ...561561+ */562562+ if ((n_tx + n_rx) > SPI_BUFSIZ)563563+ return -EINVAL;564564+565565+ spi_message_init(&message);566566+ memset(x, 0, sizeof x);567567+ if (n_tx) {568568+ x[0].len = n_tx;569569+ spi_message_add_tail(&x[0], &message);570570+ }571571+ if (n_rx) {572572+ x[1].len = n_rx;573573+ spi_message_add_tail(&x[1], &message);574574+ }575575+576576+ /* ... unless someone else is using the pre-allocated buffer */577577+ if (down_trylock(&lock)) {578578+ local_buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);579579+ if (!local_buf)580580+ return -ENOMEM;581581+ } else582582+ local_buf = buf;583583+584584+ memcpy(local_buf, txbuf, n_tx);585585+ x[0].tx_buf = local_buf;586586+ x[1].rx_buf = local_buf + n_tx;587587+588588+ /* do the i/o */589589+ status = spi_sync(spi, &message);590590+ if (status == 0) {591591+ memcpy(rxbuf, x[1].rx_buf, n_rx);592592+ status = message.status;593593+ }594594+595595+ if (x[0].tx_buf == buf)596596+ up(&lock);597597+ else598598+ kfree(local_buf);599599+600600+ return status;601601+}602602+EXPORT_SYMBOL_GPL(spi_write_then_read);603603+604604+/*-------------------------------------------------------------------------*/605605+606606+static int __init spi_init(void)607607+{608608+ int status;609609+610610+ buf = kmalloc(SPI_BUFSIZ, SLAB_KERNEL);611611+ if (!buf) {612612+ status = -ENOMEM;613613+ goto err0;614614+ }615615+616616+ status = bus_register(&spi_bus_type);617617+ if (status < 0)618618+ goto err1;619619+620620+ status = class_register(&spi_master_class);621621+ if (status < 0)622622+ goto err2;623623+ return 0;624624+625625+err2:626626+ bus_unregister(&spi_bus_type);627627+err1:628628+ kfree(buf);629629+ buf = NULL;630630+err0:631631+ return status;632632+}633633+634634+/* board_info is normally registered in arch_initcall(),635635+ * but even essential drivers wait till later636636+ *637637+ * REVISIT only boardinfo really needs static linking. the rest (device and638638+ * driver registration) _could_ be dynamically linked (modular) ... costs639639+ * include needing to have boardinfo data structures be much more public.640640+ */641641+subsys_initcall(spi_init);642642+
+472
drivers/spi/spi_bitbang.c
···11+/*22+ * spi_bitbang.c - polling/bitbanging SPI master controller driver utilities33+ *44+ * This program is free software; you can redistribute it and/or modify55+ * it under the terms of the GNU General Public License as published by66+ * the Free Software Foundation; either version 2 of the License, or77+ * (at your option) any later version.88+ *99+ * This program is distributed in the hope that it will be useful,1010+ * but WITHOUT ANY WARRANTY; without even the implied warranty of1111+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the1212+ * GNU General Public License for more details.1313+ *1414+ * You should have received a copy of the GNU General Public License1515+ * along with this program; if not, write to the Free Software1616+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA1717+ */1818+1919+#include <linux/config.h>2020+#include <linux/init.h>2121+#include <linux/spinlock.h>2222+#include <linux/workqueue.h>2323+#include <linux/interrupt.h>2424+#include <linux/delay.h>2525+#include <linux/errno.h>2626+#include <linux/platform_device.h>2727+2828+#include <linux/spi/spi.h>2929+#include <linux/spi/spi_bitbang.h>3030+3131+3232+/*----------------------------------------------------------------------*/3333+3434+/*3535+ * FIRST PART (OPTIONAL): word-at-a-time spi_transfer support.3636+ * Use this for GPIO or shift-register level hardware APIs.3737+ *3838+ * spi_bitbang_cs is in spi_device->controller_state, which is unavailable3939+ * to glue code. These bitbang setup() and cleanup() routines are always4040+ * used, though maybe they're called from controller-aware code.4141+ *4242+ * chipselect() and friends may use use spi_device->controller_data and4343+ * controller registers as appropriate.4444+ *4545+ *4646+ * NOTE: SPI controller pins can often be used as GPIO pins instead,4747+ * which means you could use a bitbang driver either to get hardware4848+ * working quickly, or testing for differences that aren't speed related.4949+ */5050+5151+struct spi_bitbang_cs {5252+ unsigned nsecs; /* (clock cycle time)/2 */5353+ u32 (*txrx_word)(struct spi_device *spi, unsigned nsecs,5454+ u32 word, u8 bits);5555+ unsigned (*txrx_bufs)(struct spi_device *,5656+ u32 (*txrx_word)(5757+ struct spi_device *spi,5858+ unsigned nsecs,5959+ u32 word, u8 bits),6060+ unsigned, struct spi_transfer *);6161+};6262+6363+static unsigned bitbang_txrx_8(6464+ struct spi_device *spi,6565+ u32 (*txrx_word)(struct spi_device *spi,6666+ unsigned nsecs,6767+ u32 word, u8 bits),6868+ unsigned ns,6969+ struct spi_transfer *t7070+) {7171+ unsigned bits = spi->bits_per_word;7272+ unsigned count = t->len;7373+ const u8 *tx = t->tx_buf;7474+ u8 *rx = t->rx_buf;7575+7676+ while (likely(count > 0)) {7777+ u8 word = 0;7878+7979+ if (tx)8080+ word = *tx++;8181+ word = txrx_word(spi, ns, word, bits);8282+ if (rx)8383+ *rx++ = word;8484+ count -= 1;8585+ }8686+ return t->len - count;8787+}8888+8989+static unsigned bitbang_txrx_16(9090+ struct spi_device *spi,9191+ u32 (*txrx_word)(struct spi_device *spi,9292+ unsigned nsecs,9393+ u32 word, u8 bits),9494+ unsigned ns,9595+ struct spi_transfer *t9696+) {9797+ unsigned bits = spi->bits_per_word;9898+ unsigned count = t->len;9999+ const u16 *tx = t->tx_buf;100100+ u16 *rx = t->rx_buf;101101+102102+ while (likely(count > 1)) {103103+ u16 word = 0;104104+105105+ if (tx)106106+ word = *tx++;107107+ word = txrx_word(spi, ns, word, bits);108108+ if (rx)109109+ *rx++ = word;110110+ count -= 2;111111+ }112112+ return t->len - count;113113+}114114+115115+static unsigned bitbang_txrx_32(116116+ struct spi_device *spi,117117+ u32 (*txrx_word)(struct spi_device *spi,118118+ unsigned nsecs,119119+ u32 word, u8 bits),120120+ unsigned ns,121121+ struct spi_transfer *t122122+) {123123+ unsigned bits = spi->bits_per_word;124124+ unsigned count = t->len;125125+ const u32 *tx = t->tx_buf;126126+ u32 *rx = t->rx_buf;127127+128128+ while (likely(count > 3)) {129129+ u32 word = 0;130130+131131+ if (tx)132132+ word = *tx++;133133+ word = txrx_word(spi, ns, word, bits);134134+ if (rx)135135+ *rx++ = word;136136+ count -= 4;137137+ }138138+ return t->len - count;139139+}140140+141141+/**142142+ * spi_bitbang_setup - default setup for per-word I/O loops143143+ */144144+int spi_bitbang_setup(struct spi_device *spi)145145+{146146+ struct spi_bitbang_cs *cs = spi->controller_state;147147+ struct spi_bitbang *bitbang;148148+149149+ if (!spi->max_speed_hz)150150+ return -EINVAL;151151+152152+ if (!cs) {153153+ cs = kzalloc(sizeof *cs, SLAB_KERNEL);154154+ if (!cs)155155+ return -ENOMEM;156156+ spi->controller_state = cs;157157+ }158158+ bitbang = spi_master_get_devdata(spi->master);159159+160160+ if (!spi->bits_per_word)161161+ spi->bits_per_word = 8;162162+163163+ /* spi_transfer level calls that work per-word */164164+ if (spi->bits_per_word <= 8)165165+ cs->txrx_bufs = bitbang_txrx_8;166166+ else if (spi->bits_per_word <= 16)167167+ cs->txrx_bufs = bitbang_txrx_16;168168+ else if (spi->bits_per_word <= 32)169169+ cs->txrx_bufs = bitbang_txrx_32;170170+ else171171+ return -EINVAL;172172+173173+ /* per-word shift register access, in hardware or bitbanging */174174+ cs->txrx_word = bitbang->txrx_word[spi->mode & (SPI_CPOL|SPI_CPHA)];175175+ if (!cs->txrx_word)176176+ return -EINVAL;177177+178178+ /* nsecs = (clock period)/2 */179179+ cs->nsecs = (1000000000/2) / (spi->max_speed_hz);180180+ if (cs->nsecs > MAX_UDELAY_MS * 1000)181181+ return -EINVAL;182182+183183+ dev_dbg(&spi->dev, "%s, mode %d, %u bits/w, %u nsec\n",184184+ __FUNCTION__, spi->mode & (SPI_CPOL | SPI_CPHA),185185+ spi->bits_per_word, 2 * cs->nsecs);186186+187187+ /* NOTE we _need_ to call chipselect() early, ideally with adapter188188+ * setup, unless the hardware defaults cooperate to avoid confusion189189+ * between normal (active low) and inverted chipselects.190190+ */191191+192192+ /* deselect chip (low or high) */193193+ spin_lock(&bitbang->lock);194194+ if (!bitbang->busy) {195195+ bitbang->chipselect(spi, BITBANG_CS_INACTIVE);196196+ ndelay(cs->nsecs);197197+ }198198+ spin_unlock(&bitbang->lock);199199+200200+ return 0;201201+}202202+EXPORT_SYMBOL_GPL(spi_bitbang_setup);203203+204204+/**205205+ * spi_bitbang_cleanup - default cleanup for per-word I/O loops206206+ */207207+void spi_bitbang_cleanup(const struct spi_device *spi)208208+{209209+ kfree(spi->controller_state);210210+}211211+EXPORT_SYMBOL_GPL(spi_bitbang_cleanup);212212+213213+static int spi_bitbang_bufs(struct spi_device *spi, struct spi_transfer *t)214214+{215215+ struct spi_bitbang_cs *cs = spi->controller_state;216216+ unsigned nsecs = cs->nsecs;217217+218218+ return cs->txrx_bufs(spi, cs->txrx_word, nsecs, t);219219+}220220+221221+/*----------------------------------------------------------------------*/222222+223223+/*224224+ * SECOND PART ... simple transfer queue runner.225225+ *226226+ * This costs a task context per controller, running the queue by227227+ * performing each transfer in sequence. Smarter hardware can queue228228+ * several DMA transfers at once, and process several controller queues229229+ * in parallel; this driver doesn't match such hardware very well.230230+ *231231+ * Drivers can provide word-at-a-time i/o primitives, or provide232232+ * transfer-at-a-time ones to leverage dma or fifo hardware.233233+ */234234+static void bitbang_work(void *_bitbang)235235+{236236+ struct spi_bitbang *bitbang = _bitbang;237237+ unsigned long flags;238238+239239+ spin_lock_irqsave(&bitbang->lock, flags);240240+ bitbang->busy = 1;241241+ while (!list_empty(&bitbang->queue)) {242242+ struct spi_message *m;243243+ struct spi_device *spi;244244+ unsigned nsecs;245245+ struct spi_transfer *t = NULL;246246+ unsigned tmp;247247+ unsigned cs_change;248248+ int status;249249+250250+ m = container_of(bitbang->queue.next, struct spi_message,251251+ queue);252252+ list_del_init(&m->queue);253253+ spin_unlock_irqrestore(&bitbang->lock, flags);254254+255255+ /* FIXME this is made-up ... the correct value is known to256256+ * word-at-a-time bitbang code, and presumably chipselect()257257+ * should enforce these requirements too?258258+ */259259+ nsecs = 100;260260+261261+ spi = m->spi;262262+ tmp = 0;263263+ cs_change = 1;264264+ status = 0;265265+266266+ list_for_each_entry (t, &m->transfers, transfer_list) {267267+ if (bitbang->shutdown) {268268+ status = -ESHUTDOWN;269269+ break;270270+ }271271+272272+ /* set up default clock polarity, and activate chip;273273+ * this implicitly updates clock and spi modes as274274+ * previously recorded for this device via setup().275275+ * (and also deselects any other chip that might be276276+ * selected ...)277277+ */278278+ if (cs_change) {279279+ bitbang->chipselect(spi, BITBANG_CS_ACTIVE);280280+ ndelay(nsecs);281281+ }282282+ cs_change = t->cs_change;283283+ if (!t->tx_buf && !t->rx_buf && t->len) {284284+ status = -EINVAL;285285+ break;286286+ }287287+288288+ /* transfer data. the lower level code handles any289289+ * new dma mappings it needs. our caller always gave290290+ * us dma-safe buffers.291291+ */292292+ if (t->len) {293293+ /* REVISIT dma API still needs a designated294294+ * DMA_ADDR_INVALID; ~0 might be better.295295+ */296296+ if (!m->is_dma_mapped)297297+ t->rx_dma = t->tx_dma = 0;298298+ status = bitbang->txrx_bufs(spi, t);299299+ }300300+ if (status != t->len) {301301+ if (status > 0)302302+ status = -EMSGSIZE;303303+ break;304304+ }305305+ m->actual_length += status;306306+ status = 0;307307+308308+ /* protocol tweaks before next transfer */309309+ if (t->delay_usecs)310310+ udelay(t->delay_usecs);311311+312312+ if (!cs_change)313313+ continue;314314+ if (t->transfer_list.next == &m->transfers)315315+ break;316316+317317+ /* sometimes a short mid-message deselect of the chip318318+ * may be needed to terminate a mode or command319319+ */320320+ ndelay(nsecs);321321+ bitbang->chipselect(spi, BITBANG_CS_INACTIVE);322322+ ndelay(nsecs);323323+ }324324+325325+ m->status = status;326326+ m->complete(m->context);327327+328328+ /* normally deactivate chipselect ... unless no error and329329+ * cs_change has hinted that the next message will probably330330+ * be for this chip too.331331+ */332332+ if (!(status == 0 && cs_change)) {333333+ ndelay(nsecs);334334+ bitbang->chipselect(spi, BITBANG_CS_INACTIVE);335335+ ndelay(nsecs);336336+ }337337+338338+ spin_lock_irqsave(&bitbang->lock, flags);339339+ }340340+ bitbang->busy = 0;341341+ spin_unlock_irqrestore(&bitbang->lock, flags);342342+}343343+344344+/**345345+ * spi_bitbang_transfer - default submit to transfer queue346346+ */347347+int spi_bitbang_transfer(struct spi_device *spi, struct spi_message *m)348348+{349349+ struct spi_bitbang *bitbang;350350+ unsigned long flags;351351+352352+ m->actual_length = 0;353353+ m->status = -EINPROGRESS;354354+355355+ bitbang = spi_master_get_devdata(spi->master);356356+ if (bitbang->shutdown)357357+ return -ESHUTDOWN;358358+359359+ spin_lock_irqsave(&bitbang->lock, flags);360360+ list_add_tail(&m->queue, &bitbang->queue);361361+ queue_work(bitbang->workqueue, &bitbang->work);362362+ spin_unlock_irqrestore(&bitbang->lock, flags);363363+364364+ return 0;365365+}366366+EXPORT_SYMBOL_GPL(spi_bitbang_transfer);367367+368368+/*----------------------------------------------------------------------*/369369+370370+/**371371+ * spi_bitbang_start - start up a polled/bitbanging SPI master driver372372+ * @bitbang: driver handle373373+ *374374+ * Caller should have zero-initialized all parts of the structure, and then375375+ * provided callbacks for chip selection and I/O loops. If the master has376376+ * a transfer method, its final step should call spi_bitbang_transfer; or,377377+ * that's the default if the transfer routine is not initialized. It should378378+ * also set up the bus number and number of chipselects.379379+ *380380+ * For i/o loops, provide callbacks either per-word (for bitbanging, or for381381+ * hardware that basically exposes a shift register) or per-spi_transfer382382+ * (which takes better advantage of hardware like fifos or DMA engines).383383+ *384384+ * Drivers using per-word I/O loops should use (or call) spi_bitbang_setup and385385+ * spi_bitbang_cleanup to handle those spi master methods. Those methods are386386+ * the defaults if the bitbang->txrx_bufs routine isn't initialized.387387+ *388388+ * This routine registers the spi_master, which will process requests in a389389+ * dedicated task, keeping IRQs unblocked most of the time. To stop390390+ * processing those requests, call spi_bitbang_stop().391391+ */392392+int spi_bitbang_start(struct spi_bitbang *bitbang)393393+{394394+ int status;395395+396396+ if (!bitbang->master || !bitbang->chipselect)397397+ return -EINVAL;398398+399399+ INIT_WORK(&bitbang->work, bitbang_work, bitbang);400400+ spin_lock_init(&bitbang->lock);401401+ INIT_LIST_HEAD(&bitbang->queue);402402+403403+ if (!bitbang->master->transfer)404404+ bitbang->master->transfer = spi_bitbang_transfer;405405+ if (!bitbang->txrx_bufs) {406406+ bitbang->use_dma = 0;407407+ bitbang->txrx_bufs = spi_bitbang_bufs;408408+ if (!bitbang->master->setup) {409409+ bitbang->master->setup = spi_bitbang_setup;410410+ bitbang->master->cleanup = spi_bitbang_cleanup;411411+ }412412+ } else if (!bitbang->master->setup)413413+ return -EINVAL;414414+415415+ /* this task is the only thing to touch the SPI bits */416416+ bitbang->busy = 0;417417+ bitbang->workqueue = create_singlethread_workqueue(418418+ bitbang->master->cdev.dev->bus_id);419419+ if (bitbang->workqueue == NULL) {420420+ status = -EBUSY;421421+ goto err1;422422+ }423423+424424+ /* driver may get busy before register() returns, especially425425+ * if someone registered boardinfo for devices426426+ */427427+ status = spi_register_master(bitbang->master);428428+ if (status < 0)429429+ goto err2;430430+431431+ return status;432432+433433+err2:434434+ destroy_workqueue(bitbang->workqueue);435435+err1:436436+ return status;437437+}438438+EXPORT_SYMBOL_GPL(spi_bitbang_start);439439+440440+/**441441+ * spi_bitbang_stop - stops the task providing spi communication442442+ */443443+int spi_bitbang_stop(struct spi_bitbang *bitbang)444444+{445445+ unsigned limit = 500;446446+447447+ spin_lock_irq(&bitbang->lock);448448+ bitbang->shutdown = 0;449449+ while (!list_empty(&bitbang->queue) && limit--) {450450+ spin_unlock_irq(&bitbang->lock);451451+452452+ dev_dbg(bitbang->master->cdev.dev, "wait for queue\n");453453+ msleep(10);454454+455455+ spin_lock_irq(&bitbang->lock);456456+ }457457+ spin_unlock_irq(&bitbang->lock);458458+ if (!list_empty(&bitbang->queue)) {459459+ dev_err(bitbang->master->cdev.dev, "queue didn't empty\n");460460+ return -EBUSY;461461+ }462462+463463+ destroy_workqueue(bitbang->workqueue);464464+465465+ spi_unregister_master(bitbang->master);466466+467467+ return 0;468468+}469469+EXPORT_SYMBOL_GPL(spi_bitbang_stop);470470+471471+MODULE_LICENSE("GPL");472472+
+423
drivers/spi/spi_butterfly.c
···11+/*22+ * spi_butterfly.c - parport-to-butterfly adapter33+ *44+ * Copyright (C) 2005 David Brownell55+ *66+ * This program is free software; you can redistribute it and/or modify77+ * it under the terms of the GNU General Public License as published by88+ * the Free Software Foundation; either version 2 of the License, or99+ * (at your option) any later version.1010+ *1111+ * This program is distributed in the hope that it will be useful,1212+ * but WITHOUT ANY WARRANTY; without even the implied warranty of1313+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the1414+ * GNU General Public License for more details.1515+ *1616+ * You should have received a copy of the GNU General Public License1717+ * along with this program; if not, write to the Free Software1818+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.1919+ */2020+#include <linux/config.h>2121+#include <linux/kernel.h>2222+#include <linux/init.h>2323+#include <linux/delay.h>2424+#include <linux/platform_device.h>2525+#include <linux/parport.h>2626+2727+#include <linux/spi/spi.h>2828+#include <linux/spi/spi_bitbang.h>2929+#include <linux/spi/flash.h>3030+3131+#include <linux/mtd/partitions.h>3232+3333+3434+/*3535+ * This uses SPI to talk with an "AVR Butterfly", which is a $US20 card3636+ * with a battery powered AVR microcontroller and lots of goodies. You3737+ * can use GCC to develop firmware for this.3838+ *3939+ * See Documentation/spi/butterfly for information about how to build4040+ * and use this custom parallel port cable.4141+ */4242+4343+#undef HAVE_USI /* nyet */4444+4545+4646+/* DATA output bits (pins 2..9 == D0..D7) */4747+#define butterfly_nreset (1 << 1) /* pin 3 */4848+4949+#define spi_sck_bit (1 << 0) /* pin 2 */5050+#define spi_mosi_bit (1 << 7) /* pin 9 */5151+5252+#define usi_sck_bit (1 << 3) /* pin 5 */5353+#define usi_mosi_bit (1 << 4) /* pin 6 */5454+5555+#define vcc_bits ((1 << 6) | (1 << 5)) /* pins 7, 8 */5656+5757+/* STATUS input bits */5858+#define spi_miso_bit PARPORT_STATUS_BUSY /* pin 11 */5959+6060+#define usi_miso_bit PARPORT_STATUS_PAPEROUT /* pin 12 */6161+6262+/* CONTROL output bits */6363+#define spi_cs_bit PARPORT_CONTROL_SELECT /* pin 17 */6464+/* USI uses no chipselect */6565+6666+6767+6868+static inline struct butterfly *spidev_to_pp(struct spi_device *spi)6969+{7070+ return spi->controller_data;7171+}7272+7373+static inline int is_usidev(struct spi_device *spi)7474+{7575+#ifdef HAVE_USI7676+ return spi->chip_select != 1;7777+#else7878+ return 0;7979+#endif8080+}8181+8282+8383+struct butterfly {8484+ /* REVISIT ... for now, this must be first */8585+ struct spi_bitbang bitbang;8686+8787+ struct parport *port;8888+ struct pardevice *pd;8989+9090+ u8 lastbyte;9191+9292+ struct spi_device *dataflash;9393+ struct spi_device *butterfly;9494+ struct spi_board_info info[2];9595+9696+};9797+9898+/*----------------------------------------------------------------------*/9999+100100+/*101101+ * these routines may be slower than necessary because they're hiding102102+ * the fact that there are two different SPI busses on this cable: one103103+ * to the DataFlash chip (or AVR SPI controller), the other to the104104+ * AVR USI controller.105105+ */106106+107107+static inline void108108+setsck(struct spi_device *spi, int is_on)109109+{110110+ struct butterfly *pp = spidev_to_pp(spi);111111+ u8 bit, byte = pp->lastbyte;112112+113113+ if (is_usidev(spi))114114+ bit = usi_sck_bit;115115+ else116116+ bit = spi_sck_bit;117117+118118+ if (is_on)119119+ byte |= bit;120120+ else121121+ byte &= ~bit;122122+ parport_write_data(pp->port, byte);123123+ pp->lastbyte = byte;124124+}125125+126126+static inline void127127+setmosi(struct spi_device *spi, int is_on)128128+{129129+ struct butterfly *pp = spidev_to_pp(spi);130130+ u8 bit, byte = pp->lastbyte;131131+132132+ if (is_usidev(spi))133133+ bit = usi_mosi_bit;134134+ else135135+ bit = spi_mosi_bit;136136+137137+ if (is_on)138138+ byte |= bit;139139+ else140140+ byte &= ~bit;141141+ parport_write_data(pp->port, byte);142142+ pp->lastbyte = byte;143143+}144144+145145+static inline int getmiso(struct spi_device *spi)146146+{147147+ struct butterfly *pp = spidev_to_pp(spi);148148+ int value;149149+ u8 bit;150150+151151+ if (is_usidev(spi))152152+ bit = usi_miso_bit;153153+ else154154+ bit = spi_miso_bit;155155+156156+ /* only STATUS_BUSY is NOT negated */157157+ value = !(parport_read_status(pp->port) & bit);158158+ return (bit == PARPORT_STATUS_BUSY) ? value : !value;159159+}160160+161161+static void butterfly_chipselect(struct spi_device *spi, int value)162162+{163163+ struct butterfly *pp = spidev_to_pp(spi);164164+165165+ /* set default clock polarity */166166+ if (value)167167+ setsck(spi, spi->mode & SPI_CPOL);168168+169169+ /* no chipselect on this USI link config */170170+ if (is_usidev(spi))171171+ return;172172+173173+ /* here, value == "activate or not" */174174+175175+ /* most PARPORT_CONTROL_* bits are negated */176176+ if (spi_cs_bit == PARPORT_CONTROL_INIT)177177+ value = !value;178178+179179+ /* here, value == "bit value to write in control register" */180180+181181+ parport_frob_control(pp->port, spi_cs_bit, value ? spi_cs_bit : 0);182182+}183183+184184+185185+/* we only needed to implement one mode here, and choose SPI_MODE_0 */186186+187187+#define spidelay(X) do{}while(0)188188+//#define spidelay ndelay189189+190190+#define EXPAND_BITBANG_TXRX191191+#include <linux/spi/spi_bitbang.h>192192+193193+static u32194194+butterfly_txrx_word_mode0(struct spi_device *spi,195195+ unsigned nsecs,196196+ u32 word, u8 bits)197197+{198198+ return bitbang_txrx_be_cpha0(spi, nsecs, 0, word, bits);199199+}200200+201201+/*----------------------------------------------------------------------*/202202+203203+/* override default partitioning with cmdlinepart */204204+static struct mtd_partition partitions[] = { {205205+ /* JFFS2 wants partitions of 4*N blocks for this device ... */206206+207207+ /* sector 0 = 8 pages * 264 bytes/page (1 block)208208+ * sector 1 = 248 pages * 264 bytes/page209209+ */210210+ .name = "bookkeeping", // 66 KB211211+ .offset = 0,212212+ .size = (8 + 248) * 264,213213+// .mask_flags = MTD_WRITEABLE,214214+}, {215215+ /* sector 2 = 256 pages * 264 bytes/page216216+ * sectors 3-5 = 512 pages * 264 bytes/page217217+ */218218+ .name = "filesystem", // 462 KB219219+ .offset = MTDPART_OFS_APPEND,220220+ .size = MTDPART_SIZ_FULL,221221+} };222222+223223+static struct flash_platform_data flash = {224224+ .name = "butterflash",225225+ .parts = partitions,226226+ .nr_parts = ARRAY_SIZE(partitions),227227+};228228+229229+230230+/* REVISIT remove this ugly global and its "only one" limitation */231231+static struct butterfly *butterfly;232232+233233+static void butterfly_attach(struct parport *p)234234+{235235+ struct pardevice *pd;236236+ int status;237237+ struct butterfly *pp;238238+ struct spi_master *master;239239+ struct platform_device *pdev;240240+241241+ if (butterfly)242242+ return;243243+244244+ /* REVISIT: this just _assumes_ a butterfly is there ... no probe,245245+ * and no way to be selective about what it binds to.246246+ */247247+248248+ /* FIXME where should master->cdev.dev come from?249249+ * e.g. /sys/bus/pnp0/00:0b, some PCI thing, etc250250+ * setting up a platform device like this is an ugly kluge...251251+ */252252+ pdev = platform_device_register_simple("butterfly", -1, NULL, 0);253253+254254+ master = spi_alloc_master(&pdev->dev, sizeof *pp);255255+ if (!master) {256256+ status = -ENOMEM;257257+ goto done;258258+ }259259+ pp = spi_master_get_devdata(master);260260+261261+ /*262262+ * SPI and bitbang hookup263263+ *264264+ * use default setup(), cleanup(), and transfer() methods; and265265+ * only bother implementing mode 0. Start it later.266266+ */267267+ master->bus_num = 42;268268+ master->num_chipselect = 2;269269+270270+ pp->bitbang.master = spi_master_get(master);271271+ pp->bitbang.chipselect = butterfly_chipselect;272272+ pp->bitbang.txrx_word[SPI_MODE_0] = butterfly_txrx_word_mode0;273273+274274+ /*275275+ * parport hookup276276+ */277277+ pp->port = p;278278+ pd = parport_register_device(p, "spi_butterfly",279279+ NULL, NULL, NULL,280280+ 0 /* FLAGS */, pp);281281+ if (!pd) {282282+ status = -ENOMEM;283283+ goto clean0;284284+ }285285+ pp->pd = pd;286286+287287+ status = parport_claim(pd);288288+ if (status < 0)289289+ goto clean1;290290+291291+ /*292292+ * Butterfly reset, powerup, run firmware293293+ */294294+ pr_debug("%s: powerup/reset Butterfly\n", p->name);295295+296296+ /* nCS for dataflash (this bit is inverted on output) */297297+ parport_frob_control(pp->port, spi_cs_bit, 0);298298+299299+ /* stabilize power with chip in reset (nRESET), and300300+ * both spi_sck_bit and usi_sck_bit clear (CPOL=0)301301+ */302302+ pp->lastbyte |= vcc_bits;303303+ parport_write_data(pp->port, pp->lastbyte);304304+ msleep(5);305305+306306+ /* take it out of reset; assume long reset delay */307307+ pp->lastbyte |= butterfly_nreset;308308+ parport_write_data(pp->port, pp->lastbyte);309309+ msleep(100);310310+311311+312312+ /*313313+ * Start SPI ... for now, hide that we're two physical busses.314314+ */315315+ status = spi_bitbang_start(&pp->bitbang);316316+ if (status < 0)317317+ goto clean2;318318+319319+ /* Bus 1 lets us talk to at45db041b (firmware disables AVR)320320+ * or AVR (firmware resets at45, acts as spi slave)321321+ */322322+ pp->info[0].max_speed_hz = 15 * 1000 * 1000;323323+ strcpy(pp->info[0].modalias, "mtd_dataflash");324324+ pp->info[0].platform_data = &flash;325325+ pp->info[0].chip_select = 1;326326+ pp->info[0].controller_data = pp;327327+ pp->dataflash = spi_new_device(pp->bitbang.master, &pp->info[0]);328328+ if (pp->dataflash)329329+ pr_debug("%s: dataflash at %s\n", p->name,330330+ pp->dataflash->dev.bus_id);331331+332332+#ifdef HAVE_USI333333+ /* even more custom AVR firmware */334334+ pp->info[1].max_speed_hz = 10 /* ?? */ * 1000 * 1000;335335+ strcpy(pp->info[1].modalias, "butterfly");336336+ // pp->info[1].platform_data = ... TBD ... ;337337+ pp->info[1].chip_select = 2,338338+ pp->info[1].controller_data = pp;339339+ pp->butterfly = spi_new_device(pp->bitbang.master, &pp->info[1]);340340+ if (pp->butterfly)341341+ pr_debug("%s: butterfly at %s\n", p->name,342342+ pp->butterfly->dev.bus_id);343343+344344+ /* FIXME setup ACK for the IRQ line ... */345345+#endif346346+347347+ // dev_info(_what?_, ...)348348+ pr_info("%s: AVR Butterfly\n", p->name);349349+ butterfly = pp;350350+ return;351351+352352+clean2:353353+ /* turn off VCC */354354+ parport_write_data(pp->port, 0);355355+356356+ parport_release(pp->pd);357357+clean1:358358+ parport_unregister_device(pd);359359+clean0:360360+ (void) spi_master_put(pp->bitbang.master);361361+done:362362+ platform_device_unregister(pdev);363363+ pr_debug("%s: butterfly probe, fail %d\n", p->name, status);364364+}365365+366366+static void butterfly_detach(struct parport *p)367367+{368368+ struct butterfly *pp;369369+ struct platform_device *pdev;370370+ int status;371371+372372+ /* FIXME this global is ugly ... but, how to quickly get from373373+ * the parport to the "struct butterfly" associated with it?374374+ * "old school" driver-internal device lists?375375+ */376376+ if (!butterfly || butterfly->port != p)377377+ return;378378+ pp = butterfly;379379+ butterfly = NULL;380380+381381+#ifdef HAVE_USI382382+ spi_unregister_device(pp->butterfly);383383+ pp->butterfly = NULL;384384+#endif385385+ spi_unregister_device(pp->dataflash);386386+ pp->dataflash = NULL;387387+388388+ status = spi_bitbang_stop(&pp->bitbang);389389+390390+ /* turn off VCC */391391+ parport_write_data(pp->port, 0);392392+ msleep(10);393393+394394+ parport_release(pp->pd);395395+ parport_unregister_device(pp->pd);396396+397397+ pdev = to_platform_device(pp->bitbang.master->cdev.dev);398398+399399+ (void) spi_master_put(pp->bitbang.master);400400+401401+ platform_device_unregister(pdev);402402+}403403+404404+static struct parport_driver butterfly_driver = {405405+ .name = "spi_butterfly",406406+ .attach = butterfly_attach,407407+ .detach = butterfly_detach,408408+};409409+410410+411411+static int __init butterfly_init(void)412412+{413413+ return parport_register_driver(&butterfly_driver);414414+}415415+device_initcall(butterfly_init);416416+417417+static void __exit butterfly_exit(void)418418+{419419+ parport_unregister_driver(&butterfly_driver);420420+}421421+module_exit(butterfly_exit);422422+423423+MODULE_LICENSE("GPL");
+18
include/linux/spi/ads7846.h
···11+/* linux/spi/ads7846.h */22+33+/* Touchscreen characteristics vary between boards and models. The44+ * platform_data for the device's "struct device" holds this information.55+ *66+ * It's OK if the min/max values are zero.77+ */88+struct ads7846_platform_data {99+ u16 model; /* 7843, 7845, 7846. */1010+ u16 vref_delay_usecs; /* 0 for external vref; etc */1111+ u16 x_plate_ohms;1212+ u16 y_plate_ohms;1313+1414+ u16 x_min, x_max;1515+ u16 y_min, y_max;1616+ u16 pressure_min, pressure_max;1717+};1818+
+31
include/linux/spi/flash.h
···11+#ifndef LINUX_SPI_FLASH_H22+#define LINUX_SPI_FLASH_H33+44+struct mtd_partition;55+66+/**77+ * struct flash_platform_data: board-specific flash data88+ * @name: optional flash device name (eg, as used with mtdparts=)99+ * @parts: optional array of mtd_partitions for static partitioning1010+ * @nr_parts: number of mtd_partitions for static partitoning1111+ * @type: optional flash device type (e.g. m25p80 vs m25p64), for use1212+ * with chips that can't be queried for JEDEC or other IDs1313+ *1414+ * Board init code (in arch/.../mach-xxx/board-yyy.c files) can1515+ * provide information about SPI flash parts (such as DataFlash) to1616+ * help set up the device and its appropriate default partitioning.1717+ *1818+ * Note that for DataFlash, sizes for pages, blocks, and sectors are1919+ * rarely powers of two; and partitions should be sector-aligned.2020+ */2121+struct flash_platform_data {2222+ char *name;2323+ struct mtd_partition *parts;2424+ unsigned int nr_parts;2525+2626+ char *type;2727+2828+ /* we'll likely add more ... use JEDEC IDs, etc */2929+};3030+3131+#endif
+668
include/linux/spi/spi.h
···11+/*22+ * Copyright (C) 2005 David Brownell33+ *44+ * This program is free software; you can redistribute it and/or modify55+ * it under the terms of the GNU General Public License as published by66+ * the Free Software Foundation; either version 2 of the License, or77+ * (at your option) any later version.88+ *99+ * This program is distributed in the hope that it will be useful,1010+ * but WITHOUT ANY WARRANTY; without even the implied warranty of1111+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the1212+ * GNU General Public License for more details.1313+ *1414+ * You should have received a copy of the GNU General Public License1515+ * along with this program; if not, write to the Free Software1616+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.1717+ */1818+1919+#ifndef __LINUX_SPI_H2020+#define __LINUX_SPI_H2121+2222+/*2323+ * INTERFACES between SPI master-side drivers and SPI infrastructure.2424+ * (There's no SPI slave support for Linux yet...)2525+ */2626+extern struct bus_type spi_bus_type;2727+2828+/**2929+ * struct spi_device - Master side proxy for an SPI slave device3030+ * @dev: Driver model representation of the device.3131+ * @master: SPI controller used with the device.3232+ * @max_speed_hz: Maximum clock rate to be used with this chip3333+ * (on this board); may be changed by the device's driver.3434+ * @chip-select: Chipselect, distinguishing chips handled by "master".3535+ * @mode: The spi mode defines how data is clocked out and in.3636+ * This may be changed by the device's driver.3737+ * @bits_per_word: Data transfers involve one or more words; word sizes3838+ * like eight or 12 bits are common. In-memory wordsizes are3939+ * powers of two bytes (e.g. 20 bit samples use 32 bits).4040+ * This may be changed by the device's driver.4141+ * @irq: Negative, or the number passed to request_irq() to receive4242+ * interrupts from this device.4343+ * @controller_state: Controller's runtime state4444+ * @controller_data: Board-specific definitions for controller, such as4545+ * FIFO initialization parameters; from board_info.controller_data4646+ *4747+ * An spi_device is used to interchange data between an SPI slave4848+ * (usually a discrete chip) and CPU memory.4949+ *5050+ * In "dev", the platform_data is used to hold information about this5151+ * device that's meaningful to the device's protocol driver, but not5252+ * to its controller. One example might be an identifier for a chip5353+ * variant with slightly different functionality.5454+ */5555+struct spi_device {5656+ struct device dev;5757+ struct spi_master *master;5858+ u32 max_speed_hz;5959+ u8 chip_select;6060+ u8 mode;6161+#define SPI_CPHA 0x01 /* clock phase */6262+#define SPI_CPOL 0x02 /* clock polarity */6363+#define SPI_MODE_0 (0|0) /* (original MicroWire) */6464+#define SPI_MODE_1 (0|SPI_CPHA)6565+#define SPI_MODE_2 (SPI_CPOL|0)6666+#define SPI_MODE_3 (SPI_CPOL|SPI_CPHA)6767+#define SPI_CS_HIGH 0x04 /* chipselect active high? */6868+ u8 bits_per_word;6969+ int irq;7070+ void *controller_state;7171+ void *controller_data;7272+ const char *modalias;7373+7474+ // likely need more hooks for more protocol options affecting how7575+ // the controller talks to each chip, like:7676+ // - bit order (default is wordwise msb-first)7777+ // - memory packing (12 bit samples into low bits, others zeroed)7878+ // - priority7979+ // - drop chipselect after each word8080+ // - chipselect delays8181+ // - ...8282+};8383+8484+static inline struct spi_device *to_spi_device(struct device *dev)8585+{8686+ return dev ? container_of(dev, struct spi_device, dev) : NULL;8787+}8888+8989+/* most drivers won't need to care about device refcounting */9090+static inline struct spi_device *spi_dev_get(struct spi_device *spi)9191+{9292+ return (spi && get_device(&spi->dev)) ? spi : NULL;9393+}9494+9595+static inline void spi_dev_put(struct spi_device *spi)9696+{9797+ if (spi)9898+ put_device(&spi->dev);9999+}100100+101101+/* ctldata is for the bus_master driver's runtime state */102102+static inline void *spi_get_ctldata(struct spi_device *spi)103103+{104104+ return spi->controller_state;105105+}106106+107107+static inline void spi_set_ctldata(struct spi_device *spi, void *state)108108+{109109+ spi->controller_state = state;110110+}111111+112112+113113+struct spi_message;114114+115115+116116+117117+struct spi_driver {118118+ int (*probe)(struct spi_device *spi);119119+ int (*remove)(struct spi_device *spi);120120+ void (*shutdown)(struct spi_device *spi);121121+ int (*suspend)(struct spi_device *spi, pm_message_t mesg);122122+ int (*resume)(struct spi_device *spi);123123+ struct device_driver driver;124124+};125125+126126+static inline struct spi_driver *to_spi_driver(struct device_driver *drv)127127+{128128+ return drv ? container_of(drv, struct spi_driver, driver) : NULL;129129+}130130+131131+extern int spi_register_driver(struct spi_driver *sdrv);132132+133133+static inline void spi_unregister_driver(struct spi_driver *sdrv)134134+{135135+ if (!sdrv)136136+ return;137137+ driver_unregister(&sdrv->driver);138138+}139139+140140+141141+142142+/**143143+ * struct spi_master - interface to SPI master controller144144+ * @cdev: class interface to this driver145145+ * @bus_num: board-specific (and often SOC-specific) identifier for a146146+ * given SPI controller.147147+ * @num_chipselect: chipselects are used to distinguish individual148148+ * SPI slaves, and are numbered from zero to num_chipselects.149149+ * each slave has a chipselect signal, but it's common that not150150+ * every chipselect is connected to a slave.151151+ * @setup: updates the device mode and clocking records used by a152152+ * device's SPI controller; protocol code may call this.153153+ * @transfer: adds a message to the controller's transfer queue.154154+ * @cleanup: frees controller-specific state155155+ *156156+ * Each SPI master controller can communicate with one or more spi_device157157+ * children. These make a small bus, sharing MOSI, MISO and SCK signals158158+ * but not chip select signals. Each device may be configured to use a159159+ * different clock rate, since those shared signals are ignored unless160160+ * the chip is selected.161161+ *162162+ * The driver for an SPI controller manages access to those devices through163163+ * a queue of spi_message transactions, copyin data between CPU memory and164164+ * an SPI slave device). For each such message it queues, it calls the165165+ * message's completion function when the transaction completes.166166+ */167167+struct spi_master {168168+ struct class_device cdev;169169+170170+ /* other than zero (== assign one dynamically), bus_num is fully171171+ * board-specific. usually that simplifies to being SOC-specific.172172+ * example: one SOC has three SPI controllers, numbered 1..3,173173+ * and one board's schematics might show it using SPI-2. software174174+ * would normally use bus_num=2 for that controller.175175+ */176176+ u16 bus_num;177177+178178+ /* chipselects will be integral to many controllers; some others179179+ * might use board-specific GPIOs.180180+ */181181+ u16 num_chipselect;182182+183183+ /* setup mode and clock, etc (spi driver may call many times) */184184+ int (*setup)(struct spi_device *spi);185185+186186+ /* bidirectional bulk transfers187187+ *188188+ * + The transfer() method may not sleep; its main role is189189+ * just to add the message to the queue.190190+ * + For now there's no remove-from-queue operation, or191191+ * any other request management192192+ * + To a given spi_device, message queueing is pure fifo193193+ *194194+ * + The master's main job is to process its message queue,195195+ * selecting a chip then transferring data196196+ * + If there are multiple spi_device children, the i/o queue197197+ * arbitration algorithm is unspecified (round robin, fifo,198198+ * priority, reservations, preemption, etc)199199+ *200200+ * + Chipselect stays active during the entire message201201+ * (unless modified by spi_transfer.cs_change != 0).202202+ * + The message transfers use clock and SPI mode parameters203203+ * previously established by setup() for this device204204+ */205205+ int (*transfer)(struct spi_device *spi,206206+ struct spi_message *mesg);207207+208208+ /* called on release() to free memory provided by spi_master */209209+ void (*cleanup)(const struct spi_device *spi);210210+};211211+212212+static inline void *spi_master_get_devdata(struct spi_master *master)213213+{214214+ return class_get_devdata(&master->cdev);215215+}216216+217217+static inline void spi_master_set_devdata(struct spi_master *master, void *data)218218+{219219+ class_set_devdata(&master->cdev, data);220220+}221221+222222+static inline struct spi_master *spi_master_get(struct spi_master *master)223223+{224224+ if (!master || !class_device_get(&master->cdev))225225+ return NULL;226226+ return master;227227+}228228+229229+static inline void spi_master_put(struct spi_master *master)230230+{231231+ if (master)232232+ class_device_put(&master->cdev);233233+}234234+235235+236236+/* the spi driver core manages memory for the spi_master classdev */237237+extern struct spi_master *238238+spi_alloc_master(struct device *host, unsigned size);239239+240240+extern int spi_register_master(struct spi_master *master);241241+extern void spi_unregister_master(struct spi_master *master);242242+243243+extern struct spi_master *spi_busnum_to_master(u16 busnum);244244+245245+/*---------------------------------------------------------------------------*/246246+247247+/*248248+ * I/O INTERFACE between SPI controller and protocol drivers249249+ *250250+ * Protocol drivers use a queue of spi_messages, each transferring data251251+ * between the controller and memory buffers.252252+ *253253+ * The spi_messages themselves consist of a series of read+write transfer254254+ * segments. Those segments always read the same number of bits as they255255+ * write; but one or the other is easily ignored by passing a null buffer256256+ * pointer. (This is unlike most types of I/O API, because SPI hardware257257+ * is full duplex.)258258+ *259259+ * NOTE: Allocation of spi_transfer and spi_message memory is entirely260260+ * up to the protocol driver, which guarantees the integrity of both (as261261+ * well as the data buffers) for as long as the message is queued.262262+ */263263+264264+/**265265+ * struct spi_transfer - a read/write buffer pair266266+ * @tx_buf: data to be written (dma-safe memory), or NULL267267+ * @rx_buf: data to be read (dma-safe memory), or NULL268268+ * @tx_dma: DMA address of tx_buf, if spi_message.is_dma_mapped269269+ * @rx_dma: DMA address of rx_buf, if spi_message.is_dma_mapped270270+ * @len: size of rx and tx buffers (in bytes)271271+ * @cs_change: affects chipselect after this transfer completes272272+ * @delay_usecs: microseconds to delay after this transfer before273273+ * (optionally) changing the chipselect status, then starting274274+ * the next transfer or completing this spi_message.275275+ * @transfer_list: transfers are sequenced through spi_message.transfers276276+ *277277+ * SPI transfers always write the same number of bytes as they read.278278+ * Protocol drivers should always provide rx_buf and/or tx_buf.279279+ * In some cases, they may also want to provide DMA addresses for280280+ * the data being transferred; that may reduce overhead, when the281281+ * underlying driver uses dma.282282+ *283283+ * If the transmit buffer is null, undefined data will be shifted out284284+ * while filling rx_buf. If the receive buffer is null, the data285285+ * shifted in will be discarded. Only "len" bytes shift out (or in).286286+ * It's an error to try to shift out a partial word. (For example, by287287+ * shifting out three bytes with word size of sixteen or twenty bits;288288+ * the former uses two bytes per word, the latter uses four bytes.)289289+ *290290+ * All SPI transfers start with the relevant chipselect active. Normally291291+ * it stays selected until after the last transfer in a message. Drivers292292+ * can affect the chipselect signal using cs_change:293293+ *294294+ * (i) If the transfer isn't the last one in the message, this flag is295295+ * used to make the chipselect briefly go inactive in the middle of the296296+ * message. Toggling chipselect in this way may be needed to terminate297297+ * a chip command, letting a single spi_message perform all of group of298298+ * chip transactions together.299299+ *300300+ * (ii) When the transfer is the last one in the message, the chip may301301+ * stay selected until the next transfer. This is purely a performance302302+ * hint; the controller driver may need to select a different device303303+ * for the next message.304304+ *305305+ * The code that submits an spi_message (and its spi_transfers)306306+ * to the lower layers is responsible for managing its memory.307307+ * Zero-initialize every field you don't set up explicitly, to308308+ * insulate against future API updates. After you submit a message309309+ * and its transfers, ignore them until its completion callback.310310+ */311311+struct spi_transfer {312312+ /* it's ok if tx_buf == rx_buf (right?)313313+ * for MicroWire, one buffer must be null314314+ * buffers must work with dma_*map_single() calls, unless315315+ * spi_message.is_dma_mapped reports a pre-existing mapping316316+ */317317+ const void *tx_buf;318318+ void *rx_buf;319319+ unsigned len;320320+321321+ dma_addr_t tx_dma;322322+ dma_addr_t rx_dma;323323+324324+ unsigned cs_change:1;325325+ u16 delay_usecs;326326+327327+ struct list_head transfer_list;328328+};329329+330330+/**331331+ * struct spi_message - one multi-segment SPI transaction332332+ * @transfers: list of transfer segments in this transaction333333+ * @spi: SPI device to which the transaction is queued334334+ * @is_dma_mapped: if true, the caller provided both dma and cpu virtual335335+ * addresses for each transfer buffer336336+ * @complete: called to report transaction completions337337+ * @context: the argument to complete() when it's called338338+ * @actual_length: the total number of bytes that were transferred in all339339+ * successful segments340340+ * @status: zero for success, else negative errno341341+ * @queue: for use by whichever driver currently owns the message342342+ * @state: for use by whichever driver currently owns the message343343+ *344344+ * An spi_message is used to execute an atomic sequence of data transfers,345345+ * each represented by a struct spi_transfer. The sequence is "atomic"346346+ * in the sense that no other spi_message may use that SPI bus until that347347+ * sequence completes. On some systems, many such sequences can execute as348348+ * as single programmed DMA transfer. On all systems, these messages are349349+ * queued, and might complete after transactions to other devices. Messages350350+ * sent to a given spi_device are alway executed in FIFO order.351351+ *352352+ * The code that submits an spi_message (and its spi_transfers)353353+ * to the lower layers is responsible for managing its memory.354354+ * Zero-initialize every field you don't set up explicitly, to355355+ * insulate against future API updates. After you submit a message356356+ * and its transfers, ignore them until its completion callback.357357+ */358358+struct spi_message {359359+ struct list_head transfers;360360+361361+ struct spi_device *spi;362362+363363+ unsigned is_dma_mapped:1;364364+365365+ /* REVISIT: we might want a flag affecting the behavior of the366366+ * last transfer ... allowing things like "read 16 bit length L"367367+ * immediately followed by "read L bytes". Basically imposing368368+ * a specific message scheduling algorithm.369369+ *370370+ * Some controller drivers (message-at-a-time queue processing)371371+ * could provide that as their default scheduling algorithm. But372372+ * others (with multi-message pipelines) could need a flag to373373+ * tell them about such special cases.374374+ */375375+376376+ /* completion is reported through a callback */377377+ void (*complete)(void *context);378378+ void *context;379379+ unsigned actual_length;380380+ int status;381381+382382+ /* for optional use by whatever driver currently owns the383383+ * spi_message ... between calls to spi_async and then later384384+ * complete(), that's the spi_master controller driver.385385+ */386386+ struct list_head queue;387387+ void *state;388388+};389389+390390+static inline void spi_message_init(struct spi_message *m)391391+{392392+ memset(m, 0, sizeof *m);393393+ INIT_LIST_HEAD(&m->transfers);394394+}395395+396396+static inline void397397+spi_message_add_tail(struct spi_transfer *t, struct spi_message *m)398398+{399399+ list_add_tail(&t->transfer_list, &m->transfers);400400+}401401+402402+static inline void403403+spi_transfer_del(struct spi_transfer *t)404404+{405405+ list_del(&t->transfer_list);406406+}407407+408408+/* It's fine to embed message and transaction structures in other data409409+ * structures so long as you don't free them while they're in use.410410+ */411411+412412+static inline struct spi_message *spi_message_alloc(unsigned ntrans, gfp_t flags)413413+{414414+ struct spi_message *m;415415+416416+ m = kzalloc(sizeof(struct spi_message)417417+ + ntrans * sizeof(struct spi_transfer),418418+ flags);419419+ if (m) {420420+ int i;421421+ struct spi_transfer *t = (struct spi_transfer *)(m + 1);422422+423423+ INIT_LIST_HEAD(&m->transfers);424424+ for (i = 0; i < ntrans; i++, t++)425425+ spi_message_add_tail(t, m);426426+ }427427+ return m;428428+}429429+430430+static inline void spi_message_free(struct spi_message *m)431431+{432432+ kfree(m);433433+}434434+435435+/**436436+ * spi_setup -- setup SPI mode and clock rate437437+ * @spi: the device whose settings are being modified438438+ *439439+ * SPI protocol drivers may need to update the transfer mode if the440440+ * device doesn't work with the mode 0 default. They may likewise need441441+ * to update clock rates or word sizes from initial values. This function442442+ * changes those settings, and must be called from a context that can sleep.443443+ * The changes take effect the next time the device is selected and data444444+ * is transferred to or from it.445445+ */446446+static inline int447447+spi_setup(struct spi_device *spi)448448+{449449+ return spi->master->setup(spi);450450+}451451+452452+453453+/**454454+ * spi_async -- asynchronous SPI transfer455455+ * @spi: device with which data will be exchanged456456+ * @message: describes the data transfers, including completion callback457457+ *458458+ * This call may be used in_irq and other contexts which can't sleep,459459+ * as well as from task contexts which can sleep.460460+ *461461+ * The completion callback is invoked in a context which can't sleep.462462+ * Before that invocation, the value of message->status is undefined.463463+ * When the callback is issued, message->status holds either zero (to464464+ * indicate complete success) or a negative error code. After that465465+ * callback returns, the driver which issued the transfer request may466466+ * deallocate the associated memory; it's no longer in use by any SPI467467+ * core or controller driver code.468468+ *469469+ * Note that although all messages to a spi_device are handled in470470+ * FIFO order, messages may go to different devices in other orders.471471+ * Some device might be higher priority, or have various "hard" access472472+ * time requirements, for example.473473+ *474474+ * On detection of any fault during the transfer, processing of475475+ * the entire message is aborted, and the device is deselected.476476+ * Until returning from the associated message completion callback,477477+ * no other spi_message queued to that device will be processed.478478+ * (This rule applies equally to all the synchronous transfer calls,479479+ * which are wrappers around this core asynchronous primitive.)480480+ */481481+static inline int482482+spi_async(struct spi_device *spi, struct spi_message *message)483483+{484484+ message->spi = spi;485485+ return spi->master->transfer(spi, message);486486+}487487+488488+/*---------------------------------------------------------------------------*/489489+490490+/* All these synchronous SPI transfer routines are utilities layered491491+ * over the core async transfer primitive. Here, "synchronous" means492492+ * they will sleep uninterruptibly until the async transfer completes.493493+ */494494+495495+extern int spi_sync(struct spi_device *spi, struct spi_message *message);496496+497497+/**498498+ * spi_write - SPI synchronous write499499+ * @spi: device to which data will be written500500+ * @buf: data buffer501501+ * @len: data buffer size502502+ *503503+ * This writes the buffer and returns zero or a negative error code.504504+ * Callable only from contexts that can sleep.505505+ */506506+static inline int507507+spi_write(struct spi_device *spi, const u8 *buf, size_t len)508508+{509509+ struct spi_transfer t = {510510+ .tx_buf = buf,511511+ .len = len,512512+ };513513+ struct spi_message m;514514+515515+ spi_message_init(&m);516516+ spi_message_add_tail(&t, &m);517517+ return spi_sync(spi, &m);518518+}519519+520520+/**521521+ * spi_read - SPI synchronous read522522+ * @spi: device from which data will be read523523+ * @buf: data buffer524524+ * @len: data buffer size525525+ *526526+ * This writes the buffer and returns zero or a negative error code.527527+ * Callable only from contexts that can sleep.528528+ */529529+static inline int530530+spi_read(struct spi_device *spi, u8 *buf, size_t len)531531+{532532+ struct spi_transfer t = {533533+ .rx_buf = buf,534534+ .len = len,535535+ };536536+ struct spi_message m;537537+538538+ spi_message_init(&m);539539+ spi_message_add_tail(&t, &m);540540+ return spi_sync(spi, &m);541541+}542542+543543+/* this copies txbuf and rxbuf data; for small transfers only! */544544+extern int spi_write_then_read(struct spi_device *spi,545545+ const u8 *txbuf, unsigned n_tx,546546+ u8 *rxbuf, unsigned n_rx);547547+548548+/**549549+ * spi_w8r8 - SPI synchronous 8 bit write followed by 8 bit read550550+ * @spi: device with which data will be exchanged551551+ * @cmd: command to be written before data is read back552552+ *553553+ * This returns the (unsigned) eight bit number returned by the554554+ * device, or else a negative error code. Callable only from555555+ * contexts that can sleep.556556+ */557557+static inline ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)558558+{559559+ ssize_t status;560560+ u8 result;561561+562562+ status = spi_write_then_read(spi, &cmd, 1, &result, 1);563563+564564+ /* return negative errno or unsigned value */565565+ return (status < 0) ? status : result;566566+}567567+568568+/**569569+ * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read570570+ * @spi: device with which data will be exchanged571571+ * @cmd: command to be written before data is read back572572+ *573573+ * This returns the (unsigned) sixteen bit number returned by the574574+ * device, or else a negative error code. Callable only from575575+ * contexts that can sleep.576576+ *577577+ * The number is returned in wire-order, which is at least sometimes578578+ * big-endian.579579+ */580580+static inline ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)581581+{582582+ ssize_t status;583583+ u16 result;584584+585585+ status = spi_write_then_read(spi, &cmd, 1, (u8 *) &result, 2);586586+587587+ /* return negative errno or unsigned value */588588+ return (status < 0) ? status : result;589589+}590590+591591+/*---------------------------------------------------------------------------*/592592+593593+/*594594+ * INTERFACE between board init code and SPI infrastructure.595595+ *596596+ * No SPI driver ever sees these SPI device table segments, but597597+ * it's how the SPI core (or adapters that get hotplugged) grows598598+ * the driver model tree.599599+ *600600+ * As a rule, SPI devices can't be probed. Instead, board init code601601+ * provides a table listing the devices which are present, with enough602602+ * information to bind and set up the device's driver. There's basic603603+ * support for nonstatic configurations too; enough to handle adding604604+ * parport adapters, or microcontrollers acting as USB-to-SPI bridges.605605+ */606606+607607+/* board-specific information about each SPI device */608608+struct spi_board_info {609609+ /* the device name and module name are coupled, like platform_bus;610610+ * "modalias" is normally the driver name.611611+ *612612+ * platform_data goes to spi_device.dev.platform_data,613613+ * controller_data goes to spi_device.controller_data,614614+ * irq is copied too615615+ */616616+ char modalias[KOBJ_NAME_LEN];617617+ const void *platform_data;618618+ void *controller_data;619619+ int irq;620620+621621+ /* slower signaling on noisy or low voltage boards */622622+ u32 max_speed_hz;623623+624624+625625+ /* bus_num is board specific and matches the bus_num of some626626+ * spi_master that will probably be registered later.627627+ *628628+ * chip_select reflects how this chip is wired to that master;629629+ * it's less than num_chipselect.630630+ */631631+ u16 bus_num;632632+ u16 chip_select;633633+634634+ /* ... may need additional spi_device chip config data here.635635+ * avoid stuff protocol drivers can set; but include stuff636636+ * needed to behave without being bound to a driver:637637+ * - chipselect polarity638638+ * - quirks like clock rate mattering when not selected639639+ */640640+};641641+642642+#ifdef CONFIG_SPI643643+extern int644644+spi_register_board_info(struct spi_board_info const *info, unsigned n);645645+#else646646+/* board init code may ignore whether SPI is configured or not */647647+static inline int648648+spi_register_board_info(struct spi_board_info const *info, unsigned n)649649+ { return 0; }650650+#endif651651+652652+653653+/* If you're hotplugging an adapter with devices (parport, usb, etc)654654+ * use spi_new_device() to describe each device. You can also call655655+ * spi_unregister_device() to start making that device vanish, but656656+ * normally that would be handled by spi_unregister_master().657657+ */658658+extern struct spi_device *659659+spi_new_device(struct spi_master *, struct spi_board_info *);660660+661661+static inline void662662+spi_unregister_device(struct spi_device *spi)663663+{664664+ if (spi)665665+ device_unregister(&spi->dev);666666+}667667+668668+#endif /* __LINUX_SPI_H */
+135
include/linux/spi/spi_bitbang.h
···11+#ifndef __SPI_BITBANG_H22+#define __SPI_BITBANG_H33+44+/*55+ * Mix this utility code with some glue code to get one of several types of66+ * simple SPI master driver. Two do polled word-at-a-time I/O:77+ *88+ * - GPIO/parport bitbangers. Provide chipselect() and txrx_word[](),99+ * expanding the per-word routines from the inline templates below.1010+ *1111+ * - Drivers for controllers resembling bare shift registers. Provide1212+ * chipselect() and txrx_word[](), with custom setup()/cleanup() methods1313+ * that use your controller's clock and chipselect registers.1414+ *1515+ * Some hardware works well with requests at spi_transfer scope:1616+ *1717+ * - Drivers leveraging smarter hardware, with fifos or DMA; or for half1818+ * duplex (MicroWire) controllers. Provide chipslect() and txrx_bufs(),1919+ * and custom setup()/cleanup() methods.2020+ */2121+struct spi_bitbang {2222+ struct workqueue_struct *workqueue;2323+ struct work_struct work;2424+2525+ spinlock_t lock;2626+ struct list_head queue;2727+ u8 busy;2828+ u8 shutdown;2929+ u8 use_dma;3030+3131+ struct spi_master *master;3232+3333+ void (*chipselect)(struct spi_device *spi, int is_on);3434+#define BITBANG_CS_ACTIVE 1 /* normally nCS, active low */3535+#define BITBANG_CS_INACTIVE 03636+3737+ /* txrx_bufs() may handle dma mapping for transfers that don't3838+ * already have one (transfer.{tx,rx}_dma is zero), or use PIO3939+ */4040+ int (*txrx_bufs)(struct spi_device *spi, struct spi_transfer *t);4141+4242+ /* txrx_word[SPI_MODE_*]() just looks like a shift register */4343+ u32 (*txrx_word[4])(struct spi_device *spi,4444+ unsigned nsecs,4545+ u32 word, u8 bits);4646+};4747+4848+/* you can call these default bitbang->master methods from your custom4949+ * methods, if you like.5050+ */5151+extern int spi_bitbang_setup(struct spi_device *spi);5252+extern void spi_bitbang_cleanup(const struct spi_device *spi);5353+extern int spi_bitbang_transfer(struct spi_device *spi, struct spi_message *m);5454+5555+/* start or stop queue processing */5656+extern int spi_bitbang_start(struct spi_bitbang *spi);5757+extern int spi_bitbang_stop(struct spi_bitbang *spi);5858+5959+#endif /* __SPI_BITBANG_H */6060+6161+/*-------------------------------------------------------------------------*/6262+6363+#ifdef EXPAND_BITBANG_TXRX6464+6565+/*6666+ * The code that knows what GPIO pins do what should have declared four6767+ * functions, ideally as inlines, before #defining EXPAND_BITBANG_TXRX6868+ * and including this header:6969+ *7070+ * void setsck(struct spi_device *, int is_on);7171+ * void setmosi(struct spi_device *, int is_on);7272+ * int getmiso(struct spi_device *);7373+ * void spidelay(unsigned);7474+ *7575+ * A non-inlined routine would call bitbang_txrx_*() routines. The7676+ * main loop could easily compile down to a handful of instructions,7777+ * especially if the delay is a NOP (to run at peak speed).7878+ *7979+ * Since this is software, the timings may not be exactly what your board's8080+ * chips need ... there may be several reasons you'd need to tweak timings8181+ * in these routines, not just make to make it faster or slower to match a8282+ * particular CPU clock rate.8383+ */8484+8585+static inline u328686+bitbang_txrx_be_cpha0(struct spi_device *spi,8787+ unsigned nsecs, unsigned cpol,8888+ u32 word, u8 bits)8989+{9090+ /* if (cpol == 0) this is SPI_MODE_0; else this is SPI_MODE_2 */9191+9292+ /* clock starts at inactive polarity */9393+ for (word <<= (32 - bits); likely(bits); bits--) {9494+9595+ /* setup MSB (to slave) on trailing edge */9696+ setmosi(spi, word & (1 << 31));9797+ spidelay(nsecs); /* T(setup) */9898+9999+ setsck(spi, !cpol);100100+ spidelay(nsecs);101101+102102+ /* sample MSB (from slave) on leading edge */103103+ word <<= 1;104104+ word |= getmiso(spi);105105+ setsck(spi, cpol);106106+ }107107+ return word;108108+}109109+110110+static inline u32111111+bitbang_txrx_be_cpha1(struct spi_device *spi,112112+ unsigned nsecs, unsigned cpol,113113+ u32 word, u8 bits)114114+{115115+ /* if (cpol == 0) this is SPI_MODE_1; else this is SPI_MODE_3 */116116+117117+ /* clock starts at inactive polarity */118118+ for (word <<= (32 - bits); likely(bits); bits--) {119119+120120+ /* setup MSB (to slave) on leading edge */121121+ setsck(spi, !cpol);122122+ setmosi(spi, word & (1 << 31));123123+ spidelay(nsecs); /* T(setup) */124124+125125+ setsck(spi, cpol);126126+ spidelay(nsecs);127127+128128+ /* sample MSB (from slave) on trailing edge */129129+ word <<= 1;130130+ word |= getmiso(spi);131131+ }132132+ return word;133133+}134134+135135+#endif /* EXPAND_BITBANG_TXRX */