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