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/acpi.h>
10 #include <linux/bits.h>
11 #include <linux/completion.h>
12 #include <linux/device.h>
13 #include <linux/gpio/consumer.h>
14 #include <linux/kthread.h>
15 #include <linux/mod_devicetable.h>
16 #include <linux/overflow.h>
17 #include <linux/scatterlist.h>
18 #include <linux/slab.h>
19 #include <linux/u64_stats_sync.h>
20
21 #include <uapi/linux/spi/spi.h>
22
23 /* Max no. of CS supported per spi device */
24 #define SPI_DEVICE_CS_CNT_MAX 4
25
26 /* Max no. of data lanes supported per spi device */
27 #define SPI_DEVICE_DATA_LANE_CNT_MAX 8
28
29 struct dma_chan;
30 struct software_node;
31 struct ptp_system_timestamp;
32 struct spi_controller;
33 struct spi_transfer;
34 struct spi_controller_mem_ops;
35 struct spi_controller_mem_caps;
36 struct spi_message;
37 struct spi_offload;
38 struct spi_offload_config;
39
40 /*
41 * INTERFACES between SPI controller-side drivers and SPI target protocol handlers,
42 * and SPI infrastructure.
43 */
44 extern const struct bus_type spi_bus_type;
45
46 /**
47 * struct spi_statistics - statistics for spi transfers
48 * @syncp: seqcount to protect members in this struct for per-cpu update
49 * on 32-bit systems
50 *
51 * @messages: number of spi-messages handled
52 * @transfers: number of spi_transfers handled
53 * @errors: number of errors during spi_transfer
54 * @timedout: number of timeouts during spi_transfer
55 *
56 * @spi_sync: number of times spi_sync is used
57 * @spi_sync_immediate:
58 * number of times spi_sync is executed immediately
59 * in calling context without queuing and scheduling
60 * @spi_async: number of times spi_async is used
61 *
62 * @bytes: number of bytes transferred to/from device
63 * @bytes_tx: number of bytes sent to device
64 * @bytes_rx: number of bytes received from device
65 *
66 * @transfer_bytes_histo:
67 * transfer bytes histogram
68 *
69 * @transfers_split_maxsize:
70 * number of transfers that have been split because of
71 * maxsize limit
72 */
73 struct spi_statistics {
74 struct u64_stats_sync syncp;
75
76 u64_stats_t messages;
77 u64_stats_t transfers;
78 u64_stats_t errors;
79 u64_stats_t timedout;
80
81 u64_stats_t spi_sync;
82 u64_stats_t spi_sync_immediate;
83 u64_stats_t spi_async;
84
85 u64_stats_t bytes;
86 u64_stats_t bytes_rx;
87 u64_stats_t bytes_tx;
88
89 #define SPI_STATISTICS_HISTO_SIZE 17
90 u64_stats_t transfer_bytes_histo[SPI_STATISTICS_HISTO_SIZE];
91
92 u64_stats_t transfers_split_maxsize;
93 };
94
95 #define SPI_STATISTICS_ADD_TO_FIELD(pcpu_stats, field, count) \
96 do { \
97 struct spi_statistics *__lstats; \
98 get_cpu(); \
99 __lstats = this_cpu_ptr(pcpu_stats); \
100 u64_stats_update_begin(&__lstats->syncp); \
101 u64_stats_add(&__lstats->field, count); \
102 u64_stats_update_end(&__lstats->syncp); \
103 put_cpu(); \
104 } while (0)
105
106 #define SPI_STATISTICS_INCREMENT_FIELD(pcpu_stats, field) \
107 do { \
108 struct spi_statistics *__lstats; \
109 get_cpu(); \
110 __lstats = this_cpu_ptr(pcpu_stats); \
111 u64_stats_update_begin(&__lstats->syncp); \
112 u64_stats_inc(&__lstats->field); \
113 u64_stats_update_end(&__lstats->syncp); \
114 put_cpu(); \
115 } while (0)
116
117 /**
118 * struct spi_delay - SPI delay information
119 * @value: Value for the delay
120 * @unit: Unit for the delay
121 */
122 struct spi_delay {
123 #define SPI_DELAY_UNIT_USECS 0
124 #define SPI_DELAY_UNIT_NSECS 1
125 #define SPI_DELAY_UNIT_SCK 2
126 u16 value;
127 u8 unit;
128 };
129
130 extern int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer);
131 extern int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer);
132 extern void spi_transfer_cs_change_delay_exec(struct spi_message *msg,
133 struct spi_transfer *xfer);
134
135 /**
136 * struct spi_device - Controller side proxy for an SPI target device
137 * @dev: Driver model representation of the device.
138 * @controller: SPI controller used with the device.
139 * @max_speed_hz: Maximum clock rate to be used with this chip
140 * (on this board); may be changed by the device's driver.
141 * The spi_transfer.speed_hz can override this for each transfer.
142 * @bits_per_word: Data transfers involve one or more words; word sizes
143 * like eight or 12 bits are common. In-memory wordsizes are
144 * powers of two bytes (e.g. 20 bit samples use 32 bits).
145 * This may be changed by the device's driver, or left at the
146 * default (0) indicating protocol words are eight bit bytes.
147 * The spi_transfer.bits_per_word can override this for each transfer.
148 * @rt: Make the pump thread real time priority.
149 * @mode: The spi mode defines how data is clocked out and in.
150 * This may be changed by the device's driver.
151 * The "active low" default for chipselect mode can be overridden
152 * (by specifying SPI_CS_HIGH) as can the "MSB first" default for
153 * each word in a transfer (by specifying SPI_LSB_FIRST).
154 * @irq: Negative, or the number passed to request_irq() to receive
155 * interrupts from this device.
156 * @controller_state: Controller's runtime state
157 * @controller_data: Board-specific definitions for controller, such as
158 * FIFO initialization parameters; from board_info.controller_data
159 * @modalias: Name of the driver to use with this device, or an alias
160 * for that name. This appears in the sysfs "modalias" attribute
161 * for driver coldplugging, and in uevents used for hotplugging
162 * @pcpu_statistics: statistics for the spi_device
163 * @word_delay: delay to be inserted between consecutive
164 * words of a transfer
165 * @cs_setup: delay to be introduced by the controller after CS is asserted
166 * @cs_hold: delay to be introduced by the controller before CS is deasserted
167 * @cs_inactive: delay to be introduced by the controller after CS is
168 * deasserted. If @cs_change_delay is used from @spi_transfer, then the
169 * two delays will be added up.
170 * @chip_select: Array of physical chipselect, spi->chipselect[i] gives
171 * the corresponding physical CS for logical CS i.
172 * @num_chipselect: Number of physical chipselects used.
173 * @cs_index_mask: Bit mask of the active chipselect(s) in the chipselect array
174 * @cs_gpiod: Array of GPIO descriptors of the corresponding chipselect lines
175 * (optional, NULL when not using a GPIO line)
176 * @tx_lane_map: Map of peripheral lanes (index) to controller lanes (value).
177 * @num_tx_lanes: Number of transmit lanes wired up.
178 * @rx_lane_map: Map of peripheral lanes (index) to controller lanes (value).
179 * @num_rx_lanes: Number of receive lanes wired up.
180 *
181 * A @spi_device is used to interchange data between an SPI target device
182 * (usually a discrete chip) and CPU memory.
183 *
184 * In @dev, the platform_data is used to hold information about this
185 * device that's meaningful to the device's protocol driver, but not
186 * to its controller. One example might be an identifier for a chip
187 * variant with slightly different functionality; another might be
188 * information about how this particular board wires the chip's pins.
189 */
190 struct spi_device {
191 struct device dev;
192 struct spi_controller *controller;
193 u32 max_speed_hz;
194 u8 bits_per_word;
195 bool rt;
196 #define SPI_NO_TX BIT(31) /* No transmit wire */
197 #define SPI_NO_RX BIT(30) /* No receive wire */
198 /*
199 * TPM specification defines flow control over SPI. Client device
200 * can insert a wait state on MISO when address is transmitted by
201 * controller on MOSI. Detecting the wait state in software is only
202 * possible for full duplex controllers. For controllers that support
203 * only half-duplex, the wait state detection needs to be implemented
204 * in hardware. TPM devices would set this flag when hardware flow
205 * control is expected from SPI controller.
206 */
207 #define SPI_TPM_HW_FLOW BIT(29) /* TPM HW flow control */
208 /*
209 * All bits defined above should be covered by SPI_MODE_KERNEL_MASK.
210 * The SPI_MODE_KERNEL_MASK has the SPI_MODE_USER_MASK counterpart,
211 * which is defined in 'include/uapi/linux/spi/spi.h'.
212 * The bits defined here are from bit 31 downwards, while in
213 * SPI_MODE_USER_MASK are from 0 upwards.
214 * These bits must not overlap. A static assert check should make sure of that.
215 * If adding extra bits, make sure to decrease the bit index below as well.
216 */
217 #define SPI_MODE_KERNEL_MASK (~(BIT(29) - 1))
218 u32 mode;
219 int irq;
220 void *controller_state;
221 void *controller_data;
222 char modalias[SPI_NAME_SIZE];
223
224 /* The statistics */
225 struct spi_statistics __percpu *pcpu_statistics;
226
227 struct spi_delay word_delay; /* Inter-word delay */
228
229 /* CS delays */
230 struct spi_delay cs_setup;
231 struct spi_delay cs_hold;
232 struct spi_delay cs_inactive;
233
234 u8 chip_select[SPI_DEVICE_CS_CNT_MAX];
235 u8 num_chipselect;
236
237 /*
238 * Bit mask of the chipselect(s) that the driver need to use from
239 * the chipselect array. When the controller is capable to handle
240 * multiple chip selects & memories are connected in parallel
241 * then more than one bit need to be set in cs_index_mask.
242 */
243 u32 cs_index_mask : SPI_DEVICE_CS_CNT_MAX;
244
245 struct gpio_desc *cs_gpiod[SPI_DEVICE_CS_CNT_MAX]; /* Chip select gpio desc */
246
247 /* Multi-lane SPI controller support. */
248 u8 tx_lane_map[SPI_DEVICE_DATA_LANE_CNT_MAX];
249 u8 num_tx_lanes;
250 u8 rx_lane_map[SPI_DEVICE_DATA_LANE_CNT_MAX];
251 u8 num_rx_lanes;
252
253 /*
254 * Likely need more hooks for more protocol options affecting how
255 * the controller talks to each chip, like:
256 * - memory packing (12 bit samples into low bits, others zeroed)
257 * - priority
258 * - chipselect delays
259 * - ...
260 */
261 };
262
263 /* Make sure that SPI_MODE_KERNEL_MASK & SPI_MODE_USER_MASK don't overlap */
264 static_assert((SPI_MODE_KERNEL_MASK & SPI_MODE_USER_MASK) == 0,
265 "SPI_MODE_USER_MASK & SPI_MODE_KERNEL_MASK must not overlap");
266
267 #define to_spi_device(__dev) container_of_const(__dev, struct spi_device, dev)
268
269 /* Most drivers won't need to care about device refcounting */
spi_dev_get(struct spi_device * spi)270 static inline struct spi_device *spi_dev_get(struct spi_device *spi)
271 {
272 return (spi && get_device(&spi->dev)) ? spi : NULL;
273 }
274
spi_dev_put(struct spi_device * spi)275 static inline void spi_dev_put(struct spi_device *spi)
276 {
277 if (spi)
278 put_device(&spi->dev);
279 }
280
281 /* ctldata is for the bus_controller driver's runtime state */
spi_get_ctldata(const struct spi_device * spi)282 static inline void *spi_get_ctldata(const struct spi_device *spi)
283 {
284 return spi->controller_state;
285 }
286
spi_set_ctldata(struct spi_device * spi,void * state)287 static inline void spi_set_ctldata(struct spi_device *spi, void *state)
288 {
289 spi->controller_state = state;
290 }
291
292 /* Device driver data */
293
spi_set_drvdata(struct spi_device * spi,void * data)294 static inline void spi_set_drvdata(struct spi_device *spi, void *data)
295 {
296 dev_set_drvdata(&spi->dev, data);
297 }
298
spi_get_drvdata(const struct spi_device * spi)299 static inline void *spi_get_drvdata(const struct spi_device *spi)
300 {
301 return dev_get_drvdata(&spi->dev);
302 }
303
spi_get_chipselect(const struct spi_device * spi,u8 idx)304 static inline u8 spi_get_chipselect(const struct spi_device *spi, u8 idx)
305 {
306 return spi->chip_select[idx];
307 }
308
spi_set_chipselect(struct spi_device * spi,u8 idx,u8 chipselect)309 static inline void spi_set_chipselect(struct spi_device *spi, u8 idx, u8 chipselect)
310 {
311 spi->chip_select[idx] = chipselect;
312 }
313
spi_get_csgpiod(const struct spi_device * spi,u8 idx)314 static inline struct gpio_desc *spi_get_csgpiod(const struct spi_device *spi, u8 idx)
315 {
316 return spi->cs_gpiod[idx];
317 }
318
spi_set_csgpiod(struct spi_device * spi,u8 idx,struct gpio_desc * csgpiod)319 static inline void spi_set_csgpiod(struct spi_device *spi, u8 idx, struct gpio_desc *csgpiod)
320 {
321 spi->cs_gpiod[idx] = csgpiod;
322 }
323
spi_is_csgpiod(struct spi_device * spi)324 static inline bool spi_is_csgpiod(struct spi_device *spi)
325 {
326 u8 idx;
327
328 for (idx = 0; idx < spi->num_chipselect; idx++) {
329 if (spi_get_csgpiod(spi, idx))
330 return true;
331 }
332 return false;
333 }
334
335 /**
336 * struct spi_driver - Host side "protocol" driver
337 * @id_table: List of SPI devices supported by this driver
338 * @probe: Binds this driver to the SPI device. Drivers can verify
339 * that the device is actually present, and may need to configure
340 * characteristics (such as bits_per_word) which weren't needed for
341 * the initial configuration done during system setup.
342 * @remove: Unbinds this driver from the SPI device
343 * @shutdown: Standard shutdown callback used during system state
344 * transitions such as powerdown/halt and kexec
345 * @driver: SPI device drivers should initialize the name and owner
346 * field of this structure.
347 *
348 * This represents the kind of device driver that uses SPI messages to
349 * interact with the hardware at the other end of a SPI link. It's called
350 * a "protocol" driver because it works through messages rather than talking
351 * directly to SPI hardware (which is what the underlying SPI controller
352 * driver does to pass those messages). These protocols are defined in the
353 * specification for the device(s) supported by the driver.
354 *
355 * As a rule, those device protocols represent the lowest level interface
356 * supported by a driver, and it will support upper level interfaces too.
357 * Examples of such upper levels include frameworks like MTD, networking,
358 * MMC, RTC, filesystem character device nodes, and hardware monitoring.
359 */
360 struct spi_driver {
361 const struct spi_device_id *id_table;
362 int (*probe)(struct spi_device *spi);
363 void (*remove)(struct spi_device *spi);
364 void (*shutdown)(struct spi_device *spi);
365 struct device_driver driver;
366 };
367
368 #define to_spi_driver(__drv) \
369 ( __drv ? container_of_const(__drv, struct spi_driver, driver) : NULL )
370
371 extern int __spi_register_driver(struct module *owner, struct spi_driver *sdrv);
372
373 /**
374 * spi_unregister_driver - reverse effect of spi_register_driver
375 * @sdrv: the driver to unregister
376 * Context: can sleep
377 */
spi_unregister_driver(struct spi_driver * sdrv)378 static inline void spi_unregister_driver(struct spi_driver *sdrv)
379 {
380 if (sdrv)
381 driver_unregister(&sdrv->driver);
382 }
383
384 extern struct spi_device *spi_new_ancillary_device(struct spi_device *spi, u8 chip_select);
385
386 /* Use a define to avoid include chaining to get THIS_MODULE */
387 #define spi_register_driver(driver) \
388 __spi_register_driver(THIS_MODULE, driver)
389
390 /**
391 * module_spi_driver() - Helper macro for registering a SPI driver
392 * @__spi_driver: spi_driver struct
393 *
394 * Helper macro for SPI drivers which do not do anything special in module
395 * init/exit. This eliminates a lot of boilerplate. Each module may only
396 * use this macro once, and calling it replaces module_init() and module_exit()
397 */
398 #define module_spi_driver(__spi_driver) \
399 module_driver(__spi_driver, spi_register_driver, \
400 spi_unregister_driver)
401
402 /**
403 * struct spi_controller - interface to SPI host or target controller
404 * @dev: device interface to this driver
405 * @list: link with the global spi_controller list
406 * @bus_num: board-specific (and often SOC-specific) identifier for a
407 * given SPI controller.
408 * @num_chipselect: chipselects are used to distinguish individual
409 * SPI targets, and are numbered from zero to num_chipselects.
410 * each target has a chipselect signal, but it's common that not
411 * every chipselect is connected to a target.
412 * @num_data_lanes: Number of data lanes supported by this controller. Default is 1.
413 * @dma_alignment: SPI controller constraint on DMA buffers alignment.
414 * @mode_bits: flags understood by this controller driver
415 * @buswidth_override_bits: flags to override for this controller driver
416 * @bits_per_word_mask: A mask indicating which values of bits_per_word are
417 * supported by the driver. Bit n indicates that a bits_per_word n+1 is
418 * supported. If set, the SPI core will reject any transfer with an
419 * unsupported bits_per_word. If not set, this value is simply ignored,
420 * and it's up to the individual driver to perform any validation.
421 * @min_speed_hz: Lowest supported transfer speed
422 * @max_speed_hz: Highest supported transfer speed
423 * @flags: other constraints relevant to this driver
424 * @slave: indicates that this is an SPI slave controller
425 * @target: indicates that this is an SPI target controller
426 * @devm_allocated: whether the allocation of this struct is devres-managed
427 * @max_transfer_size: function that returns the max transfer size for
428 * a &spi_device; may be %NULL, so the default %SIZE_MAX will be used.
429 * @max_message_size: function that returns the max message size for
430 * a &spi_device; may be %NULL, so the default %SIZE_MAX will be used.
431 * @io_mutex: mutex for physical bus access
432 * @add_lock: mutex to avoid adding devices to the same chipselect
433 * @bus_lock_spinlock: spinlock for SPI bus locking
434 * @bus_lock_mutex: mutex for exclusion of multiple callers
435 * @bus_lock_flag: indicates that the SPI bus is locked for exclusive use
436 * @setup: updates the device mode and clocking records used by a
437 * device's SPI controller; protocol code may call this. This
438 * must fail if an unrecognized or unsupported mode is requested.
439 * It's always safe to call this unless transfers are pending on
440 * the device whose settings are being modified.
441 * @set_cs_timing: optional hook for SPI devices to request SPI
442 * controller for configuring specific CS setup time, hold time and inactive
443 * delay in terms of clock counts
444 * @transfer: adds a message to the controller's transfer queue.
445 * @cleanup: frees controller-specific state
446 * @can_dma: determine whether this controller supports DMA
447 * @dma_map_dev: device which can be used for DMA mapping
448 * @cur_rx_dma_dev: device which is currently used for RX DMA mapping
449 * @cur_tx_dma_dev: device which is currently used for TX DMA mapping
450 * @queued: whether this controller is providing an internal message queue
451 * @kworker: pointer to thread struct for message pump
452 * @pump_messages: work struct for scheduling work to the message pump
453 * @queue_lock: spinlock to synchronise access to message queue
454 * @queue: message queue
455 * @cur_msg: the currently in-flight message
456 * @cur_msg_completion: a completion for the current in-flight message
457 * @cur_msg_incomplete: Flag used internally to opportunistically skip
458 * the @cur_msg_completion. This flag is used to check if the driver has
459 * already called spi_finalize_current_message().
460 * @cur_msg_need_completion: Flag used internally to opportunistically skip
461 * the @cur_msg_completion. This flag is used to signal the context that
462 * is running spi_finalize_current_message() that it needs to complete()
463 * @fallback: fallback to PIO if DMA transfer return failure with
464 * SPI_TRANS_FAIL_NO_START.
465 * @last_cs_mode_high: was (mode & SPI_CS_HIGH) true on the last call to set_cs.
466 * @last_cs: the last chip_select that is recorded by set_cs, -1 on non chip
467 * selected
468 * @last_cs_index_mask: bit mask the last chip selects that were used
469 * @xfer_completion: used by core transfer_one_message()
470 * @busy: message pump is busy
471 * @running: message pump is running
472 * @rt: whether this queue is set to run as a realtime task
473 * @auto_runtime_pm: the core should ensure a runtime PM reference is held
474 * while the hardware is prepared, using the parent
475 * device for the spidev
476 * @max_dma_len: Maximum length of a DMA transfer for the device.
477 * @prepare_transfer_hardware: a message will soon arrive from the queue
478 * so the subsystem requests the driver to prepare the transfer hardware
479 * by issuing this call
480 * @transfer_one_message: the subsystem calls the driver to transfer a single
481 * message while queuing transfers that arrive in the meantime. When the
482 * driver is finished with this message, it must call
483 * spi_finalize_current_message() so the subsystem can issue the next
484 * message
485 * @unprepare_transfer_hardware: there are currently no more messages on the
486 * queue so the subsystem notifies the driver that it may relax the
487 * hardware by issuing this call
488 *
489 * @set_cs: set the logic level of the chip select line. May be called
490 * from interrupt context.
491 * @optimize_message: optimize the message for reuse
492 * @unoptimize_message: release resources allocated by optimize_message
493 * @prepare_message: set up the controller to transfer a single message,
494 * for example doing DMA mapping. Called from threaded
495 * context.
496 * @transfer_one: transfer a single spi_transfer.
497 *
498 * - return 0 if the transfer is finished,
499 * - return 1 if the transfer is still in progress. When
500 * the driver is finished with this transfer it must
501 * call spi_finalize_current_transfer() so the subsystem
502 * can issue the next transfer. If the transfer fails, the
503 * driver must set the flag SPI_TRANS_FAIL_IO to
504 * spi_transfer->error first, before calling
505 * spi_finalize_current_transfer().
506 * Note: transfer_one and transfer_one_message are mutually
507 * exclusive; when both are set, the generic subsystem does
508 * not call your transfer_one callback.
509 * @handle_err: the subsystem calls the driver to handle an error that occurs
510 * in the generic implementation of transfer_one_message().
511 * @mem_ops: optimized/dedicated operations for interactions with SPI memory.
512 * This field is optional and should only be implemented if the
513 * controller has native support for memory like operations.
514 * @get_offload: callback for controllers with offload support to get matching
515 * offload instance. Implementations should return -ENODEV if no match is
516 * found.
517 * @put_offload: release the offload instance acquired by @get_offload.
518 * @mem_caps: controller capabilities for the handling of memory operations.
519 * @dtr_caps: true if controller has dtr(single/dual transfer rate) capability.
520 * QSPI based controller should fill this based on controller's capability.
521 * @unprepare_message: undo any work done by prepare_message().
522 * @target_abort: abort the ongoing transfer request on an SPI target controller
523 * @cs_gpiods: Array of GPIO descriptors to use as chip select lines; one per CS
524 * number. Any individual value may be NULL for CS lines that
525 * are not GPIOs (driven by the SPI controller itself).
526 * @use_gpio_descriptors: Turns on the code in the SPI core to parse and grab
527 * GPIO descriptors. This will fill in @cs_gpiods and SPI devices will have
528 * the cs_gpiod assigned if a GPIO line is found for the chipselect.
529 * @unused_native_cs: When cs_gpiods is used, spi_register_controller() will
530 * fill in this field with the first unused native CS, to be used by SPI
531 * controller drivers that need to drive a native CS when using GPIO CS.
532 * @max_native_cs: When cs_gpiods is used, and this field is filled in,
533 * spi_register_controller() will validate all native CS (including the
534 * unused native CS) against this value.
535 * @pcpu_statistics: statistics for the spi_controller
536 * @dma_tx: DMA transmit channel
537 * @dma_rx: DMA receive channel
538 * @dummy_rx: dummy receive buffer for full-duplex devices
539 * @dummy_tx: dummy transmit buffer for full-duplex devices
540 * @fw_translate_cs: If the boot firmware uses different numbering scheme
541 * what Linux expects, this optional hook can be used to translate
542 * between the two.
543 * @ptp_sts_supported: If the driver sets this to true, it must provide a
544 * time snapshot in @spi_transfer->ptp_sts as close as possible to the
545 * moment in time when @spi_transfer->ptp_sts_word_pre and
546 * @spi_transfer->ptp_sts_word_post were transmitted.
547 * If the driver does not set this, the SPI core takes the snapshot as
548 * close to the driver hand-over as possible.
549 * @irq_flags: Interrupt enable state during PTP system timestamping
550 * @queue_empty: signal green light for opportunistically skipping the queue
551 * for spi_sync transfers.
552 * @must_async: disable all fast paths in the core
553 * @defer_optimize_message: set to true if controller cannot pre-optimize messages
554 * and needs to defer the optimization step until the message is actually
555 * being transferred
556 *
557 * Each SPI controller can communicate with one or more @spi_device
558 * children. These make a small bus, sharing MOSI, MISO and SCK signals
559 * but not chip select signals. Each device may be configured to use a
560 * different clock rate, since those shared signals are ignored unless
561 * the chip is selected.
562 *
563 * The driver for an SPI controller manages access to those devices through
564 * a queue of spi_message transactions, copying data between CPU memory and
565 * an SPI target device. For each such message it queues, it calls the
566 * message's completion function when the transaction completes.
567 */
568 struct spi_controller {
569 struct device dev;
570
571 struct list_head list;
572
573 /*
574 * Other than negative (== assign one dynamically), bus_num is fully
575 * board-specific. Usually that simplifies to being SoC-specific.
576 * example: one SoC has three SPI controllers, numbered 0..2,
577 * and one board's schematics might show it using SPI-2. Software
578 * would normally use bus_num=2 for that controller.
579 */
580 s16 bus_num;
581
582 /*
583 * Chipselects will be integral to many controllers; some others
584 * might use board-specific GPIOs.
585 */
586 u16 num_chipselect;
587
588 /*
589 * Some specialized SPI controllers can have more than one physical
590 * data lane interface per controller (each having it's own serializer).
591 * This specifies the number of data lanes in that case. Other
592 * controllers do not need to set this (defaults to 1).
593 */
594 u16 num_data_lanes;
595
596 /* Some SPI controllers pose alignment requirements on DMAable
597 * buffers; let protocol drivers know about these requirements.
598 */
599 u16 dma_alignment;
600
601 /* spi_device.mode flags understood by this controller driver */
602 u32 mode_bits;
603
604 /* spi_device.mode flags override flags for this controller */
605 u32 buswidth_override_bits;
606
607 /* Bitmask of supported bits_per_word for transfers */
608 u32 bits_per_word_mask;
609 #define SPI_BPW_MASK(bits) BIT((bits) - 1)
610 #define SPI_BPW_RANGE_MASK(min, max) GENMASK((max) - 1, (min) - 1)
611
612 /* Limits on transfer speed */
613 u32 min_speed_hz;
614 u32 max_speed_hz;
615
616 /* Other constraints relevant to this driver */
617 u16 flags;
618 #define SPI_CONTROLLER_HALF_DUPLEX BIT(0) /* Can't do full duplex */
619 #define SPI_CONTROLLER_NO_RX BIT(1) /* Can't do buffer read */
620 #define SPI_CONTROLLER_NO_TX BIT(2) /* Can't do buffer write */
621 #define SPI_CONTROLLER_MUST_RX BIT(3) /* Requires rx */
622 #define SPI_CONTROLLER_MUST_TX BIT(4) /* Requires tx */
623 #define SPI_CONTROLLER_GPIO_SS BIT(5) /* GPIO CS must select target device */
624 #define SPI_CONTROLLER_SUSPENDED BIT(6) /* Currently suspended */
625 /*
626 * The spi-controller has multi chip select capability and can
627 * assert/de-assert more than one chip select at once.
628 */
629 #define SPI_CONTROLLER_MULTI_CS BIT(7)
630
631 /* Flag indicating if the allocation of this struct is devres-managed */
632 bool devm_allocated;
633
634 union {
635 /* Flag indicating this is an SPI slave controller */
636 bool slave;
637 /* Flag indicating this is an SPI target controller */
638 bool target;
639 };
640
641 /*
642 * On some hardware transfer / message size may be constrained
643 * the limit may depend on device transfer settings.
644 */
645 size_t (*max_transfer_size)(struct spi_device *spi);
646 size_t (*max_message_size)(struct spi_device *spi);
647
648 /* I/O mutex */
649 struct mutex io_mutex;
650
651 /* Used to avoid adding the same CS twice */
652 struct mutex add_lock;
653
654 /* Lock and mutex for SPI bus locking */
655 spinlock_t bus_lock_spinlock;
656 struct mutex bus_lock_mutex;
657
658 /* Flag indicating that the SPI bus is locked for exclusive use */
659 bool bus_lock_flag;
660
661 /*
662 * Setup mode and clock, etc (SPI driver may call many times).
663 *
664 * IMPORTANT: this may be called when transfers to another
665 * device are active. DO NOT UPDATE SHARED REGISTERS in ways
666 * which could break those transfers.
667 */
668 int (*setup)(struct spi_device *spi);
669
670 /*
671 * set_cs_timing() method is for SPI controllers that supports
672 * configuring CS timing.
673 *
674 * This hook allows SPI client drivers to request SPI controllers
675 * to configure specific CS timing through spi_set_cs_timing() after
676 * spi_setup().
677 */
678 int (*set_cs_timing)(struct spi_device *spi);
679
680 /*
681 * Bidirectional bulk transfers
682 *
683 * + The transfer() method may not sleep; its main role is
684 * just to add the message to the queue.
685 * + For now there's no remove-from-queue operation, or
686 * any other request management
687 * + To a given spi_device, message queueing is pure FIFO
688 *
689 * + The controller's main job is to process its message queue,
690 * selecting a chip (for controllers), then transferring data
691 * + If there are multiple spi_device children, the i/o queue
692 * arbitration algorithm is unspecified (round robin, FIFO,
693 * priority, reservations, preemption, etc)
694 *
695 * + Chipselect stays active during the entire message
696 * (unless modified by spi_transfer.cs_change != 0).
697 * + The message transfers use clock and SPI mode parameters
698 * previously established by setup() for this device
699 */
700 int (*transfer)(struct spi_device *spi,
701 struct spi_message *mesg);
702
703 /* Called on release() to free memory provided by spi_controller */
704 void (*cleanup)(struct spi_device *spi);
705
706 /*
707 * Used to enable core support for DMA handling, if can_dma()
708 * exists and returns true then the transfer will be mapped
709 * prior to transfer_one() being called. The driver should
710 * not modify or store xfer and dma_tx and dma_rx must be set
711 * while the device is prepared.
712 */
713 bool (*can_dma)(struct spi_controller *ctlr,
714 struct spi_device *spi,
715 struct spi_transfer *xfer);
716 struct device *dma_map_dev;
717 struct device *cur_rx_dma_dev;
718 struct device *cur_tx_dma_dev;
719
720 /*
721 * These hooks are for drivers that want to use the generic
722 * controller transfer queueing mechanism. If these are used, the
723 * transfer() function above must NOT be specified by the driver.
724 * Over time we expect SPI drivers to be phased over to this API.
725 */
726 bool queued;
727 struct kthread_worker *kworker;
728 struct kthread_work pump_messages;
729 spinlock_t queue_lock;
730 struct list_head queue;
731 struct spi_message *cur_msg;
732 struct completion cur_msg_completion;
733 bool cur_msg_incomplete;
734 bool cur_msg_need_completion;
735 bool busy;
736 bool running;
737 bool rt;
738 bool auto_runtime_pm;
739 bool fallback;
740 bool last_cs_mode_high;
741 s8 last_cs[SPI_DEVICE_CS_CNT_MAX];
742 u32 last_cs_index_mask : SPI_DEVICE_CS_CNT_MAX;
743 struct completion xfer_completion;
744 size_t max_dma_len;
745
746 int (*optimize_message)(struct spi_message *msg);
747 int (*unoptimize_message)(struct spi_message *msg);
748 int (*prepare_transfer_hardware)(struct spi_controller *ctlr);
749 int (*transfer_one_message)(struct spi_controller *ctlr,
750 struct spi_message *mesg);
751 int (*unprepare_transfer_hardware)(struct spi_controller *ctlr);
752 int (*prepare_message)(struct spi_controller *ctlr,
753 struct spi_message *message);
754 int (*unprepare_message)(struct spi_controller *ctlr,
755 struct spi_message *message);
756 int (*target_abort)(struct spi_controller *ctlr);
757
758 /*
759 * These hooks are for drivers that use a generic implementation
760 * of transfer_one_message() provided by the core.
761 */
762 void (*set_cs)(struct spi_device *spi, bool enable);
763 int (*transfer_one)(struct spi_controller *ctlr, struct spi_device *spi,
764 struct spi_transfer *transfer);
765 void (*handle_err)(struct spi_controller *ctlr,
766 struct spi_message *message);
767
768 /* Optimized handlers for SPI memory-like operations. */
769 const struct spi_controller_mem_ops *mem_ops;
770 const struct spi_controller_mem_caps *mem_caps;
771
772 /* SPI or QSPI controller can set to true if supports SDR/DDR transfer rate */
773 bool dtr_caps;
774
775 struct spi_offload *(*get_offload)(struct spi_device *spi,
776 const struct spi_offload_config *config);
777 void (*put_offload)(struct spi_offload *offload);
778
779 /* GPIO chip select */
780 struct gpio_desc **cs_gpiods;
781 bool use_gpio_descriptors;
782 s8 unused_native_cs;
783 s8 max_native_cs;
784
785 /* Statistics */
786 struct spi_statistics __percpu *pcpu_statistics;
787
788 /* DMA channels for use with core dmaengine helpers */
789 struct dma_chan *dma_tx;
790 struct dma_chan *dma_rx;
791
792 /* Dummy data for full duplex devices */
793 void *dummy_rx;
794 void *dummy_tx;
795
796 int (*fw_translate_cs)(struct spi_controller *ctlr, unsigned cs);
797
798 /*
799 * Driver sets this field to indicate it is able to snapshot SPI
800 * transfers (needed e.g. for reading the time of POSIX clocks)
801 */
802 bool ptp_sts_supported;
803
804 /* Interrupt enable state during PTP system timestamping */
805 unsigned long irq_flags;
806
807 /* Flag for enabling opportunistic skipping of the queue in spi_sync */
808 bool queue_empty;
809 bool must_async;
810 bool defer_optimize_message;
811 };
812
spi_controller_get_devdata(struct spi_controller * ctlr)813 static inline void *spi_controller_get_devdata(struct spi_controller *ctlr)
814 {
815 return dev_get_drvdata(&ctlr->dev);
816 }
817
spi_controller_set_devdata(struct spi_controller * ctlr,void * data)818 static inline void spi_controller_set_devdata(struct spi_controller *ctlr,
819 void *data)
820 {
821 dev_set_drvdata(&ctlr->dev, data);
822 }
823
spi_controller_get(struct spi_controller * ctlr)824 static inline struct spi_controller *spi_controller_get(struct spi_controller *ctlr)
825 {
826 if (!ctlr || !get_device(&ctlr->dev))
827 return NULL;
828 return ctlr;
829 }
830
spi_controller_put(struct spi_controller * ctlr)831 static inline void spi_controller_put(struct spi_controller *ctlr)
832 {
833 if (ctlr)
834 put_device(&ctlr->dev);
835 }
836
spi_controller_is_target(struct spi_controller * ctlr)837 static inline bool spi_controller_is_target(struct spi_controller *ctlr)
838 {
839 return IS_ENABLED(CONFIG_SPI_SLAVE) && ctlr->target;
840 }
841
842 /* PM calls that need to be issued by the driver */
843 extern int spi_controller_suspend(struct spi_controller *ctlr);
844 extern int spi_controller_resume(struct spi_controller *ctlr);
845
846 /* Calls the driver make to interact with the message queue */
847 extern struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr);
848 extern void spi_finalize_current_message(struct spi_controller *ctlr);
849 extern void spi_finalize_current_transfer(struct spi_controller *ctlr);
850
851 /* Helper calls for driver to timestamp transfer */
852 void spi_take_timestamp_pre(struct spi_controller *ctlr,
853 struct spi_transfer *xfer,
854 size_t progress, bool irqs_off);
855 void spi_take_timestamp_post(struct spi_controller *ctlr,
856 struct spi_transfer *xfer,
857 size_t progress, bool irqs_off);
858
859 /* The SPI driver core manages memory for the spi_controller classdev */
860 extern struct spi_controller *__spi_alloc_controller(struct device *host,
861 unsigned int size, bool target);
862
spi_alloc_host(struct device * dev,unsigned int size)863 static inline struct spi_controller *spi_alloc_host(struct device *dev,
864 unsigned int size)
865 {
866 return __spi_alloc_controller(dev, size, false);
867 }
868
spi_alloc_target(struct device * dev,unsigned int size)869 static inline struct spi_controller *spi_alloc_target(struct device *dev,
870 unsigned int size)
871 {
872 if (!IS_ENABLED(CONFIG_SPI_SLAVE))
873 return NULL;
874
875 return __spi_alloc_controller(dev, size, true);
876 }
877
878 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
879 unsigned int size,
880 bool target);
881
devm_spi_alloc_host(struct device * dev,unsigned int size)882 static inline struct spi_controller *devm_spi_alloc_host(struct device *dev,
883 unsigned int size)
884 {
885 return __devm_spi_alloc_controller(dev, size, false);
886 }
887
devm_spi_alloc_target(struct device * dev,unsigned int size)888 static inline struct spi_controller *devm_spi_alloc_target(struct device *dev,
889 unsigned int size)
890 {
891 if (!IS_ENABLED(CONFIG_SPI_SLAVE))
892 return NULL;
893
894 return __devm_spi_alloc_controller(dev, size, true);
895 }
896
897 extern int spi_register_controller(struct spi_controller *ctlr);
898 extern int devm_spi_register_controller(struct device *dev,
899 struct spi_controller *ctlr);
900 extern void spi_unregister_controller(struct spi_controller *ctlr);
901
902 #if IS_ENABLED(CONFIG_OF)
903 extern struct spi_controller *of_find_spi_controller_by_node(struct device_node *node);
904 #else
of_find_spi_controller_by_node(struct device_node * node)905 static inline struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
906 {
907 return NULL;
908 }
909 #endif
910
911 #if IS_ENABLED(CONFIG_ACPI) && IS_ENABLED(CONFIG_SPI_MASTER)
912 extern struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev);
913 extern struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
914 struct acpi_device *adev,
915 int index);
916 int acpi_spi_count_resources(struct acpi_device *adev);
917 #else
acpi_spi_find_controller_by_adev(struct acpi_device * adev)918 static inline struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
919 {
920 return NULL;
921 }
922
acpi_spi_device_alloc(struct spi_controller * ctlr,struct acpi_device * adev,int index)923 static inline struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
924 struct acpi_device *adev,
925 int index)
926 {
927 return ERR_PTR(-ENODEV);
928 }
929
acpi_spi_count_resources(struct acpi_device * adev)930 static inline int acpi_spi_count_resources(struct acpi_device *adev)
931 {
932 return 0;
933 }
934 #endif
935
936 /*
937 * SPI resource management while processing a SPI message
938 */
939
940 typedef void (*spi_res_release_t)(struct spi_controller *ctlr,
941 struct spi_message *msg,
942 void *res);
943
944 /**
945 * struct spi_res - SPI resource management structure
946 * @entry: list entry
947 * @release: release code called prior to freeing this resource
948 * @data: extra data allocated for the specific use-case
949 *
950 * This is based on ideas from devres, but focused on life-cycle
951 * management during spi_message processing.
952 */
953 struct spi_res {
954 struct list_head entry;
955 spi_res_release_t release;
956 unsigned long long data[]; /* Guarantee ull alignment */
957 };
958
959 /*---------------------------------------------------------------------------*/
960
961 /*
962 * I/O INTERFACE between SPI controller and protocol drivers
963 *
964 * Protocol drivers use a queue of spi_messages, each transferring data
965 * between the controller and memory buffers.
966 *
967 * The spi_messages themselves consist of a series of read+write transfer
968 * segments. Those segments always read the same number of bits as they
969 * write; but one or the other is easily ignored by passing a NULL buffer
970 * pointer. (This is unlike most types of I/O API, because SPI hardware
971 * is full duplex.)
972 *
973 * NOTE: Allocation of spi_transfer and spi_message memory is entirely
974 * up to the protocol driver, which guarantees the integrity of both (as
975 * well as the data buffers) for as long as the message is queued.
976 */
977
978 /**
979 * struct spi_transfer - a read/write buffer pair
980 * @tx_buf: data to be written (DMA-safe memory), or NULL
981 * @rx_buf: data to be read (DMA-safe memory), or NULL
982 * @tx_dma: DMA address of tx_buf, currently not for client use
983 * @rx_dma: DMA address of rx_buf, currently not for client use
984 * @tx_nbits: number of bits used for writing. If 0 the default
985 * (SPI_NBITS_SINGLE) is used.
986 * @rx_nbits: number of bits used for reading. If 0 the default
987 * (SPI_NBITS_SINGLE) is used.
988 * @multi_lane_mode: How to serialize data on multiple lanes. One of the
989 * SPI_MULTI_LANE_MODE_* values.
990 * @len: size of rx and tx buffers (in bytes)
991 * @speed_hz: Select a speed other than the device default for this
992 * transfer. If 0 the default (from @spi_device) is used.
993 * @bits_per_word: select a bits_per_word other than the device default
994 * for this transfer. If 0 the default (from @spi_device) is used.
995 * @dummy_data: indicates transfer is dummy bytes transfer.
996 * @cs_off: performs the transfer with chipselect off.
997 * @cs_change: affects chipselect after this transfer completes
998 * @cs_change_delay: delay between cs deassert and assert when
999 * @cs_change is set and @spi_transfer is not the last in @spi_message
1000 * @delay: delay to be introduced after this transfer before
1001 * (optionally) changing the chipselect status, then starting
1002 * the next transfer or completing this @spi_message.
1003 * @word_delay: inter word delay to be introduced after each word size
1004 * (set by bits_per_word) transmission.
1005 * @effective_speed_hz: the effective SCK-speed that was used to
1006 * transfer this transfer. Set to 0 if the SPI bus driver does
1007 * not support it.
1008 * @transfer_list: transfers are sequenced through @spi_message.transfers
1009 * @tx_sg_mapped: If true, the @tx_sg is mapped for DMA
1010 * @rx_sg_mapped: If true, the @rx_sg is mapped for DMA
1011 * @tx_sg: Scatterlist for transmit, currently not for client use
1012 * @rx_sg: Scatterlist for receive, currently not for client use
1013 * @offload_flags: Flags that are only applicable to specialized SPI offload
1014 * transfers. See %SPI_OFFLOAD_XFER_* in spi-offload.h.
1015 * @ptp_sts_word_pre: The word (subject to bits_per_word semantics) offset
1016 * within @tx_buf for which the SPI device is requesting that the time
1017 * snapshot for this transfer begins. Upon completing the SPI transfer,
1018 * this value may have changed compared to what was requested, depending
1019 * on the available snapshotting resolution (DMA transfer,
1020 * @ptp_sts_supported is false, etc).
1021 * @ptp_sts_word_post: See @ptp_sts_word_post. The two can be equal (meaning
1022 * that a single byte should be snapshotted).
1023 * If the core takes care of the timestamp (if @ptp_sts_supported is false
1024 * for this controller), it will set @ptp_sts_word_pre to 0, and
1025 * @ptp_sts_word_post to the length of the transfer. This is done
1026 * purposefully (instead of setting to spi_transfer->len - 1) to denote
1027 * that a transfer-level snapshot taken from within the driver may still
1028 * be of higher quality.
1029 * @ptp_sts: Pointer to a memory location held by the SPI target device where a
1030 * PTP system timestamp structure may lie. If drivers use PIO or their
1031 * hardware has some sort of assist for retrieving exact transfer timing,
1032 * they can (and should) assert @ptp_sts_supported and populate this
1033 * structure using the ptp_read_system_*ts helper functions.
1034 * The timestamp must represent the time at which the SPI target device has
1035 * processed the word, i.e. the "pre" timestamp should be taken before
1036 * transmitting the "pre" word, and the "post" timestamp after receiving
1037 * transmit confirmation from the controller for the "post" word.
1038 * @dtr_mode: true if supports double transfer rate.
1039 * @timestamped: true if the transfer has been timestamped
1040 * @error: Error status logged by SPI controller driver.
1041 *
1042 * SPI transfers always write the same number of bytes as they read.
1043 * Protocol drivers should always provide @rx_buf and/or @tx_buf.
1044 * In some cases, they may also want to provide DMA addresses for
1045 * the data being transferred; that may reduce overhead, when the
1046 * underlying driver uses DMA.
1047 *
1048 * If the transmit buffer is NULL, zeroes will be shifted out
1049 * while filling @rx_buf. If the receive buffer is NULL, the data
1050 * shifted in will be discarded. Only "len" bytes shift out (or in).
1051 * It's an error to try to shift out a partial word. (For example, by
1052 * shifting out three bytes with word size of sixteen or twenty bits;
1053 * the former uses two bytes per word, the latter uses four bytes.)
1054 *
1055 * In-memory data values are always in native CPU byte order, translated
1056 * from the wire byte order (big-endian except with SPI_LSB_FIRST). So
1057 * for example when bits_per_word is sixteen, buffers are 2N bytes long
1058 * (@len = 2N) and hold N sixteen bit words in CPU byte order.
1059 *
1060 * When the word size of the SPI transfer is not a power-of-two multiple
1061 * of eight bits, those in-memory words include extra bits. In-memory
1062 * words are always seen by protocol drivers as right-justified, so the
1063 * undefined (rx) or unused (tx) bits are always the most significant bits.
1064 *
1065 * All SPI transfers start with the relevant chipselect active. Normally
1066 * it stays selected until after the last transfer in a message. Drivers
1067 * can affect the chipselect signal using cs_change.
1068 *
1069 * (i) If the transfer isn't the last one in the message, this flag is
1070 * used to make the chipselect briefly go inactive in the middle of the
1071 * message. Toggling chipselect in this way may be needed to terminate
1072 * a chip command, letting a single spi_message perform all of group of
1073 * chip transactions together.
1074 *
1075 * (ii) When the transfer is the last one in the message, the chip may
1076 * stay selected until the next transfer. On multi-device SPI busses
1077 * with nothing blocking messages going to other devices, this is just
1078 * a performance hint; starting a message to another device deselects
1079 * this one. But in other cases, this can be used to ensure correctness.
1080 * Some devices need protocol transactions to be built from a series of
1081 * spi_message submissions, where the content of one message is determined
1082 * by the results of previous messages and where the whole transaction
1083 * ends when the chipselect goes inactive.
1084 *
1085 * When SPI can transfer in 1x,2x or 4x. It can get this transfer information
1086 * from device through @tx_nbits and @rx_nbits. In Bi-direction, these
1087 * two should both be set. User can set transfer mode with SPI_NBITS_SINGLE(1x)
1088 * SPI_NBITS_DUAL(2x) and SPI_NBITS_QUAD(4x) to support these three transfer.
1089 *
1090 * User may also set dtr_mode to true to use dual transfer mode if desired. if
1091 * not, default considered as single transfer mode.
1092 *
1093 * The code that submits an spi_message (and its spi_transfers)
1094 * to the lower layers is responsible for managing its memory.
1095 * Zero-initialize every field you don't set up explicitly, to
1096 * insulate against future API updates. After you submit a message
1097 * and its transfers, ignore them until its completion callback.
1098 */
1099 struct spi_transfer {
1100 /*
1101 * It's okay if tx_buf == rx_buf (right?).
1102 * For MicroWire, one buffer must be NULL.
1103 * Buffers must work with dma_*map_single() calls.
1104 */
1105 const void *tx_buf;
1106 void *rx_buf;
1107 unsigned len;
1108
1109 #define SPI_TRANS_FAIL_NO_START BIT(0)
1110 #define SPI_TRANS_FAIL_IO BIT(1)
1111 u16 error;
1112
1113 bool tx_sg_mapped;
1114 bool rx_sg_mapped;
1115
1116 struct sg_table tx_sg;
1117 struct sg_table rx_sg;
1118 dma_addr_t tx_dma;
1119 dma_addr_t rx_dma;
1120
1121 unsigned dummy_data:1;
1122 unsigned cs_off:1;
1123 unsigned cs_change:1;
1124 unsigned tx_nbits:4;
1125 unsigned rx_nbits:4;
1126
1127 #define SPI_MULTI_LANE_MODE_SINGLE 0 /* only use single lane */
1128 #define SPI_MULTI_LANE_MODE_STRIPE 1 /* one data word per lane */
1129 #define SPI_MULTI_LANE_MODE_MIRROR 2 /* same word sent on all lanes */
1130 unsigned multi_lane_mode: 2;
1131
1132 unsigned timestamped:1;
1133 bool dtr_mode;
1134 #define SPI_NBITS_SINGLE 0x01 /* 1-bit transfer */
1135 #define SPI_NBITS_DUAL 0x02 /* 2-bit transfer */
1136 #define SPI_NBITS_QUAD 0x04 /* 4-bit transfer */
1137 #define SPI_NBITS_OCTAL 0x08 /* 8-bit transfer */
1138 u8 bits_per_word;
1139 struct spi_delay delay;
1140 struct spi_delay cs_change_delay;
1141 struct spi_delay word_delay;
1142 u32 speed_hz;
1143
1144 u32 effective_speed_hz;
1145
1146 /* Use %SPI_OFFLOAD_XFER_* from spi-offload.h */
1147 unsigned int offload_flags;
1148
1149 unsigned int ptp_sts_word_pre;
1150 unsigned int ptp_sts_word_post;
1151
1152 struct ptp_system_timestamp *ptp_sts;
1153
1154 struct list_head transfer_list;
1155 };
1156
1157 /**
1158 * struct spi_message - one multi-segment SPI transaction
1159 * @transfers: list of transfer segments in this transaction
1160 * @spi: SPI device to which the transaction is queued
1161 * @pre_optimized: peripheral driver pre-optimized the message
1162 * @optimized: the message is in the optimized state
1163 * @prepared: spi_prepare_message was called for the this message
1164 * @status: zero for success, else negative errno
1165 * @complete: called to report transaction completions
1166 * @context: the argument to complete() when it's called
1167 * @frame_length: the total number of bytes in the message
1168 * @actual_length: the total number of bytes that were transferred in all
1169 * successful segments
1170 * @queue: for use by whichever driver currently owns the message
1171 * @state: for use by whichever driver currently owns the message
1172 * @opt_state: for use by whichever driver currently owns the message
1173 * @resources: for resource management when the SPI message is processed
1174 * @offload: (optional) offload instance used by this message
1175 *
1176 * A @spi_message is used to execute an atomic sequence of data transfers,
1177 * each represented by a struct spi_transfer. The sequence is "atomic"
1178 * in the sense that no other spi_message may use that SPI bus until that
1179 * sequence completes. On some systems, many such sequences can execute as
1180 * a single programmed DMA transfer. On all systems, these messages are
1181 * queued, and might complete after transactions to other devices. Messages
1182 * sent to a given spi_device are always executed in FIFO order.
1183 *
1184 * The code that submits an spi_message (and its spi_transfers)
1185 * to the lower layers is responsible for managing its memory.
1186 * Zero-initialize every field you don't set up explicitly, to
1187 * insulate against future API updates. After you submit a message
1188 * and its transfers, ignore them until its completion callback.
1189 */
1190 struct spi_message {
1191 struct list_head transfers;
1192
1193 struct spi_device *spi;
1194
1195 /* spi_optimize_message() was called for this message */
1196 bool pre_optimized;
1197 /* __spi_optimize_message() was called for this message */
1198 bool optimized;
1199
1200 /* spi_prepare_message() was called for this message */
1201 bool prepared;
1202
1203 /*
1204 * REVISIT: we might want a flag affecting the behavior of the
1205 * last transfer ... allowing things like "read 16 bit length L"
1206 * immediately followed by "read L bytes". Basically imposing
1207 * a specific message scheduling algorithm.
1208 *
1209 * Some controller drivers (message-at-a-time queue processing)
1210 * could provide that as their default scheduling algorithm. But
1211 * others (with multi-message pipelines) could need a flag to
1212 * tell them about such special cases.
1213 */
1214
1215 /* Completion is reported through a callback */
1216 int status;
1217 void (*complete)(void *context);
1218 void *context;
1219 unsigned frame_length;
1220 unsigned actual_length;
1221
1222 /*
1223 * For optional use by whatever driver currently owns the
1224 * spi_message ... between calls to spi_async and then later
1225 * complete(), that's the spi_controller controller driver.
1226 */
1227 struct list_head queue;
1228 void *state;
1229 /*
1230 * Optional state for use by controller driver between calls to
1231 * __spi_optimize_message() and __spi_unoptimize_message().
1232 */
1233 void *opt_state;
1234
1235 /*
1236 * Optional offload instance used by this message. This must be set
1237 * by the peripheral driver before calling spi_optimize_message().
1238 */
1239 struct spi_offload *offload;
1240
1241 /* List of spi_res resources when the SPI message is processed */
1242 struct list_head resources;
1243 };
1244
spi_message_init_no_memset(struct spi_message * m)1245 static inline void spi_message_init_no_memset(struct spi_message *m)
1246 {
1247 INIT_LIST_HEAD(&m->transfers);
1248 INIT_LIST_HEAD(&m->resources);
1249 }
1250
spi_message_init(struct spi_message * m)1251 static inline void spi_message_init(struct spi_message *m)
1252 {
1253 memset(m, 0, sizeof *m);
1254 spi_message_init_no_memset(m);
1255 }
1256
1257 static inline void
spi_message_add_tail(struct spi_transfer * t,struct spi_message * m)1258 spi_message_add_tail(struct spi_transfer *t, struct spi_message *m)
1259 {
1260 list_add_tail(&t->transfer_list, &m->transfers);
1261 }
1262
1263 static inline void
spi_transfer_del(struct spi_transfer * t)1264 spi_transfer_del(struct spi_transfer *t)
1265 {
1266 list_del(&t->transfer_list);
1267 }
1268
1269 static inline int
spi_transfer_delay_exec(struct spi_transfer * t)1270 spi_transfer_delay_exec(struct spi_transfer *t)
1271 {
1272 return spi_delay_exec(&t->delay, t);
1273 }
1274
1275 /**
1276 * spi_message_init_with_transfers - Initialize spi_message and append transfers
1277 * @m: spi_message to be initialized
1278 * @xfers: An array of SPI transfers
1279 * @num_xfers: Number of items in the xfer array
1280 *
1281 * This function initializes the given spi_message and adds each spi_transfer in
1282 * the given array to the message.
1283 */
1284 static inline void
spi_message_init_with_transfers(struct spi_message * m,struct spi_transfer * xfers,unsigned int num_xfers)1285 spi_message_init_with_transfers(struct spi_message *m,
1286 struct spi_transfer *xfers, unsigned int num_xfers)
1287 {
1288 unsigned int i;
1289
1290 spi_message_init(m);
1291 for (i = 0; i < num_xfers; ++i)
1292 spi_message_add_tail(&xfers[i], m);
1293 }
1294
1295 /*
1296 * It's fine to embed message and transaction structures in other data
1297 * structures so long as you don't free them while they're in use.
1298 */
spi_message_alloc(unsigned ntrans,gfp_t flags)1299 static inline struct spi_message *spi_message_alloc(unsigned ntrans, gfp_t flags)
1300 {
1301 struct spi_message_with_transfers {
1302 struct spi_message m;
1303 struct spi_transfer t[];
1304 } *mwt;
1305 unsigned i;
1306
1307 mwt = kzalloc_flex(*mwt, t, ntrans, flags);
1308 if (!mwt)
1309 return NULL;
1310
1311 spi_message_init_no_memset(&mwt->m);
1312 for (i = 0; i < ntrans; i++)
1313 spi_message_add_tail(&mwt->t[i], &mwt->m);
1314
1315 return &mwt->m;
1316 }
1317
spi_message_free(struct spi_message * m)1318 static inline void spi_message_free(struct spi_message *m)
1319 {
1320 kfree(m);
1321 }
1322
1323 extern int spi_optimize_message(struct spi_device *spi, struct spi_message *msg);
1324 extern void spi_unoptimize_message(struct spi_message *msg);
1325 extern int devm_spi_optimize_message(struct device *dev, struct spi_device *spi,
1326 struct spi_message *msg);
1327
1328 extern int spi_setup(struct spi_device *spi);
1329 extern int spi_async(struct spi_device *spi, struct spi_message *message);
1330 extern int spi_target_abort(struct spi_device *spi);
1331
1332 static inline size_t
spi_max_message_size(struct spi_device * spi)1333 spi_max_message_size(struct spi_device *spi)
1334 {
1335 struct spi_controller *ctlr = spi->controller;
1336
1337 if (!ctlr->max_message_size)
1338 return SIZE_MAX;
1339 return ctlr->max_message_size(spi);
1340 }
1341
1342 static inline size_t
spi_max_transfer_size(struct spi_device * spi)1343 spi_max_transfer_size(struct spi_device *spi)
1344 {
1345 struct spi_controller *ctlr = spi->controller;
1346 size_t tr_max = SIZE_MAX;
1347 size_t msg_max = spi_max_message_size(spi);
1348
1349 if (ctlr->max_transfer_size)
1350 tr_max = ctlr->max_transfer_size(spi);
1351
1352 /* Transfer size limit must not be greater than message size limit */
1353 return min(tr_max, msg_max);
1354 }
1355
1356 /**
1357 * spi_is_bpw_supported - Check if bits per word is supported
1358 * @spi: SPI device
1359 * @bpw: Bits per word
1360 *
1361 * This function checks to see if the SPI controller supports @bpw.
1362 *
1363 * Returns:
1364 * True if @bpw is supported, false otherwise.
1365 */
spi_is_bpw_supported(struct spi_device * spi,u32 bpw)1366 static inline bool spi_is_bpw_supported(struct spi_device *spi, u32 bpw)
1367 {
1368 u32 bpw_mask = spi->controller->bits_per_word_mask;
1369
1370 if (bpw == 8 || (bpw <= 32 && bpw_mask & SPI_BPW_MASK(bpw)))
1371 return true;
1372
1373 return false;
1374 }
1375
1376 /**
1377 * spi_bpw_to_bytes - Covert bits per word to bytes
1378 * @bpw: Bits per word
1379 *
1380 * This function converts the given @bpw to bytes. The result is always
1381 * power-of-two, e.g.,
1382 *
1383 * =============== =================
1384 * Input (in bits) Output (in bytes)
1385 * =============== =================
1386 * 5 1
1387 * 9 2
1388 * 21 4
1389 * 37 8
1390 * =============== =================
1391 *
1392 * It will return 0 for the 0 input.
1393 *
1394 * Returns:
1395 * Bytes for the given @bpw.
1396 */
spi_bpw_to_bytes(u32 bpw)1397 static inline u32 spi_bpw_to_bytes(u32 bpw)
1398 {
1399 return roundup_pow_of_two(BITS_TO_BYTES(bpw));
1400 }
1401
1402 /**
1403 * spi_controller_xfer_timeout - Compute a suitable timeout value
1404 * @ctlr: SPI device
1405 * @xfer: Transfer descriptor
1406 *
1407 * Compute a relevant timeout value for the given transfer. We derive the time
1408 * that it would take on a single data line and take twice this amount of time
1409 * with a minimum of 500ms to avoid false positives on loaded systems.
1410 *
1411 * Returns: Transfer timeout value in milliseconds.
1412 */
spi_controller_xfer_timeout(struct spi_controller * ctlr,struct spi_transfer * xfer)1413 static inline unsigned int spi_controller_xfer_timeout(struct spi_controller *ctlr,
1414 struct spi_transfer *xfer)
1415 {
1416 return max(xfer->len * 8 * 2 / (xfer->speed_hz / 1000), 500U);
1417 }
1418
1419 /*---------------------------------------------------------------------------*/
1420
1421 /* SPI transfer replacement methods which make use of spi_res */
1422
1423 struct spi_replaced_transfers;
1424 typedef void (*spi_replaced_release_t)(struct spi_controller *ctlr,
1425 struct spi_message *msg,
1426 struct spi_replaced_transfers *res);
1427 /**
1428 * struct spi_replaced_transfers - structure describing the spi_transfer
1429 * replacements that have occurred
1430 * so that they can get reverted
1431 * @release: some extra release code to get executed prior to
1432 * releasing this structure
1433 * @extradata: pointer to some extra data if requested or NULL
1434 * @replaced_transfers: transfers that have been replaced and which need
1435 * to get restored
1436 * @replaced_after: the transfer after which the @replaced_transfers
1437 * are to get re-inserted
1438 * @inserted: number of transfers inserted
1439 * @inserted_transfers: array of spi_transfers of array-size @inserted,
1440 * that have been replacing replaced_transfers
1441 *
1442 * Note: that @extradata will point to @inserted_transfers[@inserted]
1443 * if some extra allocation is requested, so alignment will be the same
1444 * as for spi_transfers.
1445 */
1446 struct spi_replaced_transfers {
1447 spi_replaced_release_t release;
1448 void *extradata;
1449 struct list_head replaced_transfers;
1450 struct list_head *replaced_after;
1451 size_t inserted;
1452 struct spi_transfer inserted_transfers[];
1453 };
1454
1455 /*---------------------------------------------------------------------------*/
1456
1457 /* SPI transfer transformation methods */
1458
1459 extern int spi_split_transfers_maxsize(struct spi_controller *ctlr,
1460 struct spi_message *msg,
1461 size_t maxsize);
1462 extern int spi_split_transfers_maxwords(struct spi_controller *ctlr,
1463 struct spi_message *msg,
1464 size_t maxwords);
1465
1466 /*---------------------------------------------------------------------------*/
1467
1468 /*
1469 * All these synchronous SPI transfer routines are utilities layered
1470 * over the core async transfer primitive. Here, "synchronous" means
1471 * they will sleep uninterruptibly until the async transfer completes.
1472 */
1473
1474 extern int spi_sync(struct spi_device *spi, struct spi_message *message);
1475 extern int spi_sync_locked(struct spi_device *spi, struct spi_message *message);
1476 extern int spi_bus_lock(struct spi_controller *ctlr);
1477 extern int spi_bus_unlock(struct spi_controller *ctlr);
1478
1479 /**
1480 * spi_sync_transfer - synchronous SPI data transfer
1481 * @spi: device with which data will be exchanged
1482 * @xfers: An array of spi_transfers
1483 * @num_xfers: Number of items in the xfer array
1484 * Context: can sleep
1485 *
1486 * Does a synchronous SPI data transfer of the given spi_transfer array.
1487 *
1488 * For more specific semantics see spi_sync().
1489 *
1490 * Return: zero on success, else a negative error code.
1491 */
1492 static inline int
spi_sync_transfer(struct spi_device * spi,struct spi_transfer * xfers,unsigned int num_xfers)1493 spi_sync_transfer(struct spi_device *spi, struct spi_transfer *xfers,
1494 unsigned int num_xfers)
1495 {
1496 struct spi_message msg;
1497
1498 spi_message_init_with_transfers(&msg, xfers, num_xfers);
1499
1500 return spi_sync(spi, &msg);
1501 }
1502
1503 /**
1504 * spi_write - SPI synchronous write
1505 * @spi: device to which data will be written
1506 * @buf: data buffer
1507 * @len: data buffer size
1508 * Context: can sleep
1509 *
1510 * This function writes the buffer @buf.
1511 * Callable only from contexts that can sleep.
1512 *
1513 * Return: zero on success, else a negative error code.
1514 */
1515 static inline int
spi_write(struct spi_device * spi,const void * buf,size_t len)1516 spi_write(struct spi_device *spi, const void *buf, size_t len)
1517 {
1518 struct spi_transfer t = {
1519 .tx_buf = buf,
1520 .len = len,
1521 };
1522
1523 return spi_sync_transfer(spi, &t, 1);
1524 }
1525
1526 /**
1527 * spi_read - SPI synchronous read
1528 * @spi: device from which data will be read
1529 * @buf: data buffer
1530 * @len: data buffer size
1531 * Context: can sleep
1532 *
1533 * This function reads the buffer @buf.
1534 * Callable only from contexts that can sleep.
1535 *
1536 * Return: zero on success, else a negative error code.
1537 */
1538 static inline int
spi_read(struct spi_device * spi,void * buf,size_t len)1539 spi_read(struct spi_device *spi, void *buf, size_t len)
1540 {
1541 struct spi_transfer t = {
1542 .rx_buf = buf,
1543 .len = len,
1544 };
1545
1546 return spi_sync_transfer(spi, &t, 1);
1547 }
1548
1549 /* This copies txbuf and rxbuf data; for small transfers only! */
1550 extern int spi_write_then_read(struct spi_device *spi,
1551 const void *txbuf, unsigned n_tx,
1552 void *rxbuf, unsigned n_rx);
1553
1554 /**
1555 * spi_w8r8 - SPI synchronous 8 bit write followed by 8 bit read
1556 * @spi: device with which data will be exchanged
1557 * @cmd: command to be written before data is read back
1558 * Context: can sleep
1559 *
1560 * Callable only from contexts that can sleep.
1561 *
1562 * Return: the (unsigned) eight bit number returned by the
1563 * device, or else a negative error code.
1564 */
spi_w8r8(struct spi_device * spi,u8 cmd)1565 static inline ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)
1566 {
1567 ssize_t status;
1568 u8 result;
1569
1570 status = spi_write_then_read(spi, &cmd, 1, &result, 1);
1571
1572 /* Return negative errno or unsigned value */
1573 return (status < 0) ? status : result;
1574 }
1575
1576 /**
1577 * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read
1578 * @spi: device with which data will be exchanged
1579 * @cmd: command to be written before data is read back
1580 * Context: can sleep
1581 *
1582 * The number is returned in wire-order, which is at least sometimes
1583 * big-endian.
1584 *
1585 * Callable only from contexts that can sleep.
1586 *
1587 * Return: the (unsigned) sixteen bit number returned by the
1588 * device, or else a negative error code.
1589 */
spi_w8r16(struct spi_device * spi,u8 cmd)1590 static inline ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)
1591 {
1592 ssize_t status;
1593 u16 result;
1594
1595 status = spi_write_then_read(spi, &cmd, 1, &result, 2);
1596
1597 /* Return negative errno or unsigned value */
1598 return (status < 0) ? status : result;
1599 }
1600
1601 /**
1602 * spi_w8r16be - SPI synchronous 8 bit write followed by 16 bit big-endian read
1603 * @spi: device with which data will be exchanged
1604 * @cmd: command to be written before data is read back
1605 * Context: can sleep
1606 *
1607 * This function is similar to spi_w8r16, with the exception that it will
1608 * convert the read 16 bit data word from big-endian to native endianness.
1609 *
1610 * Callable only from contexts that can sleep.
1611 *
1612 * Return: the (unsigned) sixteen bit number returned by the device in CPU
1613 * endianness, or else a negative error code.
1614 */
spi_w8r16be(struct spi_device * spi,u8 cmd)1615 static inline ssize_t spi_w8r16be(struct spi_device *spi, u8 cmd)
1616
1617 {
1618 ssize_t status;
1619 __be16 result;
1620
1621 status = spi_write_then_read(spi, &cmd, 1, &result, 2);
1622 if (status < 0)
1623 return status;
1624
1625 return be16_to_cpu(result);
1626 }
1627
1628 /*---------------------------------------------------------------------------*/
1629
1630 /*
1631 * INTERFACE between board init code and SPI infrastructure.
1632 *
1633 * No SPI driver ever sees these SPI device table segments, but
1634 * it's how the SPI core (or adapters that get hotplugged) grows
1635 * the driver model tree.
1636 *
1637 * As a rule, SPI devices can't be probed. Instead, board init code
1638 * provides a table listing the devices which are present, with enough
1639 * information to bind and set up the device's driver. There's basic
1640 * support for non-static configurations too; enough to handle adding
1641 * parport adapters, or microcontrollers acting as USB-to-SPI bridges.
1642 */
1643
1644 /**
1645 * struct spi_board_info - board-specific template for a SPI device
1646 * @modalias: Initializes spi_device.modalias; identifies the driver.
1647 * @platform_data: Initializes spi_device.platform_data; the particular
1648 * data stored there is driver-specific.
1649 * @swnode: Software node for the device.
1650 * @controller_data: Initializes spi_device.controller_data; some
1651 * controllers need hints about hardware setup, e.g. for DMA.
1652 * @irq: Initializes spi_device.irq; depends on how the board is wired.
1653 * @max_speed_hz: Initializes spi_device.max_speed_hz; based on limits
1654 * from the chip datasheet and board-specific signal quality issues.
1655 * @bus_num: Identifies which spi_controller parents the spi_device; unused
1656 * by spi_new_device(), and otherwise depends on board wiring.
1657 * @chip_select: Initializes spi_device.chip_select; depends on how
1658 * the board is wired.
1659 * @mode: Initializes spi_device.mode; based on the chip datasheet, board
1660 * wiring (some devices support both 3WIRE and standard modes), and
1661 * possibly presence of an inverter in the chipselect path.
1662 *
1663 * When adding new SPI devices to the device tree, these structures serve
1664 * as a partial device template. They hold information which can't always
1665 * be determined by drivers. Information that probe() can establish (such
1666 * as the default transfer wordsize) is not included here.
1667 *
1668 * These structures are used in two places. Their primary role is to
1669 * be stored in tables of board-specific device descriptors, which are
1670 * declared early in board initialization and then used (much later) to
1671 * populate a controller's device tree after the that controller's driver
1672 * initializes. A secondary (and atypical) role is as a parameter to
1673 * spi_new_device() call, which happens after those controller drivers
1674 * are active in some dynamic board configuration models.
1675 */
1676 struct spi_board_info {
1677 /*
1678 * The device name and module name are coupled, like platform_bus;
1679 * "modalias" is normally the driver name.
1680 *
1681 * platform_data goes to spi_device.dev.platform_data,
1682 * controller_data goes to spi_device.controller_data,
1683 * IRQ is copied too.
1684 */
1685 char modalias[SPI_NAME_SIZE];
1686 const void *platform_data;
1687 const struct software_node *swnode;
1688 void *controller_data;
1689 int irq;
1690
1691 /* Slower signaling on noisy or low voltage boards */
1692 u32 max_speed_hz;
1693
1694
1695 /*
1696 * bus_num is board specific and matches the bus_num of some
1697 * spi_controller that will probably be registered later.
1698 *
1699 * chip_select reflects how this chip is wired to that controller;
1700 * it's less than num_chipselect.
1701 */
1702 u16 bus_num;
1703 u16 chip_select;
1704
1705 /*
1706 * mode becomes spi_device.mode, and is essential for chips
1707 * where the default of SPI_CS_HIGH = 0 is wrong.
1708 */
1709 u32 mode;
1710
1711 /*
1712 * ... may need additional spi_device chip config data here.
1713 * avoid stuff protocol drivers can set; but include stuff
1714 * needed to behave without being bound to a driver:
1715 * - quirks like clock rate mattering when not selected
1716 */
1717 };
1718
1719 #ifdef CONFIG_SPI
1720 extern int
1721 spi_register_board_info(struct spi_board_info const *info, unsigned n);
1722 #else
1723 /* Board init code may ignore whether SPI is configured or not */
1724 static inline int
spi_register_board_info(struct spi_board_info const * info,unsigned n)1725 spi_register_board_info(struct spi_board_info const *info, unsigned n)
1726 { return 0; }
1727 #endif
1728
1729 /*
1730 * If you're hotplugging an adapter with devices (parport, USB, etc)
1731 * use spi_new_device() to describe each device. You can also call
1732 * spi_unregister_device() to start making that device vanish, but
1733 * normally that would be handled by spi_unregister_controller().
1734 *
1735 * You can also use spi_alloc_device() and spi_add_device() to use a two
1736 * stage registration sequence for each spi_device. This gives the caller
1737 * some more control over the spi_device structure before it is registered,
1738 * but requires that caller to initialize fields that would otherwise
1739 * be defined using the board info.
1740 */
1741 extern struct spi_device *
1742 spi_alloc_device(struct spi_controller *ctlr);
1743
1744 extern int
1745 spi_add_device(struct spi_device *spi);
1746
1747 extern struct spi_device *
1748 spi_new_device(struct spi_controller *, struct spi_board_info *);
1749
1750 extern void spi_unregister_device(struct spi_device *spi);
1751
1752 extern const struct spi_device_id *
1753 spi_get_device_id(const struct spi_device *sdev);
1754
1755 extern const void *
1756 spi_get_device_match_data(const struct spi_device *sdev);
1757
1758 static inline bool
spi_transfer_is_last(struct spi_controller * ctlr,struct spi_transfer * xfer)1759 spi_transfer_is_last(struct spi_controller *ctlr, struct spi_transfer *xfer)
1760 {
1761 return list_is_last(&xfer->transfer_list, &ctlr->cur_msg->transfers);
1762 }
1763
1764 #endif /* __LINUX_SPI_H */
1765