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