Skip to contentSkip to conversation

SPI core, refresh

PATCH In review David Brownell 3 participants 14 messages Nov 11, 2005 – Jan 26, 2006

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 SPI core, refresh

I thought I'd send out a refresh of this simple SPI framework, updated to build on recent kernels. The patch description inludes a summary of what changed ... not much, though there is now a Documentation/spi directory with a FAQ-ish writeup.

- Dave

This is the core of a small SPI framework, implementing the model of a queue of messages which complete asynchronously (with thin synchronous wrappers on top).

- It's still less than 2KB of ".text" (ARM). If there's got to be a mid-layer for something so simple, that's the right size budget. :)

- The guts use board-specific SPI device tables to build the driver model tree. (Hardware probing is rarely an option.)

- This version of Kconfig includes no drivers. At this writing there are two known master controller drivers (PXA/SSP, OMAP MicroWire) and three protocol drivers (CS8415a, ADS7846, DataFlash) with LKML mentions of other drivers in development.

- No userspace API. There are several implementations to compare. Implement them like any other driver, and bind them with sysfs.

The changes from last version are minor. One issue turned out to be a driver model bug, fixed in kernels 2.6.14-rc1 and newer.

- Matching Russell's 2.6.14-git5+ changes for device_driver suspend

    and resume calls (removing the pointless "level" parameter);

- Adding a Documentation/spi directory with a FAQ-like summary

    (with a "how to write these drivers" overview);

- Adding a new spi_busnum_to_master() for folk doing hotplug style things (mostly for developers, like with parport bitbanging). (Started from a patch by Mark Underwood.)

- Renaming the controller-specific fields in spi_device, based on discussions with Stephen Street.

- Preallocating a static cacheline-sized buffer for the rpc-style write-then-read calls, removing a lurking dma/portability issue.

- Renaming spi_message.dev to spi_message.spi (matching the naming

    convention elsewhere, avoiding ugliness like msg->dev.dev);

This is enough to write (or adapt) real drivers. This API isn't expected to change much, except adding protocol tweaking hooks as needed to handle new hardware.

include/linux/spi/spi.h new file +516 -0
@@ -0,0 +1,516 @@
+/*
+ * Copyright (C) 2005 David Brownell
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#ifndef __LINUX_SPI_H
+#define __LINUX_SPI_H
+
+/*
+ * INTERFACES between SPI master drivers and infrastructure
+ * (There's no SPI slave support for Linux yet...)
+ *
+ * A "struct device_driver" for an spi_device uses "spi_bus_type" and
+ * needs no special API wrappers (much like platform_bus).  These drivers
+ * are bound to devices based on their names (much like platform_bus),
+ * and are available in dev->driver.
+ */
+extern struct bus_type spi_bus_type;
+
+/**
+ * struct spi_device - Master side proxy for an SPI slave device
+ * @dev: Driver model representation of the device.
+ * @master: SPI controller used with the device.
+ * @max_speed_hz: Maximum clock rate to be used with this chip
+ *	(on this board); may be changed by the device's driver.
+ * @chip-select: Chipselect, distinguishing chips handled by "master".
+ * @mode: The spi mode defines how data is clocked out and in.
+ *	This may be changed by the device's driver.
+ * @bits_per_word: Data transfers involve one or more words; word sizes
+ * 	like eight or 12 bits are common.  In-memory wordsizes are
+ *	powers of two bytes (e.g. 20 bit samples use 32 bits).
+ *	This may be changed by the device's driver.
+ * @irq: Negative, or the number passed to request_irq() to receive
+ * 	interrupts from this device.
+ * @controller_state: Controller's runtime state
+ * @controller_data: Static board-specific definitions for controller, such
+ * 	as FIFO initialization parameters; from board_info.controller_data
+ *
+ * An spi_device is used to interchange data between an SPI slave
+ * (usually a discrete chip) and CPU memory.
+ *
+ * In "dev", the platform_data is used to hold information about this
+ * device that's meaningful to the device's protocol driver, but not
+ * to its controller.  One example might be an identifier for a chip
+ * variant with slightly different functionality.
+ */
+struct spi_device {
+	struct device		dev;
+	struct spi_master	*master;
+	u32			max_speed_hz;
+	u8			chip_select;
+	u8			mode;
+#define	SPI_CPHA	0x01		/* clock phase */
+#define	SPI_CPOL	0x02		/* clock polarity */
+#define	SPI_MODE_0	(0|0)
+#define	SPI_MODE_1	(0|SPI_CPHA)
+#define	SPI_MODE_2	(SPI_CPOL|0)
+#define	SPI_MODE_3	(SPI_CPOL|SPI_CPHA)
+#define	SPI_CS_HIGH	0x04		/* chipselect active high? */
+	u8			bits_per_word;
+	int			irq;
+	void			*controller_state;
+	const void		*controller_data;
+
+	// likely need more hooks for more protocol options affecting how
+	// the controller talks to its chips, like:
+	//  - bit order (default is wordwise msb-first)
+	//  - memory packing (12 bit samples into low bits, others zeroed)
+	//  - priority
+	//  - chipselect delays
+	//  - ...
+};
+
+static inline struct spi_device *to_spi_device(struct device *dev)
+{
+	return container_of(dev, struct spi_device, dev);
+}
+
+/* most drivers won't need to care about device refcounting */
+static inline struct spi_device *spi_dev_get(struct spi_device *spi)
+{
+	return (spi && get_device(&spi->dev)) ? spi : NULL;
+}
+
+static inline void spi_dev_put(struct spi_device *spi)
+{
+	if (spi)
+		put_device(&spi->dev);
+}
+
+/* ctldata is for the bus_master driver's runtime state */
+static inline void *spi_get_ctldata(struct spi_device *spi)
+{
+	return spi->controller_state;
+}
+
+static inline void spi_set_ctldata(struct spi_device *spi, void *state)
+{
+	spi->controller_state = state;
+}
+
+
+struct spi_message;
+
+
+/**
+ * struct spi_master - interface to SPI master controller
+ * @cdev: class interface to this driver
+ * @bus_num: board-specific (and often SOC-specific) identifier for a
+ * 	given SPI controller.
+ * @num_chipselects: chipselects are used to distinguish individual
+ * 	SPI slaves, and are numbered from zero to num_chipselects.
+ * 	each slave has a chipselect signal, but it's common that not
+ * 	every chipselect is connected to a slave.
+ * @setup: updates the device mode and clocking records used by a
+ * 	device's SPI controller; protocol code may call this.
+ * @transfer: adds a message to the controller's transfer queue.
+ * @cleanup: frees controller-specific state
+ *
+ * Each SPI master controller can communicate with one or more spi_device
+ * children.  These make a small bus, sharing MOSI, MISO and SCK signals
+ * but not chip select signals.  Each device may be configured to use a
+ * different clock rate, since those shared signals are ignored unless
+ * the chip is selected.
+ *
+ * The driver for an SPI controller manages access to those devices through
+ * a queue of spi_message transactions, copyin data between CPU memory and
+ * an SPI slave device).  For each such message it queues, it calls the
+ * message's completion function when the transaction completes.
+ */
+struct spi_master {
+	struct class_device	cdev;
+
+	/* other than zero (== assign one dynamically), bus_num is fully
+	 * board-specific.  usually that simplifies to being SOC-specific.
+	 * example:  one SOC has three SPI controllers, numbered 1..3,
+	 * and one board's schematics might show it using SPI-2.  software
+	 * would normally use bus_num=2 for that controller.
+	 */
+	u16			bus_num;
+
+	/* chipselects will be integral to many controllers; some others
+	 * might use board-specific GPIOs.
+	 */
+	u16			num_chipselect;
+
+	/* setup mode and clock, etc (spi driver may call many times) */
+	int			(*setup)(struct spi_device *spi);
+
+	/* bidirectional bulk transfers
+	 *
+	 * + The transfer() method may not sleep; its main role is
+	 *   just to add the message to the queue.
+	 * + For now there's no remove-from-queue operation, or
+	 *   any other request management
+	 * + To a given spi_device, message queueing is pure fifo
+	 *
+	 * + The master's main job is to process its message queue,
+	 *   selecting a chip then transferring data
+	 * + If there are multiple spi_device children, the i/o queue
+	 *   arbitration algorithm is unspecified (round robin, fifo,
+	 *   priority, reservations, preemption, etc)
+	 *
+	 * + Chipselect stays active during the entire message
+	 *   (unless modified by spi_transfer.cs_change != 0).
+	 * + The message transfers use clock and SPI mode parameters
+	 *   previously established by setup() for this device
+	 */
+	int			(*transfer)(struct spi_device *spi,
+						struct spi_message *mesg);
+
+	/* called on release() to free memory provided by spi_master */
+	void			(*cleanup)(const struct spi_device *spi);
+};
+
+/* the spi driver core manages memory for the spi_master classdev */
+extern struct spi_master *
+spi_alloc_master(struct device *host, unsigned size);
+
+extern int spi_register_master(struct spi_master *master);
+extern void spi_unregister_master(struct spi_master *master);
+
+extern struct spi_master *spi_busnum_to_master(u16 busnum);
+
+/*---------------------------------------------------------------------------*/
+
+/*
+ * I/O INTERFACE between SPI controller and protocol drivers
+ *
+ * Protocol drivers use a queue of spi_messages, each transferring data
+ * between the controller and memory buffers.
+ *
+ * The spi_messages themselves consist of a series of read+write transfer
+ * segments.  Those segments always read the same number of bits as they
+ * write; but one or the other is easily ignored by passing a null buffer
+ * pointer.  (This is unlike most types of I/O API, because SPI hardware
+ * is full duplex.)
+ *
+ * NOTE:  Allocation of spi_transfer and spi_message memory is entirely
+ * up to the protocol driver, which guarantees the integrity of both (as
+ * well as the data buffers) for as long as the message is queued.
+ */
+
+/**
+ * struct spi_transfer - a read/write buffer pair
+ * @tx_buf: data to be written, or NULL
+ * @rx_buf: data to be read, or NULL
+ * @len: size of rx and tx buffers (in bytes)
+ * @cs_change: affects chipselect after this transfer completes
+ * @delay_usecs: microseconds to delay after this transfer before
+ * 	(optionally) changing the chipselect status, then starting
+ * 	the next transfer or completing this spi_message. 
+ *
+ * SPI transfers always write the same number of bytes as they read.
+ *
+ * All SPI transfers start with the relevant chipselect active.  Drivers
+ * can change behavior of the chipselect after the transfer finishes
+ * (including any mandatory delay).  The normal behavior is to leave it
+ * selected, except for the last transfer in a message.  Setting cs_change
+ * thus allows either of two things:
+ *
+ * (i) If the transfer isn't the last one in the message, chipselect
+ * may briefly go inactive in the middle of the message.  Toggling
+ * chipselect in this way may be needed to let a single spi_message
+ * perform all of group of chip transactions together.
+ *
+ * (ii) When the transfer is the last one in the message, the chip will
+ * stay selected until the next transfer in the queue is started.  If that
+ * next transfer uses the same chipselect, this removes some overhead.
+ */
+struct spi_transfer {
+	/* it's ok if tx_buf == rx_buf (right?)
+	 * for MicroWire, one buffer must be null
+	 * buffers must work with dma_*map_single() calls
+	 */
+	const void	*tx_buf;
+	void		*rx_buf;
+	unsigned	len;
+
+	/* REVISIT for now, these are only for the controller driver's
+	 * use, for recording dma mappings
+	 */
+	dma_addr_t	tx_dma;
+	dma_addr_t	rx_dma;
+
+	unsigned	cs_change:1;
+	u16		delay_usecs;
+};
+
+/**
+ * struct spi_message - one multi-segment SPI transaction
+ * @transfers: the segements of the transaction
+ * @n_transfer: how many segments
+ * @spi: SPI device to which the transaction is queued
+ * @complete: called to report transaction completions
+ * @context: the argument to complete() when it's called
+ * @actual_length: how many bytes were transferd
+ * @status: zero for success, else negative errno
+ * @queue: for use by whichever driver currently owns the message
+ * @state: for use by whichever driver currently owns the message
+ */
+struct spi_message {
+	struct spi_transfer	*transfers;
+	unsigned		n_transfer;
+
+	struct spi_device	*spi;
+
+	/* completion is reported through a callback */
+	void 			FASTCALL((*complete)(void *context));
+	void			*context;
+	unsigned		actual_length;
+	int			status;
+
+	/* for optional use by whatever driver currently owns the
+	 * spi_message ...  between calls to spi_async and then later
+	 * complete(), that's the spi_master controller driver.
+	 */
+	struct list_head	queue;
+	void			*state;
+};
+
+/**
+ * spi_setup -- setup SPI mode and clock rate
+ * @spi: the device whose settings are being modified
+ *
+ * SPI protocol drivers may need to update the transfer mode if the
+ * device doesn't work with the mode 0 default.  They may likewise need
+ * to update clock rates or word sizes from initial values.  This function
+ * changes those settings, and must be called from a context that can sleep.
+ */
+static inline int
+spi_setup(struct spi_device *spi)
+{
+	return spi->master->setup(spi);
+}
+
+
+/**
+ * spi_async -- asynchronous SPI transfer
+ * @spi: device with which data will be exchanged
+ * @message: describes the data transfers, including completion callback
+ *
+ * This call may be used in_irq and other contexts which can't sleep,
+ * as well as from task contexts which can sleep.
+ *
+ * The completion callback is invoked in a context which can't sleep.
+ * Before that invocation, the value of message->status is undefined.
+ * When the callback is issued, message->status holds either zero (to
+ * indicate complete success) or a negative error code.
+ */
+static inline int
+spi_async(struct spi_device *spi, struct spi_message *message)
+{
+	message->spi = spi;
+	return spi->master->transfer(spi, message);
+}
+
+/*---------------------------------------------------------------------------*/
+
+/* All these synchronous SPI transfer routines are utilities layered
+ * over the core async transfer primitive.  Here, "synchronous" means
+ * they will sleep uninterruptibly until the async transfer completes.
+ */
+
+extern int spi_sync(struct spi_device *spi, struct spi_message *message);
+
+/**
+ * spi_write - SPI synchronous write
+ * @spi: device to which data will be written
+ * @buf: data buffer
+ * @len: data buffer size
+ *
+ * This writes the buffer and returns zero or a negative error code.
+ * Callable only from contexts that can sleep.
+ */
+static inline int
+spi_write(struct spi_device *spi, const u8 *buf, size_t len)
+{
+	struct spi_transfer	t = {
+			.tx_buf		= buf,
+			.rx_buf		= NULL,
+			.len		= len,
+			.cs_change	= 0,
+		};
+	struct spi_message	m = {
+			.transfers	= &t,
+			.n_transfer	= 1,
+		};
+
+	return spi_sync(spi, &m);
+}
+
+/**
+ * spi_read - SPI synchronous read
+ * @spi: device from which data will be read
+ * @buf: data buffer
+ * @len: data buffer size
+ *
+ * This writes the buffer and returns zero or a negative error code.
+ * Callable only from contexts that can sleep.
+ */
+static inline int
+spi_read(struct spi_device *spi, u8 *buf, size_t len)
+{
+	struct spi_transfer	t = {
+			.tx_buf		= NULL,
+			.rx_buf		= buf,
+			.len		= len,
+			.cs_change	= 0,
+		};
+	struct spi_message	m = {
+			.transfers	= &t,
+			.n_transfer	= 1,
+		};
+
+	return spi_sync(spi, &m);
+}
+
+extern int spi_write_then_read(struct spi_device *spi,
+		const u8 *txbuf, unsigned n_tx,
+		u8 *rxbuf, unsigned n_rx);
+
+/**
+ * spi_w8r8 - SPI synchronous 8 bit write followed by 8 bit read
+ * @spi: device with which data will be exchanged
+ * @cmd: command to be written before data is read back
+ *
+ * This returns the (unsigned) eight bit number returned by the
+ * device, or else a negative error code.  Callable only from
+ * contexts that can sleep.
+ */
+static inline int spi_w8r8(struct spi_device *spi, u8 cmd)
+{
+	int			status;
+	u8			result;
+
+	status = spi_write_then_read(spi, &cmd, 1, &result, 1);
+
+	/* return negative errno or unsigned value */
+	return (status < 0) ? status : result;
+}
+
+/**
+ * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read
+ * @spi: device with which data will be exchanged
+ * @cmd: command to be written before data is read back
+ *
+ * This returns the (unsigned) sixteen bit number returned by the
+ * device, or else a negative error code.  Callable only from
+ * contexts that can sleep.
+ *
+ * The number is returned in wire-order, which is at least sometimes
+ * big-endian.
+ */
+static inline int spi_w8r16(struct spi_device *spi, u8 cmd)
+{
+	int			status;
+	u16			result;
+
+	status = spi_write_then_read(spi, &cmd, 1, (u8 *) &result, 2);
+
+	/* return negative errno or unsigned value */
+	return (status < 0) ? status : result;
+}
+
+/*---------------------------------------------------------------------------*/
+
+/*
+ * INTERFACE between board init code and SPI infrastructure.
+ *
+ * No SPI driver ever sees these SPI device table segments, but
+ * it's how the SPI core (or adapters that get hotplugged) grows
+ * the driver model tree.
+ *
+ * As a rule, SPI devices can't be probed.  Instead, board init code
+ * provides a table listing the devices which are present, with enough
+ * information to bind and set up the device's driver.  There's basic
+ * support for nonstatic configurations too; enough to handle adding
+ * parport adapters, or microcontrollers acting as USB-to-SPI bridges.
+ */
+
+/* board-specific information about each SPI device */
+struct spi_board_info {
+	/* the device name and module name are coupled, like platform_bus;
+	 * "modalias" is normally the driver name.
+	 *
+	 * platform_data goes to spi_device.dev.platform_data,
+	 * controller_data goes to spi_device.platform_data,
+	 * irq is copied too
+	 */
+	char		modalias[KOBJ_NAME_LEN];
+	const void	*platform_data;
+	const void	*controller_data;
+	int		irq;
+
+	/* slower signaling on noisy or low voltage boards */
+	u32		max_speed_hz;
+
+
+	/* bus_num is board specific and matches the bus_num of some
+	 * spi_master that will probably be registered later.
+	 *
+	 * chip_select reflects how this chip is wired to that master;
+	 * it's less than num_chipselect.
+	 */
+	u16		bus_num;
+	u16		chip_select;
+
+	/* ... may need additional spi_device chip config data here.
+	 * avoid stuff protocol drivers can set; but include stuff
+	 * needed to behave without being bound to a driver:
+	 *  - chipselect polarity
+	 *  - quirks like clock rate mattering when not selected
+	 */
+};
+
+#ifdef	CONFIG_SPI
+extern int
+spi_register_board_info(struct spi_board_info const *info, unsigned n);
+#else
+/* board init code may ignore whether SPI is configured or not */
+static inline int
+spi_register_board_info(struct spi_board_info const *info, unsigned n)
+	{ return 0; }
+#endif
+
+
+/* If you're hotplugging an adapter with devices (parport, usb, etc)
+ * use spi_new_device() to describe each device.  You can also call
+ * spi_unregister_device() to get start making that device vanish,
+ * but normally that would be handled by spi_unregister_master().
+ */
+extern struct spi_device *
+spi_new_device(struct spi_master *, struct spi_board_info *);
+
+static inline void
+spi_unregister_device(struct spi_device *spi)
+{
+	if (spi)
+		device_unregister(&spi->dev);
+}
+
+#endif /* __LINUX_SPI_H */
drivers/spi/spi.c new file +560 -0

560 lines not on this page · raw message

drivers/spi/Kconfig new file +91 -0

91 lines not on this page · raw message

arch/arm/Kconfig +2 -0
@@ -774,6 +774,8 @@ source "drivers/char/Kconfig"
 
 source "drivers/i2c/Kconfig"
 
+source "drivers/spi/Kconfig"
+
 source "drivers/hwmon/Kconfig"
 
 #source "drivers/l3/Kconfig"
drivers/Kconfig +2 -0
@@ -44,6 +44,8 @@ source "drivers/char/Kconfig"
 
 source "drivers/i2c/Kconfig"
 
+source "drivers/spi/Kconfig"
+
 source "drivers/w1/Kconfig"
 
 source "drivers/hwmon/Kconfig"
drivers/Makefile +1 -0
@@ -40,6 +40,7 @@ obj-$(CONFIG_FUSION)		+= message/
 obj-$(CONFIG_IEEE1394)		+= ieee1394/
 obj-y				+= cdrom/
 obj-$(CONFIG_MTD)		+= mtd/
+obj-$(CONFIG_SPI)		+= spi/
 obj-$(CONFIG_PCCARD)		+= pcmcia/
 obj-$(CONFIG_DIO)		+= dio/
 obj-$(CONFIG_SBUS)		+= sbus/
drivers/spi/Makefile new file +23 -0
@@ -0,0 +1,23 @@
+#
+# Makefile for kernel SPI drivers.
+#
+
+ifeq ($(CONFIG_SPI_DEBUG),y)
+EXTRA_CFLAGS += -DDEBUG
+endif
+
+# small core, mostly translating board-specific
+# config declarations into driver model code
+obj-$(CONFIG_SPI_MASTER)		+= spi.o
+
+# SPI master controller drivers (bus)
+# 	... add above this line ...
+
+# SPI protocol drivers (device/link on bus)
+# 	... add above this line ...
+
+# SPI slave controller drivers (upstream link)
+# 	... add above this line ...
+
+# SPI slave drivers (protocol for that link)
+# 	... add above this line ...
Documentation/spi/spi-summary new file +363 -0

363 lines not on this page · raw message

#1 lore raw
Quoted 4 lines · David Brownell

I thought I'd send out a refresh of this simple SPI framework, updated to build on recent kernels. The patch description inludes a summary of what changed ... not much, though there is now a Documentation/spi directory with a FAQ-ish writeup.

I'd like to comment you framework; there are some places that still are suspicious to me. First of all, it is better to inline the patch; this makes easier commenting etc.
My comments follow:

+       void                    *controller_state;
+       const void              *controller_data;

Why to use the separate controller_data/controller_state fields ? At learuesting qest one of them fits to the platform_data +struct spi_transfer {
+ /* it's ok if tx_buf == rx_buf (right?)

+        * for MicroWire, one buffer must be null
+        * buffers must work with dma_*map_single() calls
+        */
+       const void      *tx_buf;
+       void            *rx_buf;
+       unsigned        len;

+
+ /* REVISIT for now, these are only for the controller driver's
+ * use, for recording dma mappings
+ */

+       dma_addr_t      tx_dma;
+       dma_addr_t      rx_dma;

OK, you requesting that tx/rx buffer must be DMA-capable. And why you are using stack-allocated buffers, for example, in spi_w8r8 ? If protocol driver is not enough smart to transfer small amouts of data not using DMA, this could crash the system...
+struct spi_message {

+       struct spi_transfer     *transfers;
+       unsigned                n_transfer;

+
+ struct spi_device *spi;
+
+ /* completion is reported through a callback */
+ void FASTCALL((*complete)(void *context));
As far as I understand, the protocol driver is requested to call complete somewhere after processing the message; even ignoring my preference to call this function as part of common message processing, I'd prefer to see exported/inline function like spi_message_complete (struct spi_message* msg). It is not clear that controller driver _must_ call the `complete' as part of processing message.
+static inline int spi_w8r8(struct spi_device *spi, u8 cmd) +{

+       int                     status;
+       u8                      result;

+
+ status = spi_write_then_read(spi, &cmd, 1, &result, 1);
This breaks the statement that buffers must be dma_single_map'able :( Namely, result cannot be mapped.
+/**
+ * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read
+ * @spi: device with which data will be exchanged
+ * @cmd: command to be written before data is read back
+ *
+ * This returns the (unsigned) sixteen bit number returned by the
+ * device, or else a negative error code. Callable only from
+ * contexts that can sleep.
+ *
+ * The number is returned in wire-order, which is at least sometimes
+ * big-endian.
+ */
+static inline int spi_w8r16(struct spi_device *spi, u8 cmd) +{

+       int                     status;
+       u16                     result;

+
+ status = spi_write_then_read(spi, &cmd, 1, (u8 *) &result, 2);
+
+ /* return negative errno or unsigned value */
+ return (status < 0) ? status : result;
+}
Incorrect mixing int (signed int!) and u16. What if spi_write_then_read read the value, say, 0xFFFF ? Is it the correct result or -1 indicating error ?

+ if (status < 0) {
+ dev_dbg(dev, "can't %s %s, status %d\n",
+ "add", proxy->dev.bus_id, status);
+fail:

+               class_device_put(&master->cdev);
+               kfree(proxy);
+               return NULL;

+ }
Using goto to the middle of compound statement... I personally do not like this. This can be easily moved out of block.

There will be more comments...

Signature · 1 line
cheers, dmitry pervushin
#2 lore raw
In reply to David Brownell
Quoted 6 lines
Quoted 4 lines

I thought I'd send out a refresh of this simple SPI framework, updated to build on recent kernels. The patch description inludes a summary of what changed ... not much, though there is now a Documentation/spi directory with a FAQ-ish writeup.

I'd like to comment you framework;

Thanks, but please remember to CC me directly. Until today, I didn't know you had any comments!

Quoted 3 lines

there are some places that still are
suspicious to me. First of all, it is better to inline the patch; this makes easier commenting etc.

Not when you're using a mailer that mangles inlined patches; sorry, I usually do try to switch mailers when posting patches to LKML.

    http://marc.theaimsgroup.com/?l=linux-kernel&m=113169588230519&w=2
Quoted 6 lines

My comments follow:

include/linux/spi/spi.h new file +2 -0
+       void                    *controller_state;
+       const void              *controller_data;

Why to use the separate controller_data/controller_state fields ? At learuesting qest one of them fits to the platform_data

See the kerneldoc. Basically "state" is runtime stuff managed by the controller, and "data" is static stuff that's essentially board specific configuration for use by the _controller_ driver rather than the SPI device's driver. (The platform_data is for static data used by the SPI device's driver, not the controller driver.)

You can for example see how that's used by looking at Stephen's PXA2xx SPI driver for the SSP/NSSP/ASSP controllers. I'm not sure how many other controller drivers will need that sort of mechanism, but it does seem that SPI-family protocols do need protocol tweaking hooks, and that one seems reasonable.

Quoted 15 lines
include/linux/spi/spi.h new file +14 -0
+struct spi_transfer {
+       /* it's ok if tx_buf == rx_buf (right?)
+        * for MicroWire, one buffer must be null
+        * buffers must work with dma_*map_single() calls
+        */
+       const void      *tx_buf;
+       void            *rx_buf;
+       unsigned        len;
+
+       /* REVISIT for now, these are only for the controller driver's
+        * use, for recording dma mappings
+        */
+       dma_addr_t      tx_dma;
+       dma_addr_t      rx_dma;
Quoted 2 lines

OK, you requesting that tx/rx buffer must be DMA-capable. And why you are using stack-allocated buffers, for example, in spi_w8r8 ?

Those RPC-style (or should I say MicroWire style?) helpers go through a helper specifically documented as doing (small) copies, into a DMA-safe buffer.

It'd be really tedious and annoying if drivers had to kmalloc() then kfree() a temporary buffer whenever they had to do something common like reading an ADC sample. The whole point of convenience functions (like those) is to be convenient!!

Meanwhile, yes the primary API is set up so using DMA can be the hot path. That's pretty much what all kernel driver APIs do any more. Of course, the controller driver is still free to apply heuristics like "use PIO except on large transfers".

There are two use cases I was thinking about when I did that API. One was bulk I/O, as required for the DataFlash driver ... DMA is important if you're pulling in an executable. The other was small sensor-style access, as for ADCs (touchscreen etc) or control requests issued to audio interfaces. For the latter, DMA may not be as important.

Quoted 11 lines
include/linux/spi/spi.h new file +8 -0
+struct spi_message {
+       struct spi_transfer     *transfers;
+       unsigned                n_transfer;
+
+       struct spi_device       *spi;
+
+       /* completion is reported through a callback */
+       void                    FASTCALL((*complete)(void *context));

As far as I understand, the protocol driver is requested to call complete somewhere after processing the message;

No, the controller driver is REQUIRED to call it. It's the only way to report request completion. The protocol driver provides that callback ... it's easy to use a "struct completion" there (which is why it's declared FASTCALL), but that's optional.

Quoted 5 lines

even ignoring my
preference to call this function as part of common message processing, I'd prefer to see exported/inline function like spi_message_complete (struct spi_message* msg). It is not clear that controller driver _must_ call the `complete' as part of processing message.

If you find the kerneldoc unclear, I take suggestions about what needs to change. For example, I don't see how "completion is reported through a callback" (which you quoted above) could be interpreted as implying it's not called ...

Quoted 9 lines
include/linux/spi/spi.h new file +6 -0
+static inline int spi_w8r8(struct spi_device *spi, u8 cmd)
+{
+       int                     status;
+       u8                      result;
+
+       status = spi_write_then_read(spi, &cmd, 1, &result, 1);

This breaks the statement that buffers must be dma_single_map'able :( Namely, result cannot be mapped.

No, you must have overlooked the definition of the write_then_read() call. That's very clearly defined as taking tx and rx buffers that are not DMA-safe:

+/**
+ * spi_write_then_read - SPI synchronous write followed by read
+ * @spi: device with which data will be exchanged
+ * @txbuf: data to be written (need not be dma-safe)
+ * @n_tx: size of txbuf, in bytes
+ * @rxbuf: buffer into which data will be read
+ * @n_rx: size of rxbuf, in bytes (need not be dma-safe)
+ *
+ * This performs a half duplex MicroWire style transaction with the
+ * device, sending txbuf and then reading rxbuf. The return value
+ * is zero for success, else a negative errno status code.
+ *
+ * For large transfers, use spi_sync() and dma-safe buffers.
+ */

Quoted 10 lines
include/linux/spi/spi.h new file +10 -0
+static inline int spi_w8r16(struct spi_device *spi, u8 cmd)
+{
+       int                     status;
+       u16                     result;
+
+       status = spi_write_then_read(spi, &cmd, 1, (u8 *) &result, 2);
+
+       /* return negative errno or unsigned value */
+       return (status < 0) ? status : result;
+}
Quoted 3 lines

Incorrect mixing int (signed int!) and u16. What if spi_write_then_read read the value, say, 0xFFFF ? Is it the correct result or -1 indicating error ?

That should return ssize_t then. I confess to doing this work on 32 bit CPUs, but I know that some of the uCLinux ports want to cope with cases where "int" might be 16 bits.

- Dave

#3 lore raw

cover SPI core, refresh

In reply to David Brownell

I've had several requests recently for the latest standalone version of these patches, so here it is: six patches, posted right after this message. This is very close to what's in the 2.6.15-rc5-mm3 patches, modulo bitbang tweaks and more drivers.

In sequence:

  # core
  spi.patch
  # protocol drivers
  ads7846.patch
  dataflash.patch
  m25p80.patch
  # bitbang utilities
  bitbang_spi.patch
  # bitbang adapter (example)
  butterfly.patch

The new drivers are for M25P series SPI Flash, and a parport adapter cable for a $20 AVR microcontroller board.

- Dave

#4 lore raw

PATCH 1/6 SPI core

In reply to David Brownell

Here's the current core. I expect this will change to (a) let most of it be linked as a module, not just statically; (b) let spi_transfers group into a spi_message by using a list_head. Only the second of those should be driver-visible.

- Dave

This is the core of a small SPI framework, implementing the model of a queue of messages which complete asynchronously (with thin synchronous wrappers on top).

- It's about 2KB of ".text" (ARM). If there's got to be a mid-layer for something so simple, that's the right size budget. :)

- The guts use board-specific SPI device tables to build the driver model tree. (Hardware probing is rarely an option.)

- This version of Kconfig includes no drivers, but there are several controller and protocol drivers added separately.

- No userspace API. There are several implementations to compare. Implement them like any other driver, and bind them with sysfs.

NOTE: The version now in the "mm" tree had to change the "hotplug" callback so it's named "uevent"; driver model changes. Of course, for hotplugging to work, your /sbin/hotplug should "modprobe $MODALIAS".

include/linux/spi/spi.h new file +632 -0
@@ -0,0 +1,632 @@
+/*
+ * Copyright (C) 2005 David Brownell
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#ifndef __LINUX_SPI_H
+#define __LINUX_SPI_H
+
+/*
+ * INTERFACES between SPI master-side drivers and SPI infrastructure.
+ * (There's no SPI slave support for Linux yet...)
+ */
+extern struct bus_type spi_bus_type;
+
+/**
+ * struct spi_device - Master side proxy for an SPI slave device
+ * @dev: Driver model representation of the device.
+ * @master: SPI controller used with the device.
+ * @max_speed_hz: Maximum clock rate to be used with this chip
+ *	(on this board); may be changed by the device's driver.
+ * @chip-select: Chipselect, distinguishing chips handled by "master".
+ * @mode: The spi mode defines how data is clocked out and in.
+ *	This may be changed by the device's driver.
+ * @bits_per_word: Data transfers involve one or more words; word sizes
+ * 	like eight or 12 bits are common.  In-memory wordsizes are
+ *	powers of two bytes (e.g. 20 bit samples use 32 bits).
+ *	This may be changed by the device's driver.
+ * @irq: Negative, or the number passed to request_irq() to receive
+ * 	interrupts from this device.
+ * @controller_state: Controller's runtime state
+ * @controller_data: Board-specific definitions for controller, such as
+ * 	FIFO initialization parameters; from board_info.controller_data
+ *
+ * An spi_device is used to interchange data between an SPI slave
+ * (usually a discrete chip) and CPU memory.
+ *
+ * In "dev", the platform_data is used to hold information about this
+ * device that's meaningful to the device's protocol driver, but not
+ * to its controller.  One example might be an identifier for a chip
+ * variant with slightly different functionality.
+ */
+struct spi_device {
+	struct device		dev;
+	struct spi_master	*master;
+	u32			max_speed_hz;
+	u8			chip_select;
+	u8			mode;
+#define	SPI_CPHA	0x01			/* clock phase */
+#define	SPI_CPOL	0x02			/* clock polarity */
+#define	SPI_MODE_0	(0|0)			/* (original MicroWire) */
+#define	SPI_MODE_1	(0|SPI_CPHA)
+#define	SPI_MODE_2	(SPI_CPOL|0)
+#define	SPI_MODE_3	(SPI_CPOL|SPI_CPHA)
+#define	SPI_CS_HIGH	0x04			/* chipselect active high? */
+	u8			bits_per_word;
+	int			irq;
+	void			*controller_state;
+	void			*controller_data;
+	const char		*modalias;
+
+	// likely need more hooks for more protocol options affecting how
+	// the controller talks to each chip, like:
+	//  - bit order (default is wordwise msb-first)
+	//  - memory packing (12 bit samples into low bits, others zeroed)
+	//  - priority
+	//  - drop chipselect after each word
+	//  - chipselect delays
+	//  - ...
+};
+
+static inline struct spi_device *to_spi_device(struct device *dev)
+{
+	return dev ? container_of(dev, struct spi_device, dev) : NULL;
+}
+
+/* most drivers won't need to care about device refcounting */
+static inline struct spi_device *spi_dev_get(struct spi_device *spi)
+{
+	return (spi && get_device(&spi->dev)) ? spi : NULL;
+}
+
+static inline void spi_dev_put(struct spi_device *spi)
+{
+	if (spi)
+		put_device(&spi->dev);
+}
+
+/* ctldata is for the bus_master driver's runtime state */
+static inline void *spi_get_ctldata(struct spi_device *spi)
+{
+	return spi->controller_state;
+}
+
+static inline void spi_set_ctldata(struct spi_device *spi, void *state)
+{
+	spi->controller_state = state;
+}
+
+
+struct spi_message;
+
+
+
+struct spi_driver {
+	int			(*probe)(struct spi_device *spi);
+	int			(*remove)(struct spi_device *spi);
+	void			(*shutdown)(struct spi_device *spi);
+	int			(*suspend)(struct spi_device *spi, pm_message_t mesg);
+	int			(*resume)(struct spi_device *spi);
+	struct device_driver	driver;
+};
+
+static inline struct spi_driver *to_spi_driver(struct device_driver *drv)
+{
+	return drv ? container_of(drv, struct spi_driver, driver) : NULL;
+}
+
+extern int spi_register_driver(struct spi_driver *sdrv);
+
+static inline void spi_unregister_driver(struct spi_driver *sdrv)
+{
+	if (!sdrv)
+		return;
+	driver_unregister(&sdrv->driver);
+}
+
+
+
+/**
+ * struct spi_master - interface to SPI master controller
+ * @cdev: class interface to this driver
+ * @bus_num: board-specific (and often SOC-specific) identifier for a
+ * 	given SPI controller.
+ * @num_chipselect: chipselects are used to distinguish individual
+ * 	SPI slaves, and are numbered from zero to num_chipselects.
+ * 	each slave has a chipselect signal, but it's common that not
+ * 	every chipselect is connected to a slave.
+ * @setup: updates the device mode and clocking records used by a
+ * 	device's SPI controller; protocol code may call this.
+ * @transfer: adds a message to the controller's transfer queue.
+ * @cleanup: frees controller-specific state
+ *
+ * Each SPI master controller can communicate with one or more spi_device
+ * children.  These make a small bus, sharing MOSI, MISO and SCK signals
+ * but not chip select signals.  Each device may be configured to use a
+ * different clock rate, since those shared signals are ignored unless
+ * the chip is selected.
+ *
+ * The driver for an SPI controller manages access to those devices through
+ * a queue of spi_message transactions, copyin data between CPU memory and
+ * an SPI slave device).  For each such message it queues, it calls the
+ * message's completion function when the transaction completes.
+ */
+struct spi_master {
+	struct class_device	cdev;
+
+	/* other than zero (== assign one dynamically), bus_num is fully
+	 * board-specific.  usually that simplifies to being SOC-specific.
+	 * example:  one SOC has three SPI controllers, numbered 1..3,
+	 * and one board's schematics might show it using SPI-2.  software
+	 * would normally use bus_num=2 for that controller.
+	 */
+	u16			bus_num;
+
+	/* chipselects will be integral to many controllers; some others
+	 * might use board-specific GPIOs.
+	 */
+	u16			num_chipselect;
+
+	/* setup mode and clock, etc (spi driver may call many times) */
+	int			(*setup)(struct spi_device *spi);
+
+	/* bidirectional bulk transfers
+	 *
+	 * + The transfer() method may not sleep; its main role is
+	 *   just to add the message to the queue.
+	 * + For now there's no remove-from-queue operation, or
+	 *   any other request management
+	 * + To a given spi_device, message queueing is pure fifo
+	 *
+	 * + The master's main job is to process its message queue,
+	 *   selecting a chip then transferring data
+	 * + If there are multiple spi_device children, the i/o queue
+	 *   arbitration algorithm is unspecified (round robin, fifo,
+	 *   priority, reservations, preemption, etc)
+	 *
+	 * + Chipselect stays active during the entire message
+	 *   (unless modified by spi_transfer.cs_change != 0).
+	 * + The message transfers use clock and SPI mode parameters
+	 *   previously established by setup() for this device
+	 */
+	int			(*transfer)(struct spi_device *spi,
+						struct spi_message *mesg);
+
+	/* called on release() to free memory provided by spi_master */
+	void			(*cleanup)(const struct spi_device *spi);
+};
+
+static inline void *spi_master_get_devdata(struct spi_master *master)
+{
+	return class_get_devdata(&master->cdev);
+}
+
+static inline void spi_master_set_devdata(struct spi_master *master, void *data)
+{
+	class_set_devdata(&master->cdev, data);
+}
+
+static inline struct spi_master *spi_master_get(struct spi_master *master)
+{
+	if (!master || !class_device_get(&master->cdev))
+		return NULL;
+	return master;
+}
+
+static inline void spi_master_put(struct spi_master *master)
+{
+	if (master)
+		class_device_put(&master->cdev);
+}
+
+
+/* the spi driver core manages memory for the spi_master classdev */
+extern struct spi_master *
+spi_alloc_master(struct device *host, unsigned size);
+
+extern int spi_register_master(struct spi_master *master);
+extern void spi_unregister_master(struct spi_master *master);
+
+extern struct spi_master *spi_busnum_to_master(u16 busnum);
+
+/*---------------------------------------------------------------------------*/
+
+/*
+ * I/O INTERFACE between SPI controller and protocol drivers
+ *
+ * Protocol drivers use a queue of spi_messages, each transferring data
+ * between the controller and memory buffers.
+ *
+ * The spi_messages themselves consist of a series of read+write transfer
+ * segments.  Those segments always read the same number of bits as they
+ * write; but one or the other is easily ignored by passing a null buffer
+ * pointer.  (This is unlike most types of I/O API, because SPI hardware
+ * is full duplex.)
+ *
+ * NOTE:  Allocation of spi_transfer and spi_message memory is entirely
+ * up to the protocol driver, which guarantees the integrity of both (as
+ * well as the data buffers) for as long as the message is queued.
+ */
+
+/**
+ * struct spi_transfer - a read/write buffer pair
+ * @tx_buf: data to be written (dma-safe address), or NULL
+ * @rx_buf: data to be read (dma-safe address), or NULL
+ * @tx_dma: DMA address of buffer, if spi_message.is_dma_mapped
+ * @rx_dma: DMA address of buffer, if spi_message.is_dma_mapped
+ * @len: size of rx and tx buffers (in bytes)
+ * @cs_change: affects chipselect after this transfer completes
+ * @delay_usecs: microseconds to delay after this transfer before
+ * 	(optionally) changing the chipselect status, then starting
+ * 	the next transfer or completing this spi_message.
+ *
+ * SPI transfers always write the same number of bytes as they read.
+ * Protocol drivers should always provide rx_buf and/or tx_buf.
+ * In some cases, they may also want to provide DMA addresses for
+ * the data being transferred; that may reduce overhead, when the
+ * underlying driver uses dma.
+ *
+ * All SPI transfers start with the relevant chipselect active.  Drivers
+ * can change behavior of the chipselect after the transfer finishes
+ * (including any mandatory delay).  The normal behavior is to leave it
+ * selected, except for the last transfer in a message.  Setting cs_change
+ * allows two additional behavior options:
+ *
+ * (i) If the transfer isn't the last one in the message, this flag is
+ * used to make the chipselect briefly go inactive in the middle of the
+ * message.  Toggling chipselect in this way may be needed to terminate
+ * a chip command, letting a single spi_message perform all of group of
+ * chip transactions together.
+ *
+ * (ii) When the transfer is the last one in the message, the chip may
+ * stay selected until the next transfer.  This is purely a performance
+ * hint; the controller driver may need to select a different device
+ * for the next message.
+ *
+ * The code that submits an spi_message (and its spi_transfers)
+ * to the lower layers is responsible for managing its memory.
+ * Zero-initialize every field you don't set up explicitly, to
+ * insulate against future API updates.
+ */
+struct spi_transfer {
+	/* it's ok if tx_buf == rx_buf (right?)
+	 * for MicroWire, one buffer must be null
+	 * buffers must work with dma_*map_single() calls, unless
+	 *   spi_message.is_dma_mapped reports a pre-existing mapping
+	 */
+	const void	*tx_buf;
+	void		*rx_buf;
+	unsigned	len;
+
+	dma_addr_t	tx_dma;
+	dma_addr_t	rx_dma;
+
+	unsigned	cs_change:1;
+	u16		delay_usecs;
+};
+
+/**
+ * struct spi_message - one multi-segment SPI transaction
+ * @transfers: the segements of the transaction
+ * @n_transfer: how many segments
+ * @spi: SPI device to which the transaction is queued
+ * @is_dma_mapped: if true, the caller provided both dma and cpu virtual
+ *	addresses for each transfer buffer
+ * @complete: called to report transaction completions
+ * @context: the argument to complete() when it's called
+ * @actual_length: the total number of bytes that were transferred in all
+ *	successful segments
+ * @status: zero for success, else negative errno
+ * @queue: for use by whichever driver currently owns the message
+ * @state: for use by whichever driver currently owns the message
+ *
+ * The code that submits an spi_message (and its spi_transfers)
+ * to the lower layers is responsible for managing its memory.
+ * Zero-initialize every field you don't set up explicitly, to
+ * insulate against future API updates.
+ */
+struct spi_message {
+	struct spi_transfer	*transfers;
+	unsigned		n_transfer;
+
+	struct spi_device	*spi;
+
+	unsigned		is_dma_mapped:1;
+
+	/* REVISIT:  we might want a flag affecting the behavior of the
+	 * last transfer ... allowing things like "read 16 bit length L"
+	 * immediately followed by "read L bytes".  Basically imposing
+	 * a specific message scheduling algorithm.
+	 *
+	 * Some controller drivers (message-at-a-time queue processing)
+	 * could provide that as their default scheduling algorithm.  But
+	 * others (with multi-message pipelines) could need a flag to
+	 * tell them about such special cases.
+	 */
+
+	/* completion is reported through a callback */
+	void 			FASTCALL((*complete)(void *context));
+	void			*context;
+	unsigned		actual_length;
+	int			status;
+
+	/* for optional use by whatever driver currently owns the
+	 * spi_message ...  between calls to spi_async and then later
+	 * complete(), that's the spi_master controller driver.
+	 */
+	struct list_head	queue;
+	void			*state;
+};
+
+/* It's fine to embed message and transaction structures in other data
+ * structures so long as you don't free them while they're in use.
+ */
+
+static inline struct spi_message *spi_message_alloc(unsigned ntrans, gfp_t flags)
+{
+	struct spi_message *m;
+
+	m = kzalloc(sizeof(struct spi_message)
+			+ ntrans * sizeof(struct spi_transfer),
+			flags);
+	if (m) {
+		m->transfers = (void *)(m + 1);
+		m->n_transfer = ntrans;
+	}
+	return m;
+}
+
+static inline void spi_message_free(struct spi_message *m)
+{
+	kfree(m);
+}
+
+/**
+ * spi_setup -- setup SPI mode and clock rate
+ * @spi: the device whose settings are being modified
+ *
+ * SPI protocol drivers may need to update the transfer mode if the
+ * device doesn't work with the mode 0 default.  They may likewise need
+ * to update clock rates or word sizes from initial values.  This function
+ * changes those settings, and must be called from a context that can sleep.
+ */
+static inline int
+spi_setup(struct spi_device *spi)
+{
+	return spi->master->setup(spi);
+}
+
+
+/**
+ * spi_async -- asynchronous SPI transfer
+ * @spi: device with which data will be exchanged
+ * @message: describes the data transfers, including completion callback
+ *
+ * This call may be used in_irq and other contexts which can't sleep,
+ * as well as from task contexts which can sleep.
+ *
+ * The completion callback is invoked in a context which can't sleep.
+ * Before that invocation, the value of message->status is undefined.
+ * When the callback is issued, message->status holds either zero (to
+ * indicate complete success) or a negative error code.  After that
+ * callback returns, the driver which issued the transfer request may
+ * deallocate the associated memory; it's no longer in use by any SPI
+ * core or controller driver code.
+ *
+ * Note that although all messages to a spi_device are handled in
+ * FIFO order, messages may go to different devices in other orders.
+ * Some device might be higher priority, or have various "hard" access
+ * time requirements, for example.
+ *
+ * On detection of any fault during the transfer, processing of
+ * the entire message is aborted, and the device is deselected.
+ * Until returning from the associated message completion callback,
+ * no other spi_message queued to that device will be processed.
+ * (This rule applies equally to all the synchronous transfer calls,
+ * which are wrappers around this core asynchronous primitive.)
+ */
+static inline int
+spi_async(struct spi_device *spi, struct spi_message *message)
+{
+	message->spi = spi;
+	return spi->master->transfer(spi, message);
+}
+
+/*---------------------------------------------------------------------------*/
+
+/* All these synchronous SPI transfer routines are utilities layered
+ * over the core async transfer primitive.  Here, "synchronous" means
+ * they will sleep uninterruptibly until the async transfer completes.
+ */
+
+extern int spi_sync(struct spi_device *spi, struct spi_message *message);
+
+/**
+ * spi_write - SPI synchronous write
+ * @spi: device to which data will be written
+ * @buf: data buffer
+ * @len: data buffer size
+ *
+ * This writes the buffer and returns zero or a negative error code.
+ * Callable only from contexts that can sleep.
+ */
+static inline int
+spi_write(struct spi_device *spi, const u8 *buf, size_t len)
+{
+	struct spi_transfer	t = {
+			.tx_buf		= buf,
+			.rx_buf		= NULL,
+			.len		= len,
+			.cs_change	= 0,
+		};
+	struct spi_message	m;
+
+	m.transfers	= &t;
+	m.n_transfer	= 1;
+	return spi_sync(spi, &m);
+}
+
+/**
+ * spi_read - SPI synchronous read
+ * @spi: device from which data will be read
+ * @buf: data buffer
+ * @len: data buffer size
+ *
+ * This writes the buffer and returns zero or a negative error code.
+ * Callable only from contexts that can sleep.
+ */
+static inline int
+spi_read(struct spi_device *spi, u8 *buf, size_t len)
+{
+	struct spi_transfer	t = {
+			.tx_buf		= NULL,
+			.rx_buf		= buf,
+			.len		= len,
+			.cs_change	= 0,
+		};
+	struct spi_message	m;
+
+	m.transfers	= &t;
+	m.n_transfer	= 1;
+	return spi_sync(spi, &m);
+}
+
+/* this copies txbuf and rxbuf data; for small transfers only! */
+extern int spi_write_then_read(struct spi_device *spi,
+		const u8 *txbuf, unsigned n_tx,
+		u8 *rxbuf, unsigned n_rx);
+
+/**
+ * spi_w8r8 - SPI synchronous 8 bit write followed by 8 bit read
+ * @spi: device with which data will be exchanged
+ * @cmd: command to be written before data is read back
+ *
+ * This returns the (unsigned) eight bit number returned by the
+ * device, or else a negative error code.  Callable only from
+ * contexts that can sleep.
+ */
+static inline ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)
+{
+	ssize_t			status;
+	u8			result;
+
+	status = spi_write_then_read(spi, &cmd, 1, &result, 1);
+
+	/* return negative errno or unsigned value */
+	return (status < 0) ? status : result;
+}
+
+/**
+ * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read
+ * @spi: device with which data will be exchanged
+ * @cmd: command to be written before data is read back
+ *
+ * This returns the (unsigned) sixteen bit number returned by the
+ * device, or else a negative error code.  Callable only from
+ * contexts that can sleep.
+ *
+ * The number is returned in wire-order, which is at least sometimes
+ * big-endian.
+ */
+static inline ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)
+{
+	ssize_t			status;
+	u16			result;
+
+	status = spi_write_then_read(spi, &cmd, 1, (u8 *) &result, 2);
+
+	/* return negative errno or unsigned value */
+	return (status < 0) ? status : result;
+}
+
+/*---------------------------------------------------------------------------*/
+
+/*
+ * INTERFACE between board init code and SPI infrastructure.
+ *
+ * No SPI driver ever sees these SPI device table segments, but
+ * it's how the SPI core (or adapters that get hotplugged) grows
+ * the driver model tree.
+ *
+ * As a rule, SPI devices can't be probed.  Instead, board init code
+ * provides a table listing the devices which are present, with enough
+ * information to bind and set up the device's driver.  There's basic
+ * support for nonstatic configurations too; enough to handle adding
+ * parport adapters, or microcontrollers acting as USB-to-SPI bridges.
+ */
+
+/* board-specific information about each SPI device */
+struct spi_board_info {
+	/* the device name and module name are coupled, like platform_bus;
+	 * "modalias" is normally the driver name.
+	 *
+	 * platform_data goes to spi_device.dev.platform_data,
+	 * controller_data goes to spi_device.controller_data,
+	 * irq is copied too
+	 */
+	char		modalias[KOBJ_NAME_LEN];
+	const void	*platform_data;
+	void		*controller_data;
+	int		irq;
+
+	/* slower signaling on noisy or low voltage boards */
+	u32		max_speed_hz;
+
+
+	/* bus_num is board specific and matches the bus_num of some
+	 * spi_master that will probably be registered later.
+	 *
+	 * chip_select reflects how this chip is wired to that master;
+	 * it's less than num_chipselect.
+	 */
+	u16		bus_num;
+	u16		chip_select;
+
+	/* ... may need additional spi_device chip config data here.
+	 * avoid stuff protocol drivers can set; but include stuff
+	 * needed to behave without being bound to a driver:
+	 *  - chipselect polarity
+	 *  - quirks like clock rate mattering when not selected
+	 */
+};
+
+#ifdef	CONFIG_SPI
+extern int
+spi_register_board_info(struct spi_board_info const *info, unsigned n);
+#else
+/* board init code may ignore whether SPI is configured or not */
+static inline int
+spi_register_board_info(struct spi_board_info const *info, unsigned n)
+	{ return 0; }
+#endif
+
+
+/* If you're hotplugging an adapter with devices (parport, usb, etc)
+ * use spi_new_device() to describe each device.  You can also call
+ * spi_unregister_device() to start making that device vanish, but
+ * normally that would be handled by spi_unregister_master().
+ */
+extern struct spi_device *
+spi_new_device(struct spi_master *, struct spi_board_info *);
+
+static inline void
+spi_unregister_device(struct spi_device *spi)
+{
+	if (spi)
+		device_unregister(&spi->dev);
+}
+
+#endif /* __LINUX_SPI_H */
drivers/spi/spi.c new file +633 -0

633 lines not on this page · raw message

drivers/spi/Kconfig new file +91 -0

91 lines not on this page · raw message

arch/arm/Kconfig +2 -0
@@ -730,6 +730,8 @@ source "drivers/char/Kconfig"
 
 source "drivers/i2c/Kconfig"
 
+source "drivers/spi/Kconfig"
+
 source "drivers/hwmon/Kconfig"
 
 #source "drivers/l3/Kconfig"
drivers/Kconfig +2 -0
@@ -44,6 +44,8 @@ source "drivers/char/Kconfig"
 
 source "drivers/i2c/Kconfig"
 
+source "drivers/spi/Kconfig"
+
 source "drivers/w1/Kconfig"
 
 source "drivers/hwmon/Kconfig"
drivers/Makefile +1 -0
@@ -40,6 +40,7 @@ obj-$(CONFIG_FUSION)		+= message/
 obj-$(CONFIG_IEEE1394)		+= ieee1394/
 obj-y				+= cdrom/
 obj-$(CONFIG_MTD)		+= mtd/
+obj-$(CONFIG_SPI)		+= spi/
 obj-$(CONFIG_PCCARD)		+= pcmcia/
 obj-$(CONFIG_DIO)		+= dio/
 obj-$(CONFIG_SBUS)		+= sbus/
drivers/spi/Makefile new file +23 -0
@@ -0,0 +1,23 @@
+#
+# Makefile for kernel SPI drivers.
+#
+
+ifeq ($(CONFIG_SPI_DEBUG),y)
+EXTRA_CFLAGS += -DDEBUG
+endif
+
+# small core, mostly translating board-specific
+# config declarations into driver model code
+obj-$(CONFIG_SPI_MASTER)		+= spi.o
+
+# SPI master controller drivers (bus)
+# 	... add above this line ...
+
+# SPI protocol drivers (device/link on bus)
+# 	... add above this line ...
+
+# SPI slave controller drivers (upstream link)
+# 	... add above this line ...
+
+# SPI slave drivers (protocol for that link)
+# 	... add above this line ...
Documentation/spi/spi-summary new file +443 -0

443 lines not on this page · raw message

#5 lore raw

PATCH 2/6 SPI ads7846 protocol driver

In reply to David Brownell

For touchscreen plus sensors. Lots of Linux-capable boards have these chips or one of their close siblings.

This is a driver for the ADS7846 touchscreen sensor, derived from the corgi_ts and omap_ts drivers. Key differences from those two:

- Uses the new SPI framework (minimalist version)
- <linux/spi/ads7846.h> abstracts board-specific touchscreen info
- Sysfs attributes for the temperature and voltage sensors
- Uses fewer ARM-specific IRQ primitives

The temperature and voltage sensors show up in sysfs like this:

  $ pwd
  /sys/devices/platform/omap-uwire/spi2.0-ads7846
  $ ls
  bus@          input:event0@ power/        temp1         vbatt
  driver@       modalias      temp0         vaux
  $ cat temp0
  991
  $ cat temp1
  1177
  $

So far only basic testing has been done. There's a fair amount of hardware that uses this sensor, and which also runs Linux, which should eventually be able to use this driver.

One portability note may be of special interest. It turns out that not all SPI controllers are happy issuing requests that do things like "write 8 bit command, read 12 bit response". Most of them seem happy to handle various word sizes, so the issue isn't "12 bit response" but rather "different rx and tx write sizes", despite that being a common MicroWire convention. So this version of the driver no longer reads 12 bit native-endian words; it reads 16-bit bit-endian responses, then byteswaps them and shifts the results to discard the noise.

drivers/input/touchscreen/Makefile +1 -0
@@ -4,6 +4,7 @@
 
 # Each configuration option enables a list of files.
 
+obj-$(CONFIG_TOUCHSCREEN_ADS7846)	+= ads7846.o
 obj-$(CONFIG_TOUCHSCREEN_BITSY)	+= h3600_ts_input.o
 obj-$(CONFIG_TOUCHSCREEN_CORGI)	+= corgi_ts.o
 obj-$(CONFIG_TOUCHSCREEN_GUNZE)	+= gunze.o
drivers/input/touchscreen/Kconfig +13 -0
@@ -11,6 +11,19 @@ menuconfig INPUT_TOUCHSCREEN
 
 if INPUT_TOUCHSCREEN
 
+config TOUCHSCREEN_ADS7846
+	tristate "ADS 7846 based touchscreens"
+	depends on SPI_MASTER
+	help
+	  Say Y here if you have a touchscreen interface using the
+	  ADS7846 controller, and your board-specific initialization
+	  code includes that in its table of SPI devices.
+
+	  If unsure, say N (but it's safe to say "Y").
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called ads7846.
+
 config TOUCHSCREEN_BITSY
 	tristate "Compaq iPAQ H3600 (Bitsy) touchscreen"
 	depends on SA1100_BITSY
include/linux/spi/ads7846.h new file +18 -0
@@ -0,0 +1,18 @@
+/* linux/spi/ads7846.h */
+
+/* Touchscreen characteristics vary between boards and models.  The
+ * platform_data for the device's "struct device" holds this information.
+ *
+ * It's OK if the min/max values are zero.
+ */
+struct ads7846_platform_data {
+	u16	model;			/* 7843, 7845, 7846. */
+	u16	vref_delay_usecs;	/* 0 for external vref; etc */
+	u16	x_plate_ohms;
+	u16	y_plate_ohms;
+
+	u16	x_min, x_max;
+	u16	y_min, y_max;
+	u16	pressure_min, pressure_max;
+};
+
drivers/input/touchscreen/ads7846.c new file +621 -0

621 lines not on this page · raw message

#6 lore raw

Re: [spi-devel-general] [patch 2.6.14-rc6-git 2/6] SPI ads7846 protocol driver

Quoted 10 lines · --- David Brownell

For touchscreen plus sensors. Lots of Linux-capable boards have these chips
or one of their close siblings.

Quoted 1 line

This is a driver for the ADS7846 touchscreen sensor, derived from

the corgi_ts and omap_ts drivers. Key differences from those two:

- Uses the new SPI framework (minimalist version)
- <linux/spi/ads7846.h> abstracts board-specific touchscreen info
- Sysfs attributes for the temperature and voltage sensors
- Uses fewer ARM-specific IRQ primitives

How do you test this driver on OSK? Don't we need controller driver / bitbanging interface atleast?

Also use input_allocate_device() instead of init_input_dev(). Thanx.

I have started writing OMAP2 SPI master controller driver for and tsc2101 driver based on ads7846 driver for H4 board.

---Komal Shah
http://komalshah.blogspot.com/

__________________________________
Yahoo! for Good - Make a difference this year.
http://brand.yahoo.com/cybergivingweek2005/

#7 lore raw

Re: [spi-devel-general] [patch 2.6.14-rc6-git 2/6] SPI ads7846 protocol driver

Quoted 2 lines

How do you test this driver on OSK?

With disgusting hacks to the existing uwire driver.

Quoted 1 line

Don't we need controller driver / bitbanging interface atleast?

I was thinking of replacing the hacks with spi_bitbang stuff; the txrx_bufs() method is appropriate for MicroWire since it needs to know whether to read _or_ write, and txrx_word() calls assume the full-service shift register is available.

Quoted 1 line

Also use input_allocate_device() instead of init_input_dev(). Thanx.

Got patch? :)

Quoted 2 lines

I have started writing OMAP2 SPI master controller driver for and tsc2101 driver based on ads7846 driver for H4 board.

Cool. tsc2101 + uwire will handle H2 (and H3?) also. The only API change I know of (== necessariy affects your code) will be the "spi_transfer.transfer_list" patch, which I'll get out soon.

- Dave

#8 lore raw

Re: [spi-devel-general] [patch 2.6.14-rc6-git 2/6] SPI ads7846 protocol driver

Quoted 5 lines · --- David Brownell

I was thinking of replacing the hacks with spi_bitbang stuff; the txrx_bufs() method is appropriate for MicroWire since it needs to know whether to read _or_ write, and txrx_word() calls assume the full-service shift register is available.

Please post the patch once you replace it spi_bitbang. Thanx.

Quoted 6 lines
Quoted 3 lines

Also use input_allocate_device() instead of init_input_dev().

Thanx.

Got patch? :)

I will do it with latest -mm next week.

Quoted 4 lines

Cool. tsc2101 + uwire will handle H2 (and H3?) also. The only API change I know of (== necessariy affects your code) will be the "spi_transfer.transfer_list" patch, which I'll get out soon.

Ok, I will rebase it with -mm code. I have posted the patch to linux-omap mailing list, which is not yet complete for OMAP2 SPI master controller. As I want to avoid duplicate work done by someone in the another part of world with same fwk for OMAP2 :)

---Komal Shah
http://komalshah.blogspot.com/

__________________________________________
Yahoo! DSL – Something to write home about.
Just $16.99/mo. or less.
dsl.yahoo.com

#9 lore raw

Re: [spi-devel-general] [patch 2.6.14-rc6-git 2/6] SPI ads7846 protocol driver

Quoted 7 lines
Quoted 5 lines
Quoted 2 lines

Also use input_allocate_device() instead of init_input_dev().

Thanx.

Got patch? :)

I will do it with latest -mm next week.

Well, here's an update against 2.6.16-rc1-git. It builds and initializes, but lower level issues prevent my re-testing it.

- Dave

This updates the ads7846 touchscreen driver

- to match changes to the input subsystem that kicked in since it

    was first written and debugged;

- to allow faster clocking (this driver doesn't push sample rates);

- bugfixes the conversion of spi_transfer to lists;

- some dma-unsafe command buffers are fixed.

drivers/input/touchscreen/ads7846.c +79 -43
Index: o2/drivers/input/touchscreen/ads7846.c
===================================================================
@@ -51,10 +51,13 @@
 
 #define	TS_POLL_PERIOD	msecs_to_jiffies(10)
 
+/* this driver doesn't aim at the peak continuous sample rate */
+#define	SAMPLE_BITS	(8 /*cmd*/ + 16 /*sample*/ + 2 /* before, after */)
+
 struct ts_event {
 	/* For portability, we can't read 12 bit values using SPI (which
 	 * would make the controller deliver them as native byteorder u16
-	 * with msbs zeroed).  Instead, we read them as two 8-byte values,
+	 * with msbs zeroed).  Instead, we read them as two 8-bit values,
 	 * which need byteswapping then range adjustment.
 	 */
 	__be16 x;
@@ -63,7 +66,7 @@ struct ts_event {
 };
 
 struct ads7846 {
-	struct input_dev	input;
+	struct input_dev	*input;
 	char			phys[32];
 
 	struct spi_device	*spi;
@@ -71,6 +74,7 @@ struct ads7846 {
 	u16			vref_delay_usecs;
 	u16			x_plate_ohms;
 
+	u8			read_x, read_y, read_z1, read_z2;
 	struct ts_event		tc;
 
 	struct spi_transfer	xfer[8];
@@ -141,7 +145,9 @@ static const u8	ref_off = READ_12BIT_DFR
  */
 
 struct ser_req {
+	u8			ref_on;
 	u8			command;
+	u8			ref_off;
 	u16			scratch;
 	__be16			sample;
 	struct spi_message	msg;
@@ -163,7 +169,8 @@ static int ads7846_read12_ser(struct dev
 	INIT_LIST_HEAD(&req->msg.transfers);
 
 	/* activate reference, so it has time to settle; */
-	req->xfer[0].tx_buf = &ref_on;
+	req->ref_on = ref_on;
+	req->xfer[0].tx_buf = &req->ref_on;
 	req->xfer[0].len = 1;
 	req->xfer[1].rx_buf = &req->scratch;
 	req->xfer[1].len = 2;
@@ -185,7 +192,8 @@ static int ads7846_read12_ser(struct dev
 	/* REVISIT:  take a few more samples, and compare ... */
 
 	/* turn off reference */
-	req->xfer[4].tx_buf = &ref_off;
+	req->ref_off = ref_off;
+	req->xfer[4].tx_buf = &req->ref_off;
 	req->xfer[4].len = 1;
 	req->xfer[5].rx_buf = &req->scratch;
 	req->xfer[5].len = 2;
@@ -279,21 +287,21 @@ static void ads7846_rx(void *ads)
 	 * won't notice that, even if nPENIRQ never fires ...
 	 */
 	if (!ts->pendown && Rt != 0) {
-		input_report_key(&ts->input, BTN_TOUCH, 1);
+		input_report_key(ts->input, BTN_TOUCH, 1);
 		sync = 1;
 	} else if (ts->pendown && Rt == 0) {
-		input_report_key(&ts->input, BTN_TOUCH, 0);
+		input_report_key(ts->input, BTN_TOUCH, 0);
 		sync = 1;
 	}
 
 	if (Rt) {
-		input_report_abs(&ts->input, ABS_X, x);
-		input_report_abs(&ts->input, ABS_Y, y);
-		input_report_abs(&ts->input, ABS_PRESSURE, Rt);
+		input_report_abs(ts->input, ABS_X, x);
+		input_report_abs(ts->input, ABS_Y, y);
+		input_report_abs(ts->input, ABS_PRESSURE, Rt);
 		sync = 1;
 	}
 	if (sync)
-		input_sync(&ts->input);
+		input_sync(ts->input);
 
 #ifdef	VERBOSE
 	if (Rt || ts->pendown)
@@ -401,7 +409,7 @@ static int __devinit ads7846_probe(struc
 	struct ads7846			*ts;
 	struct ads7846_platform_data	*pdata = spi->dev.platform_data;
 	struct spi_transfer		*x;
-	int				i;
+	int				status;
 
 	if (!spi->irq) {
 		dev_dbg(&spi->dev, "no IRQ?\n");
@@ -414,9 +422,9 @@ static int __devinit ads7846_probe(struc
 	}
 
 	/* don't exceed max specified sample rate */
-	if (spi->max_speed_hz > (125000 * 16)) {
+	if (spi->max_speed_hz > (125000 * SAMPLE_BITS)) {
 		dev_dbg(&spi->dev, "f(sample) %d KHz?\n",
-				(spi->max_speed_hz/16)/1000);
+				(spi->max_speed_hz/SAMPLE_BITS)/1000);
 		return -EINVAL;
 	}
 
@@ -442,79 +450,100 @@ static int __devinit ads7846_probe(struc
 	ts->vref_delay_usecs = pdata->vref_delay_usecs ? : 100;
 	ts->x_plate_ohms = pdata->x_plate_ohms ? : 400;
 
-	init_input_dev(&ts->input);
-
-	ts->input.dev = &spi->dev;
-	ts->input.name = "ADS784x Touchscreen";
-	snprintf(ts->phys, sizeof ts->phys, "%s/input0", spi->dev.bus_id);
-	ts->input.phys = ts->phys;
-
-	ts->input.evbit[0] = BIT(EV_KEY) | BIT(EV_ABS);
-	ts->input.keybit[LONG(BTN_TOUCH)] = BIT(BTN_TOUCH);
-	input_set_abs_params(&ts->input, ABS_X,
+	ts->input = input_allocate_device();
+	if (ts->input == NULL) {
+		status = -ENOMEM;
+		goto fail;
+	}
+
+	init_input_dev(ts->input);
+
+	ts->input->dev = &spi->dev;
+	ts->input->name = "ADS784x Touchscreen";
+	snprintf(ts->phys, sizeof ts->phys, "%s/input", spi->dev.bus_id);
+	ts->input->phys = ts->phys;
+
+	ts->input->evbit[0] = BIT(EV_KEY) | BIT(EV_ABS);
+	ts->input->keybit[LONG(BTN_TOUCH)] = BIT(BTN_TOUCH);
+	input_set_abs_params(ts->input, ABS_X,
 			pdata->x_min ? : 0,
 			pdata->x_max ? : MAX_12BIT,
 			0, 0);
-	input_set_abs_params(&ts->input, ABS_Y,
+	input_set_abs_params(ts->input, ABS_Y,
 			pdata->y_min ? : 0,
 			pdata->y_max ? : MAX_12BIT,
 			0, 0);
-	input_set_abs_params(&ts->input, ABS_PRESSURE,
+	input_set_abs_params(ts->input, ABS_PRESSURE,
 			pdata->pressure_min, pdata->pressure_max, 0, 0);
 
-	input_register_device(&ts->input);
+	status = input_register_device(ts->input);
+	if (status < 0)
+		goto fail;
 
 	/* set up the transfers to read touchscreen state; this assumes we
 	 * use formula #2 for pressure, not #3.
 	 */
+	INIT_LIST_HEAD(&ts->msg.transfers);
 	x = ts->xfer;
 
 	/* y- still on; turn on only y+ (and ADC) */
-	x->tx_buf = &read_y;
+	ts->read_y = read_y;
+	x->tx_buf = &ts->read_y;
 	x->len = 1;
+	spi_message_add_tail(x, &ts->msg);
+
 	x++;
 	x->rx_buf = &ts->tc.y;
 	x->len = 2;
-	x++;
+	spi_message_add_tail(x, &ts->msg);
 
 	/* turn y+ off, x- on; we'll use formula #2 */
 	if (ts->model == 7846) {
-		x->tx_buf = &read_z1;
+		x++;
+		ts->read_z1 = read_z1;
+		x->tx_buf = &ts->read_z1;
 		x->len = 1;
+		spi_message_add_tail(x, &ts->msg);
+
 		x++;
 		x->rx_buf = &ts->tc.z1;
 		x->len = 2;
-		x++;
+		spi_message_add_tail(x, &ts->msg);
 
-		x->tx_buf = &read_z2;
+		x++;
+		ts->read_z2 = read_z2;
+		x->tx_buf = &ts->read_z2;
 		x->len = 1;
+		spi_message_add_tail(x, &ts->msg);
+
 		x++;
 		x->rx_buf = &ts->tc.z2;
 		x->len = 2;
-		x++;
+		spi_message_add_tail(x, &ts->msg);
 	}
 
 	/* turn y- off, x+ on, then leave in lowpower */
-	x->tx_buf = &read_x;
+	x++;
+	ts->read_x = read_x;
+	x->tx_buf = &ts->read_x;
 	x->len = 1;
+	spi_message_add_tail(x, &ts->msg);
+
 	x++;
 	x->rx_buf = &ts->tc.x;
 	x->len = 2;
-	x++;
-
-	CS_CHANGE(x[-1]);
+	CS_CHANGE(*x);
+	spi_message_add_tail(x, &ts->msg);
 
-	for (i = 0; i < x - ts->xfer; i++)
-		spi_message_add_tail(&ts->xfer[i], &ts->msg);
 	ts->msg.complete = ads7846_rx;
 	ts->msg.context = ts;
 
 	if (request_irq(spi->irq, ads7846_irq, SA_SAMPLE_RANDOM,
-				spi->dev.bus_id, ts)) {
+				spi->dev.driver->name, ts)) {
 		dev_dbg(&spi->dev, "irq %d busy?\n", spi->irq);
-		input_unregister_device(&ts->input);
-		kfree(ts);
-		return -EBUSY;
+		input_unregister_device(ts->input);
+		status = -EBUSY;
+		goto fail;
 	}
 	set_irq_type(spi->irq, IRQT_FALLING);
 
@@ -538,6 +567,12 @@ static int __devinit ads7846_probe(struc
 	device_create_file(&spi->dev, &dev_attr_vaux);
 
 	return 0;
+fail:
+	if (ts && ts->input)
+		input_free_device(ts->input);
+	if (ts)
+		kfree(ts);
+	return status;
 }
 
 static int __devexit ads7846_remove(struct spi_device *spi)
@@ -557,7 +592,8 @@ static int __devexit ads7846_remove(stru
 		device_remove_file(&spi->dev, &dev_attr_vbatt);
 	device_remove_file(&spi->dev, &dev_attr_vaux);
 
-	input_unregister_device(&ts->input);
+	input_unregister_device(ts->input);
+	input_free_device(ts->input);
 	kfree(ts);
 
 	dev_dbg(&spi->dev, "unregistered touchscreen\n");
#10 lore raw

PATCH 3/6 SPI mtd_dataflash protocol driver

In reply to David Brownell

DataFlash is a kind of SPI flash sold by Atmel.

This is a conversion of the AT91rm9200 DataFlash MTD driver to use the lightweight SPI framework, and no longer be AT91-specific. It compiles down to less than 3KBytes on ARM.

The driver allows board-specific init code to provide platform_data with the relevant MTD partitioning information, and hotplugs.

This version has been lightly tested. Its parent at91_dataflash driver has been pretty well banged on, although kernel.org JFFS2 dataflash support was acting broken the last time I tried it.

drivers/mtd/devices/Kconfig +8 -0
@@ -47,6 +47,14 @@ config MTD_MS02NV
 	  accelerator.  Say Y here if you have a DECstation 5000/2x0 or a
 	  DECsystem 5900 equipped with such a module.
 
+config MTD_DATAFLASH
+	tristate "Support for AT45xxx DataFlash"
+	depends on MTD && SPI_MASTER && EXPERIMENTAL
+	help
+	  This enables access to AT45xxx DataFlash chips, using SPI.
+	  Sometimes DataFlash chips are packaged inside MMC-format
+	  cards; at this writing, the MMC stack won't handle those.
+
 config MTD_SLRAM
 	tristate "Uncached system RAM"
 	depends on MTD
include/linux/spi/flash.h new file +31 -0
@@ -0,0 +1,31 @@
+#ifndef LINUX_SPI_FLASH_H
+#define LINUX_SPI_FLASH_H
+
+struct mtd_partition;
+
+/**
+ * struct flash_platform_data: board-specific flash data
+ * @name: optional flash device name (eg, as used with mtdparts=)
+ * @parts: optional array of mtd_partitions for static partitioning
+ * @nr_parts: number of mtd_partitions for static partitoning
+ * @type: optional flash device type (e.g. m25p80 vs m25p64), for use
+ *	with chips that can't be queried for JEDEC or other IDs
+ *
+ * Board init code (in arch/.../mach-xxx/board-yyy.c files) can
+ * provide information about SPI flash parts (such as DataFlash) to
+ * help set up the device and its appropriate default partitioning.
+ *
+ * Note that for DataFlash, sizes for pages, blocks, and sectors are
+ * rarely powers of two; and partitions should be sector-aligned.
+ */
+struct flash_platform_data {
+	char		*name;
+	struct mtd_partition *parts;
+	unsigned int	nr_parts;
+
+	char		*type;
+
+	/* we'll likely add more ... use JEDEC IDs, etc */
+};
+
+#endif
drivers/mtd/devices/Makefile +1 -0
@@ -23,3 +23,4 @@ obj-$(CONFIG_MTD_MTDRAM)	+= mtdram.o
 obj-$(CONFIG_MTD_LART)		+= lart.o
 obj-$(CONFIG_MTD_BLKMTD)	+= blkmtd.o
 obj-$(CONFIG_MTD_BLOCK2MTD)	+= block2mtd.o
+obj-$(CONFIG_MTD_DATAFLASH)	+= mtd_dataflash.o
drivers/mtd/devices/mtd_dataflash.c new file +623 -0

623 lines not on this page · raw message

#11 lore raw

PATCH 4/6 SPI m25p flash protocol driver

In reply to David Brownell

If SPI flash isn't DataFlash, its protocol is probably very similar to the one used by these chips from ST.

This was originally a driver for the ST M25P80 SPI flash. It's been
updated slightly to handle other M25P series chips.

For many of these chips, the specific type could be probed, but for now this just requires static setup with flash_platform_data that lists the chip type (size, format) and any default partitioning to use.

From: Mike Lavender <[email protected]>

drivers/mtd/devices/Makefile +1 -0
@@ -24,3 +24,4 @@ obj-$(CONFIG_MTD_LART)		+= lart.o
 obj-$(CONFIG_MTD_BLKMTD)	+= blkmtd.o
 obj-$(CONFIG_MTD_BLOCK2MTD)	+= block2mtd.o
 obj-$(CONFIG_MTD_DATAFLASH)	+= mtd_dataflash.o
+obj-$(CONFIG_MTD_M25P80)	+= m25p80.o
drivers/mtd/devices/Kconfig +8 -0
@@ -55,6 +55,14 @@ config MTD_DATAFLASH
 	  Sometimes DataFlash chips are packaged inside MMC-format
 	  cards; at this writing, the MMC stack won't handle those.
 
+config MTD_M25P80
+	tristate "Support for M25 SPI Flash"
+	depends on MTD && SPI_MASTER && EXPERIMENTAL
+	help
+	  This enables access to ST M25P80 and similar SPI flash chips,
+	  used for program and data storage.  Set up your spi devices
+	  with the right board-specific platform data.
+
 config MTD_SLRAM
 	tristate "Uncached system RAM"
 	depends on MTD
drivers/mtd/devices/m25p80.c new file +576 -0

576 lines not on this page · raw message

#12 lore raw

PATCH 5/6 SPI bitbang utilities

In reply to David Brownell

This code supports a range of implementations for SPI controllers, from pure GPIO bitbanging up to drivers using non-queued DMA. The price includes a task context and various other restrictions that higher performance drivers may need to avoid.

This adds a bitbanging spi master, hooking up to board/adapter-specific glue code which knows how to set and read the signals (gpios etc).

That glue code gets hooked up using platform_data which includes I/O loops. Those loops could be optimized down to a few instructions accessing GPIO registers, in some common cases.

This understands all the currently defined protocol tweaking options, and could eventually serve as as reference implementation for them.

- different word sizes
- differing clock rates
- SPI modes differing only by CPOL ... chip setup, I/O loops
- SPI modes with I/O loops differing by CPHA
- delays (usecs) after transfers
- dropping chipselect mid-transfer

Not all those combinations have been tested yet; notably, not CPHA=1.

drivers/spi/Kconfig +14 -1
@@ -30,7 +30,7 @@ config SPI
 	  up to several tens of Mbit/sec.  Chips are addressed with a
 	  controller and a chipselect.  Most SPI slaves don't support
 	  dynamic device discovery; some are even write-only or read-only.
-	  
+
 	  SPI is widely used by microcontollers to talk with sensors,
 	  eeprom and flash memory, codecs and various other controller
 	  chips, analog to digital (and d-to-a) converters, and more.
@@ -66,6 +66,19 @@ config SPI_MASTER
 comment "SPI Master Controller Drivers"
 	depends on SPI_MASTER
 
+config SPI_BITBANG
+	tristate "Bitbanging SPI master"
+	depends on SPI_MASTER && EXPERIMENTAL
+	help
+	  With a few GPIO pins, your system can bitbang the SPI protocol.
+	  Select this to get SPI support through I/O pins (GPIO, parallel
+	  port, etc).  Or, some systems' SPI master controller drivers use
+	  this code to manage the per-word or per-transfer accesses to the
+	  hardware shift registers.
+
+	  This is library code, and is automatically selected by drivers that
+	  need it.  You only need to select this explicitly to support driver
+	  modules that aren't part of this kernel tree.
 
 #
 # Add new SPI master controllers in alphabetical order above this line
drivers/spi/Makefile +1 -0
@@ -11,6 +11,7 @@ endif
 obj-$(CONFIG_SPI_MASTER)		+= spi.o
 
 # SPI master controller drivers (bus)
+obj-$(CONFIG_SPI_BITBANG)		+= spi_bitbang.o
 # 	... add above this line ...
 
 # SPI protocol drivers (device/link on bus)
include/linux/spi/spi_bitbang.h new file +135 -0

135 lines not on this page · raw message

drivers/spi/spi_bitbang.c new file +457 -0

457 lines not on this page · raw message

#13 lore raw

PATCH 6/6 SPI parport adapter to AVR Butterfly

In reply to David Brownell

This patch ties together a lot of things; it lets folk with PCs use SPI to talk to an inexpensive(*) microcontroller evaluation/development board through a simple parport cable. In particular, it shows one way to hook up the parts so Linux will bitbang SPI messages to/from devices.

Linux already has a full userspace cross-development environment (avr-gcc, avrdude, etc) that can use the same adapter to update firmware. What this driver adds is the ability for Linux kernel code to use such links to talk to AVR firmware, or to the dataflash chip on that board.

(*) $20 at DigiKey, or from avrfreaks.net (with their T-Shirt).

This adds a bitbanging parport based adaptor cable for AVR Butterfly, giving SPI links to its DataFlash chip and (eventually) firmware running in the card.

drivers/spi/Kconfig +10 -0
@@ -80,6 +80,16 @@ config SPI_BITBANG
 	  need it.  You only need to select this explicitly to support driver
 	  modules that aren't part of this kernel tree.
 
+config SPI_BUTTERFLY
+	tristate "Parallel port adapter for AVR Butterfly (DEVELOPMENT)"
+	depends on SPI_MASTER && PARPORT && EXPERIMENTAL
+	select SPI_BITBANG
+	help
+	  This uses a custom parallel port cable to connect to an AVR
+	  Butterfly <http://www.atmel.com/products/avr/butterfly>, an
+	  inexpensive battery powered microcontroller evaluation board.
+	  This same cable can be used to flash new firmware.
+
 #
 # Add new SPI master controllers in alphabetical order above this line
 #
drivers/spi/Makefile +1 -0
@@ -12,6 +12,7 @@ obj-$(CONFIG_SPI_MASTER)		+= spi.o
 
 # SPI master controller drivers (bus)
 obj-$(CONFIG_SPI_BITBANG)		+= spi_bitbang.o
+obj-$(CONFIG_SPI_BUTTERFLY)		+= spi_butterfly.o
 # 	... add above this line ...
 
 # SPI protocol drivers (device/link on bus)
drivers/spi/spi_butterfly.c new file +421 -0

421 lines not on this page · raw message

Documentation/spi/butterfly new file +57 -0

57 lines not on this page · raw message