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