spi.h 49.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright (C) 2005 David Brownell
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#ifndef __LINUX_SPI_H
#define __LINUX_SPI_H

R
Randy Dunlap 已提交
18
#include <linux/device.h>
19
#include <linux/mod_devicetable.h>
20
#include <linux/slab.h>
21
#include <linux/kthread.h>
22
#include <linux/completion.h>
23
#include <linux/scatterlist.h>
R
Randy Dunlap 已提交
24

25
struct dma_chan;
26
struct property_entry;
27
struct spi_controller;
28
struct spi_transfer;
29
struct spi_flash_read_message;
R
Randy Dunlap 已提交
30

31
/*
32 33
 * INTERFACES between SPI master-side drivers and SPI slave protocol handlers,
 * and SPI infrastructure.
34 35 36
 */
extern struct bus_type spi_bus_type;

37 38
/**
 * struct spi_statistics - statistics for spi transfers
39
 * @lock:          lock protecting this structure
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
 *
 * @messages:      number of spi-messages handled
 * @transfers:     number of spi_transfers handled
 * @errors:        number of errors during spi_transfer
 * @timedout:      number of timeouts during spi_transfer
 *
 * @spi_sync:      number of times spi_sync is used
 * @spi_sync_immediate:
 *                 number of times spi_sync is executed immediately
 *                 in calling context without queuing and scheduling
 * @spi_async:     number of times spi_async is used
 *
 * @bytes:         number of bytes transferred to/from device
 * @bytes_tx:      number of bytes sent to device
 * @bytes_rx:      number of bytes received from device
 *
56 57
 * @transfer_bytes_histo:
 *                 transfer bytes histogramm
58 59 60 61
 *
 * @transfers_split_maxsize:
 *                 number of transfers that have been split because of
 *                 maxsize limit
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
 */
struct spi_statistics {
	spinlock_t		lock; /* lock for the whole structure */

	unsigned long		messages;
	unsigned long		transfers;
	unsigned long		errors;
	unsigned long		timedout;

	unsigned long		spi_sync;
	unsigned long		spi_sync_immediate;
	unsigned long		spi_async;

	unsigned long long	bytes;
	unsigned long long	bytes_rx;
	unsigned long long	bytes_tx;

79 80
#define SPI_STATISTICS_HISTO_SIZE 17
	unsigned long transfer_bytes_histo[SPI_STATISTICS_HISTO_SIZE];
81 82

	unsigned long transfers_split_maxsize;
83 84 85 86
};

void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
				       struct spi_transfer *xfer,
87
				       struct spi_controller *ctlr);
88 89 90 91 92 93 94 95 96 97 98 99

#define SPI_STATISTICS_ADD_TO_FIELD(stats, field, count)	\
	do {							\
		unsigned long flags;				\
		spin_lock_irqsave(&(stats)->lock, flags);	\
		(stats)->field += count;			\
		spin_unlock_irqrestore(&(stats)->lock, flags);	\
	} while (0)

#define SPI_STATISTICS_INCREMENT_FIELD(stats, field)	\
	SPI_STATISTICS_ADD_TO_FIELD(stats, field, 1)

100
/**
101
 * struct spi_device - Controller side proxy for an SPI slave device
102
 * @dev: Driver model representation of the device.
103 104
 * @controller: SPI controller used with the device.
 * @master: Copy of controller, for backwards compatibility.
105 106
 * @max_speed_hz: Maximum clock rate to be used with this chip
 *	(on this board); may be changed by the device's driver.
107
 *	The spi_transfer.speed_hz can override this for each transfer.
108
 * @chip_select: Chipselect, distinguishing chips handled by @controller.
109 110
 * @mode: The spi mode defines how data is clocked out and in.
 *	This may be changed by the device's driver.
D
David Brownell 已提交
111 112 113
 *	The "active low" default for chipselect mode can be overridden
 *	(by specifying SPI_CS_HIGH) as can the "MSB first" default for
 *	each word in a transfer (by specifying SPI_LSB_FIRST).
114
 * @bits_per_word: Data transfers involve one or more words; word sizes
115
 *	like eight or 12 bits are common.  In-memory wordsizes are
116
 *	powers of two bytes (e.g. 20 bit samples use 32 bits).
117 118
 *	This may be changed by the device's driver, or left at the
 *	default (0) indicating protocol words are eight bit bytes.
119
 *	The spi_transfer.bits_per_word can override this for each transfer.
120
 * @irq: Negative, or the number passed to request_irq() to receive
121
 *	interrupts from this device.
122
 * @controller_state: Controller's runtime state
123
 * @controller_data: Board-specific definitions for controller, such as
124
 *	FIFO initialization parameters; from board_info.controller_data
D
David Brownell 已提交
125 126 127
 * @modalias: Name of the driver to use with this device, or an alias
 *	for that name.  This appears in the sysfs "modalias" attribute
 *	for driver coldplugging, and in uevents used for hotplugging
128
 * @cs_gpio: gpio number of the chipselect line (optional, -ENOENT when
129
 *	when not using a GPIO line)
130
 *
131 132
 * @statistics: statistics for the spi_device
 *
D
David Brownell 已提交
133
 * A @spi_device is used to interchange data between an SPI slave
134 135
 * (usually a discrete chip) and CPU memory.
 *
D
David Brownell 已提交
136
 * In @dev, the platform_data is used to hold information about this
137 138
 * device that's meaningful to the device's protocol driver, but not
 * to its controller.  One example might be an identifier for a chip
D
David Brownell 已提交
139 140
 * variant with slightly different functionality; another might be
 * information about how this particular board wires the chip's pins.
141 142 143
 */
struct spi_device {
	struct device		dev;
144 145
	struct spi_controller	*controller;
	struct spi_controller	*master;	/* compatibility layer */
146 147
	u32			max_speed_hz;
	u8			chip_select;
148
	u8			bits_per_word;
W
wangyuhang 已提交
149
	u16			mode;
150 151
#define	SPI_CPHA	0x01			/* clock phase */
#define	SPI_CPOL	0x02			/* clock polarity */
D
David Brownell 已提交
152 153
#define	SPI_MODE_0	(0|0)			/* (original MicroWire) */
#define	SPI_MODE_1	(0|SPI_CPHA)
154 155
#define	SPI_MODE_2	(SPI_CPOL|0)
#define	SPI_MODE_3	(SPI_CPOL|SPI_CPHA)
156
#define	SPI_CS_HIGH	0x04			/* chipselect active high? */
157
#define	SPI_LSB_FIRST	0x08			/* per-word bits-on-wire */
D
David Brownell 已提交
158
#define	SPI_3WIRE	0x10			/* SI/SO signals shared */
A
Anton Vorontsov 已提交
159
#define	SPI_LOOP	0x20			/* loopback mode */
D
David Brownell 已提交
160 161
#define	SPI_NO_CS	0x40			/* 1 dev/bus, no chipselect */
#define	SPI_READY	0x80			/* slave pulls low to pause */
W
wangyuhang 已提交
162 163 164 165
#define	SPI_TX_DUAL	0x100			/* transmit with 2 wires */
#define	SPI_TX_QUAD	0x200			/* transmit with 4 wires */
#define	SPI_RX_DUAL	0x400			/* receive with 2 wires */
#define	SPI_RX_QUAD	0x800			/* receive with 4 wires */
166 167
	int			irq;
	void			*controller_state;
168
	void			*controller_data;
169
	char			modalias[SPI_NAME_SIZE];
170
	int			cs_gpio;	/* chip select gpio */
171

172 173 174
	/* the statistics */
	struct spi_statistics	statistics;

D
David Brownell 已提交
175 176 177 178 179 180 181 182 183
	/*
	 * likely need more hooks for more protocol options affecting how
	 * the controller talks to each chip, like:
	 *  - memory packing (12 bit samples into low bits, others zeroed)
	 *  - priority
	 *  - drop chipselect after each word
	 *  - chipselect delays
	 *  - ...
	 */
184 185 186 187
};

static inline struct spi_device *to_spi_device(struct device *dev)
{
188
	return dev ? container_of(dev, struct spi_device, dev) : NULL;
189 190 191 192 193 194 195 196 197 198 199 200 201 202
}

/* most drivers won't need to care about device refcounting */
static inline struct spi_device *spi_dev_get(struct spi_device *spi)
{
	return (spi && get_device(&spi->dev)) ? spi : NULL;
}

static inline void spi_dev_put(struct spi_device *spi)
{
	if (spi)
		put_device(&spi->dev);
}

203
/* ctldata is for the bus_controller driver's runtime state */
204 205 206 207 208 209 210 211 212 213
static inline void *spi_get_ctldata(struct spi_device *spi)
{
	return spi->controller_state;
}

static inline void spi_set_ctldata(struct spi_device *spi, void *state)
{
	spi->controller_state = state;
}

214 215 216 217 218 219 220 221 222 223 224
/* device driver data */

static inline void spi_set_drvdata(struct spi_device *spi, void *data)
{
	dev_set_drvdata(&spi->dev, data);
}

static inline void *spi_get_drvdata(struct spi_device *spi)
{
	return dev_get_drvdata(&spi->dev);
}
225 226

struct spi_message;
227
struct spi_transfer;
228

D
David Brownell 已提交
229 230
/**
 * struct spi_driver - Host side "protocol" driver
231
 * @id_table: List of SPI devices supported by this driver
D
David Brownell 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
 * @probe: Binds this driver to the spi device.  Drivers can verify
 *	that the device is actually present, and may need to configure
 *	characteristics (such as bits_per_word) which weren't needed for
 *	the initial configuration done during system setup.
 * @remove: Unbinds this driver from the spi device
 * @shutdown: Standard shutdown callback used during system state
 *	transitions such as powerdown/halt and kexec
 * @driver: SPI device drivers should initialize the name and owner
 *	field of this structure.
 *
 * This represents the kind of device driver that uses SPI messages to
 * interact with the hardware at the other end of a SPI link.  It's called
 * a "protocol" driver because it works through messages rather than talking
 * directly to SPI hardware (which is what the underlying SPI controller
 * driver does to pass those messages).  These protocols are defined in the
 * specification for the device(s) supported by the driver.
 *
 * As a rule, those device protocols represent the lowest level interface
 * supported by a driver, and it will support upper level interfaces too.
 * Examples of such upper levels include frameworks like MTD, networking,
 * MMC, RTC, filesystem character device nodes, and hardware monitoring.
 */
254
struct spi_driver {
255
	const struct spi_device_id *id_table;
256 257 258 259 260 261 262 263 264 265 266
	int			(*probe)(struct spi_device *spi);
	int			(*remove)(struct spi_device *spi);
	void			(*shutdown)(struct spi_device *spi);
	struct device_driver	driver;
};

static inline struct spi_driver *to_spi_driver(struct device_driver *drv)
{
	return drv ? container_of(drv, struct spi_driver, driver) : NULL;
}

267
extern int __spi_register_driver(struct module *owner, struct spi_driver *sdrv);
268

D
David Brownell 已提交
269 270 271 272 273
/**
 * spi_unregister_driver - reverse effect of spi_register_driver
 * @sdrv: the driver to unregister
 * Context: can sleep
 */
274 275
static inline void spi_unregister_driver(struct spi_driver *sdrv)
{
276 277
	if (sdrv)
		driver_unregister(&sdrv->driver);
278 279
}

280 281 282 283
/* use a define to avoid include chaining to get THIS_MODULE */
#define spi_register_driver(driver) \
	__spi_register_driver(THIS_MODULE, driver)

284 285 286 287 288 289 290 291 292 293 294
/**
 * module_spi_driver() - Helper macro for registering a SPI driver
 * @__spi_driver: spi_driver struct
 *
 * Helper macro for SPI drivers which do not do anything special in module
 * init/exit. This eliminates a lot of boilerplate. Each module may only
 * use this macro once, and calling it replaces module_init() and module_exit()
 */
#define module_spi_driver(__spi_driver) \
	module_driver(__spi_driver, spi_register_driver, \
			spi_unregister_driver)
295

296
/**
297
 * struct spi_controller - interface to SPI master or slave controller
T
Tony Jones 已提交
298
 * @dev: device interface to this driver
299
 * @list: link with the global spi_controller list
300
 * @bus_num: board-specific (and often SOC-specific) identifier for a
301
 *	given SPI controller.
302
 * @num_chipselect: chipselects are used to distinguish individual
303 304 305
 *	SPI slaves, and are numbered from zero to num_chipselects.
 *	each slave has a chipselect signal, but it's common that not
 *	every chipselect is connected to a slave.
306
 * @dma_alignment: SPI controller constraint on DMA buffers alignment.
307
 * @mode_bits: flags understood by this controller driver
308 309
 * @bits_per_word_mask: A mask indicating which values of bits_per_word are
 *	supported by the driver. Bit n indicates that a bits_per_word n+1 is
310
 *	supported. If set, the SPI core will reject any transfer with an
311 312
 *	unsupported bits_per_word. If not set, this value is simply ignored,
 *	and it's up to the individual driver to perform any validation.
313 314
 * @min_speed_hz: Lowest supported transfer speed
 * @max_speed_hz: Highest supported transfer speed
315
 * @flags: other constraints relevant to this driver
316
 * @slave: indicates that this is an SPI slave controller
R
Randy Dunlap 已提交
317 318
 * @max_transfer_size: function that returns the max transfer size for
 *	a &spi_device; may be %NULL, so the default %SIZE_MAX will be used.
319 320
 * @max_message_size: function that returns the max message size for
 *	a &spi_device; may be %NULL, so the default %SIZE_MAX will be used.
M
Mark Brown 已提交
321
 * @io_mutex: mutex for physical bus access
322
 * @bus_lock_spinlock: spinlock for SPI bus locking
M
Mark Brown 已提交
323
 * @bus_lock_mutex: mutex for exclusion of multiple callers
324
 * @bus_lock_flag: indicates that the SPI bus is locked for exclusive use
325
 * @setup: updates the device mode and clocking records used by a
D
David Brownell 已提交
326 327
 *	device's SPI controller; protocol code may call this.  This
 *	must fail if an unrecognized or unsupported mode is requested.
D
David Brownell 已提交
328 329
 *	It's always safe to call this unless transfers are pending on
 *	the device whose settings are being modified.
330 331
 * @transfer: adds a message to the controller's transfer queue.
 * @cleanup: frees controller-specific state
332 333
 * @can_dma: determine whether this controller supports DMA
 * @queued: whether this controller is providing an internal message queue
334 335 336 337 338
 * @kworker: thread struct for message pump
 * @kworker_task: pointer to task for message pump kworker thread
 * @pump_messages: work struct for scheduling work to the message pump
 * @queue_lock: spinlock to syncronise access to message queue
 * @queue: message queue
339
 * @idling: the device is entering idle state
340
 * @cur_msg: the currently in-flight message
341 342
 * @cur_msg_prepared: spi_prepare_message was called for the currently
 *                    in-flight message
T
Thierry Reding 已提交
343
 * @cur_msg_mapped: message has been mapped for DMA
344
 * @xfer_completion: used by core transfer_one_message()
345 346 347
 * @busy: message pump is busy
 * @running: message pump is running
 * @rt: whether this queue is set to run as a realtime task
348 349 350
 * @auto_runtime_pm: the core should ensure a runtime PM reference is held
 *                   while the hardware is prepared, using the parent
 *                   device for the spidev
351
 * @max_dma_len: Maximum length of a DMA transfer for the device.
352 353 354 355 356 357 358
 * @prepare_transfer_hardware: a message will soon arrive from the queue
 *	so the subsystem requests the driver to prepare the transfer hardware
 *	by issuing this call
 * @transfer_one_message: the subsystem calls the driver to transfer a single
 *	message while queuing transfers that arrive in the meantime. When the
 *	driver is finished with this message, it must call
 *	spi_finalize_current_message() so the subsystem can issue the next
359
 *	message
R
Randy Dunlap 已提交
360
 * @unprepare_transfer_hardware: there are currently no more messages on the
361 362
 *	queue so the subsystem notifies the driver that it may relax the
 *	hardware by issuing this call
363
 * @set_cs: set the logic level of the chip select line.  May be called
364
 *          from interrupt context.
365 366 367
 * @prepare_message: set up the controller to transfer a single message,
 *                   for example doing DMA mapping.  Called from threaded
 *                   context.
368 369 370 371 372
 * @transfer_one: transfer a single spi_transfer.
 *                  - return 0 if the transfer is finished,
 *                  - return 1 if the transfer is still in progress. When
 *                    the driver is finished with this transfer it must
 *                    call spi_finalize_current_transfer() so the subsystem
373 374 375 376
 *                    can issue the next transfer. Note: transfer_one and
 *                    transfer_one_message are mutually exclusive; when both
 *                    are set, the generic subsystem does not call your
 *                    transfer_one callback.
377
 * @handle_err: the subsystem calls the driver to handle an error that occurs
378
 *		in the generic implementation of transfer_one_message().
379
 * @unprepare_message: undo any work done by prepare_message().
380
 * @slave_abort: abort the ongoing transfer request on an SPI slave controller
381 382
 * @spi_flash_read: to support spi-controller hardwares that provide
 *                  accelerated interface to read from flash devices.
383 384
 * @spi_flash_can_dma: analogous to can_dma() interface, but for
 *		       controllers implementing spi_flash_read.
385
 * @flash_read_supported: spi device supports flash read
386
 * @cs_gpios: Array of GPIOs to use as chip select lines; one per CS
387
 *	number. Any individual value may be -ENOENT for CS lines that
388
 *	are not GPIOs (driven by the SPI controller itself).
389
 * @statistics: statistics for the spi_controller
T
Thierry Reding 已提交
390 391 392 393
 * @dma_tx: DMA transmit channel
 * @dma_rx: DMA receive channel
 * @dummy_rx: dummy receive buffer for full-duplex devices
 * @dummy_tx: dummy transmit buffer for full-duplex devices
394 395 396
 * @fw_translate_cs: If the boot firmware uses different numbering scheme
 *	what Linux expects, this optional hook can be used to translate
 *	between the two.
397
 *
398
 * Each SPI controller can communicate with one or more @spi_device
399 400 401 402 403 404
 * children.  These make a small bus, sharing MOSI, MISO and SCK signals
 * but not chip select signals.  Each device may be configured to use a
 * different clock rate, since those shared signals are ignored unless
 * the chip is selected.
 *
 * The driver for an SPI controller manages access to those devices through
D
David Brownell 已提交
405 406
 * a queue of spi_message transactions, copying data between CPU memory and
 * an SPI slave device.  For each such message it queues, it calls the
407 408
 * message's completion function when the transaction completes.
 */
409
struct spi_controller {
T
Tony Jones 已提交
410
	struct device	dev;
411

412 413
	struct list_head list;

414
	/* other than negative (== assign one dynamically), bus_num is fully
415
	 * board-specific.  usually that simplifies to being SOC-specific.
416
	 * example:  one SOC has three SPI controllers, numbered 0..2,
417 418 419
	 * and one board's schematics might show it using SPI-2.  software
	 * would normally use bus_num=2 for that controller.
	 */
420
	s16			bus_num;
421 422 423 424 425 426

	/* chipselects will be integral to many controllers; some others
	 * might use board-specific GPIOs.
	 */
	u16			num_chipselect;

427 428 429 430 431
	/* some SPI controllers pose alignment requirements on DMAable
	 * buffers; let protocol drivers know about these requirements.
	 */
	u16			dma_alignment;

432 433 434
	/* spi_device.mode flags understood by this controller driver */
	u16			mode_bits;

435 436
	/* bitmask of supported bits_per_word for transfers */
	u32			bits_per_word_mask;
437
#define SPI_BPW_MASK(bits) BIT((bits) - 1)
438
#define SPI_BIT_MASK(bits) (((bits) == 32) ? ~0U : (BIT(bits) - 1))
439
#define SPI_BPW_RANGE_MASK(min, max) (SPI_BIT_MASK(max) - SPI_BIT_MASK(min - 1))
440

441 442 443 444
	/* limits on transfer speed */
	u32			min_speed_hz;
	u32			max_speed_hz;

D
David Brownell 已提交
445 446
	/* other constraints relevant to this driver */
	u16			flags;
447 448 449 450 451 452 453
#define SPI_CONTROLLER_HALF_DUPLEX	BIT(0)	/* can't do full duplex */
#define SPI_CONTROLLER_NO_RX		BIT(1)	/* can't do buffer read */
#define SPI_CONTROLLER_NO_TX		BIT(2)	/* can't do buffer write */
#define SPI_CONTROLLER_MUST_RX		BIT(3)	/* requires rx */
#define SPI_CONTROLLER_MUST_TX		BIT(4)	/* requires tx */

#define SPI_MASTER_GPIO_SS		BIT(5)	/* GPIO CS must select slave */
D
David Brownell 已提交
454

455 456 457
	/* flag indicating this is an SPI slave controller */
	bool			slave;

458
	/*
459
	 * on some hardware transfer / message size may be constrained
460 461 462
	 * the limit may depend on device transfer settings
	 */
	size_t (*max_transfer_size)(struct spi_device *spi);
463
	size_t (*max_message_size)(struct spi_device *spi);
464

M
Mark Brown 已提交
465 466 467
	/* I/O mutex */
	struct mutex		io_mutex;

468 469 470 471 472 473 474
	/* lock and mutex for SPI bus locking */
	spinlock_t		bus_lock_spinlock;
	struct mutex		bus_lock_mutex;

	/* flag indicating that the SPI bus is locked for exclusive use */
	bool			bus_lock_flag;

475 476 477 478 479 480
	/* Setup mode and clock, etc (spi driver may call many times).
	 *
	 * IMPORTANT:  this may be called when transfers to another
	 * device are active.  DO NOT UPDATE SHARED REGISTERS in ways
	 * which could break those transfers.
	 */
481 482 483 484 485 486 487 488 489 490
	int			(*setup)(struct spi_device *spi);

	/* bidirectional bulk transfers
	 *
	 * + The transfer() method may not sleep; its main role is
	 *   just to add the message to the queue.
	 * + For now there's no remove-from-queue operation, or
	 *   any other request management
	 * + To a given spi_device, message queueing is pure fifo
	 *
491 492
	 * + The controller's main job is to process its message queue,
	 *   selecting a chip (for masters), then transferring data
493 494 495 496 497 498 499 500 501 502 503 504
	 * + If there are multiple spi_device children, the i/o queue
	 *   arbitration algorithm is unspecified (round robin, fifo,
	 *   priority, reservations, preemption, etc)
	 *
	 * + Chipselect stays active during the entire message
	 *   (unless modified by spi_transfer.cs_change != 0).
	 * + The message transfers use clock and SPI mode parameters
	 *   previously established by setup() for this device
	 */
	int			(*transfer)(struct spi_device *spi,
						struct spi_message *mesg);

505
	/* called on release() to free memory provided by spi_controller */
506
	void			(*cleanup)(struct spi_device *spi);
507

508 509 510 511 512 513 514
	/*
	 * Used to enable core support for DMA handling, if can_dma()
	 * exists and returns true then the transfer will be mapped
	 * prior to transfer_one() being called.  The driver should
	 * not modify or store xfer and dma_tx and dma_rx must be set
	 * while the device is prepared.
	 */
515
	bool			(*can_dma)(struct spi_controller *ctlr,
516 517 518
					   struct spi_device *spi,
					   struct spi_transfer *xfer);

519 520
	/*
	 * These hooks are for drivers that want to use the generic
521
	 * controller transfer queueing mechanism. If these are used, the
522 523 524 525 526 527 528 529 530 531
	 * transfer() function above must NOT be specified by the driver.
	 * Over time we expect SPI drivers to be phased over to this API.
	 */
	bool				queued;
	struct kthread_worker		kworker;
	struct task_struct		*kworker_task;
	struct kthread_work		pump_messages;
	spinlock_t			queue_lock;
	struct list_head		queue;
	struct spi_message		*cur_msg;
532
	bool				idling;
533 534 535
	bool				busy;
	bool				running;
	bool				rt;
536
	bool				auto_runtime_pm;
537
	bool                            cur_msg_prepared;
538
	bool				cur_msg_mapped;
539
	struct completion               xfer_completion;
540
	size_t				max_dma_len;
541

542 543
	int (*prepare_transfer_hardware)(struct spi_controller *ctlr);
	int (*transfer_one_message)(struct spi_controller *ctlr,
544
				    struct spi_message *mesg);
545 546
	int (*unprepare_transfer_hardware)(struct spi_controller *ctlr);
	int (*prepare_message)(struct spi_controller *ctlr,
547
			       struct spi_message *message);
548
	int (*unprepare_message)(struct spi_controller *ctlr,
549
				 struct spi_message *message);
550
	int (*slave_abort)(struct spi_controller *ctlr);
551 552
	int (*spi_flash_read)(struct  spi_device *spi,
			      struct spi_flash_read_message *msg);
553 554
	bool (*spi_flash_can_dma)(struct spi_device *spi,
				  struct spi_flash_read_message *msg);
555
	bool (*flash_read_supported)(struct spi_device *spi);
556

557 558 559 560 561
	/*
	 * These hooks are for drivers that use a generic implementation
	 * of transfer_one_message() provied by the core.
	 */
	void (*set_cs)(struct spi_device *spi, bool enable);
562
	int (*transfer_one)(struct spi_controller *ctlr, struct spi_device *spi,
563
			    struct spi_transfer *transfer);
564
	void (*handle_err)(struct spi_controller *ctlr,
565
			   struct spi_message *message);
566

567 568
	/* gpio chip select */
	int			*cs_gpios;
569

570 571 572
	/* statistics */
	struct spi_statistics	statistics;

573 574 575
	/* DMA channels for use with core dmaengine helpers */
	struct dma_chan		*dma_tx;
	struct dma_chan		*dma_rx;
576 577 578 579

	/* dummy data for full duplex devices */
	void			*dummy_rx;
	void			*dummy_tx;
580

581
	int (*fw_translate_cs)(struct spi_controller *ctlr, unsigned cs);
582 583
};

584
static inline void *spi_controller_get_devdata(struct spi_controller *ctlr)
D
David Brownell 已提交
585
{
586
	return dev_get_drvdata(&ctlr->dev);
D
David Brownell 已提交
587 588
}

589 590
static inline void spi_controller_set_devdata(struct spi_controller *ctlr,
					      void *data)
D
David Brownell 已提交
591
{
592
	dev_set_drvdata(&ctlr->dev, data);
D
David Brownell 已提交
593 594
}

595
static inline struct spi_controller *spi_controller_get(struct spi_controller *ctlr)
D
David Brownell 已提交
596
{
597
	if (!ctlr || !get_device(&ctlr->dev))
D
David Brownell 已提交
598
		return NULL;
599
	return ctlr;
D
David Brownell 已提交
600 601
}

602
static inline void spi_controller_put(struct spi_controller *ctlr)
D
David Brownell 已提交
603
{
604 605
	if (ctlr)
		put_device(&ctlr->dev);
D
David Brownell 已提交
606 607
}

608
static inline bool spi_controller_is_slave(struct spi_controller *ctlr)
609 610 611 612
{
	return IS_ENABLED(CONFIG_SPI_SLAVE) && ctlr->slave;
}

613
/* PM calls that need to be issued by the driver */
614 615
extern int spi_controller_suspend(struct spi_controller *ctlr);
extern int spi_controller_resume(struct spi_controller *ctlr);
616 617

/* Calls the driver make to interact with the message queue */
618 619 620
extern struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr);
extern void spi_finalize_current_message(struct spi_controller *ctlr);
extern void spi_finalize_current_transfer(struct spi_controller *ctlr);
D
David Brownell 已提交
621

622 623 624
/* the spi driver core manages memory for the spi_controller classdev */
extern struct spi_controller *__spi_alloc_controller(struct device *host,
						unsigned int size, bool slave);
625

626 627
static inline struct spi_controller *spi_alloc_master(struct device *host,
						      unsigned int size)
628 629 630 631
{
	return __spi_alloc_controller(host, size, false);
}

632 633
static inline struct spi_controller *spi_alloc_slave(struct device *host,
						     unsigned int size)
634 635 636 637 638 639
{
	if (!IS_ENABLED(CONFIG_SPI_SLAVE))
		return NULL;

	return __spi_alloc_controller(host, size, true);
}
640

641 642 643 644
extern int spi_register_controller(struct spi_controller *ctlr);
extern int devm_spi_register_controller(struct device *dev,
					struct spi_controller *ctlr);
extern void spi_unregister_controller(struct spi_controller *ctlr);
645

646
extern struct spi_controller *spi_busnum_to_master(u16 busnum);
647

648 649 650 651
/*
 * SPI resource management while processing a SPI message
 */

652
typedef void (*spi_res_release_t)(struct spi_controller *ctlr,
M
Martin Sperl 已提交
653 654 655
				  struct spi_message *msg,
				  void *res);

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
/**
 * struct spi_res - spi resource management structure
 * @entry:   list entry
 * @release: release code called prior to freeing this resource
 * @data:    extra data allocated for the specific use-case
 *
 * this is based on ideas from devres, but focused on life-cycle
 * management during spi_message processing
 */
struct spi_res {
	struct list_head        entry;
	spi_res_release_t       release;
	unsigned long long      data[]; /* guarantee ull alignment */
};

extern void *spi_res_alloc(struct spi_device *spi,
			   spi_res_release_t release,
			   size_t size, gfp_t gfp);
extern void spi_res_add(struct spi_message *message, void *res);
extern void spi_res_free(void *res);

677
extern void spi_res_release(struct spi_controller *ctlr,
678 679
			    struct spi_message *message);

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
/*---------------------------------------------------------------------------*/

/*
 * I/O INTERFACE between SPI controller and protocol drivers
 *
 * Protocol drivers use a queue of spi_messages, each transferring data
 * between the controller and memory buffers.
 *
 * The spi_messages themselves consist of a series of read+write transfer
 * segments.  Those segments always read the same number of bits as they
 * write; but one or the other is easily ignored by passing a null buffer
 * pointer.  (This is unlike most types of I/O API, because SPI hardware
 * is full duplex.)
 *
 * NOTE:  Allocation of spi_transfer and spi_message memory is entirely
 * up to the protocol driver, which guarantees the integrity of both (as
 * well as the data buffers) for as long as the message is queued.
 */

/**
 * struct spi_transfer - a read/write buffer pair
701 702
 * @tx_buf: data to be written (dma-safe memory), or NULL
 * @rx_buf: data to be read (dma-safe memory), or NULL
D
David Brownell 已提交
703 704
 * @tx_dma: DMA address of tx_buf, if @spi_message.is_dma_mapped
 * @rx_dma: DMA address of rx_buf, if @spi_message.is_dma_mapped
705
 * @tx_nbits: number of bits used for writing. If 0 the default
W
wangyuhang 已提交
706 707 708
 *      (SPI_NBITS_SINGLE) is used.
 * @rx_nbits: number of bits used for reading. If 0 the default
 *      (SPI_NBITS_SINGLE) is used.
709
 * @len: size of rx and tx buffers (in bytes)
710
 * @speed_hz: Select a speed other than the device default for this
D
David Brownell 已提交
711
 *      transfer. If 0 the default (from @spi_device) is used.
712
 * @bits_per_word: select a bits_per_word other than the device default
D
David Brownell 已提交
713
 *      for this transfer. If 0 the default (from @spi_device) is used.
714 715
 * @cs_change: affects chipselect after this transfer completes
 * @delay_usecs: microseconds to delay after this transfer before
716
 *	(optionally) changing the chipselect status, then starting
D
David Brownell 已提交
717 718
 *	the next transfer or completing this @spi_message.
 * @transfer_list: transfers are sequenced through @spi_message.transfers
719 720
 * @tx_sg: Scatterlist for transmit, currently not for client use
 * @rx_sg: Scatterlist for receive, currently not for client use
721 722
 *
 * SPI transfers always write the same number of bytes as they read.
D
David Brownell 已提交
723
 * Protocol drivers should always provide @rx_buf and/or @tx_buf.
724 725 726 727
 * In some cases, they may also want to provide DMA addresses for
 * the data being transferred; that may reduce overhead, when the
 * underlying driver uses dma.
 *
728
 * If the transmit buffer is null, zeroes will be shifted out
D
David Brownell 已提交
729
 * while filling @rx_buf.  If the receive buffer is null, the data
730 731 732 733 734
 * shifted in will be discarded.  Only "len" bytes shift out (or in).
 * It's an error to try to shift out a partial word.  (For example, by
 * shifting out three bytes with word size of sixteen or twenty bits;
 * the former uses two bytes per word, the latter uses four bytes.)
 *
D
David Brownell 已提交
735 736 737
 * In-memory data values are always in native CPU byte order, translated
 * from the wire byte order (big-endian except with SPI_LSB_FIRST).  So
 * for example when bits_per_word is sixteen, buffers are 2N bytes long
D
David Brownell 已提交
738
 * (@len = 2N) and hold N sixteen bit words in CPU byte order.
D
David Brownell 已提交
739 740 741 742 743 744
 *
 * When the word size of the SPI transfer is not a power-of-two multiple
 * of eight bits, those in-memory words include extra bits.  In-memory
 * words are always seen by protocol drivers as right-justified, so the
 * undefined (rx) or unused (tx) bits are always the most significant bits.
 *
745 746
 * All SPI transfers start with the relevant chipselect active.  Normally
 * it stays selected until after the last transfer in a message.  Drivers
D
David Brownell 已提交
747
 * can affect the chipselect signal using cs_change.
748 749 750 751 752 753 754 755
 *
 * (i) If the transfer isn't the last one in the message, this flag is
 * used to make the chipselect briefly go inactive in the middle of the
 * message.  Toggling chipselect in this way may be needed to terminate
 * a chip command, letting a single spi_message perform all of group of
 * chip transactions together.
 *
 * (ii) When the transfer is the last one in the message, the chip may
D
David Brownell 已提交
756 757 758 759 760 761 762 763
 * stay selected until the next transfer.  On multi-device SPI busses
 * with nothing blocking messages going to other devices, this is just
 * a performance hint; starting a message to another device deselects
 * this one.  But in other cases, this can be used to ensure correctness.
 * Some devices need protocol transactions to be built from a series of
 * spi_message submissions, where the content of one message is determined
 * by the results of previous messages and where the whole transaction
 * ends when the chipselect goes intactive.
D
David Brownell 已提交
764
 *
765
 * When SPI can transfer in 1x,2x or 4x. It can get this transfer information
W
wangyuhang 已提交
766 767 768 769
 * from device through @tx_nbits and @rx_nbits. In Bi-direction, these
 * two should both be set. User can set transfer mode with SPI_NBITS_SINGLE(1x)
 * SPI_NBITS_DUAL(2x) and SPI_NBITS_QUAD(4x) to support these three transfer.
 *
D
David Brownell 已提交
770 771 772
 * The code that submits an spi_message (and its spi_transfers)
 * to the lower layers is responsible for managing its memory.
 * Zero-initialize every field you don't set up explicitly, to
773 774
 * insulate against future API updates.  After you submit a message
 * and its transfers, ignore them until its completion callback.
775 776 777 778
 */
struct spi_transfer {
	/* it's ok if tx_buf == rx_buf (right?)
	 * for MicroWire, one buffer must be null
D
David Brownell 已提交
779 780
	 * buffers must work with dma_*map_single() calls, unless
	 *   spi_message.is_dma_mapped reports a pre-existing mapping
781 782 783 784 785 786 787
	 */
	const void	*tx_buf;
	void		*rx_buf;
	unsigned	len;

	dma_addr_t	tx_dma;
	dma_addr_t	rx_dma;
788 789
	struct sg_table tx_sg;
	struct sg_table rx_sg;
790 791

	unsigned	cs_change:1;
792 793
	unsigned	tx_nbits:3;
	unsigned	rx_nbits:3;
W
wangyuhang 已提交
794 795 796
#define	SPI_NBITS_SINGLE	0x01 /* 1bit transfer */
#define	SPI_NBITS_DUAL		0x02 /* 2bits transfer */
#define	SPI_NBITS_QUAD		0x04 /* 4bits transfer */
797
	u8		bits_per_word;
798
	u16		delay_usecs;
799
	u32		speed_hz;
800 801

	struct list_head transfer_list;
802 803 804 805
};

/**
 * struct spi_message - one multi-segment SPI transaction
806
 * @transfers: list of transfer segments in this transaction
807 808 809 810 811
 * @spi: SPI device to which the transaction is queued
 * @is_dma_mapped: if true, the caller provided both dma and cpu virtual
 *	addresses for each transfer buffer
 * @complete: called to report transaction completions
 * @context: the argument to complete() when it's called
T
Thierry Reding 已提交
812
 * @frame_length: the total number of bytes in the message
813 814
 * @actual_length: the total number of bytes that were transferred in all
 *	successful segments
815 816 817
 * @status: zero for success, else negative errno
 * @queue: for use by whichever driver currently owns the message
 * @state: for use by whichever driver currently owns the message
818
 * @resources: for resource management when the spi message is processed
D
David Brownell 已提交
819
 *
D
David Brownell 已提交
820
 * A @spi_message is used to execute an atomic sequence of data transfers,
821 822 823 824 825
 * each represented by a struct spi_transfer.  The sequence is "atomic"
 * in the sense that no other spi_message may use that SPI bus until that
 * sequence completes.  On some systems, many such sequences can execute as
 * as single programmed DMA transfer.  On all systems, these messages are
 * queued, and might complete after transactions to other devices.  Messages
M
Marcin Bis 已提交
826
 * sent to a given spi_device are always executed in FIFO order.
827
 *
D
David Brownell 已提交
828 829 830
 * The code that submits an spi_message (and its spi_transfers)
 * to the lower layers is responsible for managing its memory.
 * Zero-initialize every field you don't set up explicitly, to
831 832
 * insulate against future API updates.  After you submit a message
 * and its transfers, ignore them until its completion callback.
833 834
 */
struct spi_message {
835
	struct list_head	transfers;
836 837 838 839 840 841 842 843 844 845 846 847

	struct spi_device	*spi;

	unsigned		is_dma_mapped:1;

	/* REVISIT:  we might want a flag affecting the behavior of the
	 * last transfer ... allowing things like "read 16 bit length L"
	 * immediately followed by "read L bytes".  Basically imposing
	 * a specific message scheduling algorithm.
	 *
	 * Some controller drivers (message-at-a-time queue processing)
	 * could provide that as their default scheduling algorithm.  But
848
	 * others (with multi-message pipelines) could need a flag to
849 850 851 852
	 * tell them about such special cases.
	 */

	/* completion is reported through a callback */
853
	void			(*complete)(void *context);
854
	void			*context;
855
	unsigned		frame_length;
856 857 858 859 860
	unsigned		actual_length;
	int			status;

	/* for optional use by whatever driver currently owns the
	 * spi_message ...  between calls to spi_async and then later
861
	 * complete(), that's the spi_controller controller driver.
862 863 864
	 */
	struct list_head	queue;
	void			*state;
865 866 867

	/* list of spi_res reources when the spi message is processed */
	struct list_head        resources;
868 869
};

870 871 872
static inline void spi_message_init_no_memset(struct spi_message *m)
{
	INIT_LIST_HEAD(&m->transfers);
873
	INIT_LIST_HEAD(&m->resources);
874 875
}

876 877 878
static inline void spi_message_init(struct spi_message *m)
{
	memset(m, 0, sizeof *m);
879
	spi_message_init_no_memset(m);
880 881 882 883 884 885 886 887 888 889 890 891 892 893
}

static inline void
spi_message_add_tail(struct spi_transfer *t, struct spi_message *m)
{
	list_add_tail(&t->transfer_list, &m->transfers);
}

static inline void
spi_transfer_del(struct spi_transfer *t)
{
	list_del(&t->transfer_list);
}

894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
/**
 * spi_message_init_with_transfers - Initialize spi_message and append transfers
 * @m: spi_message to be initialized
 * @xfers: An array of spi transfers
 * @num_xfers: Number of items in the xfer array
 *
 * This function initializes the given spi_message and adds each spi_transfer in
 * the given array to the message.
 */
static inline void
spi_message_init_with_transfers(struct spi_message *m,
struct spi_transfer *xfers, unsigned int num_xfers)
{
	unsigned int i;

	spi_message_init(m);
	for (i = 0; i < num_xfers; ++i)
		spi_message_add_tail(&xfers[i], m);
}

D
David Brownell 已提交
914 915 916 917 918 919 920 921 922 923 924 925
/* It's fine to embed message and transaction structures in other data
 * structures so long as you don't free them while they're in use.
 */

static inline struct spi_message *spi_message_alloc(unsigned ntrans, gfp_t flags)
{
	struct spi_message *m;

	m = kzalloc(sizeof(struct spi_message)
			+ ntrans * sizeof(struct spi_transfer),
			flags);
	if (m) {
S
Shubhrajyoti D 已提交
926
		unsigned i;
927 928
		struct spi_transfer *t = (struct spi_transfer *)(m + 1);

929
		spi_message_init_no_memset(m);
930 931
		for (i = 0; i < ntrans; i++, t++)
			spi_message_add_tail(t, m);
D
David Brownell 已提交
932 933 934 935 936 937 938 939 940
	}
	return m;
}

static inline void spi_message_free(struct spi_message *m)
{
	kfree(m);
}

941
extern int spi_setup(struct spi_device *spi);
D
David Brownell 已提交
942
extern int spi_async(struct spi_device *spi, struct spi_message *message);
943 944
extern int spi_async_locked(struct spi_device *spi,
			    struct spi_message *message);
945
extern int spi_slave_abort(struct spi_device *spi);
946

947
static inline size_t
948
spi_max_message_size(struct spi_device *spi)
949
{
950 951 952
	struct spi_controller *ctlr = spi->controller;

	if (!ctlr->max_message_size)
953
		return SIZE_MAX;
954
	return ctlr->max_message_size(spi);
955 956 957 958 959
}

static inline size_t
spi_max_transfer_size(struct spi_device *spi)
{
960
	struct spi_controller *ctlr = spi->controller;
961 962 963
	size_t tr_max = SIZE_MAX;
	size_t msg_max = spi_max_message_size(spi);

964 965
	if (ctlr->max_transfer_size)
		tr_max = ctlr->max_transfer_size(spi);
966 967 968

	/* transfer size limit must not be greater than messsage size limit */
	return min(tr_max, msg_max);
969 970
}

971 972
/*---------------------------------------------------------------------------*/

973 974
/* SPI transfer replacement methods which make use of spi_res */

975
struct spi_replaced_transfers;
976
typedef void (*spi_replaced_release_t)(struct spi_controller *ctlr,
977 978
				       struct spi_message *msg,
				       struct spi_replaced_transfers *res);
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
/**
 * struct spi_replaced_transfers - structure describing the spi_transfer
 *                                 replacements that have occurred
 *                                 so that they can get reverted
 * @release:            some extra release code to get executed prior to
 *                      relasing this structure
 * @extradata:          pointer to some extra data if requested or NULL
 * @replaced_transfers: transfers that have been replaced and which need
 *                      to get restored
 * @replaced_after:     the transfer after which the @replaced_transfers
 *                      are to get re-inserted
 * @inserted:           number of transfers inserted
 * @inserted_transfers: array of spi_transfers of array-size @inserted,
 *                      that have been replacing replaced_transfers
 *
 * note: that @extradata will point to @inserted_transfers[@inserted]
 * if some extra allocation is requested, so alignment will be the same
 * as for spi_transfers
 */
struct spi_replaced_transfers {
	spi_replaced_release_t release;
	void *extradata;
	struct list_head replaced_transfers;
	struct list_head *replaced_after;
	size_t inserted;
	struct spi_transfer inserted_transfers[];
};

extern struct spi_replaced_transfers *spi_replace_transfers(
	struct spi_message *msg,
	struct spi_transfer *xfer_first,
	size_t remove,
	size_t insert,
	spi_replaced_release_t release,
	size_t extradatasize,
	gfp_t gfp);

/*---------------------------------------------------------------------------*/

1018 1019
/* SPI transfer transformation methods */

1020
extern int spi_split_transfers_maxsize(struct spi_controller *ctlr,
1021 1022 1023 1024 1025 1026
				       struct spi_message *msg,
				       size_t maxsize,
				       gfp_t gfp);

/*---------------------------------------------------------------------------*/

1027 1028 1029 1030 1031 1032
/* All these synchronous SPI transfer routines are utilities layered
 * over the core async transfer primitive.  Here, "synchronous" means
 * they will sleep uninterruptibly until the async transfer completes.
 */

extern int spi_sync(struct spi_device *spi, struct spi_message *message);
1033
extern int spi_sync_locked(struct spi_device *spi, struct spi_message *message);
1034 1035
extern int spi_bus_lock(struct spi_controller *ctlr);
extern int spi_bus_unlock(struct spi_controller *ctlr);
1036

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
/**
 * spi_sync_transfer - synchronous SPI data transfer
 * @spi: device with which data will be exchanged
 * @xfers: An array of spi_transfers
 * @num_xfers: Number of items in the xfer array
 * Context: can sleep
 *
 * Does a synchronous SPI data transfer of the given spi_transfer array.
 *
 * For more specific semantics see spi_sync().
 *
 * Return: Return: zero on success, else a negative error code.
 */
static inline int
spi_sync_transfer(struct spi_device *spi, struct spi_transfer *xfers,
	unsigned int num_xfers)
{
	struct spi_message msg;

	spi_message_init_with_transfers(&msg, xfers, num_xfers);

	return spi_sync(spi, &msg);
}

1061 1062 1063 1064 1065
/**
 * spi_write - SPI synchronous write
 * @spi: device to which data will be written
 * @buf: data buffer
 * @len: data buffer size
D
David Brownell 已提交
1066
 * Context: can sleep
1067
 *
1068
 * This function writes the buffer @buf.
1069
 * Callable only from contexts that can sleep.
1070 1071
 *
 * Return: zero on success, else a negative error code.
1072 1073
 */
static inline int
1074
spi_write(struct spi_device *spi, const void *buf, size_t len)
1075 1076 1077 1078 1079 1080
{
	struct spi_transfer	t = {
			.tx_buf		= buf,
			.len		= len,
		};

1081
	return spi_sync_transfer(spi, &t, 1);
1082 1083 1084 1085 1086 1087 1088
}

/**
 * spi_read - SPI synchronous read
 * @spi: device from which data will be read
 * @buf: data buffer
 * @len: data buffer size
D
David Brownell 已提交
1089
 * Context: can sleep
1090
 *
1091
 * This function reads the buffer @buf.
1092
 * Callable only from contexts that can sleep.
1093 1094
 *
 * Return: zero on success, else a negative error code.
1095 1096
 */
static inline int
1097
spi_read(struct spi_device *spi, void *buf, size_t len)
1098 1099 1100 1101 1102 1103
{
	struct spi_transfer	t = {
			.rx_buf		= buf,
			.len		= len,
		};

1104
	return spi_sync_transfer(spi, &t, 1);
1105 1106
}

D
David Brownell 已提交
1107
/* this copies txbuf and rxbuf data; for small transfers only! */
1108
extern int spi_write_then_read(struct spi_device *spi,
1109 1110
		const void *txbuf, unsigned n_tx,
		void *rxbuf, unsigned n_rx);
1111 1112 1113 1114 1115

/**
 * spi_w8r8 - SPI synchronous 8 bit write followed by 8 bit read
 * @spi: device with which data will be exchanged
 * @cmd: command to be written before data is read back
D
David Brownell 已提交
1116
 * Context: can sleep
1117
 *
1118 1119 1120 1121
 * Callable only from contexts that can sleep.
 *
 * Return: the (unsigned) eight bit number returned by the
 * device, or else a negative error code.
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
 */
static inline ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)
{
	ssize_t			status;
	u8			result;

	status = spi_write_then_read(spi, &cmd, 1, &result, 1);

	/* return negative errno or unsigned value */
	return (status < 0) ? status : result;
}

/**
 * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read
 * @spi: device with which data will be exchanged
 * @cmd: command to be written before data is read back
D
David Brownell 已提交
1138
 * Context: can sleep
1139 1140 1141
 *
 * The number is returned in wire-order, which is at least sometimes
 * big-endian.
1142 1143 1144 1145 1146
 *
 * Callable only from contexts that can sleep.
 *
 * Return: the (unsigned) sixteen bit number returned by the
 * device, or else a negative error code.
1147 1148 1149 1150 1151 1152
 */
static inline ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)
{
	ssize_t			status;
	u16			result;

1153
	status = spi_write_then_read(spi, &cmd, 1, &result, 2);
1154 1155 1156 1157 1158

	/* return negative errno or unsigned value */
	return (status < 0) ? status : result;
}

1159 1160 1161 1162 1163 1164 1165 1166 1167
/**
 * spi_w8r16be - SPI synchronous 8 bit write followed by 16 bit big-endian read
 * @spi: device with which data will be exchanged
 * @cmd: command to be written before data is read back
 * Context: can sleep
 *
 * This function is similar to spi_w8r16, with the exception that it will
 * convert the read 16 bit data word from big-endian to native endianness.
 *
1168 1169 1170 1171
 * Callable only from contexts that can sleep.
 *
 * Return: the (unsigned) sixteen bit number returned by the device in cpu
 * endianness, or else a negative error code.
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
 */
static inline ssize_t spi_w8r16be(struct spi_device *spi, u8 cmd)

{
	ssize_t status;
	__be16 result;

	status = spi_write_then_read(spi, &cmd, 1, &result, 2);
	if (status < 0)
		return status;

	return be16_to_cpu(result);
}

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
/**
 * struct spi_flash_read_message - flash specific information for
 * spi-masters that provide accelerated flash read interfaces
 * @buf: buffer to read data
 * @from: offset within the flash from where data is to be read
 * @len: length of data to be read
 * @retlen: actual length of data read
 * @read_opcode: read_opcode to be used to communicate with flash
 * @addr_width: number of address bytes
 * @dummy_bytes: number of dummy bytes
 * @opcode_nbits: number of lines to send opcode
 * @addr_nbits: number of lines to send address
 * @data_nbits: number of lines for data
1199 1200
 * @rx_sg: Scatterlist for receive data read from flash
 * @cur_msg_mapped: message has been mapped for DMA
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
 */
struct spi_flash_read_message {
	void *buf;
	loff_t from;
	size_t len;
	size_t retlen;
	u8 read_opcode;
	u8 addr_width;
	u8 dummy_bytes;
	u8 opcode_nbits;
	u8 addr_nbits;
	u8 data_nbits;
1213 1214
	struct sg_table rx_sg;
	bool cur_msg_mapped;
1215 1216 1217 1218 1219
};

/* SPI core interface for flash read support */
static inline bool spi_flash_read_supported(struct spi_device *spi)
{
1220 1221 1222
	return spi->controller->spi_flash_read &&
	       (!spi->controller->flash_read_supported ||
	       spi->controller->flash_read_supported(spi));
1223 1224 1225 1226 1227
}

int spi_flash_read(struct spi_device *spi,
		   struct spi_flash_read_message *msg);

1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
/*---------------------------------------------------------------------------*/

/*
 * INTERFACE between board init code and SPI infrastructure.
 *
 * No SPI driver ever sees these SPI device table segments, but
 * it's how the SPI core (or adapters that get hotplugged) grows
 * the driver model tree.
 *
 * As a rule, SPI devices can't be probed.  Instead, board init code
 * provides a table listing the devices which are present, with enough
 * information to bind and set up the device's driver.  There's basic
 * support for nonstatic configurations too; enough to handle adding
 * parport adapters, or microcontrollers acting as USB-to-SPI bridges.
 */

D
David Brownell 已提交
1244 1245 1246 1247 1248
/**
 * struct spi_board_info - board-specific template for a SPI device
 * @modalias: Initializes spi_device.modalias; identifies the driver.
 * @platform_data: Initializes spi_device.platform_data; the particular
 *	data stored there is driver-specific.
1249
 * @properties: Additional device properties for the device.
D
David Brownell 已提交
1250 1251 1252 1253 1254
 * @controller_data: Initializes spi_device.controller_data; some
 *	controllers need hints about hardware setup, e.g. for DMA.
 * @irq: Initializes spi_device.irq; depends on how the board is wired.
 * @max_speed_hz: Initializes spi_device.max_speed_hz; based on limits
 *	from the chip datasheet and board-specific signal quality issues.
1255
 * @bus_num: Identifies which spi_controller parents the spi_device; unused
D
David Brownell 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
 *	by spi_new_device(), and otherwise depends on board wiring.
 * @chip_select: Initializes spi_device.chip_select; depends on how
 *	the board is wired.
 * @mode: Initializes spi_device.mode; based on the chip datasheet, board
 *	wiring (some devices support both 3WIRE and standard modes), and
 *	possibly presence of an inverter in the chipselect path.
 *
 * When adding new SPI devices to the device tree, these structures serve
 * as a partial device template.  They hold information which can't always
 * be determined by drivers.  Information that probe() can establish (such
 * as the default transfer wordsize) is not included here.
 *
 * These structures are used in two places.  Their primary role is to
 * be stored in tables of board-specific device descriptors, which are
 * declared early in board initialization and then used (much later) to
 * populate a controller's device tree after the that controller's driver
 * initializes.  A secondary (and atypical) role is as a parameter to
 * spi_new_device() call, which happens after those controller drivers
 * are active in some dynamic board configuration models.
 */
1276 1277 1278 1279 1280
struct spi_board_info {
	/* the device name and module name are coupled, like platform_bus;
	 * "modalias" is normally the driver name.
	 *
	 * platform_data goes to spi_device.dev.platform_data,
1281
	 * controller_data goes to spi_device.controller_data,
1282
	 * device properties are copied and attached to spi_device,
1283 1284
	 * irq is copied too
	 */
1285
	char		modalias[SPI_NAME_SIZE];
1286
	const void	*platform_data;
1287
	const struct property_entry *properties;
1288
	void		*controller_data;
1289 1290 1291 1292 1293 1294 1295
	int		irq;

	/* slower signaling on noisy or low voltage boards */
	u32		max_speed_hz;


	/* bus_num is board specific and matches the bus_num of some
1296
	 * spi_controller that will probably be registered later.
1297 1298 1299 1300 1301 1302 1303
	 *
	 * chip_select reflects how this chip is wired to that master;
	 * it's less than num_chipselect.
	 */
	u16		bus_num;
	u16		chip_select;

1304 1305 1306
	/* mode becomes spi_device.mode, and is essential for chips
	 * where the default of SPI_CS_HIGH = 0 is wrong.
	 */
W
wangyuhang 已提交
1307
	u16		mode;
1308

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
	/* ... may need additional spi_device chip config data here.
	 * avoid stuff protocol drivers can set; but include stuff
	 * needed to behave without being bound to a driver:
	 *  - quirks like clock rate mattering when not selected
	 */
};

#ifdef	CONFIG_SPI
extern int
spi_register_board_info(struct spi_board_info const *info, unsigned n);
#else
/* board init code may ignore whether SPI is configured or not */
static inline int
spi_register_board_info(struct spi_board_info const *info, unsigned n)
	{ return 0; }
#endif


/* If you're hotplugging an adapter with devices (parport, usb, etc)
D
David Brownell 已提交
1328 1329
 * use spi_new_device() to describe each device.  You can also call
 * spi_unregister_device() to start making that device vanish, but
1330
 * normally that would be handled by spi_unregister_controller().
1331 1332 1333 1334 1335 1336
 *
 * You can also use spi_alloc_device() and spi_add_device() to use a two
 * stage registration sequence for each spi_device.  This gives the caller
 * some more control over the spi_device structure before it is registered,
 * but requires that caller to initialize fields that would otherwise
 * be defined using the board info.
1337
 */
1338
extern struct spi_device *
1339
spi_alloc_device(struct spi_controller *ctlr);
1340 1341 1342 1343

extern int
spi_add_device(struct spi_device *spi);

1344
extern struct spi_device *
1345
spi_new_device(struct spi_controller *, struct spi_board_info *);
1346

1347
extern void spi_unregister_device(struct spi_device *spi);
1348

1349 1350 1351
extern const struct spi_device_id *
spi_get_device_id(const struct spi_device *sdev);

1352
static inline bool
1353
spi_transfer_is_last(struct spi_controller *ctlr, struct spi_transfer *xfer)
1354
{
1355
	return list_is_last(&xfer->transfer_list, &ctlr->cur_msg->transfers);
1356 1357
}

1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380

/* Compatibility layer */
#define spi_master			spi_controller

#define SPI_MASTER_HALF_DUPLEX		SPI_CONTROLLER_HALF_DUPLEX
#define SPI_MASTER_NO_RX		SPI_CONTROLLER_NO_RX
#define SPI_MASTER_NO_TX		SPI_CONTROLLER_NO_TX
#define SPI_MASTER_MUST_RX		SPI_CONTROLLER_MUST_RX
#define SPI_MASTER_MUST_TX		SPI_CONTROLLER_MUST_TX

#define spi_master_get_devdata(_ctlr)	spi_controller_get_devdata(_ctlr)
#define spi_master_set_devdata(_ctlr, _data)	\
	spi_controller_set_devdata(_ctlr, _data)
#define spi_master_get(_ctlr)		spi_controller_get(_ctlr)
#define spi_master_put(_ctlr)		spi_controller_put(_ctlr)
#define spi_master_suspend(_ctlr)	spi_controller_suspend(_ctlr)
#define spi_master_resume(_ctlr)	spi_controller_resume(_ctlr)

#define spi_register_master(_ctlr)	spi_register_controller(_ctlr)
#define devm_spi_register_master(_dev, _ctlr) \
	devm_spi_register_controller(_dev, _ctlr)
#define spi_unregister_master(_ctlr)	spi_unregister_controller(_ctlr)

1381
#endif /* __LINUX_SPI_H */