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