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