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