]> Git Repo - linux.git/blob - include/linux/spi/spi.h
spi: Add a PTP system timestamp to the transfer structure
[linux.git] / include / linux / spi / spi.h
1 /* SPDX-License-Identifier: GPL-2.0-or-later
2  *
3  * Copyright (C) 2005 David Brownell
4  */
5
6 #ifndef __LINUX_SPI_H
7 #define __LINUX_SPI_H
8
9 #include <linux/device.h>
10 #include <linux/mod_devicetable.h>
11 #include <linux/slab.h>
12 #include <linux/kthread.h>
13 #include <linux/completion.h>
14 #include <linux/scatterlist.h>
15 #include <linux/gpio/consumer.h>
16 #include <linux/ptp_clock_kernel.h>
17
18 struct dma_chan;
19 struct property_entry;
20 struct spi_controller;
21 struct spi_transfer;
22 struct spi_controller_mem_ops;
23
24 /*
25  * INTERFACES between SPI master-side drivers and SPI slave protocol handlers,
26  * and SPI infrastructure.
27  */
28 extern struct bus_type spi_bus_type;
29
30 /**
31  * struct spi_statistics - statistics for spi transfers
32  * @lock:          lock protecting this structure
33  *
34  * @messages:      number of spi-messages handled
35  * @transfers:     number of spi_transfers handled
36  * @errors:        number of errors during spi_transfer
37  * @timedout:      number of timeouts during spi_transfer
38  *
39  * @spi_sync:      number of times spi_sync is used
40  * @spi_sync_immediate:
41  *                 number of times spi_sync is executed immediately
42  *                 in calling context without queuing and scheduling
43  * @spi_async:     number of times spi_async is used
44  *
45  * @bytes:         number of bytes transferred to/from device
46  * @bytes_tx:      number of bytes sent to device
47  * @bytes_rx:      number of bytes received from device
48  *
49  * @transfer_bytes_histo:
50  *                 transfer bytes histogramm
51  *
52  * @transfers_split_maxsize:
53  *                 number of transfers that have been split because of
54  *                 maxsize limit
55  */
56 struct spi_statistics {
57         spinlock_t              lock; /* lock for the whole structure */
58
59         unsigned long           messages;
60         unsigned long           transfers;
61         unsigned long           errors;
62         unsigned long           timedout;
63
64         unsigned long           spi_sync;
65         unsigned long           spi_sync_immediate;
66         unsigned long           spi_async;
67
68         unsigned long long      bytes;
69         unsigned long long      bytes_rx;
70         unsigned long long      bytes_tx;
71
72 #define SPI_STATISTICS_HISTO_SIZE 17
73         unsigned long transfer_bytes_histo[SPI_STATISTICS_HISTO_SIZE];
74
75         unsigned long transfers_split_maxsize;
76 };
77
78 void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
79                                        struct spi_transfer *xfer,
80                                        struct spi_controller *ctlr);
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 - Controller side proxy for an SPI slave device
95  * @dev: Driver model representation of the device.
96  * @controller: SPI controller used with the device.
97  * @master: Copy of controller, for backwards compatibility.
98  * @max_speed_hz: Maximum clock rate to be used with this chip
99  *      (on this board); may be changed by the device's driver.
100  *      The spi_transfer.speed_hz can override this for each transfer.
101  * @chip_select: Chipselect, distinguishing chips handled by @controller.
102  * @mode: The spi mode defines how data is clocked out and in.
103  *      This may be changed by the device's driver.
104  *      The "active low" default for chipselect mode can be overridden
105  *      (by specifying SPI_CS_HIGH) as can the "MSB first" default for
106  *      each word in a transfer (by specifying SPI_LSB_FIRST).
107  * @bits_per_word: Data transfers involve one or more words; word sizes
108  *      like eight or 12 bits are common.  In-memory wordsizes are
109  *      powers of two bytes (e.g. 20 bit samples use 32 bits).
110  *      This may be changed by the device's driver, or left at the
111  *      default (0) indicating protocol words are eight bit bytes.
112  *      The spi_transfer.bits_per_word can override this for each transfer.
113  * @rt: Make the pump thread real time priority.
114  * @irq: Negative, or the number passed to request_irq() to receive
115  *      interrupts from this device.
116  * @controller_state: Controller's runtime state
117  * @controller_data: Board-specific definitions for controller, such as
118  *      FIFO initialization parameters; from board_info.controller_data
119  * @modalias: Name of the driver to use with this device, or an alias
120  *      for that name.  This appears in the sysfs "modalias" attribute
121  *      for driver coldplugging, and in uevents used for hotplugging
122  * @cs_gpio: LEGACY: gpio number of the chipselect line (optional, -ENOENT when
123  *      not using a GPIO line) use cs_gpiod in new drivers by opting in on
124  *      the spi_master.
125  * @cs_gpiod: gpio descriptor of the chipselect line (optional, NULL when
126  *      not using a GPIO line)
127  * @word_delay_usecs: microsecond delay to be inserted between consecutive
128  *      words of a transfer
129  *
130  * @statistics: statistics for the spi_device
131  *
132  * A @spi_device is used to interchange data between an SPI slave
133  * (usually a discrete chip) and CPU memory.
134  *
135  * In @dev, the platform_data is used to hold information about this
136  * device that's meaningful to the device's protocol driver, but not
137  * to its controller.  One example might be an identifier for a chip
138  * variant with slightly different functionality; another might be
139  * information about how this particular board wires the chip's pins.
140  */
141 struct spi_device {
142         struct device           dev;
143         struct spi_controller   *controller;
144         struct spi_controller   *master;        /* compatibility layer */
145         u32                     max_speed_hz;
146         u8                      chip_select;
147         u8                      bits_per_word;
148         bool                    rt;
149         u32                     mode;
150 #define SPI_CPHA        0x01                    /* clock phase */
151 #define SPI_CPOL        0x02                    /* clock polarity */
152 #define SPI_MODE_0      (0|0)                   /* (original MicroWire) */
153 #define SPI_MODE_1      (0|SPI_CPHA)
154 #define SPI_MODE_2      (SPI_CPOL|0)
155 #define SPI_MODE_3      (SPI_CPOL|SPI_CPHA)
156 #define SPI_CS_HIGH     0x04                    /* chipselect active high? */
157 #define SPI_LSB_FIRST   0x08                    /* per-word bits-on-wire */
158 #define SPI_3WIRE       0x10                    /* SI/SO signals shared */
159 #define SPI_LOOP        0x20                    /* loopback mode */
160 #define SPI_NO_CS       0x40                    /* 1 dev/bus, no chipselect */
161 #define SPI_READY       0x80                    /* slave pulls low to pause */
162 #define SPI_TX_DUAL     0x100                   /* transmit with 2 wires */
163 #define SPI_TX_QUAD     0x200                   /* transmit with 4 wires */
164 #define SPI_RX_DUAL     0x400                   /* receive with 2 wires */
165 #define SPI_RX_QUAD     0x800                   /* receive with 4 wires */
166 #define SPI_CS_WORD     0x1000                  /* toggle cs after each word */
167 #define SPI_TX_OCTAL    0x2000                  /* transmit with 8 wires */
168 #define SPI_RX_OCTAL    0x4000                  /* receive with 8 wires */
169 #define SPI_3WIRE_HIZ   0x8000                  /* high impedance turnaround */
170         int                     irq;
171         void                    *controller_state;
172         void                    *controller_data;
173         char                    modalias[SPI_NAME_SIZE];
174         const char              *driver_override;
175         int                     cs_gpio;        /* LEGACY: chip select gpio */
176         struct gpio_desc        *cs_gpiod;      /* chip select gpio desc */
177         uint8_t                 word_delay_usecs; /* inter-word delay */
178
179         /* the statistics */
180         struct spi_statistics   statistics;
181
182         /*
183          * likely need more hooks for more protocol options affecting how
184          * the controller talks to each chip, like:
185          *  - memory packing (12 bit samples into low bits, others zeroed)
186          *  - priority
187          *  - chipselect delays
188          *  - ...
189          */
190 };
191
192 static inline struct spi_device *to_spi_device(struct device *dev)
193 {
194         return dev ? container_of(dev, struct spi_device, dev) : NULL;
195 }
196
197 /* most drivers won't need to care about device refcounting */
198 static inline struct spi_device *spi_dev_get(struct spi_device *spi)
199 {
200         return (spi && get_device(&spi->dev)) ? spi : NULL;
201 }
202
203 static inline void spi_dev_put(struct spi_device *spi)
204 {
205         if (spi)
206                 put_device(&spi->dev);
207 }
208
209 /* ctldata is for the bus_controller driver's runtime state */
210 static inline void *spi_get_ctldata(struct spi_device *spi)
211 {
212         return spi->controller_state;
213 }
214
215 static inline void spi_set_ctldata(struct spi_device *spi, void *state)
216 {
217         spi->controller_state = state;
218 }
219
220 /* device driver data */
221
222 static inline void spi_set_drvdata(struct spi_device *spi, void *data)
223 {
224         dev_set_drvdata(&spi->dev, data);
225 }
226
227 static inline void *spi_get_drvdata(struct spi_device *spi)
228 {
229         return dev_get_drvdata(&spi->dev);
230 }
231
232 struct spi_message;
233 struct spi_transfer;
234
235 /**
236  * struct spi_driver - Host side "protocol" driver
237  * @id_table: List of SPI devices supported by this driver
238  * @probe: Binds this driver to the spi device.  Drivers can verify
239  *      that the device is actually present, and may need to configure
240  *      characteristics (such as bits_per_word) which weren't needed for
241  *      the initial configuration done during system setup.
242  * @remove: Unbinds this driver from the spi device
243  * @shutdown: Standard shutdown callback used during system state
244  *      transitions such as powerdown/halt and kexec
245  * @driver: SPI device drivers should initialize the name and owner
246  *      field of this structure.
247  *
248  * This represents the kind of device driver that uses SPI messages to
249  * interact with the hardware at the other end of a SPI link.  It's called
250  * a "protocol" driver because it works through messages rather than talking
251  * directly to SPI hardware (which is what the underlying SPI controller
252  * driver does to pass those messages).  These protocols are defined in the
253  * specification for the device(s) supported by the driver.
254  *
255  * As a rule, those device protocols represent the lowest level interface
256  * supported by a driver, and it will support upper level interfaces too.
257  * Examples of such upper levels include frameworks like MTD, networking,
258  * MMC, RTC, filesystem character device nodes, and hardware monitoring.
259  */
260 struct spi_driver {
261         const struct spi_device_id *id_table;
262         int                     (*probe)(struct spi_device *spi);
263         int                     (*remove)(struct spi_device *spi);
264         void                    (*shutdown)(struct spi_device *spi);
265         struct device_driver    driver;
266 };
267
268 static inline struct spi_driver *to_spi_driver(struct device_driver *drv)
269 {
270         return drv ? container_of(drv, struct spi_driver, driver) : NULL;
271 }
272
273 extern int __spi_register_driver(struct module *owner, struct spi_driver *sdrv);
274
275 /**
276  * spi_unregister_driver - reverse effect of spi_register_driver
277  * @sdrv: the driver to unregister
278  * Context: can sleep
279  */
280 static inline void spi_unregister_driver(struct spi_driver *sdrv)
281 {
282         if (sdrv)
283                 driver_unregister(&sdrv->driver);
284 }
285
286 /* use a define to avoid include chaining to get THIS_MODULE */
287 #define spi_register_driver(driver) \
288         __spi_register_driver(THIS_MODULE, driver)
289
290 /**
291  * module_spi_driver() - Helper macro for registering a SPI driver
292  * @__spi_driver: spi_driver struct
293  *
294  * Helper macro for SPI drivers which do not do anything special in module
295  * init/exit. This eliminates a lot of boilerplate. Each module may only
296  * use this macro once, and calling it replaces module_init() and module_exit()
297  */
298 #define module_spi_driver(__spi_driver) \
299         module_driver(__spi_driver, spi_register_driver, \
300                         spi_unregister_driver)
301
302 /**
303  * struct spi_controller - interface to SPI master or slave controller
304  * @dev: device interface to this driver
305  * @list: link with the global spi_controller list
306  * @bus_num: board-specific (and often SOC-specific) identifier for a
307  *      given SPI controller.
308  * @num_chipselect: chipselects are used to distinguish individual
309  *      SPI slaves, and are numbered from zero to num_chipselects.
310  *      each slave has a chipselect signal, but it's common that not
311  *      every chipselect is connected to a slave.
312  * @dma_alignment: SPI controller constraint on DMA buffers alignment.
313  * @mode_bits: flags understood by this controller driver
314  * @bits_per_word_mask: A mask indicating which values of bits_per_word are
315  *      supported by the driver. Bit n indicates that a bits_per_word n+1 is
316  *      supported. If set, the SPI core will reject any transfer with an
317  *      unsupported bits_per_word. If not set, this value is simply ignored,
318  *      and it's up to the individual driver to perform any validation.
319  * @min_speed_hz: Lowest supported transfer speed
320  * @max_speed_hz: Highest supported transfer speed
321  * @flags: other constraints relevant to this driver
322  * @slave: indicates that this is an SPI slave controller
323  * @max_transfer_size: function that returns the max transfer size for
324  *      a &spi_device; may be %NULL, so the default %SIZE_MAX will be used.
325  * @max_message_size: function that returns the max message size for
326  *      a &spi_device; may be %NULL, so the default %SIZE_MAX will be used.
327  * @io_mutex: mutex for physical bus access
328  * @bus_lock_spinlock: spinlock for SPI bus locking
329  * @bus_lock_mutex: mutex for exclusion of multiple callers
330  * @bus_lock_flag: indicates that the SPI bus is locked for exclusive use
331  * @setup: updates the device mode and clocking records used by a
332  *      device's SPI controller; protocol code may call this.  This
333  *      must fail if an unrecognized or unsupported mode is requested.
334  *      It's always safe to call this unless transfers are pending on
335  *      the device whose settings are being modified.
336  * @set_cs_timing: optional hook for SPI devices to request SPI master
337  * controller for configuring specific CS setup time, hold time and inactive
338  * delay interms of clock counts
339  * @transfer: adds a message to the controller's transfer queue.
340  * @cleanup: frees controller-specific state
341  * @can_dma: determine whether this controller supports DMA
342  * @queued: whether this controller is providing an internal message queue
343  * @kworker: thread struct for message pump
344  * @kworker_task: pointer to task for message pump kworker thread
345  * @pump_messages: work struct for scheduling work to the message pump
346  * @queue_lock: spinlock to syncronise access to message queue
347  * @queue: message queue
348  * @idling: the device is entering idle state
349  * @cur_msg: the currently in-flight message
350  * @cur_msg_prepared: spi_prepare_message was called for the currently
351  *                    in-flight message
352  * @cur_msg_mapped: message has been mapped for DMA
353  * @xfer_completion: used by core transfer_one_message()
354  * @busy: message pump is busy
355  * @running: message pump is running
356  * @rt: whether this queue is set to run as a realtime task
357  * @auto_runtime_pm: the core should ensure a runtime PM reference is held
358  *                   while the hardware is prepared, using the parent
359  *                   device for the spidev
360  * @max_dma_len: Maximum length of a DMA transfer for the device.
361  * @prepare_transfer_hardware: a message will soon arrive from the queue
362  *      so the subsystem requests the driver to prepare the transfer hardware
363  *      by issuing this call
364  * @transfer_one_message: the subsystem calls the driver to transfer a single
365  *      message while queuing transfers that arrive in the meantime. When the
366  *      driver is finished with this message, it must call
367  *      spi_finalize_current_message() so the subsystem can issue the next
368  *      message
369  * @unprepare_transfer_hardware: there are currently no more messages on the
370  *      queue so the subsystem notifies the driver that it may relax the
371  *      hardware by issuing this call
372  *
373  * @set_cs: set the logic level of the chip select line.  May be called
374  *          from interrupt context.
375  * @prepare_message: set up the controller to transfer a single message,
376  *                   for example doing DMA mapping.  Called from threaded
377  *                   context.
378  * @transfer_one: transfer a single spi_transfer.
379  *                  - return 0 if the transfer is finished,
380  *                  - return 1 if the transfer is still in progress. When
381  *                    the driver is finished with this transfer it must
382  *                    call spi_finalize_current_transfer() so the subsystem
383  *                    can issue the next transfer. Note: transfer_one and
384  *                    transfer_one_message are mutually exclusive; when both
385  *                    are set, the generic subsystem does not call your
386  *                    transfer_one callback.
387  * @handle_err: the subsystem calls the driver to handle an error that occurs
388  *              in the generic implementation of transfer_one_message().
389  * @mem_ops: optimized/dedicated operations for interactions with SPI memory.
390  *           This field is optional and should only be implemented if the
391  *           controller has native support for memory like operations.
392  * @unprepare_message: undo any work done by prepare_message().
393  * @slave_abort: abort the ongoing transfer request on an SPI slave controller
394  * @cs_gpios: LEGACY: array of GPIO descs to use as chip select lines; one per
395  *      CS number. Any individual value may be -ENOENT for CS lines that
396  *      are not GPIOs (driven by the SPI controller itself). Use the cs_gpiods
397  *      in new drivers.
398  * @cs_gpiods: Array of GPIO descs to use as chip select lines; one per CS
399  *      number. Any individual value may be NULL for CS lines that
400  *      are not GPIOs (driven by the SPI controller itself).
401  * @use_gpio_descriptors: Turns on the code in the SPI core to parse and grab
402  *      GPIO descriptors rather than using global GPIO numbers grabbed by the
403  *      driver. This will fill in @cs_gpiods and @cs_gpios should not be used,
404  *      and SPI devices will have the cs_gpiod assigned rather than cs_gpio.
405  * @statistics: statistics for the spi_controller
406  * @dma_tx: DMA transmit channel
407  * @dma_rx: DMA receive channel
408  * @dummy_rx: dummy receive buffer for full-duplex devices
409  * @dummy_tx: dummy transmit buffer for full-duplex devices
410  * @fw_translate_cs: If the boot firmware uses different numbering scheme
411  *      what Linux expects, this optional hook can be used to translate
412  *      between the two.
413  * @ptp_sts_supported: If the driver sets this to true, it must provide a
414  *      time snapshot in @spi_transfer->ptp_sts as close as possible to the
415  *      moment in time when @spi_transfer->ptp_sts_word_pre and
416  *      @spi_transfer->ptp_sts_word_post were transmitted.
417  *      If the driver does not set this, the SPI core takes the snapshot as
418  *      close to the driver hand-over as possible.
419  *
420  * Each SPI controller can communicate with one or more @spi_device
421  * children.  These make a small bus, sharing MOSI, MISO and SCK signals
422  * but not chip select signals.  Each device may be configured to use a
423  * different clock rate, since those shared signals are ignored unless
424  * the chip is selected.
425  *
426  * The driver for an SPI controller manages access to those devices through
427  * a queue of spi_message transactions, copying data between CPU memory and
428  * an SPI slave device.  For each such message it queues, it calls the
429  * message's completion function when the transaction completes.
430  */
431 struct spi_controller {
432         struct device   dev;
433
434         struct list_head list;
435
436         /* other than negative (== assign one dynamically), bus_num is fully
437          * board-specific.  usually that simplifies to being SOC-specific.
438          * example:  one SOC has three SPI controllers, numbered 0..2,
439          * and one board's schematics might show it using SPI-2.  software
440          * would normally use bus_num=2 for that controller.
441          */
442         s16                     bus_num;
443
444         /* chipselects will be integral to many controllers; some others
445          * might use board-specific GPIOs.
446          */
447         u16                     num_chipselect;
448
449         /* some SPI controllers pose alignment requirements on DMAable
450          * buffers; let protocol drivers know about these requirements.
451          */
452         u16                     dma_alignment;
453
454         /* spi_device.mode flags understood by this controller driver */
455         u32                     mode_bits;
456
457         /* bitmask of supported bits_per_word for transfers */
458         u32                     bits_per_word_mask;
459 #define SPI_BPW_MASK(bits) BIT((bits) - 1)
460 #define SPI_BPW_RANGE_MASK(min, max) GENMASK((max) - 1, (min) - 1)
461
462         /* limits on transfer speed */
463         u32                     min_speed_hz;
464         u32                     max_speed_hz;
465
466         /* other constraints relevant to this driver */
467         u16                     flags;
468 #define SPI_CONTROLLER_HALF_DUPLEX      BIT(0)  /* can't do full duplex */
469 #define SPI_CONTROLLER_NO_RX            BIT(1)  /* can't do buffer read */
470 #define SPI_CONTROLLER_NO_TX            BIT(2)  /* can't do buffer write */
471 #define SPI_CONTROLLER_MUST_RX          BIT(3)  /* requires rx */
472 #define SPI_CONTROLLER_MUST_TX          BIT(4)  /* requires tx */
473
474 #define SPI_MASTER_GPIO_SS              BIT(5)  /* GPIO CS must select slave */
475
476         /* flag indicating this is an SPI slave controller */
477         bool                    slave;
478
479         /*
480          * on some hardware transfer / message size may be constrained
481          * the limit may depend on device transfer settings
482          */
483         size_t (*max_transfer_size)(struct spi_device *spi);
484         size_t (*max_message_size)(struct spi_device *spi);
485
486         /* I/O mutex */
487         struct mutex            io_mutex;
488
489         /* lock and mutex for SPI bus locking */
490         spinlock_t              bus_lock_spinlock;
491         struct mutex            bus_lock_mutex;
492
493         /* flag indicating that the SPI bus is locked for exclusive use */
494         bool                    bus_lock_flag;
495
496         /* Setup mode and clock, etc (spi driver may call many times).
497          *
498          * IMPORTANT:  this may be called when transfers to another
499          * device are active.  DO NOT UPDATE SHARED REGISTERS in ways
500          * which could break those transfers.
501          */
502         int                     (*setup)(struct spi_device *spi);
503
504         /*
505          * set_cs_timing() method is for SPI controllers that supports
506          * configuring CS timing.
507          *
508          * This hook allows SPI client drivers to request SPI controllers
509          * to configure specific CS timing through spi_set_cs_timing() after
510          * spi_setup().
511          */
512         void (*set_cs_timing)(struct spi_device *spi, u8 setup_clk_cycles,
513                               u8 hold_clk_cycles, u8 inactive_clk_cycles);
514
515         /* bidirectional bulk transfers
516          *
517          * + The transfer() method may not sleep; its main role is
518          *   just to add the message to the queue.
519          * + For now there's no remove-from-queue operation, or
520          *   any other request management
521          * + To a given spi_device, message queueing is pure fifo
522          *
523          * + The controller's main job is to process its message queue,
524          *   selecting a chip (for masters), then transferring data
525          * + If there are multiple spi_device children, the i/o queue
526          *   arbitration algorithm is unspecified (round robin, fifo,
527          *   priority, reservations, preemption, etc)
528          *
529          * + Chipselect stays active during the entire message
530          *   (unless modified by spi_transfer.cs_change != 0).
531          * + The message transfers use clock and SPI mode parameters
532          *   previously established by setup() for this device
533          */
534         int                     (*transfer)(struct spi_device *spi,
535                                                 struct spi_message *mesg);
536
537         /* called on release() to free memory provided by spi_controller */
538         void                    (*cleanup)(struct spi_device *spi);
539
540         /*
541          * Used to enable core support for DMA handling, if can_dma()
542          * exists and returns true then the transfer will be mapped
543          * prior to transfer_one() being called.  The driver should
544          * not modify or store xfer and dma_tx and dma_rx must be set
545          * while the device is prepared.
546          */
547         bool                    (*can_dma)(struct spi_controller *ctlr,
548                                            struct spi_device *spi,
549                                            struct spi_transfer *xfer);
550
551         /*
552          * These hooks are for drivers that want to use the generic
553          * controller transfer queueing mechanism. If these are used, the
554          * transfer() function above must NOT be specified by the driver.
555          * Over time we expect SPI drivers to be phased over to this API.
556          */
557         bool                            queued;
558         struct kthread_worker           kworker;
559         struct task_struct              *kworker_task;
560         struct kthread_work             pump_messages;
561         spinlock_t                      queue_lock;
562         struct list_head                queue;
563         struct spi_message              *cur_msg;
564         bool                            idling;
565         bool                            busy;
566         bool                            running;
567         bool                            rt;
568         bool                            auto_runtime_pm;
569         bool                            cur_msg_prepared;
570         bool                            cur_msg_mapped;
571         struct completion               xfer_completion;
572         size_t                          max_dma_len;
573
574         int (*prepare_transfer_hardware)(struct spi_controller *ctlr);
575         int (*transfer_one_message)(struct spi_controller *ctlr,
576                                     struct spi_message *mesg);
577         int (*unprepare_transfer_hardware)(struct spi_controller *ctlr);
578         int (*prepare_message)(struct spi_controller *ctlr,
579                                struct spi_message *message);
580         int (*unprepare_message)(struct spi_controller *ctlr,
581                                  struct spi_message *message);
582         int (*slave_abort)(struct spi_controller *ctlr);
583
584         /*
585          * These hooks are for drivers that use a generic implementation
586          * of transfer_one_message() provied by the core.
587          */
588         void (*set_cs)(struct spi_device *spi, bool enable);
589         int (*transfer_one)(struct spi_controller *ctlr, struct spi_device *spi,
590                             struct spi_transfer *transfer);
591         void (*handle_err)(struct spi_controller *ctlr,
592                            struct spi_message *message);
593
594         /* Optimized handlers for SPI memory-like operations. */
595         const struct spi_controller_mem_ops *mem_ops;
596
597         /* gpio chip select */
598         int                     *cs_gpios;
599         struct gpio_desc        **cs_gpiods;
600         bool                    use_gpio_descriptors;
601
602         /* statistics */
603         struct spi_statistics   statistics;
604
605         /* DMA channels for use with core dmaengine helpers */
606         struct dma_chan         *dma_tx;
607         struct dma_chan         *dma_rx;
608
609         /* dummy data for full duplex devices */
610         void                    *dummy_rx;
611         void                    *dummy_tx;
612
613         int (*fw_translate_cs)(struct spi_controller *ctlr, unsigned cs);
614
615         /*
616          * Driver sets this field to indicate it is able to snapshot SPI
617          * transfers (needed e.g. for reading the time of POSIX clocks)
618          */
619         bool                    ptp_sts_supported;
620
621         /* Interrupt enable state during PTP system timestamping */
622         unsigned long           irq_flags;
623 };
624
625 static inline void *spi_controller_get_devdata(struct spi_controller *ctlr)
626 {
627         return dev_get_drvdata(&ctlr->dev);
628 }
629
630 static inline void spi_controller_set_devdata(struct spi_controller *ctlr,
631                                               void *data)
632 {
633         dev_set_drvdata(&ctlr->dev, data);
634 }
635
636 static inline struct spi_controller *spi_controller_get(struct spi_controller *ctlr)
637 {
638         if (!ctlr || !get_device(&ctlr->dev))
639                 return NULL;
640         return ctlr;
641 }
642
643 static inline void spi_controller_put(struct spi_controller *ctlr)
644 {
645         if (ctlr)
646                 put_device(&ctlr->dev);
647 }
648
649 static inline bool spi_controller_is_slave(struct spi_controller *ctlr)
650 {
651         return IS_ENABLED(CONFIG_SPI_SLAVE) && ctlr->slave;
652 }
653
654 /* PM calls that need to be issued by the driver */
655 extern int spi_controller_suspend(struct spi_controller *ctlr);
656 extern int spi_controller_resume(struct spi_controller *ctlr);
657
658 /* Calls the driver make to interact with the message queue */
659 extern struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr);
660 extern void spi_finalize_current_message(struct spi_controller *ctlr);
661 extern void spi_finalize_current_transfer(struct spi_controller *ctlr);
662
663 /* Helper calls for driver to timestamp transfer */
664 void spi_take_timestamp_pre(struct spi_controller *ctlr,
665                             struct spi_transfer *xfer,
666                             const void *tx, bool irqs_off);
667 void spi_take_timestamp_post(struct spi_controller *ctlr,
668                              struct spi_transfer *xfer,
669                              const void *tx, bool irqs_off);
670
671 /* the spi driver core manages memory for the spi_controller classdev */
672 extern struct spi_controller *__spi_alloc_controller(struct device *host,
673                                                 unsigned int size, bool slave);
674
675 static inline struct spi_controller *spi_alloc_master(struct device *host,
676                                                       unsigned int size)
677 {
678         return __spi_alloc_controller(host, size, false);
679 }
680
681 static inline struct spi_controller *spi_alloc_slave(struct device *host,
682                                                      unsigned int size)
683 {
684         if (!IS_ENABLED(CONFIG_SPI_SLAVE))
685                 return NULL;
686
687         return __spi_alloc_controller(host, size, true);
688 }
689
690 extern int spi_register_controller(struct spi_controller *ctlr);
691 extern int devm_spi_register_controller(struct device *dev,
692                                         struct spi_controller *ctlr);
693 extern void spi_unregister_controller(struct spi_controller *ctlr);
694
695 extern struct spi_controller *spi_busnum_to_master(u16 busnum);
696
697 /*
698  * SPI resource management while processing a SPI message
699  */
700
701 typedef void (*spi_res_release_t)(struct spi_controller *ctlr,
702                                   struct spi_message *msg,
703                                   void *res);
704
705 /**
706  * struct spi_res - spi resource management structure
707  * @entry:   list entry
708  * @release: release code called prior to freeing this resource
709  * @data:    extra data allocated for the specific use-case
710  *
711  * this is based on ideas from devres, but focused on life-cycle
712  * management during spi_message processing
713  */
714 struct spi_res {
715         struct list_head        entry;
716         spi_res_release_t       release;
717         unsigned long long      data[]; /* guarantee ull alignment */
718 };
719
720 extern void *spi_res_alloc(struct spi_device *spi,
721                            spi_res_release_t release,
722                            size_t size, gfp_t gfp);
723 extern void spi_res_add(struct spi_message *message, void *res);
724 extern void spi_res_free(void *res);
725
726 extern void spi_res_release(struct spi_controller *ctlr,
727                             struct spi_message *message);
728
729 /*---------------------------------------------------------------------------*/
730
731 /*
732  * I/O INTERFACE between SPI controller and protocol drivers
733  *
734  * Protocol drivers use a queue of spi_messages, each transferring data
735  * between the controller and memory buffers.
736  *
737  * The spi_messages themselves consist of a series of read+write transfer
738  * segments.  Those segments always read the same number of bits as they
739  * write; but one or the other is easily ignored by passing a null buffer
740  * pointer.  (This is unlike most types of I/O API, because SPI hardware
741  * is full duplex.)
742  *
743  * NOTE:  Allocation of spi_transfer and spi_message memory is entirely
744  * up to the protocol driver, which guarantees the integrity of both (as
745  * well as the data buffers) for as long as the message is queued.
746  */
747
748 /**
749  * struct spi_transfer - a read/write buffer pair
750  * @tx_buf: data to be written (dma-safe memory), or NULL
751  * @rx_buf: data to be read (dma-safe memory), or NULL
752  * @tx_dma: DMA address of tx_buf, if @spi_message.is_dma_mapped
753  * @rx_dma: DMA address of rx_buf, if @spi_message.is_dma_mapped
754  * @tx_nbits: number of bits used for writing. If 0 the default
755  *      (SPI_NBITS_SINGLE) is used.
756  * @rx_nbits: number of bits used for reading. If 0 the default
757  *      (SPI_NBITS_SINGLE) is used.
758  * @len: size of rx and tx buffers (in bytes)
759  * @speed_hz: Select a speed other than the device default for this
760  *      transfer. If 0 the default (from @spi_device) is used.
761  * @bits_per_word: select a bits_per_word other than the device default
762  *      for this transfer. If 0 the default (from @spi_device) is used.
763  * @cs_change: affects chipselect after this transfer completes
764  * @cs_change_delay: delay between cs deassert and assert when
765  *      @cs_change is set and @spi_transfer is not the last in @spi_message
766  * @cs_change_delay_unit: unit of cs_change_delay
767  * @delay_usecs: microseconds to delay after this transfer before
768  *      (optionally) changing the chipselect status, then starting
769  *      the next transfer or completing this @spi_message.
770  * @word_delay_usecs: microseconds to inter word delay after each word size
771  *      (set by bits_per_word) transmission.
772  * @word_delay: clock cycles to inter word delay after each word size
773  *      (set by bits_per_word) transmission.
774  * @effective_speed_hz: the effective SCK-speed that was used to
775  *      transfer this transfer. Set to 0 if the spi bus driver does
776  *      not support it.
777  * @transfer_list: transfers are sequenced through @spi_message.transfers
778  * @tx_sg: Scatterlist for transmit, currently not for client use
779  * @rx_sg: Scatterlist for receive, currently not for client use
780  * @ptp_sts_word_pre: The word (subject to bits_per_word semantics) offset
781  *      within @tx_buf for which the SPI device is requesting that the time
782  *      snapshot for this transfer begins. Upon completing the SPI transfer,
783  *      this value may have changed compared to what was requested, depending
784  *      on the available snapshotting resolution (DMA transfer,
785  *      @ptp_sts_supported is false, etc).
786  * @ptp_sts_word_post: See @ptp_sts_word_post. The two can be equal (meaning
787  *      that a single byte should be snapshotted).
788  *      If the core takes care of the timestamp (if @ptp_sts_supported is false
789  *      for this controller), it will set @ptp_sts_word_pre to 0, and
790  *      @ptp_sts_word_post to the length of the transfer. This is done
791  *      purposefully (instead of setting to spi_transfer->len - 1) to denote
792  *      that a transfer-level snapshot taken from within the driver may still
793  *      be of higher quality.
794  * @ptp_sts: Pointer to a memory location held by the SPI slave device where a
795  *      PTP system timestamp structure may lie. If drivers use PIO or their
796  *      hardware has some sort of assist for retrieving exact transfer timing,
797  *      they can (and should) assert @ptp_sts_supported and populate this
798  *      structure using the ptp_read_system_*ts helper functions.
799  *      The timestamp must represent the time at which the SPI slave device has
800  *      processed the word, i.e. the "pre" timestamp should be taken before
801  *      transmitting the "pre" word, and the "post" timestamp after receiving
802  *      transmit confirmation from the controller for the "post" word.
803  * @timestamped_pre: Set by the SPI controller driver to denote it has acted
804  *      upon the @ptp_sts request. Not set when the SPI core has taken care of
805  *      the task. SPI device drivers are free to print a warning if this comes
806  *      back unset and they need the better resolution.
807  * @timestamped_post: See above. The reason why both exist is that these
808  *      booleans are also used to keep state in the core SPI logic.
809  *
810  * SPI transfers always write the same number of bytes as they read.
811  * Protocol drivers should always provide @rx_buf and/or @tx_buf.
812  * In some cases, they may also want to provide DMA addresses for
813  * the data being transferred; that may reduce overhead, when the
814  * underlying driver uses dma.
815  *
816  * If the transmit buffer is null, zeroes will be shifted out
817  * while filling @rx_buf.  If the receive buffer is null, the data
818  * shifted in will be discarded.  Only "len" bytes shift out (or in).
819  * It's an error to try to shift out a partial word.  (For example, by
820  * shifting out three bytes with word size of sixteen or twenty bits;
821  * the former uses two bytes per word, the latter uses four bytes.)
822  *
823  * In-memory data values are always in native CPU byte order, translated
824  * from the wire byte order (big-endian except with SPI_LSB_FIRST).  So
825  * for example when bits_per_word is sixteen, buffers are 2N bytes long
826  * (@len = 2N) and hold N sixteen bit words in CPU byte order.
827  *
828  * When the word size of the SPI transfer is not a power-of-two multiple
829  * of eight bits, those in-memory words include extra bits.  In-memory
830  * words are always seen by protocol drivers as right-justified, so the
831  * undefined (rx) or unused (tx) bits are always the most significant bits.
832  *
833  * All SPI transfers start with the relevant chipselect active.  Normally
834  * it stays selected until after the last transfer in a message.  Drivers
835  * can affect the chipselect signal using cs_change.
836  *
837  * (i) If the transfer isn't the last one in the message, this flag is
838  * used to make the chipselect briefly go inactive in the middle of the
839  * message.  Toggling chipselect in this way may be needed to terminate
840  * a chip command, letting a single spi_message perform all of group of
841  * chip transactions together.
842  *
843  * (ii) When the transfer is the last one in the message, the chip may
844  * stay selected until the next transfer.  On multi-device SPI busses
845  * with nothing blocking messages going to other devices, this is just
846  * a performance hint; starting a message to another device deselects
847  * this one.  But in other cases, this can be used to ensure correctness.
848  * Some devices need protocol transactions to be built from a series of
849  * spi_message submissions, where the content of one message is determined
850  * by the results of previous messages and where the whole transaction
851  * ends when the chipselect goes intactive.
852  *
853  * When SPI can transfer in 1x,2x or 4x. It can get this transfer information
854  * from device through @tx_nbits and @rx_nbits. In Bi-direction, these
855  * two should both be set. User can set transfer mode with SPI_NBITS_SINGLE(1x)
856  * SPI_NBITS_DUAL(2x) and SPI_NBITS_QUAD(4x) to support these three transfer.
857  *
858  * The code that submits an spi_message (and its spi_transfers)
859  * to the lower layers is responsible for managing its memory.
860  * Zero-initialize every field you don't set up explicitly, to
861  * insulate against future API updates.  After you submit a message
862  * and its transfers, ignore them until its completion callback.
863  */
864 struct spi_transfer {
865         /* it's ok if tx_buf == rx_buf (right?)
866          * for MicroWire, one buffer must be null
867          * buffers must work with dma_*map_single() calls, unless
868          *   spi_message.is_dma_mapped reports a pre-existing mapping
869          */
870         const void      *tx_buf;
871         void            *rx_buf;
872         unsigned        len;
873
874         dma_addr_t      tx_dma;
875         dma_addr_t      rx_dma;
876         struct sg_table tx_sg;
877         struct sg_table rx_sg;
878
879         unsigned        cs_change:1;
880         unsigned        tx_nbits:3;
881         unsigned        rx_nbits:3;
882 #define SPI_NBITS_SINGLE        0x01 /* 1bit transfer */
883 #define SPI_NBITS_DUAL          0x02 /* 2bits transfer */
884 #define SPI_NBITS_QUAD          0x04 /* 4bits transfer */
885         u8              bits_per_word;
886         u8              word_delay_usecs;
887         u16             delay_usecs;
888         u16             cs_change_delay;
889         u8              cs_change_delay_unit;
890 #define SPI_DELAY_UNIT_USECS    0
891 #define SPI_DELAY_UNIT_NSECS    1
892 #define SPI_DELAY_UNIT_SCK      2
893         u32             speed_hz;
894         u16             word_delay;
895
896         u32             effective_speed_hz;
897
898         unsigned int    ptp_sts_word_pre;
899         unsigned int    ptp_sts_word_post;
900
901         struct ptp_system_timestamp *ptp_sts;
902
903         bool            timestamped_pre;
904         bool            timestamped_post;
905
906         struct list_head transfer_list;
907 };
908
909 /**
910  * struct spi_message - one multi-segment SPI transaction
911  * @transfers: list of transfer segments in this transaction
912  * @spi: SPI device to which the transaction is queued
913  * @is_dma_mapped: if true, the caller provided both dma and cpu virtual
914  *      addresses for each transfer buffer
915  * @complete: called to report transaction completions
916  * @context: the argument to complete() when it's called
917  * @frame_length: the total number of bytes in the message
918  * @actual_length: the total number of bytes that were transferred in all
919  *      successful segments
920  * @status: zero for success, else negative errno
921  * @queue: for use by whichever driver currently owns the message
922  * @state: for use by whichever driver currently owns the message
923  * @resources: for resource management when the spi message is processed
924  *
925  * A @spi_message is used to execute an atomic sequence of data transfers,
926  * each represented by a struct spi_transfer.  The sequence is "atomic"
927  * in the sense that no other spi_message may use that SPI bus until that
928  * sequence completes.  On some systems, many such sequences can execute as
929  * as single programmed DMA transfer.  On all systems, these messages are
930  * queued, and might complete after transactions to other devices.  Messages
931  * sent to a given spi_device are always executed in FIFO order.
932  *
933  * The code that submits an spi_message (and its spi_transfers)
934  * to the lower layers is responsible for managing its memory.
935  * Zero-initialize every field you don't set up explicitly, to
936  * insulate against future API updates.  After you submit a message
937  * and its transfers, ignore them until its completion callback.
938  */
939 struct spi_message {
940         struct list_head        transfers;
941
942         struct spi_device       *spi;
943
944         unsigned                is_dma_mapped:1;
945
946         /* REVISIT:  we might want a flag affecting the behavior of the
947          * last transfer ... allowing things like "read 16 bit length L"
948          * immediately followed by "read L bytes".  Basically imposing
949          * a specific message scheduling algorithm.
950          *
951          * Some controller drivers (message-at-a-time queue processing)
952          * could provide that as their default scheduling algorithm.  But
953          * others (with multi-message pipelines) could need a flag to
954          * tell them about such special cases.
955          */
956
957         /* completion is reported through a callback */
958         void                    (*complete)(void *context);
959         void                    *context;
960         unsigned                frame_length;
961         unsigned                actual_length;
962         int                     status;
963
964         /* for optional use by whatever driver currently owns the
965          * spi_message ...  between calls to spi_async and then later
966          * complete(), that's the spi_controller controller driver.
967          */
968         struct list_head        queue;
969         void                    *state;
970
971         /* list of spi_res reources when the spi message is processed */
972         struct list_head        resources;
973 };
974
975 static inline void spi_message_init_no_memset(struct spi_message *m)
976 {
977         INIT_LIST_HEAD(&m->transfers);
978         INIT_LIST_HEAD(&m->resources);
979 }
980
981 static inline void spi_message_init(struct spi_message *m)
982 {
983         memset(m, 0, sizeof *m);
984         spi_message_init_no_memset(m);
985 }
986
987 static inline void
988 spi_message_add_tail(struct spi_transfer *t, struct spi_message *m)
989 {
990         list_add_tail(&t->transfer_list, &m->transfers);
991 }
992
993 static inline void
994 spi_transfer_del(struct spi_transfer *t)
995 {
996         list_del(&t->transfer_list);
997 }
998
999 /**
1000  * spi_message_init_with_transfers - Initialize spi_message and append transfers
1001  * @m: spi_message to be initialized
1002  * @xfers: An array of spi transfers
1003  * @num_xfers: Number of items in the xfer array
1004  *
1005  * This function initializes the given spi_message and adds each spi_transfer in
1006  * the given array to the message.
1007  */
1008 static inline void
1009 spi_message_init_with_transfers(struct spi_message *m,
1010 struct spi_transfer *xfers, unsigned int num_xfers)
1011 {
1012         unsigned int i;
1013
1014         spi_message_init(m);
1015         for (i = 0; i < num_xfers; ++i)
1016                 spi_message_add_tail(&xfers[i], m);
1017 }
1018
1019 /* It's fine to embed message and transaction structures in other data
1020  * structures so long as you don't free them while they're in use.
1021  */
1022
1023 static inline struct spi_message *spi_message_alloc(unsigned ntrans, gfp_t flags)
1024 {
1025         struct spi_message *m;
1026
1027         m = kzalloc(sizeof(struct spi_message)
1028                         + ntrans * sizeof(struct spi_transfer),
1029                         flags);
1030         if (m) {
1031                 unsigned i;
1032                 struct spi_transfer *t = (struct spi_transfer *)(m + 1);
1033
1034                 spi_message_init_no_memset(m);
1035                 for (i = 0; i < ntrans; i++, t++)
1036                         spi_message_add_tail(t, m);
1037         }
1038         return m;
1039 }
1040
1041 static inline void spi_message_free(struct spi_message *m)
1042 {
1043         kfree(m);
1044 }
1045
1046 extern void spi_set_cs_timing(struct spi_device *spi, u8 setup, u8 hold, u8 inactive_dly);
1047
1048 extern int spi_setup(struct spi_device *spi);
1049 extern int spi_async(struct spi_device *spi, struct spi_message *message);
1050 extern int spi_async_locked(struct spi_device *spi,
1051                             struct spi_message *message);
1052 extern int spi_slave_abort(struct spi_device *spi);
1053
1054 static inline size_t
1055 spi_max_message_size(struct spi_device *spi)
1056 {
1057         struct spi_controller *ctlr = spi->controller;
1058
1059         if (!ctlr->max_message_size)
1060                 return SIZE_MAX;
1061         return ctlr->max_message_size(spi);
1062 }
1063
1064 static inline size_t
1065 spi_max_transfer_size(struct spi_device *spi)
1066 {
1067         struct spi_controller *ctlr = spi->controller;
1068         size_t tr_max = SIZE_MAX;
1069         size_t msg_max = spi_max_message_size(spi);
1070
1071         if (ctlr->max_transfer_size)
1072                 tr_max = ctlr->max_transfer_size(spi);
1073
1074         /* transfer size limit must not be greater than messsage size limit */
1075         return min(tr_max, msg_max);
1076 }
1077
1078 /**
1079  * spi_is_bpw_supported - Check if bits per word is supported
1080  * @spi: SPI device
1081  * @bpw: Bits per word
1082  *
1083  * This function checks to see if the SPI controller supports @bpw.
1084  *
1085  * Returns:
1086  * True if @bpw is supported, false otherwise.
1087  */
1088 static inline bool spi_is_bpw_supported(struct spi_device *spi, u32 bpw)
1089 {
1090         u32 bpw_mask = spi->master->bits_per_word_mask;
1091
1092         if (bpw == 8 || (bpw <= 32 && bpw_mask & SPI_BPW_MASK(bpw)))
1093                 return true;
1094
1095         return false;
1096 }
1097
1098 /*---------------------------------------------------------------------------*/
1099
1100 /* SPI transfer replacement methods which make use of spi_res */
1101
1102 struct spi_replaced_transfers;
1103 typedef void (*spi_replaced_release_t)(struct spi_controller *ctlr,
1104                                        struct spi_message *msg,
1105                                        struct spi_replaced_transfers *res);
1106 /**
1107  * struct spi_replaced_transfers - structure describing the spi_transfer
1108  *                                 replacements that have occurred
1109  *                                 so that they can get reverted
1110  * @release:            some extra release code to get executed prior to
1111  *                      relasing this structure
1112  * @extradata:          pointer to some extra data if requested or NULL
1113  * @replaced_transfers: transfers that have been replaced and which need
1114  *                      to get restored
1115  * @replaced_after:     the transfer after which the @replaced_transfers
1116  *                      are to get re-inserted
1117  * @inserted:           number of transfers inserted
1118  * @inserted_transfers: array of spi_transfers of array-size @inserted,
1119  *                      that have been replacing replaced_transfers
1120  *
1121  * note: that @extradata will point to @inserted_transfers[@inserted]
1122  * if some extra allocation is requested, so alignment will be the same
1123  * as for spi_transfers
1124  */
1125 struct spi_replaced_transfers {
1126         spi_replaced_release_t release;
1127         void *extradata;
1128         struct list_head replaced_transfers;
1129         struct list_head *replaced_after;
1130         size_t inserted;
1131         struct spi_transfer inserted_transfers[];
1132 };
1133
1134 extern struct spi_replaced_transfers *spi_replace_transfers(
1135         struct spi_message *msg,
1136         struct spi_transfer *xfer_first,
1137         size_t remove,
1138         size_t insert,
1139         spi_replaced_release_t release,
1140         size_t extradatasize,
1141         gfp_t gfp);
1142
1143 /*---------------------------------------------------------------------------*/
1144
1145 /* SPI transfer transformation methods */
1146
1147 extern int spi_split_transfers_maxsize(struct spi_controller *ctlr,
1148                                        struct spi_message *msg,
1149                                        size_t maxsize,
1150                                        gfp_t gfp);
1151
1152 /*---------------------------------------------------------------------------*/
1153
1154 /* All these synchronous SPI transfer routines are utilities layered
1155  * over the core async transfer primitive.  Here, "synchronous" means
1156  * they will sleep uninterruptibly until the async transfer completes.
1157  */
1158
1159 extern int spi_sync(struct spi_device *spi, struct spi_message *message);
1160 extern int spi_sync_locked(struct spi_device *spi, struct spi_message *message);
1161 extern int spi_bus_lock(struct spi_controller *ctlr);
1162 extern int spi_bus_unlock(struct spi_controller *ctlr);
1163
1164 /**
1165  * spi_sync_transfer - synchronous SPI data transfer
1166  * @spi: device with which data will be exchanged
1167  * @xfers: An array of spi_transfers
1168  * @num_xfers: Number of items in the xfer array
1169  * Context: can sleep
1170  *
1171  * Does a synchronous SPI data transfer of the given spi_transfer array.
1172  *
1173  * For more specific semantics see spi_sync().
1174  *
1175  * Return: Return: zero on success, else a negative error code.
1176  */
1177 static inline int
1178 spi_sync_transfer(struct spi_device *spi, struct spi_transfer *xfers,
1179         unsigned int num_xfers)
1180 {
1181         struct spi_message msg;
1182
1183         spi_message_init_with_transfers(&msg, xfers, num_xfers);
1184
1185         return spi_sync(spi, &msg);
1186 }
1187
1188 /**
1189  * spi_write - SPI synchronous write
1190  * @spi: device to which data will be written
1191  * @buf: data buffer
1192  * @len: data buffer size
1193  * Context: can sleep
1194  *
1195  * This function writes the buffer @buf.
1196  * Callable only from contexts that can sleep.
1197  *
1198  * Return: zero on success, else a negative error code.
1199  */
1200 static inline int
1201 spi_write(struct spi_device *spi, const void *buf, size_t len)
1202 {
1203         struct spi_transfer     t = {
1204                         .tx_buf         = buf,
1205                         .len            = len,
1206                 };
1207
1208         return spi_sync_transfer(spi, &t, 1);
1209 }
1210
1211 /**
1212  * spi_read - SPI synchronous read
1213  * @spi: device from which data will be read
1214  * @buf: data buffer
1215  * @len: data buffer size
1216  * Context: can sleep
1217  *
1218  * This function reads the buffer @buf.
1219  * Callable only from contexts that can sleep.
1220  *
1221  * Return: zero on success, else a negative error code.
1222  */
1223 static inline int
1224 spi_read(struct spi_device *spi, void *buf, size_t len)
1225 {
1226         struct spi_transfer     t = {
1227                         .rx_buf         = buf,
1228                         .len            = len,
1229                 };
1230
1231         return spi_sync_transfer(spi, &t, 1);
1232 }
1233
1234 /* this copies txbuf and rxbuf data; for small transfers only! */
1235 extern int spi_write_then_read(struct spi_device *spi,
1236                 const void *txbuf, unsigned n_tx,
1237                 void *rxbuf, unsigned n_rx);
1238
1239 /**
1240  * spi_w8r8 - SPI synchronous 8 bit write followed by 8 bit read
1241  * @spi: device with which data will be exchanged
1242  * @cmd: command to be written before data is read back
1243  * Context: can sleep
1244  *
1245  * Callable only from contexts that can sleep.
1246  *
1247  * Return: the (unsigned) eight bit number returned by the
1248  * device, or else a negative error code.
1249  */
1250 static inline ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)
1251 {
1252         ssize_t                 status;
1253         u8                      result;
1254
1255         status = spi_write_then_read(spi, &cmd, 1, &result, 1);
1256
1257         /* return negative errno or unsigned value */
1258         return (status < 0) ? status : result;
1259 }
1260
1261 /**
1262  * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read
1263  * @spi: device with which data will be exchanged
1264  * @cmd: command to be written before data is read back
1265  * Context: can sleep
1266  *
1267  * The number is returned in wire-order, which is at least sometimes
1268  * big-endian.
1269  *
1270  * Callable only from contexts that can sleep.
1271  *
1272  * Return: the (unsigned) sixteen bit number returned by the
1273  * device, or else a negative error code.
1274  */
1275 static inline ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)
1276 {
1277         ssize_t                 status;
1278         u16                     result;
1279
1280         status = spi_write_then_read(spi, &cmd, 1, &result, 2);
1281
1282         /* return negative errno or unsigned value */
1283         return (status < 0) ? status : result;
1284 }
1285
1286 /**
1287  * spi_w8r16be - SPI synchronous 8 bit write followed by 16 bit big-endian read
1288  * @spi: device with which data will be exchanged
1289  * @cmd: command to be written before data is read back
1290  * Context: can sleep
1291  *
1292  * This function is similar to spi_w8r16, with the exception that it will
1293  * convert the read 16 bit data word from big-endian to native endianness.
1294  *
1295  * Callable only from contexts that can sleep.
1296  *
1297  * Return: the (unsigned) sixteen bit number returned by the device in cpu
1298  * endianness, or else a negative error code.
1299  */
1300 static inline ssize_t spi_w8r16be(struct spi_device *spi, u8 cmd)
1301
1302 {
1303         ssize_t status;
1304         __be16 result;
1305
1306         status = spi_write_then_read(spi, &cmd, 1, &result, 2);
1307         if (status < 0)
1308                 return status;
1309
1310         return be16_to_cpu(result);
1311 }
1312
1313 /*---------------------------------------------------------------------------*/
1314
1315 /*
1316  * INTERFACE between board init code and SPI infrastructure.
1317  *
1318  * No SPI driver ever sees these SPI device table segments, but
1319  * it's how the SPI core (or adapters that get hotplugged) grows
1320  * the driver model tree.
1321  *
1322  * As a rule, SPI devices can't be probed.  Instead, board init code
1323  * provides a table listing the devices which are present, with enough
1324  * information to bind and set up the device's driver.  There's basic
1325  * support for nonstatic configurations too; enough to handle adding
1326  * parport adapters, or microcontrollers acting as USB-to-SPI bridges.
1327  */
1328
1329 /**
1330  * struct spi_board_info - board-specific template for a SPI device
1331  * @modalias: Initializes spi_device.modalias; identifies the driver.
1332  * @platform_data: Initializes spi_device.platform_data; the particular
1333  *      data stored there is driver-specific.
1334  * @properties: Additional device properties for the device.
1335  * @controller_data: Initializes spi_device.controller_data; some
1336  *      controllers need hints about hardware setup, e.g. for DMA.
1337  * @irq: Initializes spi_device.irq; depends on how the board is wired.
1338  * @max_speed_hz: Initializes spi_device.max_speed_hz; based on limits
1339  *      from the chip datasheet and board-specific signal quality issues.
1340  * @bus_num: Identifies which spi_controller parents the spi_device; unused
1341  *      by spi_new_device(), and otherwise depends on board wiring.
1342  * @chip_select: Initializes spi_device.chip_select; depends on how
1343  *      the board is wired.
1344  * @mode: Initializes spi_device.mode; based on the chip datasheet, board
1345  *      wiring (some devices support both 3WIRE and standard modes), and
1346  *      possibly presence of an inverter in the chipselect path.
1347  *
1348  * When adding new SPI devices to the device tree, these structures serve
1349  * as a partial device template.  They hold information which can't always
1350  * be determined by drivers.  Information that probe() can establish (such
1351  * as the default transfer wordsize) is not included here.
1352  *
1353  * These structures are used in two places.  Their primary role is to
1354  * be stored in tables of board-specific device descriptors, which are
1355  * declared early in board initialization and then used (much later) to
1356  * populate a controller's device tree after the that controller's driver
1357  * initializes.  A secondary (and atypical) role is as a parameter to
1358  * spi_new_device() call, which happens after those controller drivers
1359  * are active in some dynamic board configuration models.
1360  */
1361 struct spi_board_info {
1362         /* the device name and module name are coupled, like platform_bus;
1363          * "modalias" is normally the driver name.
1364          *
1365          * platform_data goes to spi_device.dev.platform_data,
1366          * controller_data goes to spi_device.controller_data,
1367          * device properties are copied and attached to spi_device,
1368          * irq is copied too
1369          */
1370         char            modalias[SPI_NAME_SIZE];
1371         const void      *platform_data;
1372         const struct property_entry *properties;
1373         void            *controller_data;
1374         int             irq;
1375
1376         /* slower signaling on noisy or low voltage boards */
1377         u32             max_speed_hz;
1378
1379
1380         /* bus_num is board specific and matches the bus_num of some
1381          * spi_controller that will probably be registered later.
1382          *
1383          * chip_select reflects how this chip is wired to that master;
1384          * it's less than num_chipselect.
1385          */
1386         u16             bus_num;
1387         u16             chip_select;
1388
1389         /* mode becomes spi_device.mode, and is essential for chips
1390          * where the default of SPI_CS_HIGH = 0 is wrong.
1391          */
1392         u32             mode;
1393
1394         /* ... may need additional spi_device chip config data here.
1395          * avoid stuff protocol drivers can set; but include stuff
1396          * needed to behave without being bound to a driver:
1397          *  - quirks like clock rate mattering when not selected
1398          */
1399 };
1400
1401 #ifdef  CONFIG_SPI
1402 extern int
1403 spi_register_board_info(struct spi_board_info const *info, unsigned n);
1404 #else
1405 /* board init code may ignore whether SPI is configured or not */
1406 static inline int
1407 spi_register_board_info(struct spi_board_info const *info, unsigned n)
1408         { return 0; }
1409 #endif
1410
1411 /* If you're hotplugging an adapter with devices (parport, usb, etc)
1412  * use spi_new_device() to describe each device.  You can also call
1413  * spi_unregister_device() to start making that device vanish, but
1414  * normally that would be handled by spi_unregister_controller().
1415  *
1416  * You can also use spi_alloc_device() and spi_add_device() to use a two
1417  * stage registration sequence for each spi_device.  This gives the caller
1418  * some more control over the spi_device structure before it is registered,
1419  * but requires that caller to initialize fields that would otherwise
1420  * be defined using the board info.
1421  */
1422 extern struct spi_device *
1423 spi_alloc_device(struct spi_controller *ctlr);
1424
1425 extern int
1426 spi_add_device(struct spi_device *spi);
1427
1428 extern struct spi_device *
1429 spi_new_device(struct spi_controller *, struct spi_board_info *);
1430
1431 extern void spi_unregister_device(struct spi_device *spi);
1432
1433 extern const struct spi_device_id *
1434 spi_get_device_id(const struct spi_device *sdev);
1435
1436 static inline bool
1437 spi_transfer_is_last(struct spi_controller *ctlr, struct spi_transfer *xfer)
1438 {
1439         return list_is_last(&xfer->transfer_list, &ctlr->cur_msg->transfers);
1440 }
1441
1442 /* OF support code */
1443 #if IS_ENABLED(CONFIG_OF)
1444
1445 /* must call put_device() when done with returned spi_device device */
1446 extern struct spi_device *
1447 of_find_spi_device_by_node(struct device_node *node);
1448
1449 #else
1450
1451 static inline struct spi_device *
1452 of_find_spi_device_by_node(struct device_node *node)
1453 {
1454         return NULL;
1455 }
1456
1457 #endif /* IS_ENABLED(CONFIG_OF) */
1458
1459 /* Compatibility layer */
1460 #define spi_master                      spi_controller
1461
1462 #define SPI_MASTER_HALF_DUPLEX          SPI_CONTROLLER_HALF_DUPLEX
1463 #define SPI_MASTER_NO_RX                SPI_CONTROLLER_NO_RX
1464 #define SPI_MASTER_NO_TX                SPI_CONTROLLER_NO_TX
1465 #define SPI_MASTER_MUST_RX              SPI_CONTROLLER_MUST_RX
1466 #define SPI_MASTER_MUST_TX              SPI_CONTROLLER_MUST_TX
1467
1468 #define spi_master_get_devdata(_ctlr)   spi_controller_get_devdata(_ctlr)
1469 #define spi_master_set_devdata(_ctlr, _data)    \
1470         spi_controller_set_devdata(_ctlr, _data)
1471 #define spi_master_get(_ctlr)           spi_controller_get(_ctlr)
1472 #define spi_master_put(_ctlr)           spi_controller_put(_ctlr)
1473 #define spi_master_suspend(_ctlr)       spi_controller_suspend(_ctlr)
1474 #define spi_master_resume(_ctlr)        spi_controller_resume(_ctlr)
1475
1476 #define spi_register_master(_ctlr)      spi_register_controller(_ctlr)
1477 #define devm_spi_register_master(_dev, _ctlr) \
1478         devm_spi_register_controller(_dev, _ctlr)
1479 #define spi_unregister_master(_ctlr)    spi_unregister_controller(_ctlr)
1480
1481 #endif /* __LINUX_SPI_H */
This page took 0.120017 seconds and 4 git commands to generate.