spidev.c 22.4 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-or-later
Andrea Paterniani's avatar
Andrea Paterniani committed
2
/*
Grant Likely's avatar
Grant Likely committed
3
 * Simple synchronous userspace interface to SPI devices
Andrea Paterniani's avatar
Andrea Paterniani committed
4 5 6 7 8 9 10 11 12 13
 *
 * Copyright (C) 2006 SWAPP
 *	Andrea Paterniani <a.paterniani@swapp-eng.it>
 * Copyright (C) 2007 David Brownell (simplification, cleanup)
 */

#include <linux/init.h>
#include <linux/ioctl.h>
#include <linux/fs.h>
#include <linux/device.h>
14
#include <linux/err.h>
Andrea Paterniani's avatar
Andrea Paterniani committed
15 16
#include <linux/list.h>
#include <linux/errno.h>
17 18
#include <linux/mod_devicetable.h>
#include <linux/module.h>
Andrea Paterniani's avatar
Andrea Paterniani committed
19
#include <linux/mutex.h>
20
#include <linux/property.h>
Andrea Paterniani's avatar
Andrea Paterniani committed
21
#include <linux/slab.h>
22
#include <linux/compat.h>
Andrea Paterniani's avatar
Andrea Paterniani committed
23 24 25 26

#include <linux/spi/spi.h>
#include <linux/spi/spidev.h>

27
#include <linux/uaccess.h>
Andrea Paterniani's avatar
Andrea Paterniani committed
28 29 30


/*
31
 * This supports access to SPI devices using normal userspace I/O calls.
Andrea Paterniani's avatar
Andrea Paterniani committed
32 33
 * Note that while traditional UNIX/POSIX I/O semantics are half duplex,
 * and often mask message boundaries, full SPI support requires full duplex
34
 * transfers.  There are several kinds of internal message boundaries to
Andrea Paterniani's avatar
Andrea Paterniani committed
35 36 37 38 39 40 41 42 43 44 45
 * handle chipselect management and other protocol options.
 *
 * SPI has a character major number assigned.  We allocate minor numbers
 * dynamically using a bitmask.  You must use hotplug tools, such as udev
 * (or mdev with busybox) to create and destroy the /dev/spidevB.C device
 * nodes, since there is no fixed association of minor numbers with any
 * particular SPI bus or device.
 */
#define SPIDEV_MAJOR			153	/* assigned */
#define N_SPI_MINORS			32	/* ... up to 256 */

46
static DECLARE_BITMAP(minors, N_SPI_MINORS);
Andrea Paterniani's avatar
Andrea Paterniani committed
47

48
static_assert(N_SPI_MINORS > 0 && N_SPI_MINORS <= 256);
Andrea Paterniani's avatar
Andrea Paterniani committed
49

50
/* Bit masks for spi_device.mode management.  Note that incorrect
David Brownell's avatar
David Brownell committed
51 52
 * settings for some settings can cause *lots* of trouble for other
 * devices on a shared bus:
53
 *
David Brownell's avatar
David Brownell committed
54 55 56 57 58 59 60
 *  - CS_HIGH ... this device will be active when it shouldn't be
 *  - 3WIRE ... when active, it won't behave as it should
 *  - NO_CS ... there will be no explicit message boundaries; this
 *	is completely incompatible with the shared bus model
 *  - READY ... transfers may proceed when they shouldn't.
 *
 * REVISIT should changing those flags be privileged?
61
 */
62
#define SPI_MODE_MASK		(SPI_MODE_X_MASK | SPI_CS_HIGH \
David Brownell's avatar
David Brownell committed
63
				| SPI_LSB_FIRST | SPI_3WIRE | SPI_LOOP \
64
				| SPI_NO_CS | SPI_READY | SPI_TX_DUAL \
65
				| SPI_TX_QUAD | SPI_TX_OCTAL | SPI_RX_DUAL \
66 67
				| SPI_RX_QUAD | SPI_RX_OCTAL \
				| SPI_RX_CPHA_FLIP)
Andrea Paterniani's avatar
Andrea Paterniani committed
68 69

struct spidev_data {
70
	dev_t			devt;
71
	struct mutex		spi_lock;
Andrea Paterniani's avatar
Andrea Paterniani committed
72 73 74
	struct spi_device	*spi;
	struct list_head	device_entry;

75
	/* TX/RX buffers are NULL unless this device is open (users > 0) */
Andrea Paterniani's avatar
Andrea Paterniani committed
76 77
	struct mutex		buf_lock;
	unsigned		users;
78 79
	u8			*tx_buffer;
	u8			*rx_buffer;
80
	u32			speed_hz;
Andrea Paterniani's avatar
Andrea Paterniani committed
81 82 83 84 85 86 87 88 89 90 91
};

static LIST_HEAD(device_list);
static DEFINE_MUTEX(device_list_lock);

static unsigned bufsiz = 4096;
module_param(bufsiz, uint, S_IRUGO);
MODULE_PARM_DESC(bufsiz, "data bytes in biggest supported SPI message");

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

92 93 94 95
static ssize_t
spidev_sync(struct spidev_data *spidev, struct spi_message *message)
{
	int status;
96
	struct spi_device *spi;
97

98
	mutex_lock(&spidev->spi_lock);
99 100 101
	spi = spidev->spi;

	if (spi == NULL)
102 103
		status = -ESHUTDOWN;
	else
104 105 106 107
		status = spi_sync(spi, message);

	if (status == 0)
		status = message->actual_length;
108

109
	mutex_unlock(&spidev->spi_lock);
110 111 112 113 114 115 116
	return status;
}

static inline ssize_t
spidev_sync_write(struct spidev_data *spidev, size_t len)
{
	struct spi_transfer	t = {
117
			.tx_buf		= spidev->tx_buffer,
118
			.len		= len,
119
			.speed_hz	= spidev->speed_hz,
120 121 122 123 124 125 126 127 128 129 130 131
		};
	struct spi_message	m;

	spi_message_init(&m);
	spi_message_add_tail(&t, &m);
	return spidev_sync(spidev, &m);
}

static inline ssize_t
spidev_sync_read(struct spidev_data *spidev, size_t len)
{
	struct spi_transfer	t = {
132
			.rx_buf		= spidev->rx_buffer,
133
			.len		= len,
134
			.speed_hz	= spidev->speed_hz,
135 136 137 138 139 140 141 142 143 144
		};
	struct spi_message	m;

	spi_message_init(&m);
	spi_message_add_tail(&t, &m);
	return spidev_sync(spidev, &m);
}

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

Andrea Paterniani's avatar
Andrea Paterniani committed
145 146 147 148 149
/* Read-only message with current device setup */
static ssize_t
spidev_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)
{
	struct spidev_data	*spidev;
150
	ssize_t			status;
Andrea Paterniani's avatar
Andrea Paterniani committed
151 152 153 154 155 156 157 158

	/* chipselect only toggles at start or end of operation */
	if (count > bufsiz)
		return -EMSGSIZE;

	spidev = filp->private_data;

	mutex_lock(&spidev->buf_lock);
159
	status = spidev_sync_read(spidev, count);
160
	if (status > 0) {
Andrea Paterniani's avatar
Andrea Paterniani committed
161 162
		unsigned long	missing;

163
		missing = copy_to_user(buf, spidev->rx_buffer, status);
164
		if (missing == status)
Andrea Paterniani's avatar
Andrea Paterniani committed
165 166
			status = -EFAULT;
		else
167
			status = status - missing;
Andrea Paterniani's avatar
Andrea Paterniani committed
168 169 170 171 172 173 174 175 176 177 178 179
	}
	mutex_unlock(&spidev->buf_lock);

	return status;
}

/* Write-only message with current device setup */
static ssize_t
spidev_write(struct file *filp, const char __user *buf,
		size_t count, loff_t *f_pos)
{
	struct spidev_data	*spidev;
180
	ssize_t			status;
Andrea Paterniani's avatar
Andrea Paterniani committed
181 182 183 184 185 186 187 188 189
	unsigned long		missing;

	/* chipselect only toggles at start or end of operation */
	if (count > bufsiz)
		return -EMSGSIZE;

	spidev = filp->private_data;

	mutex_lock(&spidev->buf_lock);
190
	missing = copy_from_user(spidev->tx_buffer, buf, count);
191
	if (missing == 0)
192
		status = spidev_sync_write(spidev, count);
193
	else
Andrea Paterniani's avatar
Andrea Paterniani committed
194 195 196 197 198 199 200 201 202 203 204 205 206
		status = -EFAULT;
	mutex_unlock(&spidev->buf_lock);

	return status;
}

static int spidev_message(struct spidev_data *spidev,
		struct spi_ioc_transfer *u_xfers, unsigned n_xfers)
{
	struct spi_message	msg;
	struct spi_transfer	*k_xfers;
	struct spi_transfer	*k_tmp;
	struct spi_ioc_transfer *u_tmp;
207
	unsigned		n, total, tx_total, rx_total;
208
	u8			*tx_buf, *rx_buf;
Andrea Paterniani's avatar
Andrea Paterniani committed
209 210 211 212 213 214 215 216 217 218 219
	int			status = -EFAULT;

	spi_message_init(&msg);
	k_xfers = kcalloc(n_xfers, sizeof(*k_tmp), GFP_KERNEL);
	if (k_xfers == NULL)
		return -ENOMEM;

	/* Construct spi_message, copying any tx data to bounce buffer.
	 * We walk the array of user-provided transfers, using each one
	 * to initialize a kernel version of the same transfer.
	 */
220 221
	tx_buf = spidev->tx_buffer;
	rx_buf = spidev->rx_buffer;
Andrea Paterniani's avatar
Andrea Paterniani committed
222
	total = 0;
223 224
	tx_total = 0;
	rx_total = 0;
Andrea Paterniani's avatar
Andrea Paterniani committed
225 226 227
	for (n = n_xfers, k_tmp = k_xfers, u_tmp = u_xfers;
			n;
			n--, k_tmp++, u_tmp++) {
228 229 230 231 232
		/* Ensure that also following allocations from rx_buf/tx_buf will meet
		 * DMA alignment requirements.
		 */
		unsigned int len_aligned = ALIGN(u_tmp->len, ARCH_KMALLOC_MINALIGN);

Andrea Paterniani's avatar
Andrea Paterniani committed
233 234
		k_tmp->len = u_tmp->len;

235
		total += k_tmp->len;
236 237
		/* Since the function returns the total length of transfers
		 * on success, restrict the total to positive int values to
238 239
		 * avoid the return value looking like an error.  Also check
		 * each transfer length to avoid arithmetic overflow.
240
		 */
241
		if (total > INT_MAX || k_tmp->len > INT_MAX) {
242 243 244 245
			status = -EMSGSIZE;
			goto done;
		}

Andrea Paterniani's avatar
Andrea Paterniani committed
246
		if (u_tmp->rx_buf) {
247
			/* this transfer needs space in RX bounce buffer */
248
			rx_total += len_aligned;
249 250 251 252
			if (rx_total > bufsiz) {
				status = -EMSGSIZE;
				goto done;
			}
253
			k_tmp->rx_buf = rx_buf;
254
			rx_buf += len_aligned;
Andrea Paterniani's avatar
Andrea Paterniani committed
255 256
		}
		if (u_tmp->tx_buf) {
257
			/* this transfer needs space in TX bounce buffer */
258
			tx_total += len_aligned;
259 260 261 262
			if (tx_total > bufsiz) {
				status = -EMSGSIZE;
				goto done;
			}
263 264
			k_tmp->tx_buf = tx_buf;
			if (copy_from_user(tx_buf, (const u8 __user *)
Al Viro's avatar
Al Viro committed
265
						(uintptr_t) u_tmp->tx_buf,
Andrea Paterniani's avatar
Andrea Paterniani committed
266 267
					u_tmp->len))
				goto done;
268
			tx_buf += len_aligned;
Andrea Paterniani's avatar
Andrea Paterniani committed
269 270 271
		}

		k_tmp->cs_change = !!u_tmp->cs_change;
272 273
		k_tmp->tx_nbits = u_tmp->tx_nbits;
		k_tmp->rx_nbits = u_tmp->rx_nbits;
Andrea Paterniani's avatar
Andrea Paterniani committed
274
		k_tmp->bits_per_word = u_tmp->bits_per_word;
275 276
		k_tmp->delay.value = u_tmp->delay_usecs;
		k_tmp->delay.unit = SPI_DELAY_UNIT_USECS;
Andrea Paterniani's avatar
Andrea Paterniani committed
277
		k_tmp->speed_hz = u_tmp->speed_hz;
278 279
		k_tmp->word_delay.value = u_tmp->word_delay_usecs;
		k_tmp->word_delay.unit = SPI_DELAY_UNIT_USECS;
280 281
		if (!k_tmp->speed_hz)
			k_tmp->speed_hz = spidev->speed_hz;
Andrea Paterniani's avatar
Andrea Paterniani committed
282
#ifdef VERBOSE
283
		dev_dbg(&spidev->spi->dev,
284
			"  xfer len %u %s%s%s%dbits %u usec %u usec %uHz\n",
285 286 287 288 289 290 291 292
			k_tmp->len,
			k_tmp->rx_buf ? "rx " : "",
			k_tmp->tx_buf ? "tx " : "",
			k_tmp->cs_change ? "cs " : "",
			k_tmp->bits_per_word ? : spidev->spi->bits_per_word,
			k_tmp->delay.value,
			k_tmp->word_delay.value,
			k_tmp->speed_hz ? : spidev->spi->max_speed_hz);
Andrea Paterniani's avatar
Andrea Paterniani committed
293 294 295 296
#endif
		spi_message_add_tail(k_tmp, &msg);
	}

297
	status = spidev_sync(spidev, &msg);
Andrea Paterniani's avatar
Andrea Paterniani committed
298 299 300 301
	if (status < 0)
		goto done;

	/* copy any rx data out of bounce buffer */
302 303 304
	for (n = n_xfers, k_tmp = k_xfers, u_tmp = u_xfers;
			n;
			n--, k_tmp++, u_tmp++) {
Andrea Paterniani's avatar
Andrea Paterniani committed
305
		if (u_tmp->rx_buf) {
306
			if (copy_to_user((u8 __user *)
307
					(uintptr_t) u_tmp->rx_buf, k_tmp->rx_buf,
Andrea Paterniani's avatar
Andrea Paterniani committed
308 309 310 311 312 313 314 315 316 317 318 319 320
					u_tmp->len)) {
				status = -EFAULT;
				goto done;
			}
		}
	}
	status = total;

done:
	kfree(k_xfers);
	return status;
}

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
static struct spi_ioc_transfer *
spidev_get_ioc_message(unsigned int cmd, struct spi_ioc_transfer __user *u_ioc,
		unsigned *n_ioc)
{
	u32	tmp;

	/* Check type, command number and direction */
	if (_IOC_TYPE(cmd) != SPI_IOC_MAGIC
			|| _IOC_NR(cmd) != _IOC_NR(SPI_IOC_MESSAGE(0))
			|| _IOC_DIR(cmd) != _IOC_WRITE)
		return ERR_PTR(-ENOTTY);

	tmp = _IOC_SIZE(cmd);
	if ((tmp % sizeof(struct spi_ioc_transfer)) != 0)
		return ERR_PTR(-EINVAL);
	*n_ioc = tmp / sizeof(struct spi_ioc_transfer);
	if (*n_ioc == 0)
		return NULL;

	/* copy into scratch area */
341
	return memdup_user(u_ioc, tmp);
342 343
}

Alan Cox's avatar
Alan Cox committed
344 345
static long
spidev_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
Andrea Paterniani's avatar
Andrea Paterniani committed
346 347 348 349 350 351 352 353 354 355 356 357
{
	int			retval = 0;
	struct spidev_data	*spidev;
	struct spi_device	*spi;
	u32			tmp;
	unsigned		n_ioc;
	struct spi_ioc_transfer	*ioc;

	/* Check type and command number */
	if (_IOC_TYPE(cmd) != SPI_IOC_MAGIC)
		return -ENOTTY;

358 359 360
	/* guard against device removal before, or while,
	 * we issue this ioctl.
	 */
Andrea Paterniani's avatar
Andrea Paterniani committed
361
	spidev = filp->private_data;
362
	mutex_lock(&spidev->spi_lock);
363
	spi = spi_dev_get(spidev->spi);
364 365
	if (spi == NULL) {
		mutex_unlock(&spidev->spi_lock);
366
		return -ESHUTDOWN;
367
	}
Andrea Paterniani's avatar
Andrea Paterniani committed
368

Alan Cox's avatar
Alan Cox committed
369 370 371 372 373 374 375 376
	/* use the buffer lock here for triple duty:
	 *  - prevent I/O (from us) so calling spi_setup() is safe;
	 *  - prevent concurrent SPI_IOC_WR_* from morphing
	 *    data fields while SPI_IOC_RD_* reads them;
	 *  - SPI_IOC_MESSAGE needs the buffer locked "normally".
	 */
	mutex_lock(&spidev->buf_lock);

Andrea Paterniani's avatar
Andrea Paterniani committed
377 378 379
	switch (cmd) {
	/* read requests */
	case SPI_IOC_RD_MODE:
380
	case SPI_IOC_RD_MODE32:
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
		tmp = spi->mode;

		{
			struct spi_controller *ctlr = spi->controller;

			if (ctlr->use_gpio_descriptors && ctlr->cs_gpiods &&
			    ctlr->cs_gpiods[spi->chip_select])
				tmp &= ~SPI_CS_HIGH;
		}

		if (cmd == SPI_IOC_RD_MODE)
			retval = put_user(tmp & SPI_MODE_MASK,
					  (__u8 __user *)arg);
		else
			retval = put_user(tmp & SPI_MODE_MASK,
					  (__u32 __user *)arg);
397
		break;
Andrea Paterniani's avatar
Andrea Paterniani committed
398
	case SPI_IOC_RD_LSB_FIRST:
399
		retval = put_user((spi->mode & SPI_LSB_FIRST) ?  1 : 0,
Andrea Paterniani's avatar
Andrea Paterniani committed
400 401 402
					(__u8 __user *)arg);
		break;
	case SPI_IOC_RD_BITS_PER_WORD:
403
		retval = put_user(spi->bits_per_word, (__u8 __user *)arg);
Andrea Paterniani's avatar
Andrea Paterniani committed
404 405
		break;
	case SPI_IOC_RD_MAX_SPEED_HZ:
406
		retval = put_user(spidev->speed_hz, (__u32 __user *)arg);
Andrea Paterniani's avatar
Andrea Paterniani committed
407 408 409 410
		break;

	/* write requests */
	case SPI_IOC_WR_MODE:
411 412
	case SPI_IOC_WR_MODE32:
		if (cmd == SPI_IOC_WR_MODE)
413
			retval = get_user(tmp, (u8 __user *)arg);
414
		else
415
			retval = get_user(tmp, (u32 __user *)arg);
Andrea Paterniani's avatar
Andrea Paterniani committed
416
		if (retval == 0) {
417
			struct spi_controller *ctlr = spi->controller;
418
			u32	save = spi->mode;
Andrea Paterniani's avatar
Andrea Paterniani committed
419 420 421 422 423 424

			if (tmp & ~SPI_MODE_MASK) {
				retval = -EINVAL;
				break;
			}

425 426 427 428
			if (ctlr->use_gpio_descriptors && ctlr->cs_gpiods &&
			    ctlr->cs_gpiods[spi->chip_select])
				tmp |= SPI_CS_HIGH;

Andrea Paterniani's avatar
Andrea Paterniani committed
429
			tmp |= spi->mode & ~SPI_MODE_MASK;
430
			spi->mode = tmp & SPI_MODE_USER_MASK;
Andrea Paterniani's avatar
Andrea Paterniani committed
431 432 433 434
			retval = spi_setup(spi);
			if (retval < 0)
				spi->mode = save;
			else
435
				dev_dbg(&spi->dev, "spi mode %x\n", tmp);
Andrea Paterniani's avatar
Andrea Paterniani committed
436 437 438
		}
		break;
	case SPI_IOC_WR_LSB_FIRST:
439
		retval = get_user(tmp, (__u8 __user *)arg);
Andrea Paterniani's avatar
Andrea Paterniani committed
440
		if (retval == 0) {
441
			u32	save = spi->mode;
Andrea Paterniani's avatar
Andrea Paterniani committed
442 443 444 445 446 447 448 449 450 451 452 453 454 455

			if (tmp)
				spi->mode |= SPI_LSB_FIRST;
			else
				spi->mode &= ~SPI_LSB_FIRST;
			retval = spi_setup(spi);
			if (retval < 0)
				spi->mode = save;
			else
				dev_dbg(&spi->dev, "%csb first\n",
						tmp ? 'l' : 'm');
		}
		break;
	case SPI_IOC_WR_BITS_PER_WORD:
456
		retval = get_user(tmp, (__u8 __user *)arg);
Andrea Paterniani's avatar
Andrea Paterniani committed
457 458 459 460 461 462 463 464 465 466 467
		if (retval == 0) {
			u8	save = spi->bits_per_word;

			spi->bits_per_word = tmp;
			retval = spi_setup(spi);
			if (retval < 0)
				spi->bits_per_word = save;
			else
				dev_dbg(&spi->dev, "%d bits per word\n", tmp);
		}
		break;
468 469 470
	case SPI_IOC_WR_MAX_SPEED_HZ: {
		u32 save;

471
		retval = get_user(tmp, (__u32 __user *)arg);
472 473 474 475 476 477
		if (retval)
			break;
		if (tmp == 0) {
			retval = -EINVAL;
			break;
		}
Andrea Paterniani's avatar
Andrea Paterniani committed
478

479 480 481 482 483 484 485
		save = spi->max_speed_hz;

		spi->max_speed_hz = tmp;
		retval = spi_setup(spi);
		if (retval == 0) {
			spidev->speed_hz = tmp;
			dev_dbg(&spi->dev, "%d Hz (max)\n", spidev->speed_hz);
Andrea Paterniani's avatar
Andrea Paterniani committed
486 487
		}

488 489 490
		spi->max_speed_hz = save;
		break;
	}
Andrea Paterniani's avatar
Andrea Paterniani committed
491 492
	default:
		/* segmented and/or full-duplex I/O request */
493 494 495 496 497
		/* Check message and copy into scratch area */
		ioc = spidev_get_ioc_message(cmd,
				(struct spi_ioc_transfer __user *)arg, &n_ioc);
		if (IS_ERR(ioc)) {
			retval = PTR_ERR(ioc);
Andrea Paterniani's avatar
Andrea Paterniani committed
498 499
			break;
		}
500 501
		if (!ioc)
			break;	/* n_ioc is also 0 */
Andrea Paterniani's avatar
Andrea Paterniani committed
502 503 504 505 506 507

		/* translate to spi_message, execute */
		retval = spidev_message(spidev, ioc, n_ioc);
		kfree(ioc);
		break;
	}
Alan Cox's avatar
Alan Cox committed
508 509

	mutex_unlock(&spidev->buf_lock);
510
	spi_dev_put(spi);
511
	mutex_unlock(&spidev->spi_lock);
Andrea Paterniani's avatar
Andrea Paterniani committed
512 513 514
	return retval;
}

515
#ifdef CONFIG_COMPAT
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
static long
spidev_compat_ioc_message(struct file *filp, unsigned int cmd,
		unsigned long arg)
{
	struct spi_ioc_transfer __user	*u_ioc;
	int				retval = 0;
	struct spidev_data		*spidev;
	struct spi_device		*spi;
	unsigned			n_ioc, n;
	struct spi_ioc_transfer		*ioc;

	u_ioc = (struct spi_ioc_transfer __user *) compat_ptr(arg);

	/* guard against device removal before, or while,
	 * we issue this ioctl.
	 */
	spidev = filp->private_data;
533
	mutex_lock(&spidev->spi_lock);
534
	spi = spi_dev_get(spidev->spi);
535 536
	if (spi == NULL) {
		mutex_unlock(&spidev->spi_lock);
537
		return -ESHUTDOWN;
538
	}
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564

	/* SPI_IOC_MESSAGE needs the buffer locked "normally" */
	mutex_lock(&spidev->buf_lock);

	/* Check message and copy into scratch area */
	ioc = spidev_get_ioc_message(cmd, u_ioc, &n_ioc);
	if (IS_ERR(ioc)) {
		retval = PTR_ERR(ioc);
		goto done;
	}
	if (!ioc)
		goto done;	/* n_ioc is also 0 */

	/* Convert buffer pointers */
	for (n = 0; n < n_ioc; n++) {
		ioc[n].rx_buf = (uintptr_t) compat_ptr(ioc[n].rx_buf);
		ioc[n].tx_buf = (uintptr_t) compat_ptr(ioc[n].tx_buf);
	}

	/* translate to spi_message, execute */
	retval = spidev_message(spidev, ioc, n_ioc);
	kfree(ioc);

done:
	mutex_unlock(&spidev->buf_lock);
	spi_dev_put(spi);
565
	mutex_unlock(&spidev->spi_lock);
566 567 568
	return retval;
}

569 570 571
static long
spidev_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
572 573 574 575 576
	if (_IOC_TYPE(cmd) == SPI_IOC_MAGIC
			&& _IOC_NR(cmd) == _IOC_NR(SPI_IOC_MESSAGE(0))
			&& _IOC_DIR(cmd) == _IOC_WRITE)
		return spidev_compat_ioc_message(filp, cmd, arg);

577 578 579 580 581 582
	return spidev_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
}
#else
#define spidev_compat_ioctl NULL
#endif /* CONFIG_COMPAT */

Andrea Paterniani's avatar
Andrea Paterniani committed
583 584
static int spidev_open(struct inode *inode, struct file *filp)
{
585
	struct spidev_data	*spidev = NULL, *iter;
Andrea Paterniani's avatar
Andrea Paterniani committed
586 587 588 589
	int			status = -ENXIO;

	mutex_lock(&device_list_lock);

590 591
	list_for_each_entry(iter, &device_list, device_entry) {
		if (iter->devt == inode->i_rdev) {
Andrea Paterniani's avatar
Andrea Paterniani committed
592
			status = 0;
593
			spidev = iter;
Andrea Paterniani's avatar
Andrea Paterniani committed
594 595 596
			break;
		}
	}
597

598
	if (!spidev) {
599 600 601 602 603 604 605
		pr_debug("spidev: nothing for minor %d\n", iminor(inode));
		goto err_find_dev;
	}

	if (!spidev->tx_buffer) {
		spidev->tx_buffer = kmalloc(bufsiz, GFP_KERNEL);
		if (!spidev->tx_buffer) {
606
			status = -ENOMEM;
607
			goto err_find_dev;
Andrea Paterniani's avatar
Andrea Paterniani committed
608
		}
609
	}
610 611 612 613 614 615

	if (!spidev->rx_buffer) {
		spidev->rx_buffer = kmalloc(bufsiz, GFP_KERNEL);
		if (!spidev->rx_buffer) {
			status = -ENOMEM;
			goto err_alloc_rx_buf;
Andrea Paterniani's avatar
Andrea Paterniani committed
616
		}
617 618 619 620
	}

	spidev->users++;
	filp->private_data = spidev;
621
	stream_open(inode, filp);
Andrea Paterniani's avatar
Andrea Paterniani committed
622

623 624 625 626 627 628 629
	mutex_unlock(&device_list_lock);
	return 0;

err_alloc_rx_buf:
	kfree(spidev->tx_buffer);
	spidev->tx_buffer = NULL;
err_find_dev:
Andrea Paterniani's avatar
Andrea Paterniani committed
630 631 632 633 634 635 636
	mutex_unlock(&device_list_lock);
	return status;
}

static int spidev_release(struct inode *inode, struct file *filp)
{
	struct spidev_data	*spidev;
637
	int			dofree;
Andrea Paterniani's avatar
Andrea Paterniani committed
638 639 640 641

	mutex_lock(&device_list_lock);
	spidev = filp->private_data;
	filp->private_data = NULL;
642

643
	mutex_lock(&spidev->spi_lock);
644 645
	/* ... after we unbound from the underlying device? */
	dofree = (spidev->spi == NULL);
646
	mutex_unlock(&spidev->spi_lock);
647

648
	/* last close? */
Andrea Paterniani's avatar
Andrea Paterniani committed
649 650
	spidev->users--;
	if (!spidev->users) {
651

652 653 654 655 656
		kfree(spidev->tx_buffer);
		spidev->tx_buffer = NULL;

		kfree(spidev->rx_buffer);
		spidev->rx_buffer = NULL;
657 658 659

		if (dofree)
			kfree(spidev);
660 661
		else
			spidev->speed_hz = spidev->spi->max_speed_hz;
Andrea Paterniani's avatar
Andrea Paterniani committed
662
	}
663
#ifdef CONFIG_SPI_SLAVE
664 665
	if (!dofree)
		spi_slave_abort(spidev->spi);
666
#endif
Andrea Paterniani's avatar
Andrea Paterniani committed
667 668
	mutex_unlock(&device_list_lock);

669
	return 0;
Andrea Paterniani's avatar
Andrea Paterniani committed
670 671
}

672
static const struct file_operations spidev_fops = {
Andrea Paterniani's avatar
Andrea Paterniani committed
673 674 675 676 677 678 679
	.owner =	THIS_MODULE,
	/* REVISIT switch to aio primitives, so that userspace
	 * gets more complete API coverage.  It'll simplify things
	 * too, except for the locking.
	 */
	.write =	spidev_write,
	.read =		spidev_read,
Alan Cox's avatar
Alan Cox committed
680
	.unlocked_ioctl = spidev_ioctl,
681
	.compat_ioctl = spidev_compat_ioctl,
Andrea Paterniani's avatar
Andrea Paterniani committed
682 683
	.open =		spidev_open,
	.release =	spidev_release,
684
	.llseek =	no_llseek,
Andrea Paterniani's avatar
Andrea Paterniani committed
685 686 687 688 689 690 691 692 693
};

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

/* The main reason to have this class is to make mdev/udev create the
 * /dev/spidevB.C character device nodes exposing our userspace API.
 * It also simplifies memory management.
 */

694
static struct class *spidev_class;
Andrea Paterniani's avatar
Andrea Paterniani committed
695

Mark Brown's avatar
Mark Brown committed
696 697 698 699 700 701 702 703 704 705 706 707 708
static const struct spi_device_id spidev_spi_ids[] = {
	{ .name = "dh2228fv" },
	{ .name = "ltc2488" },
	{ .name = "sx1301" },
	{ .name = "bk4" },
	{ .name = "dhcom-board" },
	{ .name = "m53cpld" },
	{ .name = "spi-petra" },
	{ .name = "spi-authenta" },
	{},
};
MODULE_DEVICE_TABLE(spi, spidev_spi_ids);

709 710 711 712 713 714 715 716 717 718 719 720 721
/*
 * spidev should never be referenced in DT without a specific compatible string,
 * it is a Linux implementation thing rather than a description of the hardware.
 */
static int spidev_of_check(struct device *dev)
{
	if (device_property_match_string(dev, "compatible", "spidev") < 0)
		return 0;

	dev_err(dev, "spidev listed directly in DT is not supported\n");
	return -EINVAL;
}

722
static const struct of_device_id spidev_dt_ids[] = {
723 724 725 726 727 728 729 730
	{ .compatible = "rohm,dh2228fv", .data = &spidev_of_check },
	{ .compatible = "lineartechnology,ltc2488", .data = &spidev_of_check },
	{ .compatible = "semtech,sx1301", .data = &spidev_of_check },
	{ .compatible = "lwn,bk4", .data = &spidev_of_check },
	{ .compatible = "dh,dhcom-board", .data = &spidev_of_check },
	{ .compatible = "menlo,m53cpld", .data = &spidev_of_check },
	{ .compatible = "cisco,spi-petra", .data = &spidev_of_check },
	{ .compatible = "micron,spi-authenta", .data = &spidev_of_check },
731 732 733 734
	{},
};
MODULE_DEVICE_TABLE(of, spidev_dt_ids);

735
/* Dummy SPI devices not to be used in production systems */
736 737 738 739 740
static int spidev_acpi_check(struct device *dev)
{
	dev_warn(dev, "do not use this driver in production systems!\n");
	return 0;
}
741 742 743 744 745 746 747 748

static const struct acpi_device_id spidev_acpi_ids[] = {
	/*
	 * The ACPI SPT000* devices are only meant for development and
	 * testing. Systems used in production should have a proper ACPI
	 * description of the connected peripheral and they should also use
	 * a proper driver instead of poking directly to the SPI bus.
	 */
749 750 751
	{ "SPT0001", (kernel_ulong_t)&spidev_acpi_check },
	{ "SPT0002", (kernel_ulong_t)&spidev_acpi_check },
	{ "SPT0003", (kernel_ulong_t)&spidev_acpi_check },
752 753 754 755
	{},
};
MODULE_DEVICE_TABLE(acpi, spidev_acpi_ids);

Andrea Paterniani's avatar
Andrea Paterniani committed
756 757
/*-------------------------------------------------------------------------*/

758
static int spidev_probe(struct spi_device *spi)
Andrea Paterniani's avatar
Andrea Paterniani committed
759
{
760
	int (*match)(struct device *dev);
Andrea Paterniani's avatar
Andrea Paterniani committed
761 762 763 764
	struct spidev_data	*spidev;
	int			status;
	unsigned long		minor;

765 766 767 768 769 770
	match = device_get_match_data(&spi->dev);
	if (match) {
		status = match(&spi->dev);
		if (status)
			return status;
	}
771

Andrea Paterniani's avatar
Andrea Paterniani committed
772 773 774 775 776 777 778
	/* Allocate driver data */
	spidev = kzalloc(sizeof(*spidev), GFP_KERNEL);
	if (!spidev)
		return -ENOMEM;

	/* Initialize the driver data */
	spidev->spi = spi;
779
	mutex_init(&spidev->spi_lock);
Andrea Paterniani's avatar
Andrea Paterniani committed
780 781 782 783 784 785 786 787
	mutex_init(&spidev->buf_lock);

	INIT_LIST_HEAD(&spidev->device_entry);

	/* If we can allocate a minor number, hook up this device.
	 * Reusing minors is fine so long as udev or mdev is working.
	 */
	mutex_lock(&device_list_lock);
788
	minor = find_first_zero_bit(minors, N_SPI_MINORS);
Andrea Paterniani's avatar
Andrea Paterniani committed
789
	if (minor < N_SPI_MINORS) {
790 791 792
		struct device *dev;

		spidev->devt = MKDEV(SPIDEV_MAJOR, minor);
793 794 795
		dev = device_create(spidev_class, &spi->dev, spidev->devt,
				    spidev, "spidev%d.%d",
				    spi->master->bus_num, spi->chip_select);
796
		status = PTR_ERR_OR_ZERO(dev);
Andrea Paterniani's avatar
Andrea Paterniani committed
797 798 799 800 801 802 803 804 805 806
	} else {
		dev_dbg(&spi->dev, "no minor number available!\n");
		status = -ENODEV;
	}
	if (status == 0) {
		set_bit(minor, minors);
		list_add(&spidev->device_entry, &device_list);
	}
	mutex_unlock(&device_list_lock);

807 808
	spidev->speed_hz = spi->max_speed_hz;

809 810 811
	if (status == 0)
		spi_set_drvdata(spi, spidev);
	else
Andrea Paterniani's avatar
Andrea Paterniani committed
812 813 814 815 816
		kfree(spidev);

	return status;
}

817
static void spidev_remove(struct spi_device *spi)
Andrea Paterniani's avatar
Andrea Paterniani committed
818
{
819
	struct spidev_data	*spidev = spi_get_drvdata(spi);
Andrea Paterniani's avatar
Andrea Paterniani committed
820

821 822
	/* prevent new opens */
	mutex_lock(&device_list_lock);
823
	/* make sure ops on existing fds can abort cleanly */
824
	mutex_lock(&spidev->spi_lock);
825
	spidev->spi = NULL;
826
	mutex_unlock(&spidev->spi_lock);
Andrea Paterniani's avatar
Andrea Paterniani committed
827 828

	list_del(&spidev->device_entry);
829 830 831 832
	device_destroy(spidev_class, spidev->devt);
	clear_bit(MINOR(spidev->devt), minors);
	if (spidev->users == 0)
		kfree(spidev);
Andrea Paterniani's avatar
Andrea Paterniani committed
833 834 835
	mutex_unlock(&device_list_lock);
}

836
static struct spi_driver spidev_spi_driver = {
Andrea Paterniani's avatar
Andrea Paterniani committed
837 838
	.driver = {
		.name =		"spidev",
839
		.of_match_table = spidev_dt_ids,
840
		.acpi_match_table = spidev_acpi_ids,
Andrea Paterniani's avatar
Andrea Paterniani committed
841 842
	},
	.probe =	spidev_probe,
843
	.remove =	spidev_remove,
Mark Brown's avatar
Mark Brown committed
844
	.id_table =	spidev_spi_ids,
Andrea Paterniani's avatar
Andrea Paterniani committed
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866

	/* NOTE:  suspend/resume methods are not necessary here.
	 * We don't do anything except pass the requests to/from
	 * the underlying controller.  The refrigerator handles
	 * most issues; the controller driver handles the rest.
	 */
};

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

static int __init spidev_init(void)
{
	int status;

	/* Claim our 256 reserved device numbers.  Then register a class
	 * that will key udev/mdev to add/remove /dev nodes.  Last, register
	 * the driver which manages those device numbers.
	 */
	status = register_chrdev(SPIDEV_MAJOR, "spi", &spidev_fops);
	if (status < 0)
		return status;

867 868
	spidev_class = class_create(THIS_MODULE, "spidev");
	if (IS_ERR(spidev_class)) {
869
		unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
870
		return PTR_ERR(spidev_class);
Andrea Paterniani's avatar
Andrea Paterniani committed
871 872
	}

873
	status = spi_register_driver(&spidev_spi_driver);
Andrea Paterniani's avatar
Andrea Paterniani committed
874
	if (status < 0) {
875
		class_destroy(spidev_class);
876
		unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
Andrea Paterniani's avatar
Andrea Paterniani committed
877 878 879 880 881 882 883
	}
	return status;
}
module_init(spidev_init);

static void __exit spidev_exit(void)
{
884
	spi_unregister_driver(&spidev_spi_driver);
885
	class_destroy(spidev_class);
886
	unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
Andrea Paterniani's avatar
Andrea Paterniani committed
887 888 889 890 891 892
}
module_exit(spidev_exit);

MODULE_AUTHOR("Andrea Paterniani, <a.paterniani@swapp-eng.it>");
MODULE_DESCRIPTION("User mode SPI device interface");
MODULE_LICENSE("GPL");
893
MODULE_ALIAS("spi:spidev");