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