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