spi.h 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. /*
  2. * Copyright (C) 2005 David Brownell
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. */
  14. #ifndef __LINUX_SPI_H
  15. #define __LINUX_SPI_H
  16. #include <linux/device.h>
  17. #include <linux/mod_devicetable.h>
  18. #include <linux/slab.h>
  19. #include <linux/kthread.h>
  20. #include <linux/completion.h>
  21. #include <linux/scatterlist.h>
  22. struct dma_chan;
  23. struct spi_master;
  24. struct spi_transfer;
  25. /*
  26. * INTERFACES between SPI master-side drivers and SPI infrastructure.
  27. * (There's no SPI slave support for Linux yet...)
  28. */
  29. extern struct bus_type spi_bus_type;
  30. /**
  31. * struct spi_statistics - statistics for spi transfers
  32. * @clock: lock protecting this structure
  33. *
  34. * @messages: number of spi-messages handled
  35. * @transfers: number of spi_transfers handled
  36. * @errors: number of errors during spi_transfer
  37. * @timedout: number of timeouts during spi_transfer
  38. *
  39. * @spi_sync: number of times spi_sync is used
  40. * @spi_sync_immediate:
  41. * number of times spi_sync is executed immediately
  42. * in calling context without queuing and scheduling
  43. * @spi_async: number of times spi_async is used
  44. *
  45. * @bytes: number of bytes transferred to/from device
  46. * @bytes_tx: number of bytes sent to device
  47. * @bytes_rx: number of bytes received from device
  48. *
  49. */
  50. struct spi_statistics {
  51. spinlock_t lock; /* lock for the whole structure */
  52. unsigned long messages;
  53. unsigned long transfers;
  54. unsigned long errors;
  55. unsigned long timedout;
  56. unsigned long spi_sync;
  57. unsigned long spi_sync_immediate;
  58. unsigned long spi_async;
  59. unsigned long long bytes;
  60. unsigned long long bytes_rx;
  61. unsigned long long bytes_tx;
  62. };
  63. void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
  64. struct spi_transfer *xfer,
  65. struct spi_master *master);
  66. #define SPI_STATISTICS_ADD_TO_FIELD(stats, field, count) \
  67. do { \
  68. unsigned long flags; \
  69. spin_lock_irqsave(&(stats)->lock, flags); \
  70. (stats)->field += count; \
  71. spin_unlock_irqrestore(&(stats)->lock, flags); \
  72. } while (0)
  73. #define SPI_STATISTICS_INCREMENT_FIELD(stats, field) \
  74. SPI_STATISTICS_ADD_TO_FIELD(stats, field, 1)
  75. /**
  76. * struct spi_device - Master side proxy for an SPI slave device
  77. * @dev: Driver model representation of the device.
  78. * @master: SPI controller used with the device.
  79. * @max_speed_hz: Maximum clock rate to be used with this chip
  80. * (on this board); may be changed by the device's driver.
  81. * The spi_transfer.speed_hz can override this for each transfer.
  82. * @chip_select: Chipselect, distinguishing chips handled by @master.
  83. * @mode: The spi mode defines how data is clocked out and in.
  84. * This may be changed by the device's driver.
  85. * The "active low" default for chipselect mode can be overridden
  86. * (by specifying SPI_CS_HIGH) as can the "MSB first" default for
  87. * each word in a transfer (by specifying SPI_LSB_FIRST).
  88. * @bits_per_word: Data transfers involve one or more words; word sizes
  89. * like eight or 12 bits are common. In-memory wordsizes are
  90. * powers of two bytes (e.g. 20 bit samples use 32 bits).
  91. * This may be changed by the device's driver, or left at the
  92. * default (0) indicating protocol words are eight bit bytes.
  93. * The spi_transfer.bits_per_word can override this for each transfer.
  94. * @irq: Negative, or the number passed to request_irq() to receive
  95. * interrupts from this device.
  96. * @controller_state: Controller's runtime state
  97. * @controller_data: Board-specific definitions for controller, such as
  98. * FIFO initialization parameters; from board_info.controller_data
  99. * @modalias: Name of the driver to use with this device, or an alias
  100. * for that name. This appears in the sysfs "modalias" attribute
  101. * for driver coldplugging, and in uevents used for hotplugging
  102. * @cs_gpio: gpio number of the chipselect line (optional, -ENOENT when
  103. * when not using a GPIO line)
  104. *
  105. * @statistics: statistics for the spi_device
  106. *
  107. * A @spi_device is used to interchange data between an SPI slave
  108. * (usually a discrete chip) and CPU memory.
  109. *
  110. * In @dev, the platform_data is used to hold information about this
  111. * device that's meaningful to the device's protocol driver, but not
  112. * to its controller. One example might be an identifier for a chip
  113. * variant with slightly different functionality; another might be
  114. * information about how this particular board wires the chip's pins.
  115. */
  116. struct spi_device {
  117. struct device dev;
  118. struct spi_master *master;
  119. u32 max_speed_hz;
  120. u8 chip_select;
  121. u8 bits_per_word;
  122. u16 mode;
  123. #define SPI_CPHA 0x01 /* clock phase */
  124. #define SPI_CPOL 0x02 /* clock polarity */
  125. #define SPI_MODE_0 (0|0) /* (original MicroWire) */
  126. #define SPI_MODE_1 (0|SPI_CPHA)
  127. #define SPI_MODE_2 (SPI_CPOL|0)
  128. #define SPI_MODE_3 (SPI_CPOL|SPI_CPHA)
  129. #define SPI_CS_HIGH 0x04 /* chipselect active high? */
  130. #define SPI_LSB_FIRST 0x08 /* per-word bits-on-wire */
  131. #define SPI_3WIRE 0x10 /* SI/SO signals shared */
  132. #define SPI_LOOP 0x20 /* loopback mode */
  133. #define SPI_NO_CS 0x40 /* 1 dev/bus, no chipselect */
  134. #define SPI_READY 0x80 /* slave pulls low to pause */
  135. #define SPI_TX_DUAL 0x100 /* transmit with 2 wires */
  136. #define SPI_TX_QUAD 0x200 /* transmit with 4 wires */
  137. #define SPI_RX_DUAL 0x400 /* receive with 2 wires */
  138. #define SPI_RX_QUAD 0x800 /* receive with 4 wires */
  139. int irq;
  140. void *controller_state;
  141. void *controller_data;
  142. char modalias[SPI_NAME_SIZE];
  143. int cs_gpio; /* chip select gpio */
  144. /* the statistics */
  145. struct spi_statistics statistics;
  146. /*
  147. * likely need more hooks for more protocol options affecting how
  148. * the controller talks to each chip, like:
  149. * - memory packing (12 bit samples into low bits, others zeroed)
  150. * - priority
  151. * - drop chipselect after each word
  152. * - chipselect delays
  153. * - ...
  154. */
  155. };
  156. static inline struct spi_device *to_spi_device(struct device *dev)
  157. {
  158. return dev ? container_of(dev, struct spi_device, dev) : NULL;
  159. }
  160. /* most drivers won't need to care about device refcounting */
  161. static inline struct spi_device *spi_dev_get(struct spi_device *spi)
  162. {
  163. return (spi && get_device(&spi->dev)) ? spi : NULL;
  164. }
  165. static inline void spi_dev_put(struct spi_device *spi)
  166. {
  167. if (spi)
  168. put_device(&spi->dev);
  169. }
  170. /* ctldata is for the bus_master driver's runtime state */
  171. static inline void *spi_get_ctldata(struct spi_device *spi)
  172. {
  173. return spi->controller_state;
  174. }
  175. static inline void spi_set_ctldata(struct spi_device *spi, void *state)
  176. {
  177. spi->controller_state = state;
  178. }
  179. /* device driver data */
  180. static inline void spi_set_drvdata(struct spi_device *spi, void *data)
  181. {
  182. dev_set_drvdata(&spi->dev, data);
  183. }
  184. static inline void *spi_get_drvdata(struct spi_device *spi)
  185. {
  186. return dev_get_drvdata(&spi->dev);
  187. }
  188. struct spi_message;
  189. struct spi_transfer;
  190. /**
  191. * struct spi_driver - Host side "protocol" driver
  192. * @id_table: List of SPI devices supported by this driver
  193. * @probe: Binds this driver to the spi device. Drivers can verify
  194. * that the device is actually present, and may need to configure
  195. * characteristics (such as bits_per_word) which weren't needed for
  196. * the initial configuration done during system setup.
  197. * @remove: Unbinds this driver from the spi device
  198. * @shutdown: Standard shutdown callback used during system state
  199. * transitions such as powerdown/halt and kexec
  200. * @driver: SPI device drivers should initialize the name and owner
  201. * field of this structure.
  202. *
  203. * This represents the kind of device driver that uses SPI messages to
  204. * interact with the hardware at the other end of a SPI link. It's called
  205. * a "protocol" driver because it works through messages rather than talking
  206. * directly to SPI hardware (which is what the underlying SPI controller
  207. * driver does to pass those messages). These protocols are defined in the
  208. * specification for the device(s) supported by the driver.
  209. *
  210. * As a rule, those device protocols represent the lowest level interface
  211. * supported by a driver, and it will support upper level interfaces too.
  212. * Examples of such upper levels include frameworks like MTD, networking,
  213. * MMC, RTC, filesystem character device nodes, and hardware monitoring.
  214. */
  215. struct spi_driver {
  216. const struct spi_device_id *id_table;
  217. int (*probe)(struct spi_device *spi);
  218. int (*remove)(struct spi_device *spi);
  219. void (*shutdown)(struct spi_device *spi);
  220. struct device_driver driver;
  221. };
  222. static inline struct spi_driver *to_spi_driver(struct device_driver *drv)
  223. {
  224. return drv ? container_of(drv, struct spi_driver, driver) : NULL;
  225. }
  226. extern int spi_register_driver(struct spi_driver *sdrv);
  227. /**
  228. * spi_unregister_driver - reverse effect of spi_register_driver
  229. * @sdrv: the driver to unregister
  230. * Context: can sleep
  231. */
  232. static inline void spi_unregister_driver(struct spi_driver *sdrv)
  233. {
  234. if (sdrv)
  235. driver_unregister(&sdrv->driver);
  236. }
  237. /**
  238. * module_spi_driver() - Helper macro for registering a SPI driver
  239. * @__spi_driver: spi_driver struct
  240. *
  241. * Helper macro for SPI drivers which do not do anything special in module
  242. * init/exit. This eliminates a lot of boilerplate. Each module may only
  243. * use this macro once, and calling it replaces module_init() and module_exit()
  244. */
  245. #define module_spi_driver(__spi_driver) \
  246. module_driver(__spi_driver, spi_register_driver, \
  247. spi_unregister_driver)
  248. /**
  249. * struct spi_master - interface to SPI master controller
  250. * @dev: device interface to this driver
  251. * @list: link with the global spi_master list
  252. * @bus_num: board-specific (and often SOC-specific) identifier for a
  253. * given SPI controller.
  254. * @num_chipselect: chipselects are used to distinguish individual
  255. * SPI slaves, and are numbered from zero to num_chipselects.
  256. * each slave has a chipselect signal, but it's common that not
  257. * every chipselect is connected to a slave.
  258. * @dma_alignment: SPI controller constraint on DMA buffers alignment.
  259. * @mode_bits: flags understood by this controller driver
  260. * @bits_per_word_mask: A mask indicating which values of bits_per_word are
  261. * supported by the driver. Bit n indicates that a bits_per_word n+1 is
  262. * supported. If set, the SPI core will reject any transfer with an
  263. * unsupported bits_per_word. If not set, this value is simply ignored,
  264. * and it's up to the individual driver to perform any validation.
  265. * @min_speed_hz: Lowest supported transfer speed
  266. * @max_speed_hz: Highest supported transfer speed
  267. * @flags: other constraints relevant to this driver
  268. * @bus_lock_spinlock: spinlock for SPI bus locking
  269. * @bus_lock_mutex: mutex for SPI bus locking
  270. * @bus_lock_flag: indicates that the SPI bus is locked for exclusive use
  271. * @setup: updates the device mode and clocking records used by a
  272. * device's SPI controller; protocol code may call this. This
  273. * must fail if an unrecognized or unsupported mode is requested.
  274. * It's always safe to call this unless transfers are pending on
  275. * the device whose settings are being modified.
  276. * @transfer: adds a message to the controller's transfer queue.
  277. * @cleanup: frees controller-specific state
  278. * @can_dma: determine whether this master supports DMA
  279. * @queued: whether this master is providing an internal message queue
  280. * @kworker: thread struct for message pump
  281. * @kworker_task: pointer to task for message pump kworker thread
  282. * @pump_messages: work struct for scheduling work to the message pump
  283. * @queue_lock: spinlock to syncronise access to message queue
  284. * @queue: message queue
  285. * @idling: the device is entering idle state
  286. * @cur_msg: the currently in-flight message
  287. * @cur_msg_prepared: spi_prepare_message was called for the currently
  288. * in-flight message
  289. * @cur_msg_mapped: message has been mapped for DMA
  290. * @xfer_completion: used by core transfer_one_message()
  291. * @busy: message pump is busy
  292. * @running: message pump is running
  293. * @rt: whether this queue is set to run as a realtime task
  294. * @auto_runtime_pm: the core should ensure a runtime PM reference is held
  295. * while the hardware is prepared, using the parent
  296. * device for the spidev
  297. * @max_dma_len: Maximum length of a DMA transfer for the device.
  298. * @prepare_transfer_hardware: a message will soon arrive from the queue
  299. * so the subsystem requests the driver to prepare the transfer hardware
  300. * by issuing this call
  301. * @transfer_one_message: the subsystem calls the driver to transfer a single
  302. * message while queuing transfers that arrive in the meantime. When the
  303. * driver is finished with this message, it must call
  304. * spi_finalize_current_message() so the subsystem can issue the next
  305. * message
  306. * @unprepare_transfer_hardware: there are currently no more messages on the
  307. * queue so the subsystem notifies the driver that it may relax the
  308. * hardware by issuing this call
  309. * @set_cs: set the logic level of the chip select line. May be called
  310. * from interrupt context.
  311. * @prepare_message: set up the controller to transfer a single message,
  312. * for example doing DMA mapping. Called from threaded
  313. * context.
  314. * @transfer_one: transfer a single spi_transfer.
  315. * - return 0 if the transfer is finished,
  316. * - return 1 if the transfer is still in progress. When
  317. * the driver is finished with this transfer it must
  318. * call spi_finalize_current_transfer() so the subsystem
  319. * can issue the next transfer. Note: transfer_one and
  320. * transfer_one_message are mutually exclusive; when both
  321. * are set, the generic subsystem does not call your
  322. * transfer_one callback.
  323. * @handle_err: the subsystem calls the driver to handle an error that occurs
  324. * in the generic implementation of transfer_one_message().
  325. * @unprepare_message: undo any work done by prepare_message().
  326. * @cs_gpios: Array of GPIOs to use as chip select lines; one per CS
  327. * number. Any individual value may be -ENOENT for CS lines that
  328. * are not GPIOs (driven by the SPI controller itself).
  329. * @statistics: statistics for the spi_master
  330. * @dma_tx: DMA transmit channel
  331. * @dma_rx: DMA receive channel
  332. * @dummy_rx: dummy receive buffer for full-duplex devices
  333. * @dummy_tx: dummy transmit buffer for full-duplex devices
  334. *
  335. * Each SPI master controller can communicate with one or more @spi_device
  336. * children. These make a small bus, sharing MOSI, MISO and SCK signals
  337. * but not chip select signals. Each device may be configured to use a
  338. * different clock rate, since those shared signals are ignored unless
  339. * the chip is selected.
  340. *
  341. * The driver for an SPI controller manages access to those devices through
  342. * a queue of spi_message transactions, copying data between CPU memory and
  343. * an SPI slave device. For each such message it queues, it calls the
  344. * message's completion function when the transaction completes.
  345. */
  346. struct spi_master {
  347. struct device dev;
  348. struct list_head list;
  349. /* other than negative (== assign one dynamically), bus_num is fully
  350. * board-specific. usually that simplifies to being SOC-specific.
  351. * example: one SOC has three SPI controllers, numbered 0..2,
  352. * and one board's schematics might show it using SPI-2. software
  353. * would normally use bus_num=2 for that controller.
  354. */
  355. s16 bus_num;
  356. /* chipselects will be integral to many controllers; some others
  357. * might use board-specific GPIOs.
  358. */
  359. u16 num_chipselect;
  360. /* some SPI controllers pose alignment requirements on DMAable
  361. * buffers; let protocol drivers know about these requirements.
  362. */
  363. u16 dma_alignment;
  364. /* spi_device.mode flags understood by this controller driver */
  365. u16 mode_bits;
  366. /* bitmask of supported bits_per_word for transfers */
  367. u32 bits_per_word_mask;
  368. #define SPI_BPW_MASK(bits) BIT((bits) - 1)
  369. #define SPI_BIT_MASK(bits) (((bits) == 32) ? ~0U : (BIT(bits) - 1))
  370. #define SPI_BPW_RANGE_MASK(min, max) (SPI_BIT_MASK(max) - SPI_BIT_MASK(min - 1))
  371. /* limits on transfer speed */
  372. u32 min_speed_hz;
  373. u32 max_speed_hz;
  374. /* other constraints relevant to this driver */
  375. u16 flags;
  376. #define SPI_MASTER_HALF_DUPLEX BIT(0) /* can't do full duplex */
  377. #define SPI_MASTER_NO_RX BIT(1) /* can't do buffer read */
  378. #define SPI_MASTER_NO_TX BIT(2) /* can't do buffer write */
  379. #define SPI_MASTER_MUST_RX BIT(3) /* requires rx */
  380. #define SPI_MASTER_MUST_TX BIT(4) /* requires tx */
  381. /* lock and mutex for SPI bus locking */
  382. spinlock_t bus_lock_spinlock;
  383. struct mutex bus_lock_mutex;
  384. /* flag indicating that the SPI bus is locked for exclusive use */
  385. bool bus_lock_flag;
  386. /* Setup mode and clock, etc (spi driver may call many times).
  387. *
  388. * IMPORTANT: this may be called when transfers to another
  389. * device are active. DO NOT UPDATE SHARED REGISTERS in ways
  390. * which could break those transfers.
  391. */
  392. int (*setup)(struct spi_device *spi);
  393. /* bidirectional bulk transfers
  394. *
  395. * + The transfer() method may not sleep; its main role is
  396. * just to add the message to the queue.
  397. * + For now there's no remove-from-queue operation, or
  398. * any other request management
  399. * + To a given spi_device, message queueing is pure fifo
  400. *
  401. * + The master's main job is to process its message queue,
  402. * selecting a chip then transferring data
  403. * + If there are multiple spi_device children, the i/o queue
  404. * arbitration algorithm is unspecified (round robin, fifo,
  405. * priority, reservations, preemption, etc)
  406. *
  407. * + Chipselect stays active during the entire message
  408. * (unless modified by spi_transfer.cs_change != 0).
  409. * + The message transfers use clock and SPI mode parameters
  410. * previously established by setup() for this device
  411. */
  412. int (*transfer)(struct spi_device *spi,
  413. struct spi_message *mesg);
  414. /* called on release() to free memory provided by spi_master */
  415. void (*cleanup)(struct spi_device *spi);
  416. /*
  417. * Used to enable core support for DMA handling, if can_dma()
  418. * exists and returns true then the transfer will be mapped
  419. * prior to transfer_one() being called. The driver should
  420. * not modify or store xfer and dma_tx and dma_rx must be set
  421. * while the device is prepared.
  422. */
  423. bool (*can_dma)(struct spi_master *master,
  424. struct spi_device *spi,
  425. struct spi_transfer *xfer);
  426. /*
  427. * These hooks are for drivers that want to use the generic
  428. * master transfer queueing mechanism. If these are used, the
  429. * transfer() function above must NOT be specified by the driver.
  430. * Over time we expect SPI drivers to be phased over to this API.
  431. */
  432. bool queued;
  433. struct kthread_worker kworker;
  434. struct task_struct *kworker_task;
  435. struct kthread_work pump_messages;
  436. spinlock_t queue_lock;
  437. struct list_head queue;
  438. struct spi_message *cur_msg;
  439. bool idling;
  440. bool busy;
  441. bool running;
  442. bool rt;
  443. bool auto_runtime_pm;
  444. bool cur_msg_prepared;
  445. bool cur_msg_mapped;
  446. struct completion xfer_completion;
  447. size_t max_dma_len;
  448. int (*prepare_transfer_hardware)(struct spi_master *master);
  449. int (*transfer_one_message)(struct spi_master *master,
  450. struct spi_message *mesg);
  451. int (*unprepare_transfer_hardware)(struct spi_master *master);
  452. int (*prepare_message)(struct spi_master *master,
  453. struct spi_message *message);
  454. int (*unprepare_message)(struct spi_master *master,
  455. struct spi_message *message);
  456. /*
  457. * These hooks are for drivers that use a generic implementation
  458. * of transfer_one_message() provied by the core.
  459. */
  460. void (*set_cs)(struct spi_device *spi, bool enable);
  461. int (*transfer_one)(struct spi_master *master, struct spi_device *spi,
  462. struct spi_transfer *transfer);
  463. void (*handle_err)(struct spi_master *master,
  464. struct spi_message *message);
  465. /* gpio chip select */
  466. int *cs_gpios;
  467. /* statistics */
  468. struct spi_statistics statistics;
  469. /* DMA channels for use with core dmaengine helpers */
  470. struct dma_chan *dma_tx;
  471. struct dma_chan *dma_rx;
  472. /* dummy data for full duplex devices */
  473. void *dummy_rx;
  474. void *dummy_tx;
  475. };
  476. static inline void *spi_master_get_devdata(struct spi_master *master)
  477. {
  478. return dev_get_drvdata(&master->dev);
  479. }
  480. static inline void spi_master_set_devdata(struct spi_master *master, void *data)
  481. {
  482. dev_set_drvdata(&master->dev, data);
  483. }
  484. static inline struct spi_master *spi_master_get(struct spi_master *master)
  485. {
  486. if (!master || !get_device(&master->dev))
  487. return NULL;
  488. return master;
  489. }
  490. static inline void spi_master_put(struct spi_master *master)
  491. {
  492. if (master)
  493. put_device(&master->dev);
  494. }
  495. /* PM calls that need to be issued by the driver */
  496. extern int spi_master_suspend(struct spi_master *master);
  497. extern int spi_master_resume(struct spi_master *master);
  498. /* Calls the driver make to interact with the message queue */
  499. extern struct spi_message *spi_get_next_queued_message(struct spi_master *master);
  500. extern void spi_finalize_current_message(struct spi_master *master);
  501. extern void spi_finalize_current_transfer(struct spi_master *master);
  502. /* the spi driver core manages memory for the spi_master classdev */
  503. extern struct spi_master *
  504. spi_alloc_master(struct device *host, unsigned size);
  505. extern int spi_register_master(struct spi_master *master);
  506. extern int devm_spi_register_master(struct device *dev,
  507. struct spi_master *master);
  508. extern void spi_unregister_master(struct spi_master *master);
  509. extern struct spi_master *spi_busnum_to_master(u16 busnum);
  510. /*---------------------------------------------------------------------------*/
  511. /*
  512. * I/O INTERFACE between SPI controller and protocol drivers
  513. *
  514. * Protocol drivers use a queue of spi_messages, each transferring data
  515. * between the controller and memory buffers.
  516. *
  517. * The spi_messages themselves consist of a series of read+write transfer
  518. * segments. Those segments always read the same number of bits as they
  519. * write; but one or the other is easily ignored by passing a null buffer
  520. * pointer. (This is unlike most types of I/O API, because SPI hardware
  521. * is full duplex.)
  522. *
  523. * NOTE: Allocation of spi_transfer and spi_message memory is entirely
  524. * up to the protocol driver, which guarantees the integrity of both (as
  525. * well as the data buffers) for as long as the message is queued.
  526. */
  527. /**
  528. * struct spi_transfer - a read/write buffer pair
  529. * @tx_buf: data to be written (dma-safe memory), or NULL
  530. * @rx_buf: data to be read (dma-safe memory), or NULL
  531. * @tx_dma: DMA address of tx_buf, if @spi_message.is_dma_mapped
  532. * @rx_dma: DMA address of rx_buf, if @spi_message.is_dma_mapped
  533. * @tx_nbits: number of bits used for writing. If 0 the default
  534. * (SPI_NBITS_SINGLE) is used.
  535. * @rx_nbits: number of bits used for reading. If 0 the default
  536. * (SPI_NBITS_SINGLE) is used.
  537. * @len: size of rx and tx buffers (in bytes)
  538. * @speed_hz: Select a speed other than the device default for this
  539. * transfer. If 0 the default (from @spi_device) is used.
  540. * @bits_per_word: select a bits_per_word other than the device default
  541. * for this transfer. If 0 the default (from @spi_device) is used.
  542. * @cs_change: affects chipselect after this transfer completes
  543. * @delay_usecs: microseconds to delay after this transfer before
  544. * (optionally) changing the chipselect status, then starting
  545. * the next transfer or completing this @spi_message.
  546. * @transfer_list: transfers are sequenced through @spi_message.transfers
  547. * @tx_sg: Scatterlist for transmit, currently not for client use
  548. * @rx_sg: Scatterlist for receive, currently not for client use
  549. *
  550. * SPI transfers always write the same number of bytes as they read.
  551. * Protocol drivers should always provide @rx_buf and/or @tx_buf.
  552. * In some cases, they may also want to provide DMA addresses for
  553. * the data being transferred; that may reduce overhead, when the
  554. * underlying driver uses dma.
  555. *
  556. * If the transmit buffer is null, zeroes will be shifted out
  557. * while filling @rx_buf. If the receive buffer is null, the data
  558. * shifted in will be discarded. Only "len" bytes shift out (or in).
  559. * It's an error to try to shift out a partial word. (For example, by
  560. * shifting out three bytes with word size of sixteen or twenty bits;
  561. * the former uses two bytes per word, the latter uses four bytes.)
  562. *
  563. * In-memory data values are always in native CPU byte order, translated
  564. * from the wire byte order (big-endian except with SPI_LSB_FIRST). So
  565. * for example when bits_per_word is sixteen, buffers are 2N bytes long
  566. * (@len = 2N) and hold N sixteen bit words in CPU byte order.
  567. *
  568. * When the word size of the SPI transfer is not a power-of-two multiple
  569. * of eight bits, those in-memory words include extra bits. In-memory
  570. * words are always seen by protocol drivers as right-justified, so the
  571. * undefined (rx) or unused (tx) bits are always the most significant bits.
  572. *
  573. * All SPI transfers start with the relevant chipselect active. Normally
  574. * it stays selected until after the last transfer in a message. Drivers
  575. * can affect the chipselect signal using cs_change.
  576. *
  577. * (i) If the transfer isn't the last one in the message, this flag is
  578. * used to make the chipselect briefly go inactive in the middle of the
  579. * message. Toggling chipselect in this way may be needed to terminate
  580. * a chip command, letting a single spi_message perform all of group of
  581. * chip transactions together.
  582. *
  583. * (ii) When the transfer is the last one in the message, the chip may
  584. * stay selected until the next transfer. On multi-device SPI busses
  585. * with nothing blocking messages going to other devices, this is just
  586. * a performance hint; starting a message to another device deselects
  587. * this one. But in other cases, this can be used to ensure correctness.
  588. * Some devices need protocol transactions to be built from a series of
  589. * spi_message submissions, where the content of one message is determined
  590. * by the results of previous messages and where the whole transaction
  591. * ends when the chipselect goes intactive.
  592. *
  593. * When SPI can transfer in 1x,2x or 4x. It can get this transfer information
  594. * from device through @tx_nbits and @rx_nbits. In Bi-direction, these
  595. * two should both be set. User can set transfer mode with SPI_NBITS_SINGLE(1x)
  596. * SPI_NBITS_DUAL(2x) and SPI_NBITS_QUAD(4x) to support these three transfer.
  597. *
  598. * The code that submits an spi_message (and its spi_transfers)
  599. * to the lower layers is responsible for managing its memory.
  600. * Zero-initialize every field you don't set up explicitly, to
  601. * insulate against future API updates. After you submit a message
  602. * and its transfers, ignore them until its completion callback.
  603. */
  604. struct spi_transfer {
  605. /* it's ok if tx_buf == rx_buf (right?)
  606. * for MicroWire, one buffer must be null
  607. * buffers must work with dma_*map_single() calls, unless
  608. * spi_message.is_dma_mapped reports a pre-existing mapping
  609. */
  610. const void *tx_buf;
  611. void *rx_buf;
  612. unsigned len;
  613. dma_addr_t tx_dma;
  614. dma_addr_t rx_dma;
  615. struct sg_table tx_sg;
  616. struct sg_table rx_sg;
  617. unsigned cs_change:1;
  618. unsigned tx_nbits:3;
  619. unsigned rx_nbits:3;
  620. #define SPI_NBITS_SINGLE 0x01 /* 1bit transfer */
  621. #define SPI_NBITS_DUAL 0x02 /* 2bits transfer */
  622. #define SPI_NBITS_QUAD 0x04 /* 4bits transfer */
  623. u8 bits_per_word;
  624. u16 delay_usecs;
  625. u32 speed_hz;
  626. struct list_head transfer_list;
  627. };
  628. /**
  629. * struct spi_message - one multi-segment SPI transaction
  630. * @transfers: list of transfer segments in this transaction
  631. * @spi: SPI device to which the transaction is queued
  632. * @is_dma_mapped: if true, the caller provided both dma and cpu virtual
  633. * addresses for each transfer buffer
  634. * @complete: called to report transaction completions
  635. * @context: the argument to complete() when it's called
  636. * @frame_length: the total number of bytes in the message
  637. * @actual_length: the total number of bytes that were transferred in all
  638. * successful segments
  639. * @status: zero for success, else negative errno
  640. * @queue: for use by whichever driver currently owns the message
  641. * @state: for use by whichever driver currently owns the message
  642. *
  643. * A @spi_message is used to execute an atomic sequence of data transfers,
  644. * each represented by a struct spi_transfer. The sequence is "atomic"
  645. * in the sense that no other spi_message may use that SPI bus until that
  646. * sequence completes. On some systems, many such sequences can execute as
  647. * as single programmed DMA transfer. On all systems, these messages are
  648. * queued, and might complete after transactions to other devices. Messages
  649. * sent to a given spi_device are always executed in FIFO order.
  650. *
  651. * The code that submits an spi_message (and its spi_transfers)
  652. * to the lower layers is responsible for managing its memory.
  653. * Zero-initialize every field you don't set up explicitly, to
  654. * insulate against future API updates. After you submit a message
  655. * and its transfers, ignore them until its completion callback.
  656. */
  657. struct spi_message {
  658. struct list_head transfers;
  659. struct spi_device *spi;
  660. unsigned is_dma_mapped:1;
  661. /* REVISIT: we might want a flag affecting the behavior of the
  662. * last transfer ... allowing things like "read 16 bit length L"
  663. * immediately followed by "read L bytes". Basically imposing
  664. * a specific message scheduling algorithm.
  665. *
  666. * Some controller drivers (message-at-a-time queue processing)
  667. * could provide that as their default scheduling algorithm. But
  668. * others (with multi-message pipelines) could need a flag to
  669. * tell them about such special cases.
  670. */
  671. /* completion is reported through a callback */
  672. void (*complete)(void *context);
  673. void *context;
  674. unsigned frame_length;
  675. unsigned actual_length;
  676. int status;
  677. /* for optional use by whatever driver currently owns the
  678. * spi_message ... between calls to spi_async and then later
  679. * complete(), that's the spi_master controller driver.
  680. */
  681. struct list_head queue;
  682. void *state;
  683. };
  684. static inline void spi_message_init(struct spi_message *m)
  685. {
  686. memset(m, 0, sizeof *m);
  687. INIT_LIST_HEAD(&m->transfers);
  688. }
  689. static inline void
  690. spi_message_add_tail(struct spi_transfer *t, struct spi_message *m)
  691. {
  692. list_add_tail(&t->transfer_list, &m->transfers);
  693. }
  694. static inline void
  695. spi_transfer_del(struct spi_transfer *t)
  696. {
  697. list_del(&t->transfer_list);
  698. }
  699. /**
  700. * spi_message_init_with_transfers - Initialize spi_message and append transfers
  701. * @m: spi_message to be initialized
  702. * @xfers: An array of spi transfers
  703. * @num_xfers: Number of items in the xfer array
  704. *
  705. * This function initializes the given spi_message and adds each spi_transfer in
  706. * the given array to the message.
  707. */
  708. static inline void
  709. spi_message_init_with_transfers(struct spi_message *m,
  710. struct spi_transfer *xfers, unsigned int num_xfers)
  711. {
  712. unsigned int i;
  713. spi_message_init(m);
  714. for (i = 0; i < num_xfers; ++i)
  715. spi_message_add_tail(&xfers[i], m);
  716. }
  717. /* It's fine to embed message and transaction structures in other data
  718. * structures so long as you don't free them while they're in use.
  719. */
  720. static inline struct spi_message *spi_message_alloc(unsigned ntrans, gfp_t flags)
  721. {
  722. struct spi_message *m;
  723. m = kzalloc(sizeof(struct spi_message)
  724. + ntrans * sizeof(struct spi_transfer),
  725. flags);
  726. if (m) {
  727. unsigned i;
  728. struct spi_transfer *t = (struct spi_transfer *)(m + 1);
  729. INIT_LIST_HEAD(&m->transfers);
  730. for (i = 0; i < ntrans; i++, t++)
  731. spi_message_add_tail(t, m);
  732. }
  733. return m;
  734. }
  735. static inline void spi_message_free(struct spi_message *m)
  736. {
  737. kfree(m);
  738. }
  739. extern int spi_setup(struct spi_device *spi);
  740. extern int spi_async(struct spi_device *spi, struct spi_message *message);
  741. extern int spi_async_locked(struct spi_device *spi,
  742. struct spi_message *message);
  743. /*---------------------------------------------------------------------------*/
  744. /* All these synchronous SPI transfer routines are utilities layered
  745. * over the core async transfer primitive. Here, "synchronous" means
  746. * they will sleep uninterruptibly until the async transfer completes.
  747. */
  748. extern int spi_sync(struct spi_device *spi, struct spi_message *message);
  749. extern int spi_sync_locked(struct spi_device *spi, struct spi_message *message);
  750. extern int spi_bus_lock(struct spi_master *master);
  751. extern int spi_bus_unlock(struct spi_master *master);
  752. /**
  753. * spi_write - SPI synchronous write
  754. * @spi: device to which data will be written
  755. * @buf: data buffer
  756. * @len: data buffer size
  757. * Context: can sleep
  758. *
  759. * This writes the buffer and returns zero or a negative error code.
  760. * Callable only from contexts that can sleep.
  761. */
  762. static inline int
  763. spi_write(struct spi_device *spi, const void *buf, size_t len)
  764. {
  765. struct spi_transfer t = {
  766. .tx_buf = buf,
  767. .len = len,
  768. };
  769. struct spi_message m;
  770. spi_message_init(&m);
  771. spi_message_add_tail(&t, &m);
  772. return spi_sync(spi, &m);
  773. }
  774. /**
  775. * spi_read - SPI synchronous read
  776. * @spi: device from which data will be read
  777. * @buf: data buffer
  778. * @len: data buffer size
  779. * Context: can sleep
  780. *
  781. * This reads the buffer and returns zero or a negative error code.
  782. * Callable only from contexts that can sleep.
  783. */
  784. static inline int
  785. spi_read(struct spi_device *spi, void *buf, size_t len)
  786. {
  787. struct spi_transfer t = {
  788. .rx_buf = buf,
  789. .len = len,
  790. };
  791. struct spi_message m;
  792. spi_message_init(&m);
  793. spi_message_add_tail(&t, &m);
  794. return spi_sync(spi, &m);
  795. }
  796. /**
  797. * spi_sync_transfer - synchronous SPI data transfer
  798. * @spi: device with which data will be exchanged
  799. * @xfers: An array of spi_transfers
  800. * @num_xfers: Number of items in the xfer array
  801. * Context: can sleep
  802. *
  803. * Does a synchronous SPI data transfer of the given spi_transfer array.
  804. *
  805. * For more specific semantics see spi_sync().
  806. *
  807. * It returns zero on success, else a negative error code.
  808. */
  809. static inline int
  810. spi_sync_transfer(struct spi_device *spi, struct spi_transfer *xfers,
  811. unsigned int num_xfers)
  812. {
  813. struct spi_message msg;
  814. spi_message_init_with_transfers(&msg, xfers, num_xfers);
  815. return spi_sync(spi, &msg);
  816. }
  817. /* this copies txbuf and rxbuf data; for small transfers only! */
  818. extern int spi_write_then_read(struct spi_device *spi,
  819. const void *txbuf, unsigned n_tx,
  820. void *rxbuf, unsigned n_rx);
  821. /**
  822. * spi_w8r8 - SPI synchronous 8 bit write followed by 8 bit read
  823. * @spi: device with which data will be exchanged
  824. * @cmd: command to be written before data is read back
  825. * Context: can sleep
  826. *
  827. * This returns the (unsigned) eight bit number returned by the
  828. * device, or else a negative error code. Callable only from
  829. * contexts that can sleep.
  830. */
  831. static inline ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)
  832. {
  833. ssize_t status;
  834. u8 result;
  835. status = spi_write_then_read(spi, &cmd, 1, &result, 1);
  836. /* return negative errno or unsigned value */
  837. return (status < 0) ? status : result;
  838. }
  839. /**
  840. * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read
  841. * @spi: device with which data will be exchanged
  842. * @cmd: command to be written before data is read back
  843. * Context: can sleep
  844. *
  845. * This returns the (unsigned) sixteen bit number returned by the
  846. * device, or else a negative error code. Callable only from
  847. * contexts that can sleep.
  848. *
  849. * The number is returned in wire-order, which is at least sometimes
  850. * big-endian.
  851. */
  852. static inline ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)
  853. {
  854. ssize_t status;
  855. u16 result;
  856. status = spi_write_then_read(spi, &cmd, 1, &result, 2);
  857. /* return negative errno or unsigned value */
  858. return (status < 0) ? status : result;
  859. }
  860. /**
  861. * spi_w8r16be - SPI synchronous 8 bit write followed by 16 bit big-endian read
  862. * @spi: device with which data will be exchanged
  863. * @cmd: command to be written before data is read back
  864. * Context: can sleep
  865. *
  866. * This returns the (unsigned) sixteen bit number returned by the device in cpu
  867. * endianness, or else a negative error code. Callable only from contexts that
  868. * can sleep.
  869. *
  870. * This function is similar to spi_w8r16, with the exception that it will
  871. * convert the read 16 bit data word from big-endian to native endianness.
  872. *
  873. */
  874. static inline ssize_t spi_w8r16be(struct spi_device *spi, u8 cmd)
  875. {
  876. ssize_t status;
  877. __be16 result;
  878. status = spi_write_then_read(spi, &cmd, 1, &result, 2);
  879. if (status < 0)
  880. return status;
  881. return be16_to_cpu(result);
  882. }
  883. /*---------------------------------------------------------------------------*/
  884. /*
  885. * INTERFACE between board init code and SPI infrastructure.
  886. *
  887. * No SPI driver ever sees these SPI device table segments, but
  888. * it's how the SPI core (or adapters that get hotplugged) grows
  889. * the driver model tree.
  890. *
  891. * As a rule, SPI devices can't be probed. Instead, board init code
  892. * provides a table listing the devices which are present, with enough
  893. * information to bind and set up the device's driver. There's basic
  894. * support for nonstatic configurations too; enough to handle adding
  895. * parport adapters, or microcontrollers acting as USB-to-SPI bridges.
  896. */
  897. /**
  898. * struct spi_board_info - board-specific template for a SPI device
  899. * @modalias: Initializes spi_device.modalias; identifies the driver.
  900. * @platform_data: Initializes spi_device.platform_data; the particular
  901. * data stored there is driver-specific.
  902. * @controller_data: Initializes spi_device.controller_data; some
  903. * controllers need hints about hardware setup, e.g. for DMA.
  904. * @irq: Initializes spi_device.irq; depends on how the board is wired.
  905. * @max_speed_hz: Initializes spi_device.max_speed_hz; based on limits
  906. * from the chip datasheet and board-specific signal quality issues.
  907. * @bus_num: Identifies which spi_master parents the spi_device; unused
  908. * by spi_new_device(), and otherwise depends on board wiring.
  909. * @chip_select: Initializes spi_device.chip_select; depends on how
  910. * the board is wired.
  911. * @mode: Initializes spi_device.mode; based on the chip datasheet, board
  912. * wiring (some devices support both 3WIRE and standard modes), and
  913. * possibly presence of an inverter in the chipselect path.
  914. *
  915. * When adding new SPI devices to the device tree, these structures serve
  916. * as a partial device template. They hold information which can't always
  917. * be determined by drivers. Information that probe() can establish (such
  918. * as the default transfer wordsize) is not included here.
  919. *
  920. * These structures are used in two places. Their primary role is to
  921. * be stored in tables of board-specific device descriptors, which are
  922. * declared early in board initialization and then used (much later) to
  923. * populate a controller's device tree after the that controller's driver
  924. * initializes. A secondary (and atypical) role is as a parameter to
  925. * spi_new_device() call, which happens after those controller drivers
  926. * are active in some dynamic board configuration models.
  927. */
  928. struct spi_board_info {
  929. /* the device name and module name are coupled, like platform_bus;
  930. * "modalias" is normally the driver name.
  931. *
  932. * platform_data goes to spi_device.dev.platform_data,
  933. * controller_data goes to spi_device.controller_data,
  934. * irq is copied too
  935. */
  936. char modalias[SPI_NAME_SIZE];
  937. const void *platform_data;
  938. void *controller_data;
  939. int irq;
  940. /* slower signaling on noisy or low voltage boards */
  941. u32 max_speed_hz;
  942. /* bus_num is board specific and matches the bus_num of some
  943. * spi_master that will probably be registered later.
  944. *
  945. * chip_select reflects how this chip is wired to that master;
  946. * it's less than num_chipselect.
  947. */
  948. u16 bus_num;
  949. u16 chip_select;
  950. /* mode becomes spi_device.mode, and is essential for chips
  951. * where the default of SPI_CS_HIGH = 0 is wrong.
  952. */
  953. u16 mode;
  954. /* ... may need additional spi_device chip config data here.
  955. * avoid stuff protocol drivers can set; but include stuff
  956. * needed to behave without being bound to a driver:
  957. * - quirks like clock rate mattering when not selected
  958. */
  959. };
  960. #ifdef CONFIG_SPI
  961. extern int
  962. spi_register_board_info(struct spi_board_info const *info, unsigned n);
  963. #else
  964. /* board init code may ignore whether SPI is configured or not */
  965. static inline int
  966. spi_register_board_info(struct spi_board_info const *info, unsigned n)
  967. { return 0; }
  968. #endif
  969. /* If you're hotplugging an adapter with devices (parport, usb, etc)
  970. * use spi_new_device() to describe each device. You can also call
  971. * spi_unregister_device() to start making that device vanish, but
  972. * normally that would be handled by spi_unregister_master().
  973. *
  974. * You can also use spi_alloc_device() and spi_add_device() to use a two
  975. * stage registration sequence for each spi_device. This gives the caller
  976. * some more control over the spi_device structure before it is registered,
  977. * but requires that caller to initialize fields that would otherwise
  978. * be defined using the board info.
  979. */
  980. extern struct spi_device *
  981. spi_alloc_device(struct spi_master *master);
  982. extern int
  983. spi_add_device(struct spi_device *spi);
  984. extern struct spi_device *
  985. spi_new_device(struct spi_master *, struct spi_board_info *);
  986. static inline void
  987. spi_unregister_device(struct spi_device *spi)
  988. {
  989. if (spi)
  990. device_unregister(&spi->dev);
  991. }
  992. extern const struct spi_device_id *
  993. spi_get_device_id(const struct spi_device *sdev);
  994. static inline bool
  995. spi_transfer_is_last(struct spi_master *master, struct spi_transfer *xfer)
  996. {
  997. return list_is_last(&xfer->transfer_list, &master->cur_msg->transfers);
  998. }
  999. #endif /* __LINUX_SPI_H */