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