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