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