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