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