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