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