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