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