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