Merge remote-tracking branches 'spi/topic/doc', 'spi/topic/dw' and 'spi/topic/flash...
[linux-2.6-block.git] / include / linux / spi / spi.h
1 /*
2  * Copyright (C) 2005 David Brownell
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #ifndef __LINUX_SPI_H
16 #define __LINUX_SPI_H
17
18 #include <linux/device.h>
19 #include <linux/mod_devicetable.h>
20 #include <linux/slab.h>
21 #include <linux/kthread.h>
22 #include <linux/completion.h>
23 #include <linux/scatterlist.h>
24
25 struct dma_chan;
26 struct spi_master;
27 struct spi_transfer;
28 struct spi_flash_read_message;
29
30 /*
31  * INTERFACES between SPI master-side drivers and SPI infrastructure.
32  * (There's no SPI slave support for Linux yet...)
33  */
34 extern struct bus_type spi_bus_type;
35
36 /**
37  * struct spi_statistics - statistics for spi transfers
38  * @lock:          lock protecting this structure
39  *
40  * @messages:      number of spi-messages handled
41  * @transfers:     number of spi_transfers handled
42  * @errors:        number of errors during spi_transfer
43  * @timedout:      number of timeouts during spi_transfer
44  *
45  * @spi_sync:      number of times spi_sync is used
46  * @spi_sync_immediate:
47  *                 number of times spi_sync is executed immediately
48  *                 in calling context without queuing and scheduling
49  * @spi_async:     number of times spi_async is used
50  *
51  * @bytes:         number of bytes transferred to/from device
52  * @bytes_tx:      number of bytes sent to device
53  * @bytes_rx:      number of bytes received from device
54  *
55  * @transfer_bytes_histo:
56  *                 transfer bytes histogramm
57  */
58 struct spi_statistics {
59         spinlock_t              lock; /* lock for the whole structure */
60
61         unsigned long           messages;
62         unsigned long           transfers;
63         unsigned long           errors;
64         unsigned long           timedout;
65
66         unsigned long           spi_sync;
67         unsigned long           spi_sync_immediate;
68         unsigned long           spi_async;
69
70         unsigned long long      bytes;
71         unsigned long long      bytes_rx;
72         unsigned long long      bytes_tx;
73
74 #define SPI_STATISTICS_HISTO_SIZE 17
75         unsigned long transfer_bytes_histo[SPI_STATISTICS_HISTO_SIZE];
76 };
77
78 void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
79                                        struct spi_transfer *xfer,
80                                        struct spi_master *master);
81
82 #define SPI_STATISTICS_ADD_TO_FIELD(stats, field, count)        \
83         do {                                                    \
84                 unsigned long flags;                            \
85                 spin_lock_irqsave(&(stats)->lock, flags);       \
86                 (stats)->field += count;                        \
87                 spin_unlock_irqrestore(&(stats)->lock, flags);  \
88         } while (0)
89
90 #define SPI_STATISTICS_INCREMENT_FIELD(stats, field)    \
91         SPI_STATISTICS_ADD_TO_FIELD(stats, field, 1)
92
93 /**
94  * struct spi_device - Master side proxy for an SPI slave device
95  * @dev: Driver model representation of the device.
96  * @master: SPI controller used with the device.
97  * @max_speed_hz: Maximum clock rate to be used with this chip
98  *      (on this board); may be changed by the device's driver.
99  *      The spi_transfer.speed_hz can override this for each transfer.
100  * @chip_select: Chipselect, distinguishing chips handled by @master.
101  * @mode: The spi mode defines how data is clocked out and in.
102  *      This may be changed by the device's driver.
103  *      The "active low" default for chipselect mode can be overridden
104  *      (by specifying SPI_CS_HIGH) as can the "MSB first" default for
105  *      each word in a transfer (by specifying SPI_LSB_FIRST).
106  * @bits_per_word: Data transfers involve one or more words; word sizes
107  *      like eight or 12 bits are common.  In-memory wordsizes are
108  *      powers of two bytes (e.g. 20 bit samples use 32 bits).
109  *      This may be changed by the device's driver, or left at the
110  *      default (0) indicating protocol words are eight bit bytes.
111  *      The spi_transfer.bits_per_word can override this for each transfer.
112  * @irq: Negative, or the number passed to request_irq() to receive
113  *      interrupts from this device.
114  * @controller_state: Controller's runtime state
115  * @controller_data: Board-specific definitions for controller, such as
116  *      FIFO initialization parameters; from board_info.controller_data
117  * @modalias: Name of the driver to use with this device, or an alias
118  *      for that name.  This appears in the sysfs "modalias" attribute
119  *      for driver coldplugging, and in uevents used for hotplugging
120  * @cs_gpio: gpio number of the chipselect line (optional, -ENOENT when
121  *      when not using a GPIO line)
122  *
123  * @statistics: statistics for the spi_device
124  *
125  * A @spi_device is used to interchange data between an SPI slave
126  * (usually a discrete chip) and CPU memory.
127  *
128  * In @dev, the platform_data is used to hold information about this
129  * device that's meaningful to the device's protocol driver, but not
130  * to its controller.  One example might be an identifier for a chip
131  * variant with slightly different functionality; another might be
132  * information about how this particular board wires the chip's pins.
133  */
134 struct spi_device {
135         struct device           dev;
136         struct spi_master       *master;
137         u32                     max_speed_hz;
138         u8                      chip_select;
139         u8                      bits_per_word;
140         u16                     mode;
141 #define SPI_CPHA        0x01                    /* clock phase */
142 #define SPI_CPOL        0x02                    /* clock polarity */
143 #define SPI_MODE_0      (0|0)                   /* (original MicroWire) */
144 #define SPI_MODE_1      (0|SPI_CPHA)
145 #define SPI_MODE_2      (SPI_CPOL|0)
146 #define SPI_MODE_3      (SPI_CPOL|SPI_CPHA)
147 #define SPI_CS_HIGH     0x04                    /* chipselect active high? */
148 #define SPI_LSB_FIRST   0x08                    /* per-word bits-on-wire */
149 #define SPI_3WIRE       0x10                    /* SI/SO signals shared */
150 #define SPI_LOOP        0x20                    /* loopback mode */
151 #define SPI_NO_CS       0x40                    /* 1 dev/bus, no chipselect */
152 #define SPI_READY       0x80                    /* slave pulls low to pause */
153 #define SPI_TX_DUAL     0x100                   /* transmit with 2 wires */
154 #define SPI_TX_QUAD     0x200                   /* transmit with 4 wires */
155 #define SPI_RX_DUAL     0x400                   /* receive with 2 wires */
156 #define SPI_RX_QUAD     0x800                   /* receive with 4 wires */
157         int                     irq;
158         void                    *controller_state;
159         void                    *controller_data;
160         char                    modalias[SPI_NAME_SIZE];
161         int                     cs_gpio;        /* chip select gpio */
162
163         /* the statistics */
164         struct spi_statistics   statistics;
165
166         /*
167          * likely need more hooks for more protocol options affecting how
168          * the controller talks to each chip, like:
169          *  - memory packing (12 bit samples into low bits, others zeroed)
170          *  - priority
171          *  - drop chipselect after each word
172          *  - chipselect delays
173          *  - ...
174          */
175 };
176
177 static inline struct spi_device *to_spi_device(struct device *dev)
178 {
179         return dev ? container_of(dev, struct spi_device, dev) : NULL;
180 }
181
182 /* most drivers won't need to care about device refcounting */
183 static inline struct spi_device *spi_dev_get(struct spi_device *spi)
184 {
185         return (spi && get_device(&spi->dev)) ? spi : NULL;
186 }
187
188 static inline void spi_dev_put(struct spi_device *spi)
189 {
190         if (spi)
191                 put_device(&spi->dev);
192 }
193
194 /* ctldata is for the bus_master driver's runtime state */
195 static inline void *spi_get_ctldata(struct spi_device *spi)
196 {
197         return spi->controller_state;
198 }
199
200 static inline void spi_set_ctldata(struct spi_device *spi, void *state)
201 {
202         spi->controller_state = state;
203 }
204
205 /* device driver data */
206
207 static inline void spi_set_drvdata(struct spi_device *spi, void *data)
208 {
209         dev_set_drvdata(&spi->dev, data);
210 }
211
212 static inline void *spi_get_drvdata(struct spi_device *spi)
213 {
214         return dev_get_drvdata(&spi->dev);
215 }
216
217 struct spi_message;
218 struct spi_transfer;
219
220 /**
221  * struct spi_driver - Host side "protocol" driver
222  * @id_table: List of SPI devices supported by this driver
223  * @probe: Binds this driver to the spi device.  Drivers can verify
224  *      that the device is actually present, and may need to configure
225  *      characteristics (such as bits_per_word) which weren't needed for
226  *      the initial configuration done during system setup.
227  * @remove: Unbinds this driver from the spi device
228  * @shutdown: Standard shutdown callback used during system state
229  *      transitions such as powerdown/halt and kexec
230  * @driver: SPI device drivers should initialize the name and owner
231  *      field of this structure.
232  *
233  * This represents the kind of device driver that uses SPI messages to
234  * interact with the hardware at the other end of a SPI link.  It's called
235  * a "protocol" driver because it works through messages rather than talking
236  * directly to SPI hardware (which is what the underlying SPI controller
237  * driver does to pass those messages).  These protocols are defined in the
238  * specification for the device(s) supported by the driver.
239  *
240  * As a rule, those device protocols represent the lowest level interface
241  * supported by a driver, and it will support upper level interfaces too.
242  * Examples of such upper levels include frameworks like MTD, networking,
243  * MMC, RTC, filesystem character device nodes, and hardware monitoring.
244  */
245 struct spi_driver {
246         const struct spi_device_id *id_table;
247         int                     (*probe)(struct spi_device *spi);
248         int                     (*remove)(struct spi_device *spi);
249         void                    (*shutdown)(struct spi_device *spi);
250         struct device_driver    driver;
251 };
252
253 static inline struct spi_driver *to_spi_driver(struct device_driver *drv)
254 {
255         return drv ? container_of(drv, struct spi_driver, driver) : NULL;
256 }
257
258 extern int __spi_register_driver(struct module *owner, struct spi_driver *sdrv);
259
260 /**
261  * spi_unregister_driver - reverse effect of spi_register_driver
262  * @sdrv: the driver to unregister
263  * Context: can sleep
264  */
265 static inline void spi_unregister_driver(struct spi_driver *sdrv)
266 {
267         if (sdrv)
268                 driver_unregister(&sdrv->driver);
269 }
270
271 /* use a define to avoid include chaining to get THIS_MODULE */
272 #define spi_register_driver(driver) \
273         __spi_register_driver(THIS_MODULE, driver)
274
275 /**
276  * module_spi_driver() - Helper macro for registering a SPI driver
277  * @__spi_driver: spi_driver struct
278  *
279  * Helper macro for SPI drivers which do not do anything special in module
280  * init/exit. This eliminates a lot of boilerplate. Each module may only
281  * use this macro once, and calling it replaces module_init() and module_exit()
282  */
283 #define module_spi_driver(__spi_driver) \
284         module_driver(__spi_driver, spi_register_driver, \
285                         spi_unregister_driver)
286
287 /**
288  * struct spi_master - interface to SPI master controller
289  * @dev: device interface to this driver
290  * @list: link with the global spi_master list
291  * @bus_num: board-specific (and often SOC-specific) identifier for a
292  *      given SPI controller.
293  * @num_chipselect: chipselects are used to distinguish individual
294  *      SPI slaves, and are numbered from zero to num_chipselects.
295  *      each slave has a chipselect signal, but it's common that not
296  *      every chipselect is connected to a slave.
297  * @dma_alignment: SPI controller constraint on DMA buffers alignment.
298  * @mode_bits: flags understood by this controller driver
299  * @bits_per_word_mask: A mask indicating which values of bits_per_word are
300  *      supported by the driver. Bit n indicates that a bits_per_word n+1 is
301  *      supported. If set, the SPI core will reject any transfer with an
302  *      unsupported bits_per_word. If not set, this value is simply ignored,
303  *      and it's up to the individual driver to perform any validation.
304  * @min_speed_hz: Lowest supported transfer speed
305  * @max_speed_hz: Highest supported transfer speed
306  * @flags: other constraints relevant to this driver
307  * @max_transfer_size: function that returns the max transfer size for
308  *      a &spi_device; may be %NULL, so the default %SIZE_MAX will be used.
309  * @bus_lock_spinlock: spinlock for SPI bus locking
310  * @bus_lock_mutex: mutex for SPI bus locking
311  * @bus_lock_flag: indicates that the SPI bus is locked for exclusive use
312  * @setup: updates the device mode and clocking records used by a
313  *      device's SPI controller; protocol code may call this.  This
314  *      must fail if an unrecognized or unsupported mode is requested.
315  *      It's always safe to call this unless transfers are pending on
316  *      the device whose settings are being modified.
317  * @transfer: adds a message to the controller's transfer queue.
318  * @cleanup: frees controller-specific state
319  * @can_dma: determine whether this master supports DMA
320  * @queued: whether this master is providing an internal message queue
321  * @kworker: thread struct for message pump
322  * @kworker_task: pointer to task for message pump kworker thread
323  * @pump_messages: work struct for scheduling work to the message pump
324  * @queue_lock: spinlock to syncronise access to message queue
325  * @queue: message queue
326  * @idling: the device is entering idle state
327  * @cur_msg: the currently in-flight message
328  * @cur_msg_prepared: spi_prepare_message was called for the currently
329  *                    in-flight message
330  * @cur_msg_mapped: message has been mapped for DMA
331  * @xfer_completion: used by core transfer_one_message()
332  * @busy: message pump is busy
333  * @running: message pump is running
334  * @rt: whether this queue is set to run as a realtime task
335  * @auto_runtime_pm: the core should ensure a runtime PM reference is held
336  *                   while the hardware is prepared, using the parent
337  *                   device for the spidev
338  * @max_dma_len: Maximum length of a DMA transfer for the device.
339  * @prepare_transfer_hardware: a message will soon arrive from the queue
340  *      so the subsystem requests the driver to prepare the transfer hardware
341  *      by issuing this call
342  * @transfer_one_message: the subsystem calls the driver to transfer a single
343  *      message while queuing transfers that arrive in the meantime. When the
344  *      driver is finished with this message, it must call
345  *      spi_finalize_current_message() so the subsystem can issue the next
346  *      message
347  * @unprepare_transfer_hardware: there are currently no more messages on the
348  *      queue so the subsystem notifies the driver that it may relax the
349  *      hardware by issuing this call
350  * @set_cs: set the logic level of the chip select line.  May be called
351  *          from interrupt context.
352  * @prepare_message: set up the controller to transfer a single message,
353  *                   for example doing DMA mapping.  Called from threaded
354  *                   context.
355  * @transfer_one: transfer a single spi_transfer.
356  *                  - return 0 if the transfer is finished,
357  *                  - return 1 if the transfer is still in progress. When
358  *                    the driver is finished with this transfer it must
359  *                    call spi_finalize_current_transfer() so the subsystem
360  *                    can issue the next transfer. Note: transfer_one and
361  *                    transfer_one_message are mutually exclusive; when both
362  *                    are set, the generic subsystem does not call your
363  *                    transfer_one callback.
364  * @handle_err: the subsystem calls the driver to handle an error that occurs
365  *              in the generic implementation of transfer_one_message().
366  * @unprepare_message: undo any work done by prepare_message().
367  * @spi_flash_read: to support spi-controller hardwares that provide
368  *                  accelerated interface to read from flash devices.
369  * @cs_gpios: Array of GPIOs to use as chip select lines; one per CS
370  *      number. Any individual value may be -ENOENT for CS lines that
371  *      are not GPIOs (driven by the SPI controller itself).
372  * @statistics: statistics for the spi_master
373  * @dma_tx: DMA transmit channel
374  * @dma_rx: DMA receive channel
375  * @dummy_rx: dummy receive buffer for full-duplex devices
376  * @dummy_tx: dummy transmit buffer for full-duplex devices
377  * @fw_translate_cs: If the boot firmware uses different numbering scheme
378  *      what Linux expects, this optional hook can be used to translate
379  *      between the two.
380  *
381  * Each SPI master controller can communicate with one or more @spi_device
382  * children.  These make a small bus, sharing MOSI, MISO and SCK signals
383  * but not chip select signals.  Each device may be configured to use a
384  * different clock rate, since those shared signals are ignored unless
385  * the chip is selected.
386  *
387  * The driver for an SPI controller manages access to those devices through
388  * a queue of spi_message transactions, copying data between CPU memory and
389  * an SPI slave device.  For each such message it queues, it calls the
390  * message's completion function when the transaction completes.
391  */
392 struct spi_master {
393         struct device   dev;
394
395         struct list_head list;
396
397         /* other than negative (== assign one dynamically), bus_num is fully
398          * board-specific.  usually that simplifies to being SOC-specific.
399          * example:  one SOC has three SPI controllers, numbered 0..2,
400          * and one board's schematics might show it using SPI-2.  software
401          * would normally use bus_num=2 for that controller.
402          */
403         s16                     bus_num;
404
405         /* chipselects will be integral to many controllers; some others
406          * might use board-specific GPIOs.
407          */
408         u16                     num_chipselect;
409
410         /* some SPI controllers pose alignment requirements on DMAable
411          * buffers; let protocol drivers know about these requirements.
412          */
413         u16                     dma_alignment;
414
415         /* spi_device.mode flags understood by this controller driver */
416         u16                     mode_bits;
417
418         /* bitmask of supported bits_per_word for transfers */
419         u32                     bits_per_word_mask;
420 #define SPI_BPW_MASK(bits) BIT((bits) - 1)
421 #define SPI_BIT_MASK(bits) (((bits) == 32) ? ~0U : (BIT(bits) - 1))
422 #define SPI_BPW_RANGE_MASK(min, max) (SPI_BIT_MASK(max) - SPI_BIT_MASK(min - 1))
423
424         /* limits on transfer speed */
425         u32                     min_speed_hz;
426         u32                     max_speed_hz;
427
428         /* other constraints relevant to this driver */
429         u16                     flags;
430 #define SPI_MASTER_HALF_DUPLEX  BIT(0)          /* can't do full duplex */
431 #define SPI_MASTER_NO_RX        BIT(1)          /* can't do buffer read */
432 #define SPI_MASTER_NO_TX        BIT(2)          /* can't do buffer write */
433 #define SPI_MASTER_MUST_RX      BIT(3)          /* requires rx */
434 #define SPI_MASTER_MUST_TX      BIT(4)          /* requires tx */
435
436         /*
437          * on some hardware transfer size may be constrained
438          * the limit may depend on device transfer settings
439          */
440         size_t (*max_transfer_size)(struct spi_device *spi);
441
442         /* lock and mutex for SPI bus locking */
443         spinlock_t              bus_lock_spinlock;
444         struct mutex            bus_lock_mutex;
445
446         /* flag indicating that the SPI bus is locked for exclusive use */
447         bool                    bus_lock_flag;
448
449         /* Setup mode and clock, etc (spi driver may call many times).
450          *
451          * IMPORTANT:  this may be called when transfers to another
452          * device are active.  DO NOT UPDATE SHARED REGISTERS in ways
453          * which could break those transfers.
454          */
455         int                     (*setup)(struct spi_device *spi);
456
457         /* bidirectional bulk transfers
458          *
459          * + The transfer() method may not sleep; its main role is
460          *   just to add the message to the queue.
461          * + For now there's no remove-from-queue operation, or
462          *   any other request management
463          * + To a given spi_device, message queueing is pure fifo
464          *
465          * + The master's main job is to process its message queue,
466          *   selecting a chip then transferring data
467          * + If there are multiple spi_device children, the i/o queue
468          *   arbitration algorithm is unspecified (round robin, fifo,
469          *   priority, reservations, preemption, etc)
470          *
471          * + Chipselect stays active during the entire message
472          *   (unless modified by spi_transfer.cs_change != 0).
473          * + The message transfers use clock and SPI mode parameters
474          *   previously established by setup() for this device
475          */
476         int                     (*transfer)(struct spi_device *spi,
477                                                 struct spi_message *mesg);
478
479         /* called on release() to free memory provided by spi_master */
480         void                    (*cleanup)(struct spi_device *spi);
481
482         /*
483          * Used to enable core support for DMA handling, if can_dma()
484          * exists and returns true then the transfer will be mapped
485          * prior to transfer_one() being called.  The driver should
486          * not modify or store xfer and dma_tx and dma_rx must be set
487          * while the device is prepared.
488          */
489         bool                    (*can_dma)(struct spi_master *master,
490                                            struct spi_device *spi,
491                                            struct spi_transfer *xfer);
492
493         /*
494          * These hooks are for drivers that want to use the generic
495          * master transfer queueing mechanism. If these are used, the
496          * transfer() function above must NOT be specified by the driver.
497          * Over time we expect SPI drivers to be phased over to this API.
498          */
499         bool                            queued;
500         struct kthread_worker           kworker;
501         struct task_struct              *kworker_task;
502         struct kthread_work             pump_messages;
503         spinlock_t                      queue_lock;
504         struct list_head                queue;
505         struct spi_message              *cur_msg;
506         bool                            idling;
507         bool                            busy;
508         bool                            running;
509         bool                            rt;
510         bool                            auto_runtime_pm;
511         bool                            cur_msg_prepared;
512         bool                            cur_msg_mapped;
513         struct completion               xfer_completion;
514         size_t                          max_dma_len;
515
516         int (*prepare_transfer_hardware)(struct spi_master *master);
517         int (*transfer_one_message)(struct spi_master *master,
518                                     struct spi_message *mesg);
519         int (*unprepare_transfer_hardware)(struct spi_master *master);
520         int (*prepare_message)(struct spi_master *master,
521                                struct spi_message *message);
522         int (*unprepare_message)(struct spi_master *master,
523                                  struct spi_message *message);
524         int (*spi_flash_read)(struct  spi_device *spi,
525                               struct spi_flash_read_message *msg);
526
527         /*
528          * These hooks are for drivers that use a generic implementation
529          * of transfer_one_message() provied by the core.
530          */
531         void (*set_cs)(struct spi_device *spi, bool enable);
532         int (*transfer_one)(struct spi_master *master, struct spi_device *spi,
533                             struct spi_transfer *transfer);
534         void (*handle_err)(struct spi_master *master,
535                            struct spi_message *message);
536
537         /* gpio chip select */
538         int                     *cs_gpios;
539
540         /* statistics */
541         struct spi_statistics   statistics;
542
543         /* DMA channels for use with core dmaengine helpers */
544         struct dma_chan         *dma_tx;
545         struct dma_chan         *dma_rx;
546
547         /* dummy data for full duplex devices */
548         void                    *dummy_rx;
549         void                    *dummy_tx;
550
551         int (*fw_translate_cs)(struct spi_master *master, unsigned cs);
552 };
553
554 static inline void *spi_master_get_devdata(struct spi_master *master)
555 {
556         return dev_get_drvdata(&master->dev);
557 }
558
559 static inline void spi_master_set_devdata(struct spi_master *master, void *data)
560 {
561         dev_set_drvdata(&master->dev, data);
562 }
563
564 static inline struct spi_master *spi_master_get(struct spi_master *master)
565 {
566         if (!master || !get_device(&master->dev))
567                 return NULL;
568         return master;
569 }
570
571 static inline void spi_master_put(struct spi_master *master)
572 {
573         if (master)
574                 put_device(&master->dev);
575 }
576
577 /* PM calls that need to be issued by the driver */
578 extern int spi_master_suspend(struct spi_master *master);
579 extern int spi_master_resume(struct spi_master *master);
580
581 /* Calls the driver make to interact with the message queue */
582 extern struct spi_message *spi_get_next_queued_message(struct spi_master *master);
583 extern void spi_finalize_current_message(struct spi_master *master);
584 extern void spi_finalize_current_transfer(struct spi_master *master);
585
586 /* the spi driver core manages memory for the spi_master classdev */
587 extern struct spi_master *
588 spi_alloc_master(struct device *host, unsigned size);
589
590 extern int spi_register_master(struct spi_master *master);
591 extern int devm_spi_register_master(struct device *dev,
592                                     struct spi_master *master);
593 extern void spi_unregister_master(struct spi_master *master);
594
595 extern struct spi_master *spi_busnum_to_master(u16 busnum);
596
597 /*---------------------------------------------------------------------------*/
598
599 /*
600  * I/O INTERFACE between SPI controller and protocol drivers
601  *
602  * Protocol drivers use a queue of spi_messages, each transferring data
603  * between the controller and memory buffers.
604  *
605  * The spi_messages themselves consist of a series of read+write transfer
606  * segments.  Those segments always read the same number of bits as they
607  * write; but one or the other is easily ignored by passing a null buffer
608  * pointer.  (This is unlike most types of I/O API, because SPI hardware
609  * is full duplex.)
610  *
611  * NOTE:  Allocation of spi_transfer and spi_message memory is entirely
612  * up to the protocol driver, which guarantees the integrity of both (as
613  * well as the data buffers) for as long as the message is queued.
614  */
615
616 /**
617  * struct spi_transfer - a read/write buffer pair
618  * @tx_buf: data to be written (dma-safe memory), or NULL
619  * @rx_buf: data to be read (dma-safe memory), or NULL
620  * @tx_dma: DMA address of tx_buf, if @spi_message.is_dma_mapped
621  * @rx_dma: DMA address of rx_buf, if @spi_message.is_dma_mapped
622  * @tx_nbits: number of bits used for writing. If 0 the default
623  *      (SPI_NBITS_SINGLE) is used.
624  * @rx_nbits: number of bits used for reading. If 0 the default
625  *      (SPI_NBITS_SINGLE) is used.
626  * @len: size of rx and tx buffers (in bytes)
627  * @speed_hz: Select a speed other than the device default for this
628  *      transfer. If 0 the default (from @spi_device) is used.
629  * @bits_per_word: select a bits_per_word other than the device default
630  *      for this transfer. If 0 the default (from @spi_device) is used.
631  * @cs_change: affects chipselect after this transfer completes
632  * @delay_usecs: microseconds to delay after this transfer before
633  *      (optionally) changing the chipselect status, then starting
634  *      the next transfer or completing this @spi_message.
635  * @transfer_list: transfers are sequenced through @spi_message.transfers
636  * @tx_sg: Scatterlist for transmit, currently not for client use
637  * @rx_sg: Scatterlist for receive, currently not for client use
638  *
639  * SPI transfers always write the same number of bytes as they read.
640  * Protocol drivers should always provide @rx_buf and/or @tx_buf.
641  * In some cases, they may also want to provide DMA addresses for
642  * the data being transferred; that may reduce overhead, when the
643  * underlying driver uses dma.
644  *
645  * If the transmit buffer is null, zeroes will be shifted out
646  * while filling @rx_buf.  If the receive buffer is null, the data
647  * shifted in will be discarded.  Only "len" bytes shift out (or in).
648  * It's an error to try to shift out a partial word.  (For example, by
649  * shifting out three bytes with word size of sixteen or twenty bits;
650  * the former uses two bytes per word, the latter uses four bytes.)
651  *
652  * In-memory data values are always in native CPU byte order, translated
653  * from the wire byte order (big-endian except with SPI_LSB_FIRST).  So
654  * for example when bits_per_word is sixteen, buffers are 2N bytes long
655  * (@len = 2N) and hold N sixteen bit words in CPU byte order.
656  *
657  * When the word size of the SPI transfer is not a power-of-two multiple
658  * of eight bits, those in-memory words include extra bits.  In-memory
659  * words are always seen by protocol drivers as right-justified, so the
660  * undefined (rx) or unused (tx) bits are always the most significant bits.
661  *
662  * All SPI transfers start with the relevant chipselect active.  Normally
663  * it stays selected until after the last transfer in a message.  Drivers
664  * can affect the chipselect signal using cs_change.
665  *
666  * (i) If the transfer isn't the last one in the message, this flag is
667  * used to make the chipselect briefly go inactive in the middle of the
668  * message.  Toggling chipselect in this way may be needed to terminate
669  * a chip command, letting a single spi_message perform all of group of
670  * chip transactions together.
671  *
672  * (ii) When the transfer is the last one in the message, the chip may
673  * stay selected until the next transfer.  On multi-device SPI busses
674  * with nothing blocking messages going to other devices, this is just
675  * a performance hint; starting a message to another device deselects
676  * this one.  But in other cases, this can be used to ensure correctness.
677  * Some devices need protocol transactions to be built from a series of
678  * spi_message submissions, where the content of one message is determined
679  * by the results of previous messages and where the whole transaction
680  * ends when the chipselect goes intactive.
681  *
682  * When SPI can transfer in 1x,2x or 4x. It can get this transfer information
683  * from device through @tx_nbits and @rx_nbits. In Bi-direction, these
684  * two should both be set. User can set transfer mode with SPI_NBITS_SINGLE(1x)
685  * SPI_NBITS_DUAL(2x) and SPI_NBITS_QUAD(4x) to support these three transfer.
686  *
687  * The code that submits an spi_message (and its spi_transfers)
688  * to the lower layers is responsible for managing its memory.
689  * Zero-initialize every field you don't set up explicitly, to
690  * insulate against future API updates.  After you submit a message
691  * and its transfers, ignore them until its completion callback.
692  */
693 struct spi_transfer {
694         /* it's ok if tx_buf == rx_buf (right?)
695          * for MicroWire, one buffer must be null
696          * buffers must work with dma_*map_single() calls, unless
697          *   spi_message.is_dma_mapped reports a pre-existing mapping
698          */
699         const void      *tx_buf;
700         void            *rx_buf;
701         unsigned        len;
702
703         dma_addr_t      tx_dma;
704         dma_addr_t      rx_dma;
705         struct sg_table tx_sg;
706         struct sg_table rx_sg;
707
708         unsigned        cs_change:1;
709         unsigned        tx_nbits:3;
710         unsigned        rx_nbits:3;
711 #define SPI_NBITS_SINGLE        0x01 /* 1bit transfer */
712 #define SPI_NBITS_DUAL          0x02 /* 2bits transfer */
713 #define SPI_NBITS_QUAD          0x04 /* 4bits transfer */
714         u8              bits_per_word;
715         u16             delay_usecs;
716         u32             speed_hz;
717
718         struct list_head transfer_list;
719 };
720
721 /**
722  * struct spi_message - one multi-segment SPI transaction
723  * @transfers: list of transfer segments in this transaction
724  * @spi: SPI device to which the transaction is queued
725  * @is_dma_mapped: if true, the caller provided both dma and cpu virtual
726  *      addresses for each transfer buffer
727  * @complete: called to report transaction completions
728  * @context: the argument to complete() when it's called
729  * @frame_length: the total number of bytes in the message
730  * @actual_length: the total number of bytes that were transferred in all
731  *      successful segments
732  * @status: zero for success, else negative errno
733  * @queue: for use by whichever driver currently owns the message
734  * @state: for use by whichever driver currently owns the message
735  *
736  * A @spi_message is used to execute an atomic sequence of data transfers,
737  * each represented by a struct spi_transfer.  The sequence is "atomic"
738  * in the sense that no other spi_message may use that SPI bus until that
739  * sequence completes.  On some systems, many such sequences can execute as
740  * as single programmed DMA transfer.  On all systems, these messages are
741  * queued, and might complete after transactions to other devices.  Messages
742  * sent to a given spi_device are always executed in FIFO order.
743  *
744  * The code that submits an spi_message (and its spi_transfers)
745  * to the lower layers is responsible for managing its memory.
746  * Zero-initialize every field you don't set up explicitly, to
747  * insulate against future API updates.  After you submit a message
748  * and its transfers, ignore them until its completion callback.
749  */
750 struct spi_message {
751         struct list_head        transfers;
752
753         struct spi_device       *spi;
754
755         unsigned                is_dma_mapped:1;
756
757         /* REVISIT:  we might want a flag affecting the behavior of the
758          * last transfer ... allowing things like "read 16 bit length L"
759          * immediately followed by "read L bytes".  Basically imposing
760          * a specific message scheduling algorithm.
761          *
762          * Some controller drivers (message-at-a-time queue processing)
763          * could provide that as their default scheduling algorithm.  But
764          * others (with multi-message pipelines) could need a flag to
765          * tell them about such special cases.
766          */
767
768         /* completion is reported through a callback */
769         void                    (*complete)(void *context);
770         void                    *context;
771         unsigned                frame_length;
772         unsigned                actual_length;
773         int                     status;
774
775         /* for optional use by whatever driver currently owns the
776          * spi_message ...  between calls to spi_async and then later
777          * complete(), that's the spi_master controller driver.
778          */
779         struct list_head        queue;
780         void                    *state;
781 };
782
783 static inline void spi_message_init_no_memset(struct spi_message *m)
784 {
785         INIT_LIST_HEAD(&m->transfers);
786 }
787
788 static inline void spi_message_init(struct spi_message *m)
789 {
790         memset(m, 0, sizeof *m);
791         spi_message_init_no_memset(m);
792 }
793
794 static inline void
795 spi_message_add_tail(struct spi_transfer *t, struct spi_message *m)
796 {
797         list_add_tail(&t->transfer_list, &m->transfers);
798 }
799
800 static inline void
801 spi_transfer_del(struct spi_transfer *t)
802 {
803         list_del(&t->transfer_list);
804 }
805
806 /**
807  * spi_message_init_with_transfers - Initialize spi_message and append transfers
808  * @m: spi_message to be initialized
809  * @xfers: An array of spi transfers
810  * @num_xfers: Number of items in the xfer array
811  *
812  * This function initializes the given spi_message and adds each spi_transfer in
813  * the given array to the message.
814  */
815 static inline void
816 spi_message_init_with_transfers(struct spi_message *m,
817 struct spi_transfer *xfers, unsigned int num_xfers)
818 {
819         unsigned int i;
820
821         spi_message_init(m);
822         for (i = 0; i < num_xfers; ++i)
823                 spi_message_add_tail(&xfers[i], m);
824 }
825
826 /* It's fine to embed message and transaction structures in other data
827  * structures so long as you don't free them while they're in use.
828  */
829
830 static inline struct spi_message *spi_message_alloc(unsigned ntrans, gfp_t flags)
831 {
832         struct spi_message *m;
833
834         m = kzalloc(sizeof(struct spi_message)
835                         + ntrans * sizeof(struct spi_transfer),
836                         flags);
837         if (m) {
838                 unsigned i;
839                 struct spi_transfer *t = (struct spi_transfer *)(m + 1);
840
841                 INIT_LIST_HEAD(&m->transfers);
842                 for (i = 0; i < ntrans; i++, t++)
843                         spi_message_add_tail(t, m);
844         }
845         return m;
846 }
847
848 static inline void spi_message_free(struct spi_message *m)
849 {
850         kfree(m);
851 }
852
853 extern int spi_setup(struct spi_device *spi);
854 extern int spi_async(struct spi_device *spi, struct spi_message *message);
855 extern int spi_async_locked(struct spi_device *spi,
856                             struct spi_message *message);
857
858 static inline size_t
859 spi_max_transfer_size(struct spi_device *spi)
860 {
861         struct spi_master *master = spi->master;
862         if (!master->max_transfer_size)
863                 return SIZE_MAX;
864         return master->max_transfer_size(spi);
865 }
866
867 /*---------------------------------------------------------------------------*/
868
869 /* All these synchronous SPI transfer routines are utilities layered
870  * over the core async transfer primitive.  Here, "synchronous" means
871  * they will sleep uninterruptibly until the async transfer completes.
872  */
873
874 extern int spi_sync(struct spi_device *spi, struct spi_message *message);
875 extern int spi_sync_locked(struct spi_device *spi, struct spi_message *message);
876 extern int spi_bus_lock(struct spi_master *master);
877 extern int spi_bus_unlock(struct spi_master *master);
878
879 /**
880  * spi_write - SPI synchronous write
881  * @spi: device to which data will be written
882  * @buf: data buffer
883  * @len: data buffer size
884  * Context: can sleep
885  *
886  * This function writes the buffer @buf.
887  * Callable only from contexts that can sleep.
888  *
889  * Return: zero on success, else a negative error code.
890  */
891 static inline int
892 spi_write(struct spi_device *spi, const void *buf, size_t len)
893 {
894         struct spi_transfer     t = {
895                         .tx_buf         = buf,
896                         .len            = len,
897                 };
898         struct spi_message      m;
899
900         spi_message_init(&m);
901         spi_message_add_tail(&t, &m);
902         return spi_sync(spi, &m);
903 }
904
905 /**
906  * spi_read - SPI synchronous read
907  * @spi: device from which data will be read
908  * @buf: data buffer
909  * @len: data buffer size
910  * Context: can sleep
911  *
912  * This function reads the buffer @buf.
913  * Callable only from contexts that can sleep.
914  *
915  * Return: zero on success, else a negative error code.
916  */
917 static inline int
918 spi_read(struct spi_device *spi, void *buf, size_t len)
919 {
920         struct spi_transfer     t = {
921                         .rx_buf         = buf,
922                         .len            = len,
923                 };
924         struct spi_message      m;
925
926         spi_message_init(&m);
927         spi_message_add_tail(&t, &m);
928         return spi_sync(spi, &m);
929 }
930
931 /**
932  * spi_sync_transfer - synchronous SPI data transfer
933  * @spi: device with which data will be exchanged
934  * @xfers: An array of spi_transfers
935  * @num_xfers: Number of items in the xfer array
936  * Context: can sleep
937  *
938  * Does a synchronous SPI data transfer of the given spi_transfer array.
939  *
940  * For more specific semantics see spi_sync().
941  *
942  * Return: Return: zero on success, else a negative error code.
943  */
944 static inline int
945 spi_sync_transfer(struct spi_device *spi, struct spi_transfer *xfers,
946         unsigned int num_xfers)
947 {
948         struct spi_message msg;
949
950         spi_message_init_with_transfers(&msg, xfers, num_xfers);
951
952         return spi_sync(spi, &msg);
953 }
954
955 /* this copies txbuf and rxbuf data; for small transfers only! */
956 extern int spi_write_then_read(struct spi_device *spi,
957                 const void *txbuf, unsigned n_tx,
958                 void *rxbuf, unsigned n_rx);
959
960 /**
961  * spi_w8r8 - SPI synchronous 8 bit write followed by 8 bit read
962  * @spi: device with which data will be exchanged
963  * @cmd: command to be written before data is read back
964  * Context: can sleep
965  *
966  * Callable only from contexts that can sleep.
967  *
968  * Return: the (unsigned) eight bit number returned by the
969  * device, or else a negative error code.
970  */
971 static inline ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)
972 {
973         ssize_t                 status;
974         u8                      result;
975
976         status = spi_write_then_read(spi, &cmd, 1, &result, 1);
977
978         /* return negative errno or unsigned value */
979         return (status < 0) ? status : result;
980 }
981
982 /**
983  * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read
984  * @spi: device with which data will be exchanged
985  * @cmd: command to be written before data is read back
986  * Context: can sleep
987  *
988  * The number is returned in wire-order, which is at least sometimes
989  * big-endian.
990  *
991  * Callable only from contexts that can sleep.
992  *
993  * Return: the (unsigned) sixteen bit number returned by the
994  * device, or else a negative error code.
995  */
996 static inline ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)
997 {
998         ssize_t                 status;
999         u16                     result;
1000
1001         status = spi_write_then_read(spi, &cmd, 1, &result, 2);
1002
1003         /* return negative errno or unsigned value */
1004         return (status < 0) ? status : result;
1005 }
1006
1007 /**
1008  * spi_w8r16be - SPI synchronous 8 bit write followed by 16 bit big-endian read
1009  * @spi: device with which data will be exchanged
1010  * @cmd: command to be written before data is read back
1011  * Context: can sleep
1012  *
1013  * This function is similar to spi_w8r16, with the exception that it will
1014  * convert the read 16 bit data word from big-endian to native endianness.
1015  *
1016  * Callable only from contexts that can sleep.
1017  *
1018  * Return: the (unsigned) sixteen bit number returned by the device in cpu
1019  * endianness, or else a negative error code.
1020  */
1021 static inline ssize_t spi_w8r16be(struct spi_device *spi, u8 cmd)
1022
1023 {
1024         ssize_t status;
1025         __be16 result;
1026
1027         status = spi_write_then_read(spi, &cmd, 1, &result, 2);
1028         if (status < 0)
1029                 return status;
1030
1031         return be16_to_cpu(result);
1032 }
1033
1034 /**
1035  * struct spi_flash_read_message - flash specific information for
1036  * spi-masters that provide accelerated flash read interfaces
1037  * @buf: buffer to read data
1038  * @from: offset within the flash from where data is to be read
1039  * @len: length of data to be read
1040  * @retlen: actual length of data read
1041  * @read_opcode: read_opcode to be used to communicate with flash
1042  * @addr_width: number of address bytes
1043  * @dummy_bytes: number of dummy bytes
1044  * @opcode_nbits: number of lines to send opcode
1045  * @addr_nbits: number of lines to send address
1046  * @data_nbits: number of lines for data
1047  */
1048 struct spi_flash_read_message {
1049         void *buf;
1050         loff_t from;
1051         size_t len;
1052         size_t retlen;
1053         u8 read_opcode;
1054         u8 addr_width;
1055         u8 dummy_bytes;
1056         u8 opcode_nbits;
1057         u8 addr_nbits;
1058         u8 data_nbits;
1059 };
1060
1061 /* SPI core interface for flash read support */
1062 static inline bool spi_flash_read_supported(struct spi_device *spi)
1063 {
1064         return spi->master->spi_flash_read ? true : false;
1065 }
1066
1067 int spi_flash_read(struct spi_device *spi,
1068                    struct spi_flash_read_message *msg);
1069
1070 /*---------------------------------------------------------------------------*/
1071
1072 /*
1073  * INTERFACE between board init code and SPI infrastructure.
1074  *
1075  * No SPI driver ever sees these SPI device table segments, but
1076  * it's how the SPI core (or adapters that get hotplugged) grows
1077  * the driver model tree.
1078  *
1079  * As a rule, SPI devices can't be probed.  Instead, board init code
1080  * provides a table listing the devices which are present, with enough
1081  * information to bind and set up the device's driver.  There's basic
1082  * support for nonstatic configurations too; enough to handle adding
1083  * parport adapters, or microcontrollers acting as USB-to-SPI bridges.
1084  */
1085
1086 /**
1087  * struct spi_board_info - board-specific template for a SPI device
1088  * @modalias: Initializes spi_device.modalias; identifies the driver.
1089  * @platform_data: Initializes spi_device.platform_data; the particular
1090  *      data stored there is driver-specific.
1091  * @controller_data: Initializes spi_device.controller_data; some
1092  *      controllers need hints about hardware setup, e.g. for DMA.
1093  * @irq: Initializes spi_device.irq; depends on how the board is wired.
1094  * @max_speed_hz: Initializes spi_device.max_speed_hz; based on limits
1095  *      from the chip datasheet and board-specific signal quality issues.
1096  * @bus_num: Identifies which spi_master parents the spi_device; unused
1097  *      by spi_new_device(), and otherwise depends on board wiring.
1098  * @chip_select: Initializes spi_device.chip_select; depends on how
1099  *      the board is wired.
1100  * @mode: Initializes spi_device.mode; based on the chip datasheet, board
1101  *      wiring (some devices support both 3WIRE and standard modes), and
1102  *      possibly presence of an inverter in the chipselect path.
1103  *
1104  * When adding new SPI devices to the device tree, these structures serve
1105  * as a partial device template.  They hold information which can't always
1106  * be determined by drivers.  Information that probe() can establish (such
1107  * as the default transfer wordsize) is not included here.
1108  *
1109  * These structures are used in two places.  Their primary role is to
1110  * be stored in tables of board-specific device descriptors, which are
1111  * declared early in board initialization and then used (much later) to
1112  * populate a controller's device tree after the that controller's driver
1113  * initializes.  A secondary (and atypical) role is as a parameter to
1114  * spi_new_device() call, which happens after those controller drivers
1115  * are active in some dynamic board configuration models.
1116  */
1117 struct spi_board_info {
1118         /* the device name and module name are coupled, like platform_bus;
1119          * "modalias" is normally the driver name.
1120          *
1121          * platform_data goes to spi_device.dev.platform_data,
1122          * controller_data goes to spi_device.controller_data,
1123          * irq is copied too
1124          */
1125         char            modalias[SPI_NAME_SIZE];
1126         const void      *platform_data;
1127         void            *controller_data;
1128         int             irq;
1129
1130         /* slower signaling on noisy or low voltage boards */
1131         u32             max_speed_hz;
1132
1133
1134         /* bus_num is board specific and matches the bus_num of some
1135          * spi_master that will probably be registered later.
1136          *
1137          * chip_select reflects how this chip is wired to that master;
1138          * it's less than num_chipselect.
1139          */
1140         u16             bus_num;
1141         u16             chip_select;
1142
1143         /* mode becomes spi_device.mode, and is essential for chips
1144          * where the default of SPI_CS_HIGH = 0 is wrong.
1145          */
1146         u16             mode;
1147
1148         /* ... may need additional spi_device chip config data here.
1149          * avoid stuff protocol drivers can set; but include stuff
1150          * needed to behave without being bound to a driver:
1151          *  - quirks like clock rate mattering when not selected
1152          */
1153 };
1154
1155 #ifdef  CONFIG_SPI
1156 extern int
1157 spi_register_board_info(struct spi_board_info const *info, unsigned n);
1158 #else
1159 /* board init code may ignore whether SPI is configured or not */
1160 static inline int
1161 spi_register_board_info(struct spi_board_info const *info, unsigned n)
1162         { return 0; }
1163 #endif
1164
1165
1166 /* If you're hotplugging an adapter with devices (parport, usb, etc)
1167  * use spi_new_device() to describe each device.  You can also call
1168  * spi_unregister_device() to start making that device vanish, but
1169  * normally that would be handled by spi_unregister_master().
1170  *
1171  * You can also use spi_alloc_device() and spi_add_device() to use a two
1172  * stage registration sequence for each spi_device.  This gives the caller
1173  * some more control over the spi_device structure before it is registered,
1174  * but requires that caller to initialize fields that would otherwise
1175  * be defined using the board info.
1176  */
1177 extern struct spi_device *
1178 spi_alloc_device(struct spi_master *master);
1179
1180 extern int
1181 spi_add_device(struct spi_device *spi);
1182
1183 extern struct spi_device *
1184 spi_new_device(struct spi_master *, struct spi_board_info *);
1185
1186 extern void spi_unregister_device(struct spi_device *spi);
1187
1188 extern const struct spi_device_id *
1189 spi_get_device_id(const struct spi_device *sdev);
1190
1191 static inline bool
1192 spi_transfer_is_last(struct spi_master *master, struct spi_transfer *xfer)
1193 {
1194         return list_is_last(&xfer->transfer_list, &master->cur_msg->transfers);
1195 }
1196
1197 #endif /* __LINUX_SPI_H */