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