2005-11-30 16:50:39

by Vitaly Wool

[permalink] [raw]
Subject: [PATCH 2.6-git] SPI core refresh

Greetings,

This is an updated version of SPI framework developed by Dmitry Pervushin and Vitaly Wool.

The main changes are:

- Matching rmk's 2.6.14-git5+ changes for device_driver suspend and resume calls
- The character device interface was reworked

I still think that we need to continue converging with David Brownell's core, despite some misalignments happening in the email exchange :). Although it's not yet done in our core, I plan to move to
- using chained SPI messages as David does
- maybe rework the SPI device interface more taking David's one as a reference

However, there also are some advantages of our core compared to David's I'd like to mention

- it can be compiled as a module
- it is DMA-safe
- it is priority inversion-free
- it can gain more performance with multiple controllers
- it's more adapted for use in real-time environments
- it's not so lightweight, but it leaves less effort for the bus driver developer.

It's also been proven to work on SPI EEPROMs and SPI WiFi module (the latter was a really good survival test! :)).

Signed-off-by: Vitaly Wool <[email protected]>
Signed-off-by: dmitry pervushin <[email protected]>

arch/arm/Kconfig | 2
drivers/Kconfig | 2
drivers/Makefile | 1
drivers/spi/Kconfig | 33 ++
drivers/spi/Makefile | 14 +
drivers/spi/spi-core.c | 650 +++++++++++++++++++++++++++++++++++++++++++++++++
drivers/spi/spi-dev.c | 176 +++++++++++++
include/linux/spi.h | 297 ++++++++++++++++++++++
8 files changed, 1175 insertions(+)

diff -uNr linux-2.6.orig/include/linux/spi.h linux-2.6/include/linux/spi.h
--- linux-2.6.orig/include/linux/spi.h 1970-01-01 03:00:00.000000000 +0300
+++ linux-2.6/include/linux/spi.h 2005-11-30 19:03:51.000000000 +0300
@@ -0,0 +1,297 @@
+/*
+ * linux/include/linux/spi/spi.h
+ *
+ * Copyright (C) 2005 MontaVista Software, Inc <[email protected]>
+ *
+ * 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.
+ *
+ * Derived from l3.h by Jamey Hicks
+ */
+#ifndef SPI_H
+#define SPI_H
+
+#include <linux/types.h>
+#include <linux/device.h>
+
+#define kzalloc(size,type) kcalloc(1,size,type)
+
+struct spi_device;
+struct spi_driver;
+struct spi_msg;
+struct spi_bus_driver;
+
+extern struct bus_type spi_bus;
+
+struct spi_bus_data {
+ struct semaphore lock;
+ struct list_head msgs;
+ atomic_t exiting;
+ struct task_struct *thread;
+ wait_queue_head_t queue;
+ struct spi_device *selected_device;
+ struct spi_bus_driver *bus;
+ char *id;
+};
+
+#define TO_SPI_BUS_DRIVER(drv) container_of( drv, struct spi_bus_driver, driver )
+struct spi_bus_driver {
+ int (*xfer) (struct spi_msg * msg);
+ void (*select) (struct spi_device * dev);
+ void (*deselect) (struct spi_device * dev);
+ void (*set_clock) (struct device * bus_device, u32 clock_hz);
+ void (*reset) (struct device *bus_device, u32 context);
+ struct spi_msg *
+ (*retrieve) (struct spi_bus_driver *bus, struct spi_bus_data *data);
+ struct device_driver driver;
+};
+
+#define TO_SPI_DEV(device) container_of( device, struct spi_device, dev )
+struct spi_device {
+ char name[BUS_ID_SIZE];
+ void *private;
+ int minor;
+ struct class_device *cdev;
+ struct device dev;
+};
+
+#define TO_SPI_DRIVER(drv) container_of( drv, struct spi_driver, driver )
+struct spi_driver {
+ void *(*alloc) (size_t, int);
+ void (*free) (const void *);
+ unsigned char *(*get_buffer) (struct spi_device *, void *);
+ void (*release_buffer) (struct spi_device *, unsigned char *);
+ void (*control) (struct spi_device *, int mode, u32 ctl);
+ struct device_driver driver;
+};
+
+#define SPI_DEV_DRV( device ) TO_SPI_DRIVER( (device)->dev.driver )
+
+#define spi_device_lock( dev ) /* down( dev->dev.sem ) */
+#define spi_device_unlock( dev ) /* up( dev->dev.sem ) */
+
+/*
+ * struct spi_msg
+ *
+ * This structure represent the SPI message internally. You should never use fields of this structure directly
+ * Please use corresponding functions to create/destroy/access fields
+ *
+ */
+struct spi_msg {
+ u32 flags;
+#define SPI_M_RD 0x00000001
+#define SPI_M_WR 0x00000002 /**< Write mode flag */
+#define SPI_M_CSREL 0x00000004 /**< CS release level at end of the frame */
+#define SPI_M_CS 0x00000008 /**< CS active level at begining of frame ( default low ) */
+#define SPI_M_CPOL 0x00000010 /**< Clock polarity */
+#define SPI_M_CPHA 0x00000020 /**< Clock Phase */
+#define SPI_M_EXTBUF 0x80000000 /** externally allocated buffers */
+#define SPI_M_ASYNC_CB 0x40000000 /** use workqueue to deliver callbacks */
+#define SPI_M_DNA 0x20000000 /** do not allocate buffers */
+
+ unsigned short len; /* msg length */
+ unsigned long clock;
+ struct spi_device *device;
+ void *context;
+ void *arg;
+ void *parent; /* in case of complex messages */
+ struct list_head link;
+
+ void (*status) (struct spi_msg * msg, int code);
+
+ void *devbuf_rd, *devbuf_wr;
+ u8 *databuf_rd, *databuf_wr;
+
+ struct work_struct wq_item;
+};
+
+#ifdef CONFIG_SPI_CHARDEV
+extern struct class_device *spi_class_device_create(int minor, struct device *device);
+extern void spi_class_device_destroy(int minor);
+#else
+#define spi_class_device_create(a, b) NULL
+#define spi_class_device_destroy(a) do { } while (0)
+#endif
+
+static inline struct spi_msg *spimsg_alloc(struct spi_device *device,
+ unsigned flags,
+ unsigned short len,
+ void (*status) (struct spi_msg *,
+ int code))
+{
+ struct spi_msg *msg;
+ struct spi_driver *drv = SPI_DEV_DRV(device);
+ int msgsize = sizeof (struct spi_msg);
+
+ if (drv->alloc || (flags & (SPI_M_RD|SPI_M_WR)) == (SPI_M_RD | SPI_M_WR ) ) {
+ pr_debug ( "%s: external buffers\n", __FUNCTION__ );
+ flags |= SPI_M_EXTBUF;
+ } else {
+ pr_debug ("%s: no ext buffers, msgsize increased from %d by %d to %d\n", __FUNCTION__,
+ msgsize, len, msgsize + len );
+ msgsize += len;
+ }
+
+ msg = kmalloc( msgsize, GFP_KERNEL);
+ if (!msg)
+ return NULL;
+ memset(msg, 0, sizeof(struct spi_msg));
+ msg->len = len;
+ msg->status = status;
+ msg->device = device;
+ msg->flags = flags;
+ INIT_LIST_HEAD(&msg->link);
+
+ if (flags & SPI_M_DNA )
+ return msg;
+
+ /* otherwise, we need to set up pointers */
+ if (!(flags & SPI_M_EXTBUF)) {
+ msg->databuf_rd = msg->databuf_wr =
+ (u8*)msg + sizeof ( struct spi_msg);
+ } else {
+ if (flags & SPI_M_RD) {
+ msg->devbuf_rd = drv->alloc ?
+ drv->alloc(len, GFP_KERNEL) : kmalloc(len, GFP_KERNEL);
+ msg->databuf_rd = drv->get_buffer ?
+ drv->get_buffer(device, msg->devbuf_rd) : msg->devbuf_rd;
+ }
+ if (flags & SPI_M_WR) {
+ msg->devbuf_wr = drv->alloc ?
+ drv->alloc(len, GFP_KERNEL) : kmalloc(len, GFP_KERNEL);
+ msg->databuf_wr = drv->get_buffer ?
+ drv->get_buffer(device, msg->devbuf_wr) : msg->devbuf_wr;
+ }
+ }
+ pr_debug("%s: msg = %p, RD=(%p,%p) WR=(%p,%p). Actual flags = %s+%s\n",
+ __FUNCTION__,
+ msg,
+ msg->devbuf_rd, msg->databuf_rd,
+ msg->devbuf_wr, msg->databuf_wr,
+ msg->flags & SPI_M_RD ? "RD" : "~rd",
+ msg->flags & SPI_M_WR ? "WR" : "~wr");
+ return msg;
+}
+
+static inline void spimsg_free(struct spi_msg *msg)
+{
+ void (*do_free) (const void *) = kfree;
+ struct spi_driver *drv = SPI_DEV_DRV(msg->device);
+
+ if (msg) {
+
+ if ( !(msg->flags & SPI_M_DNA) || (msg->flags & SPI_M_EXTBUF) ) {
+ if (drv->free)
+ do_free = drv->free;
+ if (drv->release_buffer) {
+ if (msg->databuf_rd)
+ drv->release_buffer(msg->device,
+ msg->databuf_rd);
+ if (msg->databuf_wr)
+ drv->release_buffer(msg->device,
+ msg->databuf_wr);
+ }
+ if (msg->devbuf_rd)
+ do_free(msg->devbuf_rd);
+ if (msg->devbuf_wr)
+ do_free(msg->devbuf_wr);
+ }
+ kfree(msg);
+ }
+}
+
+static inline u8 *spimsg_buffer_rd(struct spi_msg *msg)
+{
+ return msg ? msg->databuf_rd : NULL;
+}
+
+static inline u8 *spimsg_buffer_wr(struct spi_msg *msg)
+{
+ return msg ? msg->databuf_wr : NULL;
+}
+
+static inline u8 *spimsg_buffer(struct spi_msg *msg)
+{
+ if (!msg)
+ return NULL;
+ if ((msg->flags & (SPI_M_RD | SPI_M_WR)) == (SPI_M_RD | SPI_M_WR)) {
+ printk(KERN_ERR "%s: what buffer do you really want ?\n",
+ __FUNCTION__);
+ return NULL;
+ }
+ if (msg->flags & SPI_M_RD)
+ return msg->databuf_rd;
+ if (msg->flags & SPI_M_WR)
+ return msg->databuf_wr;
+}
+
+static inline void spimsg_set_rd( struct spi_msg* msg, void* buf )
+{
+ msg->databuf_rd = buf;
+}
+
+static inline void spimsg_set_wr (struct spi_msg *msg, void *buf )
+{
+ msg->databuf_wr = buf;
+}
+
+
+#define SPIMSG_OK 0x01
+#define SPIMSG_FAILED 0x80
+#define SPIMSG_STARTED 0x02
+#define SPIMSG_DONE 0x04
+
+#define SPI_MAJOR 153
+
+struct spi_driver;
+struct spi_device;
+
+#ifdef CONFIG_SPI_CHARDEV
+extern int __init spidev_init(void);
+extern void __exit spidev_cleanup(void);
+#else
+#define spidev_init() (0)
+#define spidev_cleanup() do { } while (0)
+#endif
+
+static inline int spi_bus_driver_register (struct spi_bus_driver *bus_driver)
+{
+ return driver_register (&bus_driver->driver);
+}
+
+void spi_bus_driver_unregister(struct spi_bus_driver *);
+int spi_bus_driver_init(struct spi_bus_driver *driver, struct device *dev);
+struct spi_device* spi_device_add(struct device *parent, char *name, void *private);
+
+static inline int spi_driver_add(struct spi_driver *drv)
+{
+ drv->driver.bus = &spi_bus;
+ return driver_register(&drv->driver);
+}
+static inline void spi_driver_del(struct spi_driver *drv)
+{
+ driver_unregister(&drv->driver);
+}
+
+extern void spi_bus_reset(struct device* bus, u32 context);
+extern int spi_write(struct spi_device *dev, const char *buf, int len);
+extern int spi_read(struct spi_device *dev, char *buf, int len);
+
+extern int spi_queue(struct spi_msg *message);
+extern int spi_transfer(struct spi_msg *message,
+ void (*status) (struct spi_msg *, int));
+extern int spi_bus_populate(struct device *parent, char *device,
+ void (*assign) (struct device *parent,
+ struct spi_device *));
+struct spi_device_desc {
+ char* name;
+ void* params;
+};
+extern int spi_bus_populate2(struct device *parent,
+ struct spi_device_desc *devices,
+ void (*assign) (struct device *parent,
+ struct spi_device *,
+ void *));
+
+#endif /* SPI_H */
diff -uNr linux-2.6.orig/arch/arm/Kconfig linux-2.6/arch/arm/Kconfig
--- linux-2.6.orig/arch/arm/Kconfig 2005-11-30 16:19:55.000000000 +0300
+++ linux-2.6/arch/arm/Kconfig 2005-11-30 16:22:35.000000000 +0300
@@ -748,6 +748,8 @@

source "drivers/mmc/Kconfig"

+source "drivers/spi/Kconfig"
+
endmenu

source "fs/Kconfig"

diff -uNr linux-2.6.orig/drivers/Kconfig linux-2.6/drivers/Kconfig
--- linux-2.6.orig/drivers/Kconfig 2005-11-30 16:19:55.000000000 +0300
+++ linux-2.6/drivers/Kconfig 2005-11-30 16:22:35.000000000 +0300
@@ -44,6 +44,8 @@

source "drivers/i2c/Kconfig"

+source "drivers/spi/Kconfig"
+
source "drivers/w1/Kconfig"

source "drivers/hwmon/Kconfig"
diff -uNr linux-2.6.orig/drivers/Makefile linux-2.6/drivers/Makefile
--- linux-2.6.orig/drivers/Makefile 2005-11-30 16:19:55.000000000 +0300
+++ linux-2.6/drivers/Makefile 2005-11-30 16:22:35.000000000 +0300
@@ -69,3 +69,4 @@
obj-y += firmware/
obj-$(CONFIG_CRYPTO) += crypto/
obj-$(CONFIG_SUPERH) += sh/
+obj-$(CONFIG_SPI) += spi/
diff -uNr linux-2.6.orig/drivers/spi/Kconfig linux-2.6/drivers/spi/Kconfig
--- linux-2.6.orig/drivers/spi/Kconfig 1970-01-01 03:00:00.000000000 +0300
+++ linux-2.6/drivers/spi/Kconfig 2005-11-30 16:22:35.000000000 +0300
@@ -0,0 +1,33 @@
+#
+# SPI device configuration
+#
+menu "SPI support"
+
+config SPI
+ default Y
+ tristate "SPI (Serial Peripheral Interface) bus support"
+ default false
+ help
+ Say Y if you need to enable SPI support on your kernel.
+ Say M if you want to create the spi-core loadable module.
+
+config SPI_DEBUG
+ bool "SPI debug output"
+ depends on SPI
+ default false
+ help
+ Say Y there if you'd like to see debug output from SPI drivers
+ If unsure, say N
+
+config SPI_CHARDEV
+ default Y
+ tristate "SPI device interface"
+ depends on SPI
+ help
+ Say Y here to use /dev/spiNN device files. They make it possible to have user-space
+ programs use the SPI bus.
+ This support is also available as a module. If so, the module
+ will be called spi-dev.
+
+endmenu
+
diff -uNr linux-2.6.orig/drivers/spi/Makefile linux-2.6/drivers/spi/Makefile
--- linux-2.6.orig/drivers/spi/Makefile 1970-01-01 03:00:00.000000000 +0300
+++ linux-2.6/drivers/spi/Makefile 2005-11-30 16:22:35.000000000 +0300
@@ -0,0 +1,14 @@
+#
+# Makefile for the kernel spi bus driver.
+#
+
+obj-$(CONFIG_SPI) += spi-core.o
+# bus drivers
+# ...functional drivers
+# ...and the common spi-dev driver
+obj-$(CONFIG_SPI_CHARDEV) += spi-dev.o
+
+ifeq ($(CONFIG_SPI_DEBUG),y)
+EXTRA_CFLAGS += -DDEBUG
+endif
+
diff -uNr linux-2.6.orig/drivers/spi/spi-core.c linux-2.6/drivers/spi/spi-core.c
--- linux-2.6.orig/drivers/spi/spi-core.c 1970-01-01 03:00:00.000000000 +0300
+++ linux-2.6/drivers/spi/spi-core.c 2005-11-30 19:03:52.000000000 +0300
@@ -0,0 +1,650 @@
+/*
+ * drivers/spi/spi-core.c
+ *
+ * Copyright (C) 2005 MontaVista Software, Inc <[email protected]>
+ *
+ * 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.
+ *
+ */
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/config.h>
+#include <linux/errno.h>
+#include <linux/slab.h>
+#include <linux/device.h>
+#include <linux/proc_fs.h>
+#include <linux/kmod.h>
+#include <linux/init.h>
+#include <linux/wait.h>
+#include <linux/kthread.h>
+#include <linux/spi.h>
+#include <asm/atomic.h>
+
+static int spi_thread(void *context);
+static int spi_device_del(struct device *dev, void *data);
+
+/**
+ * spi_bus_match_name - verify that driver matches device on spi bus
+ *
+ * @dev: device that hasn't yet being assigned to any driver
+ * @drv: driver for spi device
+ *
+ * Drivers and devices on SPI bus are matched by name, just like the
+ * platform devices, with exception of SPI_DEV_CHAR. Driver with this name
+ * will be matched against any device
+**/
+static int spi_bus_match_name(struct device *dev, struct device_driver *drv)
+{
+ return !strcmp(TO_SPI_DEV(dev)->name, drv->name);
+}
+
+/**
+ * spi_bus_suspend - suspend all devices on the spi bus
+ *
+ * @dev: spi device to be suspended
+ * @message: PM message
+ *
+ * This function set device on SPI bus to suspended state, just like platform_bus does
+**/
+static int spi_bus_suspend(struct device * dev, pm_message_t message)
+{
+ int ret = 0;
+
+ if (dev->driver && dev->driver->suspend)
+ ret = dev->driver->suspend(dev, message);
+ return ret;
+}
+
+/**
+ * spi_bus_resume - resume functioning of all devices on spi bus
+ *
+ * @dev: device to resume
+ *
+ * This function resumes device on SPI bus, just like platform_bus does
+**/
+static int spi_bus_resume(struct device * dev)
+{
+ int ret = 0;
+
+ if (dev->driver && dev->driver->resume)
+ ret = dev->driver->resume(dev);
+ return ret;
+}
+
+/**
+ * spi_bus - the &bus_type structure for SPI devices and drivers
+ *
+ * @name: the name of subsystem, "spi" here
+ * @match: function that matches devices to their drivers
+ * @suspend: PM callback to suspend device
+ * @resume: PM callback to resume device
+**/
+struct bus_type spi_bus = {
+ .name = "spi",
+ .match = spi_bus_match_name,
+ .suspend = spi_bus_suspend,
+ .resume = spi_bus_resume,
+};
+
+/**
+ * spi_bus_driver_init - init internal bus driver structures
+ *
+ * @bus: registered spi_bus_driver structure
+ * @dev: device that represents spi controller
+ *
+ * Once registered by spi_bus_register, the bus driver needs initialization, that
+ * includes starting thread, initializing internal structures.. The best place where
+ * the spi_bus_driver_init is in the `probe' function, when we already sure that passed
+ * device object is SPI master controller
+**/
+int spi_bus_driver_init(struct spi_bus_driver *bus, struct device *dev)
+{
+ struct spi_bus_data *pd =
+ kmalloc(sizeof(struct spi_bus_data), GFP_KERNEL);
+ int err = 0;
+
+ if (!pd) {
+ err = -ENOMEM;
+ goto init_failed_1;
+ }
+ atomic_set(&pd->exiting, 0);
+ pd->bus = bus;
+ init_MUTEX(&pd->lock);
+ INIT_LIST_HEAD(&pd->msgs);
+ init_waitqueue_head(&pd->queue);
+ pd->id = dev->bus_id;
+ pd->thread = kthread_run(spi_thread, pd, "%s-work", pd->id);
+ if (IS_ERR(pd->thread)) {
+ err = PTR_ERR(pd->thread);
+ goto init_failed_2;
+ }
+ dev->platform_data = pd;
+ return 0;
+
+init_failed_2:
+ kfree(pd);
+init_failed_1:
+ return err;
+}
+
+/**
+ * __spi_bus_free -- unregister all children of the spi bus
+ *
+ * @dev: the spi bus `device' object
+ * @context: not used, will be NULL
+ *
+ * This is internal function that is called when unregistering bus driver. Responsibility
+ * of this function is freeing the resources that were requested by spi_bus_driver_init
+ **/
+static int __spi_bus_free(struct device *dev, void *context)
+{
+ struct spi_bus_data *pd = dev->platform_data;
+
+ if (pd) {
+ atomic_inc(&pd->exiting);
+ kthread_stop(pd->thread);
+ kfree(pd);
+ }
+
+ dev_dbg(dev, "unregistering children\n");
+
+ device_for_each_child(dev, NULL, spi_device_del);
+ return 0;
+}
+
+/**
+ * spi_bus_driver_unregister - unregister SPI bus controller from the system
+ *
+ * @bus_driver: driver registered by call to spi_bus_driver_register
+ *
+ * unregisters the SPI bus from the system. Before unregistering, it deletes
+ * each SPI device on the bus using call to __spi_device_free
+**/
+void spi_bus_driver_unregister(struct spi_bus_driver *bus_driver)
+{
+ if (bus_driver) {
+ driver_for_each_device(&bus_driver->driver, NULL, NULL, __spi_bus_free);
+ driver_unregister(&bus_driver->driver);
+ }
+}
+
+/**
+ * spi_device_release - release the spi device structure
+ *
+ * @dev: spi_device to be released
+ *
+ * Pointer to this function will be put to dev->release place
+ * This fus called as a part of device removing
+**/
+void spi_device_release(struct device *dev)
+{
+ struct spi_device* sdev = TO_SPI_DEV(dev);
+
+ kfree(sdev);
+}
+
+/**
+ * spi_device_add - add the new (discovered) SPI device to the bus. Mostly used by bus drivers
+ *
+ * @parent: the bus device object
+ * @name: name of device (non-null!)
+ * @bus_data: bus data to be assigned to device
+ *
+ * SPI devices usually cannot be discovered by SPI bus driver, so it needs to take the configuration
+ * somewhere from hardcoded structures, and prepare bus_data for its devices
+**/
+struct spi_device* spi_device_add(struct device *parent, char *name, void *bus_data)
+{
+ struct spi_device* dev;
+ static int minor = 0;
+
+ if (!name)
+ goto dev_add_out;
+
+ dev = kmalloc(sizeof(struct spi_device), GFP_KERNEL);
+ if( !dev )
+ goto dev_add_out;
+
+ memset(&dev->dev, 0, sizeof(dev->dev));
+ dev->dev.parent = parent;
+ dev->dev.bus = &spi_bus;
+ strncpy(dev->name, name, sizeof(dev->name));
+ strncpy(dev->dev.bus_id, name, sizeof(dev->dev.bus_id));
+ dev->dev.release = spi_device_release;
+ dev->dev.platform_data = bus_data;
+
+ if (device_register(&dev->dev)<0) {
+ dev_dbg(parent, "device '%s' cannot be added\n", name);
+ goto dev_add_out_2;
+ }
+ dev->cdev = spi_class_device_create(minor, &dev->dev);
+ dev->minor = minor++;
+ return dev;
+
+dev_add_out_2:
+ kfree(dev);
+dev_add_out:
+ return NULL;
+}
+
+static int spi_device_del(struct device *dev, void *data)
+{
+ struct spi_device *spidev = TO_SPI_DEV(dev);
+ if (spidev->cdev) {
+ spi_class_device_destroy(spidev->minor);
+ spidev->cdev = NULL;
+ }
+ device_unregister(&spidev->dev);
+ return 0;
+}
+/**
+ * spi_queue - queue the message to be processed asynchronously
+ *
+ * @msg: message to be sent
+ *
+ * This function queues the message to spi bus driver's queue. The bus driver
+ * retrieves the message from queue according to its own rules (see retrieve method)
+ * and sends the message to target device. If message has no callback method, originator
+ * of message would get no chance to know where the message is processed. The better
+ * solution is using spi_transfer function, which will return error code if no callback
+ * is provided, or transfer the message synchronously.
+**/
+int spi_queue(struct spi_msg *msg)
+{
+ struct device *dev = &msg->device->dev;
+ struct spi_bus_data *pd = dev->parent->platform_data;
+
+ down(&pd->lock);
+ list_add_tail(&msg->link, &pd->msgs);
+ dev_dbg(dev->parent, "message has been queued\n");
+ up(&pd->lock);
+ wake_up_interruptible(&pd->queue);
+ return 0;
+}
+
+/**
+ * __spi_transfer_callback - callback to process synchronous messages
+ *
+ * @msg: message that is about to complete
+ * @code: message status
+ *
+ * callback for synchronously processed message. If spi_transfer determines
+ * that there is no callback provided neither by msg->status nor callback
+ * parameter, the __spi_transfer_callback will be used, and spi_transfer
+ * does not return until transfer is finished
+ *
+**/
+static void __spi_transfer_callback(struct spi_msg *msg, int code)
+{
+ if (code & (SPIMSG_OK | SPIMSG_FAILED))
+ complete((struct completion *)msg->context);
+}
+
+/*
+ * spi_transfer - transfer the message either in sync or async way
+ *
+ * @msg: message to process
+ * @callback: user-supplied callback
+ *
+ * If both msg->status and callback are set, the error code of -EINVAL
+ * will be returned
+ */
+int spi_transfer(struct spi_msg *msg, void (*callback) (struct spi_msg *, int))
+{
+ struct completion msg_done;
+ int err = -EINVAL;
+
+ if (callback && !msg->status) {
+ msg->status = callback;
+ callback = NULL;
+ }
+
+ if (!callback) {
+ if (!msg->status) {
+ init_completion(&msg_done);
+ msg->context = &msg_done;
+ msg->status = __spi_transfer_callback;
+ spi_queue(msg);
+ wait_for_completion(&msg_done);
+ err = 0;
+ } else {
+ err = spi_queue(msg);
+ }
+ }
+
+ return err;
+}
+
+/**
+ * spi_thread_awake - function that called to determine if thread needs to process any messages
+ *
+ * @bd: pointer to struct spi_bus_data
+ *
+ * Thread wakes up if there is signal to exit (bd->exiting is set) or there are any messages
+ * in bus' queue.
+ */
+static int spi_thread_awake(struct spi_bus_data *bd)
+{
+ int ret;
+
+ if (atomic_read(&bd->exiting)) {
+ return 1;
+ }
+ down(&bd->lock);
+ ret = !list_empty(&bd->msgs);
+ up(&bd->lock);
+ return ret;
+}
+
+static void spi_async_callback(void *_msg)
+{
+ struct spi_msg *msg = _msg;
+
+ msg->status (msg, SPIMSG_OK);
+}
+
+/**
+ * spi_bus_fifo_retrieve - simple function to retrieve the first message from the queue
+ *
+ * @this: spi_bus_driver that needs to retrieve next message from queue
+ * @data: pointer to spi_bus_data structure associated with spi_bus_driver
+ *
+ * This is pretty simple `retrieve' function. It retrieves the first message from the queue,
+ * and does not care about target of the message. For simple cases, this function is the best
+ * and the fastest solution to provide as retrieve method of bus driver
+ **/
+static struct spi_msg *spi_bus_fifo_retrieve (struct spi_bus_driver *this, struct spi_bus_data *data)
+{
+ return list_entry(data->msgs.next, struct spi_msg, link);
+}
+
+/**
+ * spi_bus_simple_retrieve -- retrieve message from the queue with taking into account previous target
+ *
+ * @this: spi_bus_driver that needs to retrieve next message from queue
+ * @data: pointer to spi_bus_data structure associated with spi_bus_driver
+ *
+ * this function is more complex than spi_bus_fifo_retrieve; it takes into account the already selected
+ * device on SPI bus, and tries to retrieve the message targeted to the same device.
+ *
+ **/
+static struct spi_msg *spi_bus_simple_retrieve( struct spi_bus_driver *this, struct spi_bus_data *data)
+{
+ int found = 0;
+ struct spi_msg *msg;
+
+ list_for_each_entry(msg, &data->msgs, link) {
+ if (!data->selected_device || msg->device == data->selected_device) {
+ found = 1;
+ break;
+ }
+ }
+ if (!found)
+ /*
+ * all messages for current selected_device
+ * are processed.
+ * let's switch to another device
+ */
+ msg = list_entry(data->msgs.next, struct spi_msg, link);
+
+ return msg;
+}
+
+/**
+ * spi_bus_next_msg - the wrapper for retrieve method for bus driver
+ *
+ * @this: spi_bus_driver that needs to retrieve next message from queue
+ * @data: pointer to spi_bus_data structure associated with spi_bus_driver
+ *
+ * If bus driver provides the `retrieve' method, it is called to retrieve the next message
+ * from queue. Otherwise, the spi_bus_fifo_retrieve is called
+ *
+ **/
+static struct spi_msg *spi_bus_next_msg( struct spi_bus_driver *this, struct spi_bus_data *data)
+{
+ if (!this)
+ return NULL;
+ if (this->retrieve)
+ return this->retrieve (this, data);
+ return spi_bus_fifo_retrieve( this, data );
+}
+
+/**
+ * spi_thread - the thread that calls bus functions to perform actual transfers
+ *
+ * @pd: pointer to struct spi_bus_data with bus-specific data
+ *
+ * This function is started as separate thread to perform actual
+ * transfers on SPI bus
+ **/
+static int spi_thread(void *context)
+{
+ struct spi_bus_data *bd = context;
+ struct spi_msg *msg;
+ int xfer_status;
+ struct workqueue_struct *wq;
+
+ wq = create_workqueue ( bd->id );
+ if (!wq)
+ pr_debug( "%s: cannot create workqueue, async callbacks will be unavailable\n", bd->id );
+
+ while (!kthread_should_stop()) {
+
+ wait_event_interruptible(bd->queue, spi_thread_awake(bd));
+
+ if (atomic_read(&bd->exiting))
+ goto thr_exit;
+
+ down(&bd->lock);
+ while (!list_empty(&bd->msgs)) {
+ /*
+ * this part is locked by bus_data->lock,
+ * to protect spi_msg extraction
+ */
+ msg = spi_bus_next_msg( bd->bus, bd );
+
+ /* verify if device needs re-selecting */
+ if (bd->selected_device != msg->device) {
+ if (bd->selected_device && bd->bus->deselect)
+ bd->bus->deselect (bd->selected_device);
+ bd->selected_device = msg->device;
+ if (bd->bus->select)
+ bd->bus->select (bd->selected_device);
+ }
+ list_del(&msg->link);
+ up(&bd->lock);
+
+ /*
+ * and this part is locked by device's lock;
+ * spi_queue will be able to queue new
+ * messages
+ *
+ * note that bd->selected_device is locked, not msg->device
+ * they are the same, but msg can be freed in msg->status function
+ */
+ spi_device_lock(&bd->selected_device);
+ if (bd->bus->set_clock && msg->clock)
+ bd->bus->set_clock(msg->device->dev.parent,
+ msg->clock);
+ xfer_status = bd->bus->xfer(msg);
+ if (msg->status) {
+ if (msg->flags & SPI_M_ASYNC_CB) {
+ INIT_WORK( &msg->wq_item, spi_async_callback, msg);
+ queue_work (wq, &msg->wq_item);
+ } else {
+ msg->status(msg,
+ xfer_status == 0 ? SPIMSG_OK :
+ SPIMSG_FAILED);
+ }
+ }
+
+ spi_device_unlock(&bd_selected->device);
+
+ /* lock the bus_data again... */
+ down(&bd->lock);
+ }
+ if (bd->bus->deselect)
+ bd->bus->deselect(bd->selected_device);
+ bd->selected_device = NULL;
+ /* device has been just deselected, unlocking the bus */
+ up(&bd->lock);
+ }
+
+thr_exit:
+ if (wq)
+ destroy_workqueue (wq);
+ return 0;
+}
+
+/**
+ * spi_write - send data to a device on an SPI bus
+ *
+ * @dev: the target device
+ * @buf: buffer to be sent
+ * @len: buffer's length
+ *
+ * Returns the number of bytes transferred, or negative error code.
+**/
+int spi_write(struct spi_device *dev, const char *buf, int len)
+{
+ struct spi_msg *msg = spimsg_alloc(dev, SPI_M_WR, len, NULL);
+ int ret;
+
+ memcpy(spimsg_buffer_wr(msg), buf, len);
+ ret = spi_transfer(msg, NULL);
+ return ret == 1 ? len : ret;
+}
+
+/**
+ * spi_read - receive data from a device on an SPI bus
+ *
+ * @dev: the target device
+ * @buf: buffer to be sent
+ * @len: buffer's length
+ *
+ * Returns the number of bytes transferred, or negative error code.
+**/
+int spi_read(struct spi_device *dev, char *buf, int len)
+{
+ int ret;
+ struct spi_msg *msg = spimsg_alloc(dev, SPI_M_RD, len, NULL);
+
+ ret = spi_transfer(msg, NULL);
+ memcpy(buf, spimsg_buffer_rd(msg), len);
+ return ret == 1 ? len : ret;
+}
+
+/**
+ * spi_bus_populate/spi_bus_populate2 - populate the bus
+ *
+ * @parent: the SPI bus device object
+ * @devices: string that represents bus population
+ * @devices_s: array of structures that represents bus population
+ * @callback: optional pointer to function that called on each device's add
+ *
+ * These two functions intended to populate the SPI bus corresponding to
+ * device passed as 1st parameter. The difference is in the way to describe
+ * new SPI slave devices: the spi_bus_populate takes the ASCII string delimited
+ * by '\0', where each section matches one SPI device name _and_ its parameters,
+ * and the spi_bus_populate2 takes the array of structures spi_device_desc.
+ *
+ * If some device cannot be added because of spi_device_add fail, the function will
+ * not try to parse the rest of list
+ */
+int spi_bus_populate(struct device *parent,
+ char *devices,
+ void (*callback) (struct device * bus,
+ struct spi_device * new_dev))
+{
+ struct spi_device *new_device;
+ int count = 0;
+
+ while (devices[0]) {
+ dev_dbg(parent, " discovered new SPI device, name '%s'\n",
+ devices);
+ if ((new_device = spi_device_add(parent, devices, NULL)) == NULL)
+ break;
+ if (callback)
+ callback(parent, new_device);
+ devices += (strlen(devices) + 1);
+ count++;
+ }
+ return count;
+}
+
+int spi_bus_populate2(struct device *parent,
+ struct spi_device_desc* devices_s,
+ void (*callback) (struct device* bus,
+ struct spi_device *new_dev,
+ void* params))
+{
+ struct spi_device *new_device;
+ int count = 0;
+
+ while (devices_s->name) {
+ dev_dbg(parent, " discovered new SPI device, name '%s'\n",
+ devices_s->name );
+ if ((new_device = spi_device_add(parent, devices_s->name, devices_s->params)) == NULL)
+ break;
+ if (callback)
+ callback(parent, new_device, devices_s->params);
+ devices_s++;
+ count++;
+ }
+ return count;
+}
+
+/**
+ * spi_bus_reset - reset the spi bus
+ *
+ * @bus: device object that represents the SPI bus
+ * @context: u32 value to be passed to reset method of bus
+ *
+ * This is simple wrapper for bus' `reset' method
+ *
+**/
+void spi_bus_reset (struct device* bus, u32 context)
+{
+ if (bus && bus->driver && TO_SPI_BUS_DRIVER(bus->driver)->reset)
+ TO_SPI_BUS_DRIVER(bus->driver)->reset( bus, context );
+}
+
+static int __init spi_core_init(void)
+{
+ int ret = spidev_init();
+
+ if (ret == 0)
+ ret = bus_register(&spi_bus);
+
+ return ret;
+}
+
+static void __exit spi_core_exit(void)
+{
+ bus_unregister(&spi_bus);
+ spidev_cleanup();
+}
+
+subsys_initcall(spi_core_init);
+module_exit(spi_core_exit);
+
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("dmitry pervushin <[email protected]>");
+
+EXPORT_SYMBOL_GPL(spi_bus_reset);
+EXPORT_SYMBOL_GPL(spi_queue);
+EXPORT_SYMBOL_GPL(spi_device_add);
+EXPORT_SYMBOL_GPL(spi_bus_driver_unregister);
+EXPORT_SYMBOL_GPL(spi_bus_populate);
+EXPORT_SYMBOL_GPL(spi_bus_populate2);
+EXPORT_SYMBOL_GPL(spi_transfer);
+EXPORT_SYMBOL_GPL(spi_write);
+EXPORT_SYMBOL_GPL(spi_read);
+EXPORT_SYMBOL_GPL(spi_bus);
+EXPORT_SYMBOL_GPL(spi_bus_driver_init);
+EXPORT_SYMBOL_GPL(spi_bus_fifo_retrieve);
+EXPORT_SYMBOL_GPL(spi_bus_simple_retrieve);
+
diff -uNr linux-2.6.orig/drivers/spi/spi-dev.c linux-2.6/drivers/spi/spi-dev.c
--- linux-2.6.orig/drivers/spi/spi-dev.c 1970-01-01 03:00:00.000000000 +0300
+++ linux-2.6/drivers/spi/spi-dev.c 2005-11-30 19:03:54.000000000 +0300
@@ -0,0 +1,176 @@
+/*
+ spi-dev.c - spi driver, char device interface
+
+ Copyright (C) 2005 MontaVista Software, Inc <[email protected]>
+
+ 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.
+*/
+
+#include <linux/init.h>
+#include <linux/config.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/device.h>
+#include <linux/fs.h>
+#include <linux/slab.h>
+#include <linux/version.h>
+#include <linux/smp_lock.h>
+
+#include <linux/init.h>
+#include <asm/uaccess.h>
+#include <linux/spi.h>
+
+#define SPI_TRANSFER_MAX 65535L
+
+struct spidev_driver_data {
+ int minor;
+};
+
+static struct class *spidev_class;
+
+static ssize_t spidev_read(struct file *file, char *buf, size_t count,
+ loff_t * offset);
+static ssize_t spidev_write(struct file *file, const char *buf, size_t count,
+ loff_t * offset);
+
+static int spidev_open(struct inode *inode, struct file *file);
+static int spidev_release(struct inode *inode, struct file *file);
+
+struct class_device *spi_class_device_create(int minor, struct device *device)
+{
+ return class_device_create(spidev_class, NULL, MKDEV(SPI_MAJOR, minor), device, "spi%d", minor);
+}
+
+void spi_class_device_destroy(int minor)
+{
+ class_device_destroy(spidev_class, MKDEV(SPI_MAJOR, minor));
+}
+
+static struct file_operations spidev_fops = {
+ .owner = THIS_MODULE,
+ .llseek = no_llseek,
+ .read = spidev_read,
+ .write = spidev_write,
+ .open = spidev_open,
+ .release = spidev_release,
+};
+
+static ssize_t spidev_read(struct file *file, char *buf, size_t count,
+ loff_t * offset)
+{
+ struct spi_device *dev = (struct spi_device *)file->private_data;
+ if (count > SPI_TRANSFER_MAX)
+ count = SPI_TRANSFER_MAX;
+ return spi_read(dev, buf, count);
+}
+
+static ssize_t spidev_write(struct file *file, const char *buf, size_t count,
+ loff_t * offset)
+{
+ struct spi_device *dev = (struct spi_device *)file->private_data;
+ if (count > SPI_TRANSFER_MAX)
+ count = SPI_TRANSFER_MAX;
+ return spi_write(dev, buf, count);
+}
+
+struct spidev_openclose {
+ unsigned int minor;
+ struct file *file;
+};
+
+static int spidev_do_open(struct device *the_dev, void *context)
+{
+ struct spidev_openclose *o = (struct spidev_openclose *)context;
+ struct spi_device *dev = TO_SPI_DEV(the_dev);
+ struct spidev_driver_data *drvdata;
+
+ drvdata = (struct spidev_driver_data *)dev_get_drvdata(the_dev);
+ if (!drvdata) {
+ pr_debug("%s: oops, drvdata is NULL !\n", __FUNCTION__);
+ goto do_open_fail;
+ }
+
+ pr_debug("drvdata->minor = %d vs %d\n", drvdata->minor, o->minor);
+ if (drvdata->minor == o->minor) {
+ get_device(&dev->dev);
+ o->file->private_data = dev;
+ return 1;
+ }
+
+do_open_fail:
+ return 0;
+}
+
+int spidev_open(struct inode *inode, struct file *file)
+{
+ struct spidev_openclose o;
+ int status;
+
+ o.minor = iminor(inode);
+ o.file = file;
+ status = bus_for_each_dev(&spi_bus, NULL, &o, spidev_do_open);
+ if (status == 0) {
+ status = -ENODEV;
+ }
+ return status < 0 ? status : 0;
+}
+
+static int spidev_release(struct inode *inode, struct file *file)
+{
+ struct spi_device *dev = file->private_data;
+
+ if (dev)
+ put_device(&dev->dev);
+ file->private_data = NULL;
+
+ return 0;
+}
+
+int __init spidev_init(void)
+{
+ int res;
+
+ if ((res = register_chrdev(SPI_MAJOR, "spi", &spidev_fops)) != 0) {
+ goto out;
+ }
+
+ spidev_class = class_create(THIS_MODULE, "spi");
+ if (IS_ERR(spidev_class)) {
+ printk(KERN_ERR "%s: error creating class\n", __FUNCTION__);
+ res = -EINVAL;
+ goto out_unreg;
+ }
+
+ return 0;
+
+out_unreg:
+ unregister_chrdev(SPI_MAJOR, "spi");
+out:
+ printk(KERN_ERR "%s: Driver initialization failed\n", __FILE__);
+ return res;
+}
+
+void __exit spidev_cleanup(void)
+{
+ class_destroy(spidev_class);
+ unregister_chrdev(SPI_MAJOR, "spi");
+}
+
+MODULE_AUTHOR("dmitry pervushin <[email protected]>");
+MODULE_DESCRIPTION("SPI /dev entries driver");
+MODULE_LICENSE("GPL");
+
+module_init(spidev_init);
+module_exit(spidev_cleanup);


2005-11-30 19:17:37

by Russell King

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

On Wed, Nov 30, 2005 at 07:50:53PM +0300, Vitaly Wool wrote:
> The main changes are:
>
> - Matching rmk's 2.6.14-git5+ changes for device_driver suspend and
> resume calls

Although it isn't obvious in this patch, I request that you don't use
use struct device_driver function methods directly in your drivers but
add suitable function methods in your spi_driver for probe/remove/
shutdown as required, and arrange for the SPI core to convert from
the generic device driver function methods to spi_driver function
methods.

I'm planning to eliminate all the device_driver function methods
entirely - the probe/remove/shutdown methods will eventually be
moved to bus_type.

--
Russell King
Linux kernel 2.6 ARM Linux - http://www.arm.linux.org.uk/
maintainer of: 2.6 Serial core

2005-11-30 20:29:32

by Mark Underwood

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh


--- Vitaly Wool <[email protected]> wrote:

> Greetings,
>
> This is an updated version of SPI framework developed by Dmitry Pervushin and Vitaly Wool.
>
> The main changes are:
>
> - Matching rmk's 2.6.14-git5+ changes for device_driver suspend and resume calls
> - The character device interface was reworked
>
> I still think that we need to continue converging with David Brownell's core, despite some
> misalignments happening in the email exchange :). Although it's not yet done in our core, I plan
> to move to
> - using chained SPI messages as David does
> - maybe rework the SPI device interface more taking David's one as a reference
>
> However, there also are some advantages of our core compared to David's I'd like to mention
>
> - it can be compiled as a module
So can David's. You can use BIOS tables in which case you must compile the SPI core into the
kernel but you can also use spi_new_device which allows the SPI core to be built as a module (and
is how I am using it).

> - it is DMA-safe
To my understanding David's core is DMA-safe. Yes there is a question mark over one of the helper
functions, but the _main_ functions _are_ DMA-safe.

> - it is priority inversion-free
> - it can gain more performance with multiple controllers
Sorry I'm not sure what you mean here.

> - it's more adapted for use in real-time environments
> - it's not so lightweight, but it leaves less effort for the bus driver developer.

But also less flexibility. A core layer shouldn't _force_ a policy
on a bus driver. I am currently developing an adapter driver for David's system and I wouldn't say
that the core is making me do things I think the core should do. Please could you provide examples
of where you think Davids SPI core requires 'effort'.

Mark






___________________________________________________________
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com

2005-11-30 20:45:18

by Greg KH

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

On Wed, Nov 30, 2005 at 07:50:53PM +0300, Vitaly Wool wrote:
> Greetings,
>
> This is an updated version of SPI framework developed by Dmitry Pervushin and Vitaly Wool.
>
> The main changes are:
>
> - Matching rmk's 2.6.14-git5+ changes for device_driver suspend and resume calls
> - The character device interface was reworked
>
> I still think that we need to continue converging with David
> Brownell's core, despite some misalignments happening in the email
> exchange :). Although it's not yet done in our core, I plan to move to
> - using chained SPI messages as David does
> - maybe rework the SPI device interface more taking David's one as a reference

I think you both need to work together to come to some kind of
understanding before either one can make it into mainline.

> However, there also are some advantages of our core compared to David's I'd like to mention
>
> - it can be compiled as a module
> - it is DMA-safe

What do you mean by this?

> - it is priority inversion-free

And David's isn't?

> - it can gain more performance with multiple controllers

What do you mean by this?

> - it's more adapted for use in real-time environments

Again, more explaination please.

> - it's not so lightweight, but it leaves less effort for the bus driver developer.

So bus drivers are smaller than David's? But with what tradeoffs?

> +#define kzalloc(size,type) kcalloc(1,size,type)

kzalloc is already a kernel function, please don't overload it.

> +#define TO_SPI_DEV(device) container_of( device, struct spi_device, dev )
> +struct spi_device {
> + char name[BUS_ID_SIZE];
> + void *private;

struct device already has a private pointer, please use that.

> + int minor;
> + struct class_device *cdev;

struct class_device has a dev_t, why not use that?

> +#define spi_device_lock( dev ) /* down( dev->dev.sem ) */
> +#define spi_device_unlock( dev ) /* up( dev->dev.sem ) */

Um, that doesn't look good...


> +
> +/*
> + * struct spi_msg
> + *
> + * This structure represent the SPI message internally. You should never use fields of this structure directly

Proper line lenght please.

And document these structures using kerneldoc, explaining what the
different fields are. Especially for new stuff like this.

> + * Please use corresponding functions to create/destroy/access fields

Those functions are?

> + *
> + */
> +struct spi_msg {
> + u32 flags;
> +#define SPI_M_RD 0x00000001
> +#define SPI_M_WR 0x00000002 /**< Write mode flag */
> +#define SPI_M_CSREL 0x00000004 /**< CS release level at end of the frame */
> +#define SPI_M_CS 0x00000008 /**< CS active level at begining of frame ( default low ) */
> +#define SPI_M_CPOL 0x00000010 /**< Clock polarity */
> +#define SPI_M_CPHA 0x00000020 /**< Clock Phase */
> +#define SPI_M_EXTBUF 0x80000000 /** externally allocated buffers */
> +#define SPI_M_ASYNC_CB 0x40000000 /** use workqueue to deliver callbacks */
> +#define SPI_M_DNA 0x20000000 /** do not allocate buffers */
> +
> + unsigned short len; /* msg length */

u16 perhaps?

> + unsigned long clock;

Do you really want unsigned long here?

> + struct spi_device *device;
> + void *context;
> + void *arg;
> + void *parent; /* in case of complex messages */

That's a lot of void pointers, not good.

> + struct list_head link;
> +
> + void (*status) (struct spi_msg * msg, int code);
> +
> + void *devbuf_rd, *devbuf_wr;

What are these for?

> + u8 *databuf_rd, *databuf_wr;
> +
> + struct work_struct wq_item;
> +};
> +
> +#ifdef CONFIG_SPI_CHARDEV
> +extern struct class_device *spi_class_device_create(int minor, struct device *device);
> +extern void spi_class_device_destroy(int minor);
> +#else
> +#define spi_class_device_create(a, b) NULL
> +#define spi_class_device_destroy(a) do { } while (0)

Make these inline to get typechecking if the option is disabled.

> +#endif
> +
> +static inline struct spi_msg *spimsg_alloc(struct spi_device *device,
> + unsigned flags,
> + unsigned short len,
> + void (*status) (struct spi_msg *,
> + int code))
> +{
> + struct spi_msg *msg;
> + struct spi_driver *drv = SPI_DEV_DRV(device);
> + int msgsize = sizeof (struct spi_msg);
> +
> + if (drv->alloc || (flags & (SPI_M_RD|SPI_M_WR)) == (SPI_M_RD | SPI_M_WR ) ) {
> + pr_debug ( "%s: external buffers\n", __FUNCTION__ );
> + flags |= SPI_M_EXTBUF;
> + } else {
> + pr_debug ("%s: no ext buffers, msgsize increased from %d by %d to %d\n", __FUNCTION__,
> + msgsize, len, msgsize + len );
> + msgsize += len;
> + }
> +
> + msg = kmalloc( msgsize, GFP_KERNEL);
> + if (!msg)
> + return NULL;
> + memset(msg, 0, sizeof(struct spi_msg));
> + msg->len = len;
> + msg->status = status;
> + msg->device = device;
> + msg->flags = flags;
> + INIT_LIST_HEAD(&msg->link);
> +
> + if (flags & SPI_M_DNA )
> + return msg;
> +
> + /* otherwise, we need to set up pointers */
> + if (!(flags & SPI_M_EXTBUF)) {
> + msg->databuf_rd = msg->databuf_wr =
> + (u8*)msg + sizeof ( struct spi_msg);
> + } else {
> + if (flags & SPI_M_RD) {
> + msg->devbuf_rd = drv->alloc ?
> + drv->alloc(len, GFP_KERNEL) : kmalloc(len, GFP_KERNEL);
> + msg->databuf_rd = drv->get_buffer ?
> + drv->get_buffer(device, msg->devbuf_rd) : msg->devbuf_rd;
> + }
> + if (flags & SPI_M_WR) {
> + msg->devbuf_wr = drv->alloc ?
> + drv->alloc(len, GFP_KERNEL) : kmalloc(len, GFP_KERNEL);
> + msg->databuf_wr = drv->get_buffer ?
> + drv->get_buffer(device, msg->devbuf_wr) : msg->devbuf_wr;
> + }
> + }
> + pr_debug("%s: msg = %p, RD=(%p,%p) WR=(%p,%p). Actual flags = %s+%s\n",
> + __FUNCTION__,
> + msg,
> + msg->devbuf_rd, msg->databuf_rd,
> + msg->devbuf_wr, msg->databuf_wr,
> + msg->flags & SPI_M_RD ? "RD" : "~rd",
> + msg->flags & SPI_M_WR ? "WR" : "~wr");
> + return msg;
> +}
> +
> +static inline void spimsg_free(struct spi_msg *msg)
> +{
> + void (*do_free) (const void *) = kfree;
> + struct spi_driver *drv = SPI_DEV_DRV(msg->device);
> +
> + if (msg) {
> +
> + if ( !(msg->flags & SPI_M_DNA) || (msg->flags & SPI_M_EXTBUF) ) {
> + if (drv->free)
> + do_free = drv->free;
> + if (drv->release_buffer) {
> + if (msg->databuf_rd)
> + drv->release_buffer(msg->device,
> + msg->databuf_rd);
> + if (msg->databuf_wr)
> + drv->release_buffer(msg->device,
> + msg->databuf_wr);
> + }
> + if (msg->devbuf_rd)
> + do_free(msg->devbuf_rd);
> + if (msg->devbuf_wr)
> + do_free(msg->devbuf_wr);
> + }
> + kfree(msg);
> + }
> +}

These are all pretty big functions to be inline in a .h file, don't you
think?

> +extern int spi_bus_populate(struct device *parent, char *device,
> + void (*assign) (struct device *parent,
> + struct spi_device *));
> +struct spi_device_desc {
> + char* name;
> + void* params;
> +};
> +extern int spi_bus_populate2(struct device *parent,
> + struct spi_device_desc *devices,
> + void (*assign) (struct device *parent,
> + struct spi_device *,
> + void *));

Where is spi_bus_populate3 and 4? :)

thanks.

greg k-h

2005-11-30 21:27:07

by David Brownell

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

Here's the attached "mailer doesn't mangle these" version.


Attachments:
(No filename) (59.00 B)
spi.patch (59.50 kB)
Download all attachments

2005-11-30 21:26:31

by David Brownell

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

And here's what you were comparing it to. I'll post this twice,
once inline (here) for inlined followups, and once as an attachment
(next) for anyone that wants to apply it ... since I recall "kmail"
liking to zealously mangle tabs and line ends.

Oh, and a bitbang/parport driver seems to be limping. :)

- 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 posted to LKML (on 11-Nov-2005) are minor,
and include:

- One bugfix (removes a FIXME), with the visible effect of making device
names be "spiB.C" where B is the bus number and C is the chipselect.

- The "caller provides DMA mappings" mechanism now has kerneldoc, for
DMA drivers that want to be fancy.

- Hey, the framework init can be subsys_init. Even though board init
logic fires earlier, at arch_init ... since the framework init is
for driver support, and the board init support uses static init.

- Various additional spec/doc clarifications based on discussions
with other folk. It adds a brief "thank you" at the end, for folk
who've helped nudge this framework into existence.

NOTE: The version now in the "mm" tree had to change the "hotplug"
callback to be named "uevent"; driver model changes. And of course,
for hotplugging to work, /sbin/hotplug should "modprobe $MODALIAS".


Index: g26/include/linux/spi/spi.h
===================================================================
--- /dev/null 1970-01-01 00:00:00.000000000 +0000
+++ g26/include/linux/spi/spi.h 2005-11-30 10:49:04.000000000 -0800
@@ -0,0 +1,542 @@
+/*
+ * 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) /* original MicroWire */
+#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;
+ const char *modalias;
+
+ // 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_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);
+};
+
+/* 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.
+ */
+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;
+
+ 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: 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;
+
+ 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;
+};
+
+/**
+ * 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.
+ *
+ * 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.
+ */
+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 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.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 */
Index: g26/drivers/spi/spi.c
===================================================================
--- /dev/null 1970-01-01 00:00:00.000000000 +0000
+++ g26/drivers/spi/spi.c 2005-11-29 11:08:24.000000000 -0800
@@ -0,0 +1,557 @@
+/*
+ * spi.c - SPI init/core code
+ *
+ * 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.
+ */
+
+#include <linux/autoconf.h>
+#include <linux/kernel.h>
+#include <linux/device.h>
+#include <linux/init.h>
+#include <linux/cache.h>
+#include <linux/spi/spi.h>
+
+
+/* SPI bustype and spi_master class are registered during early boot,
+ * usually before board init code provides the SPI device tables, and
+ * are available later when driver init code needs them.
+ *
+ * Drivers for SPI devices started out like those for platform bus
+ * devices. But both have changed in 2.6.15; maybe this should get
+ * an "spi_driver" structure at some point (not currently needed)
+ */
+static void spidev_release(struct device *dev)
+{
+ const struct spi_device *spi = to_spi_device(dev);
+
+ /* spi masters may cleanup for released devices */
+ if (spi->master->cleanup)
+ spi->master->cleanup(spi);
+
+ class_device_put(&spi->master->cdev);
+ kfree(dev);
+}
+
+static ssize_t
+modalias_show(struct device *dev, struct device_attribute *a, char *buf)
+{
+ const struct spi_device *spi = to_spi_device(dev);
+
+ return snprintf(buf, BUS_ID_SIZE + 1, "%s\n", spi->modalias);
+}
+
+static struct device_attribute spi_dev_attrs[] = {
+ __ATTR_RO(modalias),
+ __ATTR_NULL,
+};
+
+/* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
+ * and the sysfs version makes coldplug work too.
+ */
+
+static int spi_match_device(struct device *dev, struct device_driver *drv)
+{
+ const struct spi_device *spi = to_spi_device(dev);
+
+ return strncmp(spi->modalias, drv->name, BUS_ID_SIZE) == 0;
+}
+
+static int spi_hotplug(struct device *dev, char **envp, int num_envp,
+ char *buffer, int buffer_size)
+{
+ const struct spi_device *spi = to_spi_device(dev);
+
+ envp[0] = buffer;
+ snprintf(buffer, buffer_size, "MODALIAS=%s", spi->modalias);
+ envp[1] = NULL;
+ return 0;
+}
+
+#ifdef CONFIG_PM
+
+/* Suspend/resume in "struct device_driver" don't really need that
+ * strange third parameter, so we just make it a constant and expect
+ * SPI drivers to ignore it just like most platform drivers do.
+ *
+ * NOTE: the suspend() method for an spi_master controller driver
+ * should verify that all its child devices are marked as suspended;
+ * suspend requests delivered through sysfs power/state files don't
+ * enforce such constraints.
+ */
+static int spi_suspend(struct device *dev, pm_message_t message)
+{
+ int value;
+
+ if (!dev->driver || !dev->driver->suspend)
+ return 0;
+
+ /* suspend will stop irqs and dma; no more i/o */
+ value = dev->driver->suspend(dev, message);
+ if (value == 0)
+ dev->power.power_state = message;
+ return value;
+}
+
+static int spi_resume(struct device *dev)
+{
+ int value;
+
+ if (!dev->driver || !dev->driver->resume)
+ return 0;
+
+ /* resume may restart the i/o queue */
+ value = dev->driver->resume(dev);
+ if (value == 0)
+ dev->power.power_state = PMSG_ON;
+ return value;
+}
+
+#else
+#define spi_suspend NULL
+#define spi_resume NULL
+#endif
+
+struct bus_type spi_bus_type = {
+ .name = "spi",
+ .dev_attrs = spi_dev_attrs,
+ .match = spi_match_device,
+ .hotplug = spi_hotplug,
+ .suspend = spi_suspend,
+ .resume = spi_resume,
+};
+EXPORT_SYMBOL_GPL(spi_bus_type);
+
+/*-------------------------------------------------------------------------*/
+
+/* SPI devices should normally not be created by SPI device drivers; that
+ * would make them board-specific. Similarly with SPI master drivers.
+ * Device registration normally goes into like arch/.../mach.../board-YYY.c
+ * with other readonly (flashable) information about mainboard devices.
+ */
+
+struct boardinfo {
+ struct list_head list;
+ unsigned n_board_info;
+ struct spi_board_info board_info[0];
+};
+
+static LIST_HEAD(board_list);
+static DECLARE_MUTEX(board_lock);
+
+
+/* On typical mainboards, this is purely internal; and it's not needed
+ * after board init creates the hard-wired devices. Some development
+ * platforms may not be able to use spi_register_board_info though, and
+ * this is exported so that for example a USB or parport based adapter
+ * driver could add devices (which it would learn about out-of-band).
+ */
+struct spi_device *__init_or_module
+spi_new_device(struct spi_master *master, struct spi_board_info *chip)
+{
+ struct spi_device *proxy;
+ struct device *dev = master->cdev.dev;
+ int status;
+
+ /* NOTE: caller did any chip->bus_num checks necessary */
+
+ if (!class_device_get(&master->cdev))
+ return NULL;
+
+ proxy = kzalloc(sizeof *proxy, GFP_KERNEL);
+ if (!proxy) {
+ dev_err(dev, "can't alloc dev for cs%d\n",
+ chip->chip_select);
+ goto fail;
+ }
+ proxy->master = master;
+ proxy->chip_select = chip->chip_select;
+ proxy->max_speed_hz = chip->max_speed_hz;
+ proxy->irq = chip->irq;
+ proxy->modalias = chip->modalias;
+
+ snprintf(proxy->dev.bus_id, sizeof proxy->dev.bus_id,
+ "%s.%u", master->cdev.class_id,
+ chip->chip_select);
+ proxy->dev.parent = dev;
+ proxy->dev.bus = &spi_bus_type;
+ proxy->dev.platform_data = (void *) chip->platform_data;
+ proxy->controller_data = chip->controller_data;
+ proxy->controller_state = NULL;
+ proxy->dev.release = spidev_release;
+
+ /* drivers may modify this default i/o setup */
+ status = master->setup(proxy);
+ if (status < 0) {
+ dev_dbg(dev, "can't %s %s, status %d\n",
+ "setup", proxy->dev.bus_id, status);
+ goto fail;
+ }
+
+ /* driver core catches callers that misbehave by defining
+ * devices that already exist.
+ */
+ status = device_register(&proxy->dev);
+ 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;
+ }
+ dev_dbg(dev, "registered child %s\n", proxy->dev.bus_id);
+ return proxy;
+}
+EXPORT_SYMBOL_GPL(spi_new_device);
+
+/*
+ * Board-specific early init code calls this (probably during arch_initcall)
+ * with segments of the SPI device table. Any device nodes are created later,
+ * after the relevant parent SPI controller (bus_num) is defined. We keep
+ * this table of devices forever, so that reloading a controller driver will
+ * not make Linux forget about these hard-wired devices.
+ *
+ * Other code can also call this, e.g. a particular add-on board might provide
+ * SPI devices through its expansion connector, so code initializing that board
+ * would naturally declare its SPI devices.
+ *
+ * The board info passed can safely be __initdata ... but be careful of
+ * any embedded pointers (platform_data, etc), they're copied as-is.
+ */
+int __init
+spi_register_board_info(struct spi_board_info const *info, unsigned n)
+{
+ struct boardinfo *bi;
+
+ bi = kmalloc (sizeof (*bi) + n * sizeof (*info), GFP_KERNEL);
+ if (!bi)
+ return -ENOMEM;
+ bi->n_board_info = n;
+ memcpy(bi->board_info, info, n * sizeof (*info));
+
+ down(&board_lock);
+ list_add_tail(&bi->list, &board_list);
+ up(&board_lock);
+ return 0;
+}
+EXPORT_SYMBOL_GPL(spi_register_board_info);
+
+/* FIXME someone should add support for a __setup("spi", ...) that
+ * creates board info from kernel command lines
+ */
+
+static void __init_or_module
+scan_boardinfo(struct spi_master *master)
+{
+ struct boardinfo *bi;
+ struct device *dev = master->cdev.dev;
+
+ down(&board_lock);
+ list_for_each_entry(bi, &board_list, list) {
+ struct spi_board_info *chip = bi->board_info;
+ unsigned n;
+
+ for (n = bi->n_board_info; n > 0; n--, chip++) {
+ if (chip->bus_num != master->bus_num)
+ continue;
+ /* some controllers only have one chip, so they
+ * might not use chipselects. otherwise, the
+ * chipselects are numbered 0..max.
+ */
+ if (chip->chip_select >= master->num_chipselect
+ && master->num_chipselect) {
+ dev_dbg(dev, "cs%d > max %d\n",
+ chip->chip_select,
+ master->num_chipselect);
+ continue;
+ }
+ (void) spi_new_device(master, chip);
+ }
+ }
+ up(&board_lock);
+}
+
+/*-------------------------------------------------------------------------*/
+
+static void spi_master_release(struct class_device *cdev)
+{
+ struct spi_master *master;
+
+ master = container_of(cdev, struct spi_master, cdev);
+ put_device(master->cdev.dev);
+ master->cdev.dev = NULL;
+ kfree(master);
+}
+
+static struct class spi_master_class = {
+ .name = "spi_master",
+ .owner = THIS_MODULE,
+ .release = spi_master_release,
+};
+
+
+/**
+ * spi_alloc_master - allocate SPI master controller
+ * @dev: the controller, possibly using the platform_bus
+ * @size: how much driver-private data to preallocate; a pointer to this
+ * memory in the class_data field of the returned class_device
+ *
+ * This call is used only by SPI master controller drivers, which are the
+ * only ones directly touching chip registers. It's how they allocate
+ * an spi_master structure, prior to calling spi_add_master().
+ *
+ * This must be called from context that can sleep. It returns the SPI
+ * master structure on success, else NULL.
+ *
+ * The caller is responsible for assigning the bus number and initializing
+ * the master's methods before calling spi_add_master(), or else (on error)
+ * calling class_device_put() to prevent a memory leak.
+ */
+struct spi_master * __init_or_module
+spi_alloc_master(struct device *dev, unsigned size)
+{
+ struct spi_master *master;
+
+ master = kzalloc(size + sizeof *master, SLAB_KERNEL);
+ if (!master)
+ return NULL;
+
+ master->cdev.class = &spi_master_class;
+ master->cdev.dev = get_device(dev);
+ class_set_devdata(&master->cdev, &master[1]);
+
+ return master;
+}
+EXPORT_SYMBOL_GPL(spi_alloc_master);
+
+/**
+ * spi_register_master - register SPI master controller
+ * @master: initialized master, originally from spi_alloc_master()
+ *
+ * SPI master controllers connect to their drivers using some non-SPI bus,
+ * such as the platform bus. The final stage of probe() in that code
+ * includes calling spi_register_master() to hook up to this SPI bus glue.
+ *
+ * SPI controllers use board specific (often SOC specific) bus numbers,
+ * and board-specific addressing for SPI devices combines those numbers
+ * with chip select numbers. Since SPI does not directly support dynamic
+ * device identification, boards need configuration tables telling which
+ * chip is at which address.
+ *
+ * This must be called from context that can sleep. It returns zero on
+ * success, else a negative error code (dropping the master's refcount).
+ */
+int __init_or_module
+spi_register_master(struct spi_master *master)
+{
+ static atomic_t dyn_bus_id = ATOMIC_INIT(0);
+ struct device *dev = master->cdev.dev;
+ int status = -ENODEV;
+ int dynamic = 0;
+
+ /* convention: dynamically assigned bus IDs count down from the max */
+ if (master->bus_num == 0) {
+ master->bus_num = atomic_dec_return(&dyn_bus_id);
+ dynamic = 1;
+ }
+
+ /* register the device, then userspace will see it.
+ * registration fails if the bus ID is in use.
+ */
+ snprintf(master->cdev.class_id, sizeof master->cdev.class_id,
+ "spi%u", master->bus_num);
+ status = class_device_register(&master->cdev);
+ if (status < 0) {
+ class_device_put(&master->cdev);
+ goto done;
+ }
+ dev_dbg(dev, "registered master %s%s\n", master->cdev.class_id,
+ dynamic ? " (dynamic)" : "");
+
+ /* populate children from any spi device tables */
+ scan_boardinfo(master);
+ status = 0;
+done:
+ return status;
+}
+EXPORT_SYMBOL_GPL(spi_register_master);
+
+
+static int __unregister(struct device *dev, void *unused)
+{
+ /* note: before about 2.6.14-rc1 this would corrupt memory: */
+ device_unregister(dev);
+ return 0;
+}
+
+/**
+ * spi_unregister_master - unregister SPI master controller
+ * @master: the master being unregistered
+ *
+ * This call is used only by SPI master controller drivers, which are the
+ * only ones directly touching chip registers.
+ *
+ * This must be called from context that can sleep.
+ */
+void spi_unregister_master(struct spi_master *master)
+{
+ class_device_unregister(&master->cdev);
+ (void) device_for_each_child(master->cdev.dev, NULL, __unregister);
+}
+EXPORT_SYMBOL_GPL(spi_unregister_master);
+
+/**
+ * spi_busnum_to_master - look up master associated with bus_num
+ * @bus_num: the master's bus number
+ *
+ * This call may be used with devices that are registered after
+ * arch init time. It returns a refcounted pointer to the relevant
+ * spi_master (which the caller must release), or NULL if there is
+ * no such master registered.
+ */
+struct spi_master *spi_busnum_to_master(u16 bus_num)
+{
+ if (bus_num) {
+ char name[8];
+ struct kobject *bus;
+
+ snprintf(name, sizeof name, "spi%u", bus_num);
+ bus = kset_find_obj(&spi_master_class.subsys.kset, name);
+ if (bus)
+ return container_of(bus, struct spi_master, cdev.kobj);
+ }
+ return NULL;
+}
+EXPORT_SYMBOL_GPL(spi_busnum_to_master);
+
+
+/*-------------------------------------------------------------------------*/
+
+/**
+ * spi_sync - blocking/synchronous SPI data transfers
+ * @spi: device with which data will be exchanged
+ * @message: describes the data transfers
+ *
+ * This call may only be used from a context that may sleep. The sleep
+ * is non-interruptible, and has no timeout. Low-overhead controller
+ * drivers may DMA directly into and out of the message buffers.
+ *
+ * Note that the SPI device's chip select is active during the message,
+ * and then is normally disabled between messages. Drivers for some
+ * frequently-used devices may want to minimize costs of selecting a chip,
+ * by leaving it selected in anticipation that the next message will go
+ * to the same chip. (That may increase power usage.)
+ *
+ * The return value is a negative error code if the message could not be
+ * submitted, else zero. When the value is zero, then message->status is
+ * also defined: it's the completion code for the transfer, either zero
+ * or a negative error code from the controller driver.
+ */
+int spi_sync(struct spi_device *spi, struct spi_message *message)
+{
+ DECLARE_COMPLETION(done);
+ int status;
+
+ message->complete = (void (*)(void *)) complete;
+ message->context = &done;
+ status = spi_async(spi, message);
+ if (status == 0)
+ wait_for_completion(&done);
+ message->context = NULL;
+ return status;
+}
+EXPORT_SYMBOL_GPL(spi_sync);
+
+#define SPI_BUFSIZ (SMP_CACHE_BYTES)
+
+static u8 *buf;
+
+/**
+ * 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.
+ * This call may only be used from a context that may sleep.
+ *
+ * Parameters to this routine are always copied using a small buffer,
+ * large transfers should use use spi_{async,sync}() calls with
+ * dma-safe buffers.
+ */
+int spi_write_then_read(struct spi_device *spi,
+ const u8 *txbuf, unsigned n_tx,
+ u8 *rxbuf, unsigned n_rx)
+{
+ static DECLARE_MUTEX(lock);
+
+ int status;
+ struct spi_message message;
+ struct spi_transfer x[2];
+
+ /* Use preallocated DMA-safe buffer. We can't avoid copying here,
+ * (as a pure convenience thing), but we can keep heap costs
+ * out of the hot path.
+ */
+ if ((n_tx + n_rx) > SPI_BUFSIZ)
+ return -EINVAL;
+
+ down(&lock);
+ memset(x, 0, sizeof x);
+
+ memcpy(buf, txbuf, n_tx);
+ x[0].tx_buf = buf;
+ x[0].len = n_tx;
+
+ x[1].rx_buf = buf + n_tx;
+ x[1].len = n_rx;
+
+ /* do the i/o */
+ message.transfers = x;
+ message.n_transfer = ARRAY_SIZE(x);
+ status = spi_sync(spi, &message);
+ if (status == 0) {
+ memcpy(rxbuf, x[1].rx_buf, n_rx);
+ status = message.status;
+ }
+
+ up(&lock);
+ return status;
+}
+EXPORT_SYMBOL_GPL(spi_write_then_read);
+
+/*-------------------------------------------------------------------------*/
+
+static int __init spi_init(void)
+{
+ buf = kmalloc(SPI_BUFSIZ, SLAB_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
+ bus_register(&spi_bus_type);
+ class_register(&spi_master_class);
+ return 0;
+}
+/* board_info is normally registered in arch_initcall(),
+ * but even essential drivers wait till later
+ */
+subsys_initcall(spi_init);
+
Index: g26/drivers/spi/Kconfig
===================================================================
--- /dev/null 1970-01-01 00:00:00.000000000 +0000
+++ g26/drivers/spi/Kconfig 2005-11-30 12:10:12.000000000 -0800
@@ -0,0 +1,91 @@
+#
+# SPI driver configuration
+#
+# NOTE: the reason this doesn't show SPI slave support is mostly that
+# nobody's needed a slave side API yet. The master-role API is not
+# fully appropriate there, so it'd need some thought to do well.
+#
+menu "SPI support"
+
+# someday this stuff should be set using arch/CPU/PLATFORM/Kconfig
+config SPI_ARCH_HAS_MASTER
+ boolean
+ default y if ARCH_AT91
+ default y if ARCH_OMAP
+ default y if ARCH_PXA
+ default y if X86 # devel hack only!! (ICH7 can...)
+
+config SPI_ARCH_HAS_SLAVE
+ boolean
+ default y if ARCH_AT91
+ default y if ARCH_OMAP
+ default y if ARCH_PXA
+
+config SPI
+ bool "SPI support"
+ depends on SPI_ARCH_HAS_MASTER || SPI_ARCH_HAS_SLAVE
+ help
+ The "Serial Peripheral Interface" is a low level synchronous
+ protocol. Chips that support SPI can have data transfer rates
+ 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.
+ MMC and SD cards can be accessed using SPI protocol; and for
+ DataFlash cards used in MMC sockets, SPI must always be used.
+
+ SPI is one of a family of similar protocols using a four wire
+ interface (select, clock, data in, data out) including Microwire
+ (half duplex), SSP, SSI, and PSP. This driver framework should
+ work with most such devices and controllers.
+
+config SPI_DEBUG
+ boolean "Debug support for SPI drivers"
+ depends on SPI && DEBUG_KERNEL
+ help
+ Say "yes" to enable debug messaging (like dev_dbg and pr_debug),
+ sysfs, and debugfs support in SPI controller and protocol drivers.
+
+#
+# MASTER side ... talking to discrete SPI slave chips including microcontrollers
+#
+
+config SPI_MASTER
+# boolean "SPI Master Support"
+ boolean
+ default SPI && SPI_ARCH_HAS_MASTER
+ help
+ If your system has an master-capable SPI controller (which
+ provides the clock and chipselect), you can enable that
+ controller and the protocol drivers for the SPI slave chips
+ that are connected.
+
+comment "SPI Master Controller Drivers"
+ depends on SPI_MASTER
+
+
+#
+# Add new SPI master controllers in alphabetical order above this line
+#
+
+
+#
+# There are lots of SPI device types, with sensors and memory
+# being probably the most widely used ones.
+#
+comment "SPI Protocol Masters"
+ depends on SPI_MASTER
+
+
+#
+# Add new SPI protocol masters in alphabetical order above this line
+#
+
+
+# (slave support would go here)
+
+endmenu # "SPI support"
+
Index: g26/arch/arm/Kconfig
===================================================================
--- g26.orig/arch/arm/Kconfig 2005-11-27 22:06:56.000000000 -0800
+++ g26/arch/arm/Kconfig 2005-11-28 16:38:41.000000000 -0800
@@ -730,6 +730,8 @@ source "drivers/char/Kconfig"

source "drivers/i2c/Kconfig"

+source "drivers/spi/Kconfig"
+
source "drivers/hwmon/Kconfig"

#source "drivers/l3/Kconfig"
Index: g26/drivers/Kconfig
===================================================================
--- g26.orig/drivers/Kconfig 2005-11-27 22:06:56.000000000 -0800
+++ g26/drivers/Kconfig 2005-11-28 16:38:41.000000000 -0800
@@ -44,6 +44,8 @@ source "drivers/char/Kconfig"

source "drivers/i2c/Kconfig"

+source "drivers/spi/Kconfig"
+
source "drivers/w1/Kconfig"

source "drivers/hwmon/Kconfig"
Index: g26/drivers/Makefile
===================================================================
--- g26.orig/drivers/Makefile 2005-11-27 22:06:56.000000000 -0800
+++ g26/drivers/Makefile 2005-11-28 16:38:41.000000000 -0800
@@ -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/
Index: g26/drivers/spi/Makefile
===================================================================
--- /dev/null 1970-01-01 00:00:00.000000000 +0000
+++ g26/drivers/spi/Makefile 2005-11-30 12:10:12.000000000 -0800
@@ -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 ...
Index: g26/Documentation/spi/spi-summary
===================================================================
--- /dev/null 1970-01-01 00:00:00.000000000 +0000
+++ g26/Documentation/spi/spi-summary 2005-11-28 16:38:41.000000000 -0800
@@ -0,0 +1,416 @@
+Overview of Linux kernel SPI support
+====================================
+
+22-Nov-2005
+
+What is SPI?
+------------
+The "Serial Peripheral Interface" (SPI) is a four-wire point-to-point
+serial link used to connect microcontrollers to sensors and memory.
+
+The three signal wires hold a clock (SCLK, often on the order of 10 MHz),
+and parallel data lines with "Master Out, Slave In" (MOSI) or "Master In,
+Slave Out" (MISO) signals. (Other names are also used.) There are four
+clocking modes through which data is exchanged; mode-0 and mode-3 are most
+commonly used.
+
+SPI masters may use a "chip select" line to activate a given SPI slave
+device, so those three signal wires may be connected to several chips
+in parallel. All SPI slaves support chipselects. Some devices have
+other signals, often including an interrupt to the master.
+
+Unlike serial busses like USB or SMBUS, even low level protocols for
+SPI slave functions are usually not interoperable between vendors
+(except for cases like SPI memory chips).
+
+ - SPI may be used for request/response style device protocols, as with
+ touchscreen sensors and memory chips.
+
+ - It may also be used to stream data in either direction (half duplex),
+ or both of them at the same time (full duplex).
+
+ - Some devices may use eight bit words. Others may different word
+ lengths, such as streams of 12-bit or 20-bit digital samples.
+
+In the same way, SPI slaves will only rarely support any kind of automatic
+discovery/enumeration protocol. The tree of slave devices accessible from
+a given SPI master will normally be set up manually, with configuration
+tables.
+
+SPI is only one of the names used by such four-wire protocols, and
+most controllers have no problem handling "MicroWire" (think of it as
+half-duplex SPI, for request/response protocols), SSP ("Synchronous
+Serial Protocol"), PSP ("Programmable Serial Protocol"), and other
+related protocols.
+
+Microcontrollers often support both master and slave sides of the SPI
+protocol. This document (and Linux) currently only supports the master
+side of SPI interactions.
+
+
+Who uses it? On what kinds of systems?
+---------------------------------------
+Linux developers using SPI are probably writing device drivers for embedded
+systems boards. SPI is used to control external chips, and it is also a
+protocol supported by every MMC or SD memory card. (The older "DataFlash"
+cards, predating MMC cards but using the same connectors and card shape,
+support only SPI.) Some PC hardware uses SPI flash for BIOS code.
+
+SPI slave chips range from digital/analog converters used for analog
+sensors and codecs, to memory, to peripherals like USB controllers
+or Ethernet adapters; and more.
+
+Most systems using SPI will integrate a few devices on a mainboard.
+Some provide SPI links on expansion connectors; in cases where no
+dedicated SPI controller exists, GPIO pins can be used to create a
+low speed "bitbanging" adapter. Very few systems will "hotplug" an SPI
+controller; the reasons to use SPI focus on low cost and simple operation,
+and if dynamic reconfiguration is important, USB will often be a more
+appropriate low-pincount peripheral bus.
+
+Many microcontrollers that can run Linux integrate one or more I/O
+interfaces with SPI modes. Given SPI support, they could use MMC or SD
+cards without needing a special purpose MMC/SD/SDIO controller.
+
+
+How do these driver programming interfaces work?
+------------------------------------------------
+The <linux/spi/spi.h> header file includes kerneldoc, as does the
+main source code, and you should certainly read that. This is just
+an overview, so you get the big picture before the details.
+
+There are two types of SPI driver, here called:
+
+ Controller drivers ... these are often built in to System-On-Chip
+ processors, and often support both Master and Slave roles.
+ These drivers touch hardware registers and may use DMA.
+
+ Protocol drivers ... these pass messages through the controller
+ driver to communicate with a Slave or Master device on the
+ other side of an SPI link.
+
+So for example one protocol driver might talk to the MTD layer to export
+data to filesystems stored on SPI flash like DataFlash; and others might
+control audio interfaces, present touchscreen sensors as input interfaces,
+or monitor temperature and voltage levels during industrial processing.
+And those might all be sharing the same controller driver.
+
+A "struct spi_device" encapsulates the master-side interface between
+those two types of driver. At this writing, Linux has no slave side
+programming interface.
+
+There is a minimal core of SPI programming interfaces, focussing on
+using driver model to connect controller and protocol drivers using
+device tables provided by board specific initialization code. SPI
+shows up in sysfs in several locations:
+
+ /sys/devices/.../CTLR/spiB.C ... spi_device for on bus "B",
+ chipselect C, accessed through CTLR.
+
+ /sys/bus/spi/devices/spiB.C ... symlink to the physical
+ spiB-C device
+
+ /sys/bus/spi/drivers/D ... driver for one or more spi*.* devices
+
+ /sys/class/spi_master/spiB ... class device for the controller
+ managing bus "B". All the spiB.* devices share the same
+ physical SPI bus segment, with SCLK, MOSI, and MISO.
+
+The basic I/O primitive submits an asynchronous message to an I/O queue
+maintained by the controller driver. A completion callback is issued
+asynchronously when the data transfer(s) in that message completes.
+There are also some simple synchronous wrappers for those calls.
+
+
+How does board-specific init code declare SPI devices?
+------------------------------------------------------
+Linux needs several kinds of information to properly configure SPI devices.
+That information is normally provided by board-specific code, even for
+chips that do support some of automated discovery/enumeration.
+
+DECLARE CONTROLLERS
+
+The first kind of information is a list of what SPI controllers exist.
+For System-on-Chip (SOC) based boards, these will usually be platform
+devices, and the controller may need some platform_data in order to
+operate properly. The "struct platform_device" will include resources
+like the physical address of the controller's first register and its IRQ.
+
+Platforms will often abstract the "register SPI controller" operation,
+maybe coupling it with code to initialize pin configurations, so that
+the arch/.../mach-*/board-*.c files for several boards can all share the
+same basic controller setup code. This is because most SOCs have several
+SPI-capable controllers, and only the ones actually usable on a given
+board should normally be set up and registered.
+
+So for example arch/.../mach-*/board-*.c files might have code like:
+
+ #include <asm/arch/spi.h> /* for mysoc_spi_data */
+
+ /* if your mach-* infrastructure doesn't support kernels that can
+ * run on multiple boards, pdata wouldn't benefit from "__init".
+ */
+ static struct mysoc_spi_data __init pdata = { ... };
+
+ static __init board_init(void)
+ {
+ ...
+ /* this board only uses SPI controller #2 */
+ mysoc_register_spi(2, &pdata);
+ ...
+ }
+
+And SOC-specific utility code might look something like:
+
+ #include <asm/arch/spi.h>
+
+ static struct platform_device spi2 = { ... };
+
+ void mysoc_register_spi(unsigned n, struct mysoc_spi_data *pdata)
+ {
+ struct mysoc_spi_data *pdata2;
+
+ pdata2 = kmalloc(sizeof *pdata2, GFP_KERNEL);
+ *pdata2 = pdata;
+ ...
+ if (n == 2) {
+ spi2->dev.platform_data = pdata2;
+ register_platform_device(&spi2);
+
+ /* also: set up pin modes so the spi2 signals are
+ * visible on the relevant pins ... bootloaders on
+ * production boards may already have done this, but
+ * developer boards will often need Linux to do it.
+ */
+ }
+ ...
+ }
+
+Notice how the platform_data for boards may be different, even if the
+same SOC controller is used. For example, on one board SPI might use
+an external clock, where another derives the SPI clock from current
+settings of some master clock.
+
+
+DECLARE SLAVE DEVICES
+
+The second kind of information is a list of what SPI slave devices exist
+on the target board, often with some board-specific data needed for the
+driver to work correctly.
+
+Normally your arch/.../mach-*/board-*.c files would provide a small table
+listing the SPI devices on each board. (This would typically be only a
+small handful.) That might look like:
+
+ static struct ads7846_platform_data ads_info = {
+ .vref_delay_usecs = 100,
+ .x_plate_ohms = 580,
+ .y_plate_ohms = 410,
+ };
+
+ static struct spi_board_info spi_board_info[] __initdata = {
+ {
+ .modalias = "ads7846",
+ .platform_data = &ads_info,
+ .mode = SPI_MODE_0,
+ .irq = GPIO_IRQ(31),
+ .max_speed_hz = 120000 /* max sample rate at 3V */ * 16,
+ .bus_num = 1,
+ .chip_select = 0,
+ },
+ };
+
+Again, notice how board-specific information is provided; each chip may need
+several types. This example shows generic constraints like the fastest SPI
+clock to allow (a function of board voltage in this case) or how an IRQ pin
+is wired, plus chip-specific constraints like an important delay that's
+changed by the capacitance at one pin.
+
+(There's also "controller_data", information that may be useful to the
+controller driver. An example would be peripheral-specific DMA tuning
+data or chipselect callbacks. This is stored in spi_device later.)
+
+The board_info should provide enough information to let the system work
+without the chip's driver being loaded. The most troublesome aspect of
+that is likely the SPI_CS_HIGH bit in the spi_device.mode field, since
+sharing a bus with a device that interprets chipselect "backwards" is
+not possible.
+
+Then your board initialization code would register that table with the SPI
+infrastructure, so that it's available later when the SPI master controller
+driver is registered:
+
+ spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info));
+
+Like with other static board-specific setup, you won't unregister those.
+
+
+NON-STATIC CONFIGURATIONS
+
+Developer boards often play by different rules than product boards, and one
+example is the potential need to hotplug SPI devices and/or controllers.
+
+For those cases you might need to use use spi_busnum_to_master() to look
+up the spi bus master, and will likely need spi_new_device() to provide the
+board info based on the board that was hotplugged. Of course, you'd later
+call at least spi_unregister_device() when that board is removed.
+
+
+How do I write an "SPI Protocol Driver"?
+----------------------------------------
+All SPI drivers are currently kernel drivers. A userspace driver API
+would just be another kernel driver, probably offering some lowlevel
+access through aio_read(), aio_write(), and ioctl() calls and using the
+standard userspace sysfs mechanisms to bind to a given SPI device.
+
+SPI protocol drivers are normal device drivers, with no more wrapper
+than needed by platform devices:
+
+ static struct device_driver CHIP_driver = {
+ .name = "CHIP",
+ .bus = &spi_bus_type,
+ .probe = CHIP_probe,
+ .remove = __exit_p(CHIP_remove),
+ .suspend = CHIP_suspend,
+ .resume = CHIP_resume,
+ };
+
+The SPI core will autmatically attempt to bind this driver to any SPI
+device whose board_info gave a modalias of "CHIP". Your probe() code
+might look like this unless you're creating a class_device:
+
+ static int __init CHIP_probe(struct device *dev)
+ {
+ struct spi_device *spi = to_spi_device(dev);
+ struct CHIP *chip;
+ struct CHIP_platform_data *pdata = dev->platform_data;
+
+ /* get memory for driver's per-chip state */
+ chip = kzalloc(sizeof *chip, GFP_KERNEL);
+ if (!chip)
+ return -ENOMEM;
+ dev_set_drvdata(dev, chip);
+
+ ... etc
+ return 0;
+ }
+
+As soon as it enters probe(), the driver may issue I/O requests to
+the SPI device using "struct spi_message". When remove() returns,
+the driver guarantees that it won't submit any more such messages.
+
+ - An spi_message is a sequence of of protocol operations, executed
+ as one atomic sequence. SPI driver controls include:
+
+ + when bidirectional reads and writes start ... by how its
+ sequence of spi_transfer requests is arranged;
+
+ + optionally defining short delays after transfers ... using
+ the spi_transfer.delay_usecs setting;
+
+ + whether the chipselect becomes inactive after a transfer and
+ any delay ... by using the spi_transfer.cs_change flag;
+
+ + hinting whether the next message is likely to go to this same
+ device ... using the spi_transfer.cs_change flag on the last
+ transfer in that atomic group, and potentially saving costs
+ for chip deselect and select operations.
+
+ - Follow standard kernel rules, and provide DMA-safe buffers in
+ your messages. That way controller drivers using DMA aren't forced
+ to make extra copies unless the hardware requires it (e.g. working
+ around hardware errata that force the use of bounce buffering).
+
+ If standard dma_map_single() handling of these buffers is inappropriate,
+ you can use spi_message.is_dma_mapped to tell the controller driver
+ that you've already provided the relevant DMA addresses.
+
+ - The basic I/O primitive is spi_async(). Async requests may be
+ issued in any context (irq handler, task, etc) and completion
+ is reported using a callback provided with the message.
+
+ - There are also synchronous wrappers like spi_sync(), and wrappers
+ like spi_read(), spi_write(), and spi_write_then_read(). These
+ may be issued only in contexts that may sleep, and they're all
+ clean (and small, and "optional") layers over spi_async().
+
+ - The spi_write_then_read() call, and convenience wrappers around
+ it, should only be used with small amounts of data where the
+ cost of an extra copy may be ignored. It's designed to support
+ common RPC-style requests, such as writing an eight bit command
+ and reading a sixteen bit response -- spi_w8r16() being one its
+ wrappers, doing exactly that.
+
+Some drivers may need to modify spi_device characteristics like the
+transfer mode, wordsize, or clock rate. This is done with spi_setup(),
+which would normally be called from probe() before the first I/O is
+done to the device.
+
+While "spi_device" would be the bottom boundary of the driver, the
+upper boundaries might include sysfs (especially for sensor readings),
+the input layer, ALSA, networking, MTD, the character device framework,
+or other Linux subsystems.
+
+
+How do I write an "SPI Master Controller Driver"?
+-------------------------------------------------
+An SPI controller will probably be registered on the platform_bus; write
+a driver to bind to the device, whichever bus is involved.
+
+The main task of this type of driver is to provide an "spi_master".
+Use spi_alloc_master() to allocate the master, and class_get_devdata()
+to get the driver-private data allocated for that device.
+
+ struct spi_master *master;
+ struct CONTROLLER *c;
+
+ master = spi_alloc_master(dev, sizeof *c);
+ if (!master)
+ return -ENODEV;
+
+ c = class_get_devdata(&master->cdev);
+
+The driver will initialize the fields of that spi_master, including the
+bus number (maybe the same as the platform device ID) and three methods
+used to interact with the SPI core and SPI protocol drivers. It will
+also initialize its own internal state.
+
+ master->setup(struct spi_device *spi)
+ This sets up the device clock rate, SPI mode, and word sizes.
+ Drivers may change the defaults provided by board_info, and then
+ call spi_setup(spi) to invoke this routine. It may sleep.
+
+ master->transfer(struct spi_device *spi, struct spi_message *message)
+ This must not sleep. Its responsibility is arrange that the
+ transfer happens and its complete() callback is issued; the two
+ will normally happen later, after other transfers complete.
+
+ master->cleanup(struct spi_device *spi)
+ Your controller driver may use spi_device.controller_state to hold
+ state it dynamically associates with that device. If you do that,
+ be sure to provide the cleanup() method to free that state.
+
+The bulk of the driver will be managing the I/O queue fed by transfer().
+
+That queue could be purely conceptual. For example, a driver used only
+for low-frequency sensor acess might be fine using synchronous PIO.
+
+But the queue will probably be very real, using message->queue, PIO,
+often DMA (especially if the root filesystem is in SPI flash), and
+execution contexts like IRQ handlers, tasklets, or workqueues (such
+as keventd). Your driver can be as fancy, or as simple, as you need.
+
+
+THANKS TO
+---------
+Contributors to Linux-SPI discussions include (in alphabetical order,
+by last name):
+
+David Brownell
+Russell King
+Dmitry Pervushin
+Stephen Street
+Mark Underwood
+Andrew Victor
+Vitaly Wool
+

2005-11-30 21:36:40

by David Brownell

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

On Wednesday 30 November 2005 8:50 am, Vitaly Wool wrote:

> However, there also are some advantages of our core compared to David's I'd like to mention

I'd also be interested in your responses to the comparison I wrote up last week.
(Post dated 23-November to that spi-devel list...)


> - it can be compiled as a module

Which as I pointed out would be a rather minor patch to mine. There's a
bit of code to manage the board-specific SPI tables, which _can't_ be
a module. Then there's something less than 2KB of code (ARM .text) that
could live in a module. I can't get excited about making that live in
a module, but I'd take a patch to change that.


> - it is DMA-safe

Which as I pointed out is incorrect. The core API (async) has always
been fully DMA-safe. And a **LOT** lower overhead than yours, which
allocates buffers behind the back of drivers, and encourages lots of
memcpy rather than just doing DMA directly to/from the buffers that
are provided by the SPI protocol drivers.


> - it is priority inversion-free
> - it can gain more performance with multiple controllers
> - it's more adapted for use in real-time environments

You'd have to explain what you mean by all of these. I could guess
based on what you've said before (disagree!), but that won't help.


> - it's not so lightweight, but it leaves less effort for the bus driver developer.

Whereas in my previous comments about your framework, I think I've
pointed out that imposing needless and restrictive policies on how
the controller drivers work is a Bad Thing.

- Dave

2005-11-30 21:59:16

by Stephen Street

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

On Wed, 2005-11-30 at 13:36 -0800, David Brownell wrote:
> > - it is DMA-safe
>
> Which as I pointed out is incorrect. The core API (async) has always
> been fully DMA-safe. And a **LOT** lower overhead than yours, which
> allocates buffers behind the back of drivers, and encourages lots of
> memcpy rather than just doing DMA directly to/from the buffers that
> are provided by the SPI protocol drivers.

Minimal (or no) core intervention on the DMA code path is a good thing.
I need to fix some broken hardware with software and must to move 96
bytes from one SPI device to another on the same SPI bus every for 4ms.
Needless memcpy's will cause substantial performance problems in my
application. Thinner is definitely better.

-Stephen

2005-12-01 07:17:38

by Vitaly Wool

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

Mark Underwood wrote:

>>However, there also are some advantages of our core compared to David's I'd like to mention
>>
>>- it can be compiled as a module
>>
>>
>So can David's. You can use BIOS tables in which case you must compile the SPI core into the
>kernel but you can also use spi_new_device which allows the SPI core to be built as a module (and
>is how I am using it).
>
>
You limit the functionality, so it's not the case.

>
>
>>- it is DMA-safe
>>
>>
>To my understanding David's core is DMA-safe. Yes there is a question mark over one of the helper
>functions, but the _main_ functions _are_ DMA-safe.
>
>
Yeah, I can agree with this statement. However, as it turns out, the
latest David's core eliminates this issue.

>
>
>>- it is priority inversion-free
>>- it can gain more performance with multiple controllers
>>
>>
>Sorry I'm not sure what you mean here.
>
>
If there's more than one SPI controller onboard, spi_write_then_read
will serialize the transfers related to two different controllers what
will have significant negative impact on the transfer speed (so DMA
won't help increasing the speed in this case). Moreover, if, say, two
kernel threads with different priorities are working with two SPI
controllers respectively *priority inversion* will happen.
You might also want to learn more about real-time systems
characterictics such as priority inversion, BTW.

>
>
>>- it's more adapted for use in real-time environments
>>- it's not so lightweight, but it leaves less effort for the bus driver developer.
>>
>>
>
>But also less flexibility. A core layer shouldn't _force_ a policy
>
>
Nope, it's just a default policy.

>on a bus driver. I am currently developing an adapter driver for David's system and I wouldn't say
>that the core is making me do things I think the core should do. Please could you provide examples
>of where you think Davids SPI core requires 'effort'.
>
>
Main are
- the need to call 'complete' in controller driver
- the need to implement policy in controller driver

Vitaly

2005-12-01 07:24:41

by Vitaly Wool

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

David Brownell wrote:

>>- it can be compiled as a module
>>
>>
>
>Which as I pointed out would be a rather minor patch to mine. There's a
>bit of code to manage the board-specific SPI tables, which _can't_ be
>a module. Then there's something less than 2KB of code (ARM .text) that
>could live in a module. I can't get excited about making that live in
>a module, but I'd take a patch to change that.
>
>
Well, it's a sign of convergence :)

>
>
>
>>- it is DMA-safe
>>
>>
>
>Which as I pointed out is incorrect. The core API (async) has always
>been fully DMA-safe. And a **LOT** lower overhead than yours, which
>allocates buffers behind the back of drivers, and encourages lots of
>memcpy rather than just doing DMA directly to/from the buffers that
>are provided by the SPI protocol drivers.
>
>
Lower overhead? Lemme absolutely disagree with you. Please be aware that
memory allocation routines are abstract, so no necessary memory allocation.
Yeah, anyway, your latest core doesn't look DMA-unsafe to me.

>
>
>>- it is priority inversion-free
>>- it can gain more performance with multiple controllers
>>- it's more adapted for use in real-time environments
>>
>>
>
>You'd have to explain what you mean by all of these. I could guess
>based on what you've said before (disagree!), but that won't help.
>
>
Your taking semaphore in spi_write_then_read which all the sync routines
are based on may lead to priority inversion and of course is not optimal
in terms of overall performance, if there's more than one controller
(have you tested your core in this situation BTW?)
Suppose you have two kernel threads with different priorities dealing
with SPI controller each... Of course you'll get priority inversion when
the thread with higher prio will wait for semaphore release!

>
>
>
>>- it's not so lightweight, but it leaves less effort for the bus driver developer.
>>
>>
>
>Whereas in my previous comments about your framework, I think I've
>pointed out that imposing needless and restrictive policies on how
>the controller drivers work is a Bad Thing.
>
>
It's just a *reasonable* _default_ policy.

Vitaly

2005-12-01 07:31:25

by Vitaly Wool

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

Stephen Street wrote:

>On Wed, 2005-11-30 at 13:36 -0800, David Brownell wrote:
>
>
>>>- it is DMA-safe
>>>
>>>
>>Which as I pointed out is incorrect. The core API (async) has always
>>been fully DMA-safe. And a **LOT** lower overhead than yours, which
>>allocates buffers behind the back of drivers, and encourages lots of
>>memcpy rather than just doing DMA directly to/from the buffers that
>>are provided by the SPI protocol drivers.
>>
>>
>
>Minimal (or no) core intervention on the DMA code path is a good thing.
>I need to fix some broken hardware with software and must to move 96
>bytes from one SPI device to another on the same SPI bus every for 4ms.
>Needless memcpy's will cause substantial performance problems in my
>application. Thinner is definitely better.
>
>
Oh yep, I must agree with you here, thanks.
However, it's not a big thing to change memcpy to spi_memcpy which will
copy the data only when necessary.
That's what I definitely had been doing but didn't include in the patch
sent, oops. :(
I'll come up with that shortly.

Vitaly

2005-12-01 18:31:22

by David Brownell

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

On Wednesday 30 November 2005 11:17 pm, Vitaly Wool wrote:
> Mark Underwood wrote:
>
> >>However, there also are some advantages of our core compared to David's I'd like to mention
> >>
> >>- it can be compiled as a module
>
> >So can David's. You can use BIOS tables in which case you must compile the SPI core into the
> >kernel but you can also use spi_new_device which allows the SPI core to be built as a module (and
> >is how I am using it).
>
> You limit the functionality, so it's not the case.

As noted in my comparison of last week (you're still ignoring that):

?- Mine lets board-specific device tables be declared in the
? ?relevant arch_setup() thing (board-*.c). ?Both frameworks allow
? ?later board specific code to dynamically declare the devices,
? ?with binary (Dave's) or parsed-text (Dmitry's) descriptions.

What Mark said was that in this case he used the "late" init. You seem
to be saying he's not allowed to do that. Which is nonsense; there are
distinct mechanisms for the good reason that "late" init doesn't work
so well without dynamic discovery ... which SPI itself doesn't support.
Hence the need for board-specific "this hardware exists" tables.


> If there's more than one SPI controller onboard, spi_write_then_read
> will serialize the transfers ...

Which, as has been pointed out, would be a trivial thing to fix
if anyone were actually to have a problem. Sure it'd incur the
cost of a kmalloc on at least some paths -- serializing in the
slab layer instead! -- but that's one price of using convenience
helpers not performance oriented calls.


> Moreover, if, say, two
> kernel threads with different priorities are working with two SPI
> controllers respectively *priority inversion* will happen.

That characteristic being inherited from semaphores (or were they
updated with RT_PREEMPT?), and being in common with most I/O queues
in the system. Not something to blame on any line of code I wrote.

Oh, and I noticed a priority inversion in your API which shows
up with one SPI controller managing two devices. Whoops! I'd
far rather have such inversions be implementation artifacts; it's
easy to patch an implementation, hard to change all API users.


> >>- it's more adapted for use in real-time environments
> >>- it's not so lightweight, but it leaves less effort for the bus driver developer.
> >
> >But also less flexibility. A core layer shouldn't _force_ a policy
>
> Nope, it's just a default policy.

One that every driver pays the price for. Allocating a task even
when it doesn't need it; every call going through a midlayer that
wants to take over queue management policy; and more. (Unless you
made a big un-remarked change in a patch you called "refresh"...)


> >on a bus driver. I am currently developing an adapter driver for David's system and I wouldn't say
> >that the core is making me do things I think the core should do. Please could you provide examples
> >of where you think Davids SPI core requires 'effort'.
>
> Main are
> - the need to call 'complete' in controller driver

So you think it's better to have consistent semantics be optional?

That seems to be the notion behind your spi_transfer() call, which
can't decide whether it's going to be synchronous or asynchronous.
Instead, it decided to be error prone and be both. :)


> - the need to implement policy in controller driver

The "policy" in question is something that sometimes needs to
be board-specific -- priority to THAT device, synch with THIS
external signal, etc -- which is why I see it as a drawback
that you insist the core implement one policy.

One policy is painfully easy to implement: FIFO, processing
the requests in the order they arrive. Easy to implement,
even with spinlocks, in a dozen lines of code. If anyone
has a hard time writing that, they shouldn't be trying to
write a device driver.

- Dave

2005-12-02 05:48:22

by Vitaly Wool

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

David Brownell wrote:

>On Wednesday 30 November 2005 11:17 pm, Vitaly Wool wrote:
>
>
>>Mark Underwood wrote:
>>
>>
>>
>>>>However, there also are some advantages of our core compared to David's I'd like to mention
>>>>
>>>>- it can be compiled as a module
>>>>
>>>>
>>>So can David's. You can use BIOS tables in which case you must compile the SPI core into the
>>>kernel but you can also use spi_new_device which allows the SPI core to be built as a module (and
>>>is how I am using it).
>>>
>>>
>>You limit the functionality, so it's not the case.
>>
>>
>
>As noted in my comparison of last week (you're still ignoring that):
>
> - Mine lets board-specific device tables be declared in the
> relevant arch_setup() thing (board-*.c). Both frameworks allow
> later board specific code to dynamically declare the devices,
> with binary (Dave's) or parsed-text (Dmitry's) descriptions.
>
>What Mark said was that in this case he used the "late" init. You seem
>to be saying he's not allowed to do that. Which is nonsense; there are
>distinct mechanisms for the good reason that "late" init doesn't work
>so well without dynamic discovery ... which SPI itself doesn't support.
>Hence the need for board-specific "this hardware exists" tables.
>
>
>
Can you please clarify what you mean here? Better even if Mark describes
what he does. The ideal situation would be if he posted a patch.

>
>
>>If there's more than one SPI controller onboard, spi_write_then_read
>>will serialize the transfers ...
>>
>>
>
>Which, as has been pointed out, would be a trivial thing to fix
>if anyone were actually to have a problem. Sure it'd incur the
>cost of a kmalloc on at least some paths -- serializing in the
>slab layer instead! -- but that's one price of using convenience
>helpers not performance oriented calls.
>
>
Well, most of the drivers will use that helpers I guess.
The thing however is that if you try to implement this in a "clean" way
you will come to a sport of framework we've developed for memeory
allocations, as I've saild previously.

>
>
>
>> Moreover, if, say, two
>>kernel threads with different priorities are working with two SPI
>>controllers respectively *priority inversion* will happen.
>>
>>
>
>That characteristic being inherited from semaphores (or were they
>updated with RT_PREEMPT?), and being in common with most I/O queues
>in the system. Not something to blame on any line of code I wrote.
>
>
I think they weren't.
The whole thing doesn't seem thought out nicely to me. The solution
exists, of course, and that is -- do somthing similar to what we did there.

>Oh, and I noticed a priority inversion in your API which shows
>up with one SPI controller managing two devices. Whoops! I'd
>far rather have such inversions be implementation artifacts; it's
>easy to patch an implementation, hard to change all API users.
>
>
Not sure if I understood you. Can you please describe the situation when
this prio inversion happens?
What priorities are you talking about? One controller is one thread, so
it's _one_ priority, consequently there's nothing to invert.
As for your second statement, I don't argue. The fact however is that if
you implement the mehtod which corrects priority inverstion problems
your core will not be either so lightweight or so flexible. :)

>
>
>
>>>>- it's more adapted for use in real-time environments
>>>>- it's not so lightweight, but it leaves less effort for the bus driver developer.
>>>>
>>>>
>>>But also less flexibility. A core layer shouldn't _force_ a policy
>>>
>>>
>>Nope, it's just a default policy.
>>
>>
>
>One that every driver pays the price for. Allocating a task even
>when it doesn't need it; every call going through a midlayer that
>wants to take over queue management policy; and more. (Unless you
>made a big un-remarked change in a patch you called "refresh"...)
>
>
It's not obvious that this price is high.
Anyway, it's a point I should agree with; this functionality better be a
config option. Feel free to submit a patch, as you like to say.

>
>
>
>>>on a bus driver. I am currently developing an adapter driver for David's system and I wouldn't say
>>>that the core is making me do things I think the core should do. Please could you provide examples
>>>of where you think Davids SPI core requires 'effort'.
>>>
>>>
>>Main are
>>- the need to call 'complete' in controller driver
>>
>>
>
>So you think it's better to have consistent semantics be optional?
>
>That seems to be the notion behind your spi_transfer() call, which
>can't decide whether it's going to be synchronous or asynchronous.
>Instead, it decided to be error prone and be both. :)
>
>
>
>
Not sure if I understood you here, sorry.

>>- the need to implement policy in controller driver
>>
>>
>
>The "policy" in question is something that sometimes needs to
>be board-specific -- priority to THAT device, synch with THIS
>external signal, etc -- which is why I see it as a drawback
>that you insist the core implement one policy.
>
>
Again, the policy can be overridden.

Vitaly

2005-12-02 18:38:00

by Mark Underwood

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh


--- Vitaly Wool <[email protected]> wrote:

> David Brownell wrote:
>
> >On Wednesday 30 November 2005 11:17 pm, Vitaly Wool wrote:
> >
> >
> >>Mark Underwood wrote:
> >>
> >>
> >>
> >>>>However, there also are some advantages of our core compared to David's I'd like to mention
> >>>>
> >>>>- it can be compiled as a module
> >>>>
> >>>>
> >>>So can David's. You can use BIOS tables in which case you must compile the SPI core into the
> >>>kernel but you can also use spi_new_device which allows the SPI core to be built as a module
> (and
> >>>is how I am using it).
> >>>
> >>>
> >>You limit the functionality, so it's not the case.
> >>
> >>
> >
> >As noted in my comparison of last week (you're still ignoring that):
> >
> > - Mine lets board-specific device tables be declared in the
> > relevant arch_setup() thing (board-*.c). Both frameworks allow
> > later board specific code to dynamically declare the devices,
> > with binary (Dave's) or parsed-text (Dmitry's) descriptions.
> >
> >What Mark said was that in this case he used the "late" init. You seem
> >to be saying he's not allowed to do that. Which is nonsense; there are
> >distinct mechanisms for the good reason that "late" init doesn't work
> >so well without dynamic discovery ... which SPI itself doesn't support.
> >Hence the need for board-specific "this hardware exists" tables.
> >
> >
> >
> Can you please clarify what you mean here? Better even if Mark describes
> what he does. The ideal situation would be if he posted a patch.
>

Here it is :)

--- /dev/null 2005-12-02 17:53:19.000000000 +0000
+++ parport_plat.c 2005-11-26 16:57:24.000000000 +0000
@@ -0,0 +1,66 @@
+/*
+ * parport_plat.c - Platfrom file describing the SPI parport adapter
+ * board that has an eeprom on it.
+ *
+ * Copyright (C) 2005 Mark Underwood
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ */
+
+/* This is an example of how to declare and register SPI devices which
+ * are not declared at arch init time.
+ */
+
+#include <linux/device.h>
+#include <linux/init.h>
+#include <linux/module.h>
+#include "../../include/linux/spi/spi.h"
+
+struct spi_board_info parport_eeprom_board = {
+ .modalias = "eeprom",
+ .max_speed_hz = 500000,
+ .bus_num = 1,
+ .chip_select = 2,
+};
+
+struct spi_device *device;
+
+static int __init parport_plat_init(void)
+{
+ struct spi_master *master;
+
+ master = spi_busnum_to_master(parport_eeprom_board.bus_num);
+ if (master)
+ {
+ device = spi_new_device(master, &parport_eeprom_board);
+ if (device)
+ printk("Registerd to bus %s\n", device->dev.bus_id);
+ else
+ {
+ printk("Failed registering %s !\n", parport_eeprom_board.modalias);
+ return -ENODEV;
+ }
+ }
+ else
+ {
+ printk("No master!\n");
+ return -ENODEV;
+ }
+
+ return 0;
+}
+
+static void __exit parport_plat_cleanup(void)
+{
+ spi_unregister_device(device);
+}
+
+module_init(parport_plat_init);
+module_exit(parport_plat_cleanup);
+
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Mark Underwood basicmark(at)yahoo.com");
+MODULE_DESCRIPTION("SPI parport adapter with eeprom platform file");


> >
> >
> >>If there's more than one SPI controller onboard, spi_write_then_read
> >>will serialize the transfers ...
> >>
> >>
> >
> >Which, as has been pointed out, would be a trivial thing to fix
> >if anyone were actually to have a problem. Sure it'd incur the
> >cost of a kmalloc on at least some paths -- serializing in the
> >slab layer instead! -- but that's one price of using convenience
> >helpers not performance oriented calls.
> >
> >
> Well, most of the drivers will use that helpers I guess.
> The thing however is that if you try to implement this in a "clean" way
> you will come to a sport of framework we've developed for memeory
> allocations, as I've saild previously.
>
> >
> >
> >
> >> Moreover, if, say, two
> >>kernel threads with different priorities are working with two SPI
> >>controllers respectively *priority inversion* will happen.
> >>
> >>
> >
> >That characteristic being inherited from semaphores (or were they
> >updated with RT_PREEMPT?), and being in common with most I/O queues
> >in the system. Not something to blame on any line of code I wrote.
> >
> >
> I think they weren't.
> The whole thing doesn't seem thought out nicely to me. The solution
> exists, of course, and that is -- do somthing similar to what we did there.
>

I know what priority inversion is and I can't see where I would happen in Davids SPI core.

I'm sorry but your transfer technique is far more complex then it needs to be. Davids transfer
technique follows that of the USB subsystem, why do you think that SPI, which is _much simpler_,
requires this amount of complexity?

In your subsystem for every adapter you _force_ and thread and a workqueue on that adapter :(,
most adapter drivers will not need either!

> >Oh, and I noticed a priority inversion in your API which shows
> >up with one SPI controller managing two devices. Whoops! I'd
> >far rather have such inversions be implementation artifacts; it's
> >easy to patch an implementation, hard to change all API users.
> >
> >
> Not sure if I understood you. Can you please describe the situation when
> this prio inversion happens?
> What priorities are you talking about? One controller is one thread, so
> it's _one_ priority, consequently there's nothing to invert.
> As for your second statement, I don't argue. The fact however is that if
> you implement the mehtod which corrects priority inverstion problems
> your core will not be either so lightweight or so flexible. :)
>

What priority inversion problem is there to fix in Davids core !?!

> >
> >
> >
> >>>>- it's more adapted for use in real-time environments
> >>>>- it's not so lightweight, but it leaves less effort for the bus driver developer.
> >>>>
> >>>>
> >>>But also less flexibility. A core layer shouldn't _force_ a policy
> >>>
> >>>
> >>Nope, it's just a default policy.
> >>
> >>
> >
> >One that every driver pays the price for. Allocating a task even
> >when it doesn't need it; every call going through a midlayer that
> >wants to take over queue management policy; and more. (Unless you
> >made a big un-remarked change in a patch you called "refresh"...)
> >
> >
> It's not obvious that this price is high.
> Anyway, it's a point I should agree with; this functionality better be a
> config option. Feel free to submit a patch, as you like to say.
>
> >
> >
> >
> >>>on a bus driver. I am currently developing an adapter driver for David's system and I
> wouldn't say
> >>>that the core is making me do things I think the core should do. Please could you provide
> examples
> >>>of where you think Davids SPI core requires 'effort'.
> >>>
> >>>
> >>Main are
> >>- the need to call 'complete' in controller driver
> >>
> >>
> >
> >So you think it's better to have consistent semantics be optional?
> >
> >That seems to be the notion behind your spi_transfer() call, which
> >can't decide whether it's going to be synchronous or asynchronous.
> >Instead, it decided to be error prone and be both. :)
> >
> >
> >
> >
> Not sure if I understood you here, sorry.
>
> >>- the need to implement policy in controller driver
> >>
> >>
> >
> >The "policy" in question is something that sometimes needs to
> >be board-specific -- priority to THAT device, synch with THIS
> >external signal, etc -- which is why I see it as a drawback
> >that you insist the core implement one policy.
> >
> >
> Again, the policy can be overridden.

I thought in general a device driver should't force a policy on its use surely this goes double
(or more) for a driver core.

Mark

>
> Vitaly
>




___________________________________________________________
To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com

2005-12-12 16:56:49

by Vitaly Wool

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

BTW:

David Brownell wrote:

>+How do I write an "SPI Master Controller Driver"?
>+-------------------------------------------------
>+An SPI controller will probably be registered on the platform_bus; write
>+a driver to bind to the device, whichever bus is involved.
>+
>+The main task of this type of driver is to provide an "spi_master".
>+Use spi_alloc_master() to allocate the master, and class_get_devdata()
>+to get the driver-private data allocated for that device.
>+
>+ struct spi_master *master;
>+ struct CONTROLLER *c;
>+
>+ master = spi_alloc_master(dev, sizeof *c);
>+ if (!master)
>+ return -ENODEV;
>+
>+ c = class_get_devdata(&master->cdev);
>
>
Here's an example of a mixture of two approaches which leads to
misleading code.
If you want to have abstract spi_master, then you have to disallow (or
at least discourage) explicit usage of spi_master fields, otherwise
'kzalloc is your friend' and you don't have toadd this spi_alloc_master
API as it's basically useless IMHO.

As opposed to this, we use abstract handles where possible (i. e. for
spi_message).
I'd have understood your dissatisfaction with that if you were
consistently following the approach 'expose everything, forget the
extensibility, viva lightwieghtness', but you're mixing things.

Vitaly

2005-12-13 22:16:36

by David Brownell

[permalink] [raw]
Subject: Re: [PATCH 2.6-git] SPI core refresh

On Monday 12 December 2005 8:57 am, Vitaly Wool wrote:
> BTW:
>
> David Brownell wrote:
>
> >+How do I write an "SPI Master Controller Driver"?
> >+-------------------------------------------------
> >+An SPI controller will probably be registered on the platform_bus; write
> >+a driver to bind to the device, whichever bus is involved.
> >+
> >+The main task of this type of driver is to provide an "spi_master".
> >+Use spi_alloc_master() to allocate the master, and class_get_devdata()
> >+to get the driver-private data allocated for that device.
> >+
> >+ struct spi_master *master;
> >+ struct CONTROLLER *c;
> >+
> >+ master = spi_alloc_master(dev, sizeof *c);
> >+ if (!master)
> >+ return -ENODEV;
> >+
> >+ c = class_get_devdata(&master->cdev);
> >
> >
> Here's an example of a mixture of two approaches which leads to
> misleading code.

I can't see that, myself. I count three things, separated in as
close to "the usual way" as I've heard of: the spi_master, which
essentially bridges some bus (platform etc) to SPI; the class
device, associated one-to-one with the master; and the controller
state used to implement the bridging.

Have you ever noticed how alloc_etherdev() works? This is much
the same approach as that function (and its siblings) use. Not
identical, but that could change. The infrastructure code allocates
one block for the publicly visible state (spi_master in this case,
"struct netdevice" for alloc_netdev) and the private data. You
want something like a "netdev_priv" backed by some different
implementation?


> If you want to have abstract spi_master, then you have to disallow (or
> at least discourage) explicit usage of spi_master fields, otherwise
> 'kzalloc is your friend' and you don't have toadd this spi_alloc_master
> API as it's basically useless IMHO.

Well, it's what ensures that the class device is set up reasonably,
and incidentally takes its memory management out of the hands of
the controller driver. Of course, "the Right Way" to handle such
class devices has changed recently, and this code may be a closer
match to "the Previous Right Way" than the new one. ;)


> As opposed to this, we use abstract handles where possible (i. e. for
> spi_message).
> I'd have understood your dissatisfaction with that if you were
> consistently following the approach 'expose everything, forget the
> extensibility, viva lightwieghtness', but you're mixing things.

Data abstraction isn't all-or-nothing, especially in C. And in
particular, there's a lot to be said for low level APIs not being
fully opaque ... abstraction has costs, both in terms of growing
conceptual complexity (you're supporting multiple things behind
the abstraction, else why even bother?), loss of visibility into
what's really going on, and in terms of lines of having more source
(and likely object) code to cope with.

The opaque way to access a "struct", as C++ or Java users know, is
to have get()/set() functions for every member. And at the end of
the day, that's just a lot of code bloat, which tends to slow things
down (unless someone inlined it all, rather non-opaquely).

So no, I don't see an inconsistency in wrapping up common code so
it doesn't have to be copied/pasted everywhere (adding bugs), and
not wrapping up code that boils down to "xfer->buf = ptr" (where
funcall style wrappers hide how cheap it is).

- Dave