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