Linux Audio

Check our new training course

Loading...
v3.1
   1/*
   2 * SPI init/core code
   3 *
   4 * Copyright (C) 2005 David Brownell
   5 *
   6 * This program is free software; you can redistribute it and/or modify
   7 * it under the terms of the GNU General Public License as published by
   8 * the Free Software Foundation; either version 2 of the License, or
   9 * (at your option) any later version.
  10 *
  11 * This program is distributed in the hope that it will be useful,
  12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14 * GNU General Public License for more details.
  15 *
  16 * You should have received a copy of the GNU General Public License
  17 * along with this program; if not, write to the Free Software
  18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  19 */
  20
  21#include <linux/kernel.h>
  22#include <linux/device.h>
  23#include <linux/init.h>
  24#include <linux/cache.h>
 
 
  25#include <linux/mutex.h>
  26#include <linux/of_device.h>
 
 
  27#include <linux/slab.h>
  28#include <linux/mod_devicetable.h>
  29#include <linux/spi/spi.h>
  30#include <linux/of_spi.h>
 
 
  31#include <linux/pm_runtime.h>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  32
  33static void spidev_release(struct device *dev)
  34{
  35	struct spi_device	*spi = to_spi_device(dev);
  36
  37	/* spi masters may cleanup for released devices */
  38	if (spi->master->cleanup)
  39		spi->master->cleanup(spi);
  40
  41	spi_master_put(spi->master);
  42	kfree(spi);
  43}
  44
  45static ssize_t
  46modalias_show(struct device *dev, struct device_attribute *a, char *buf)
  47{
  48	const struct spi_device	*spi = to_spi_device(dev);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  49
  50	return sprintf(buf, "%s\n", spi->modalias);
  51}
  52
  53static struct device_attribute spi_dev_attrs[] = {
  54	__ATTR_RO(modalias),
  55	__ATTR_NULL,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  56};
  57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  58/* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
  59 * and the sysfs version makes coldplug work too.
  60 */
  61
  62static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
  63						const struct spi_device *sdev)
  64{
  65	while (id->name[0]) {
  66		if (!strcmp(sdev->modalias, id->name))
  67			return id;
  68		id++;
  69	}
  70	return NULL;
  71}
  72
  73const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
  74{
  75	const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
  76
  77	return spi_match_id(sdrv->id_table, sdev);
  78}
  79EXPORT_SYMBOL_GPL(spi_get_device_id);
  80
  81static int spi_match_device(struct device *dev, struct device_driver *drv)
  82{
  83	const struct spi_device	*spi = to_spi_device(dev);
  84	const struct spi_driver	*sdrv = to_spi_driver(drv);
  85
 
 
 
 
  86	/* Attempt an OF style match */
  87	if (of_driver_match_device(dev, drv))
  88		return 1;
  89
 
 
 
 
  90	if (sdrv->id_table)
  91		return !!spi_match_id(sdrv->id_table, spi);
  92
  93	return strcmp(spi->modalias, drv->name) == 0;
  94}
  95
  96static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
  97{
  98	const struct spi_device		*spi = to_spi_device(dev);
 
  99
 100	add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
 101	return 0;
 102}
 103
 104#ifdef CONFIG_PM_SLEEP
 105static int spi_legacy_suspend(struct device *dev, pm_message_t message)
 106{
 107	int			value = 0;
 108	struct spi_driver	*drv = to_spi_driver(dev->driver);
 109
 110	/* suspend will stop irqs and dma; no more i/o */
 111	if (drv) {
 112		if (drv->suspend)
 113			value = drv->suspend(to_spi_device(dev), message);
 114		else
 115			dev_dbg(dev, "... can't suspend\n");
 116	}
 117	return value;
 118}
 119
 120static int spi_legacy_resume(struct device *dev)
 121{
 122	int			value = 0;
 123	struct spi_driver	*drv = to_spi_driver(dev->driver);
 
 124
 125	/* resume may restart the i/o queue */
 126	if (drv) {
 127		if (drv->resume)
 128			value = drv->resume(to_spi_device(dev));
 129		else
 130			dev_dbg(dev, "... can't resume\n");
 
 
 
 
 131	}
 132	return value;
 133}
 134
 135static int spi_pm_suspend(struct device *dev)
 136{
 137	const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 138
 139	if (pm)
 140		return pm_generic_suspend(dev);
 141	else
 142		return spi_legacy_suspend(dev, PMSG_SUSPEND);
 143}
 144
 145static int spi_pm_resume(struct device *dev)
 146{
 147	const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 
 
 
 
 
 
 148
 149	if (pm)
 150		return pm_generic_resume(dev);
 151	else
 152		return spi_legacy_resume(dev);
 153}
 154
 155static int spi_pm_freeze(struct device *dev)
 156{
 157	const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 158
 159	if (pm)
 160		return pm_generic_freeze(dev);
 161	else
 162		return spi_legacy_suspend(dev, PMSG_FREEZE);
 163}
 164
 165static int spi_pm_thaw(struct device *dev)
 166{
 167	const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 168
 169	if (pm)
 170		return pm_generic_thaw(dev);
 171	else
 172		return spi_legacy_resume(dev);
 173}
 
 174
 175static int spi_pm_poweroff(struct device *dev)
 176{
 177	const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 178
 179	if (pm)
 180		return pm_generic_poweroff(dev);
 181	else
 182		return spi_legacy_suspend(dev, PMSG_HIBERNATE);
 183}
 184
 185static int spi_pm_restore(struct device *dev)
 186{
 187	const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
 
 188
 189	if (pm)
 190		return pm_generic_restore(dev);
 191	else
 192		return spi_legacy_resume(dev);
 193}
 194#else
 195#define spi_pm_suspend	NULL
 196#define spi_pm_resume	NULL
 197#define spi_pm_freeze	NULL
 198#define spi_pm_thaw	NULL
 199#define spi_pm_poweroff	NULL
 200#define spi_pm_restore	NULL
 201#endif
 202
 203static const struct dev_pm_ops spi_pm = {
 204	.suspend = spi_pm_suspend,
 205	.resume = spi_pm_resume,
 206	.freeze = spi_pm_freeze,
 207	.thaw = spi_pm_thaw,
 208	.poweroff = spi_pm_poweroff,
 209	.restore = spi_pm_restore,
 210	SET_RUNTIME_PM_OPS(
 211		pm_generic_runtime_suspend,
 212		pm_generic_runtime_resume,
 213		pm_generic_runtime_idle
 214	)
 215};
 216
 217struct bus_type spi_bus_type = {
 218	.name		= "spi",
 219	.dev_attrs	= spi_dev_attrs,
 220	.match		= spi_match_device,
 221	.uevent		= spi_uevent,
 222	.pm		= &spi_pm,
 
 
 223};
 224EXPORT_SYMBOL_GPL(spi_bus_type);
 225
 226
 227static int spi_drv_probe(struct device *dev)
 228{
 229	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
 230
 231	return sdrv->probe(to_spi_device(dev));
 232}
 233
 234static int spi_drv_remove(struct device *dev)
 235{
 236	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
 237
 238	return sdrv->remove(to_spi_device(dev));
 239}
 240
 241static void spi_drv_shutdown(struct device *dev)
 242{
 243	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
 244
 245	sdrv->shutdown(to_spi_device(dev));
 246}
 247
 248/**
 249 * spi_register_driver - register a SPI driver
 
 250 * @sdrv: the driver to register
 251 * Context: can sleep
 
 
 252 */
 253int spi_register_driver(struct spi_driver *sdrv)
 254{
 
 255	sdrv->driver.bus = &spi_bus_type;
 256	if (sdrv->probe)
 257		sdrv->driver.probe = spi_drv_probe;
 258	if (sdrv->remove)
 259		sdrv->driver.remove = spi_drv_remove;
 260	if (sdrv->shutdown)
 261		sdrv->driver.shutdown = spi_drv_shutdown;
 262	return driver_register(&sdrv->driver);
 263}
 264EXPORT_SYMBOL_GPL(spi_register_driver);
 265
 266/*-------------------------------------------------------------------------*/
 267
 268/* SPI devices should normally not be created by SPI device drivers; that
 269 * would make them board-specific.  Similarly with SPI master drivers.
 270 * Device registration normally goes into like arch/.../mach.../board-YYY.c
 271 * with other readonly (flashable) information about mainboard devices.
 272 */
 273
 274struct boardinfo {
 275	struct list_head	list;
 276	struct spi_board_info	board_info;
 277};
 278
 279static LIST_HEAD(board_list);
 280static LIST_HEAD(spi_master_list);
 281
 282/*
 283 * Used to protect add/del opertion for board_info list and
 284 * spi_master list, and their matching process
 
 285 */
 286static DEFINE_MUTEX(board_lock);
 287
 288/**
 289 * spi_alloc_device - Allocate a new SPI device
 290 * @master: Controller to which device is connected
 291 * Context: can sleep
 292 *
 293 * Allows a driver to allocate and initialize a spi_device without
 294 * registering it immediately.  This allows a driver to directly
 295 * fill the spi_device with device parameters before calling
 296 * spi_add_device() on it.
 297 *
 298 * Caller is responsible to call spi_add_device() on the returned
 299 * spi_device structure to add it to the SPI master.  If the caller
 300 * needs to discard the spi_device without adding it, then it should
 301 * call spi_dev_put() on it.
 302 *
 303 * Returns a pointer to the new device, or NULL.
 304 */
 305struct spi_device *spi_alloc_device(struct spi_master *master)
 306{
 307	struct spi_device	*spi;
 308	struct device		*dev = master->dev.parent;
 309
 310	if (!spi_master_get(master))
 311		return NULL;
 312
 313	spi = kzalloc(sizeof *spi, GFP_KERNEL);
 314	if (!spi) {
 315		dev_err(dev, "cannot alloc spi_device\n");
 316		spi_master_put(master);
 317		return NULL;
 318	}
 319
 320	spi->master = master;
 321	spi->dev.parent = dev;
 322	spi->dev.bus = &spi_bus_type;
 323	spi->dev.release = spidev_release;
 
 
 
 
 
 324	device_initialize(&spi->dev);
 325	return spi;
 326}
 327EXPORT_SYMBOL_GPL(spi_alloc_device);
 328
 329/**
 330 * spi_add_device - Add spi_device allocated with spi_alloc_device
 331 * @spi: spi_device to register
 332 *
 333 * Companion function to spi_alloc_device.  Devices allocated with
 334 * spi_alloc_device can be added onto the spi bus with this function.
 335 *
 336 * Returns 0 on success; negative errno on failure
 337 */
 338int spi_add_device(struct spi_device *spi)
 339{
 340	static DEFINE_MUTEX(spi_add_lock);
 341	struct device *dev = spi->master->dev.parent;
 342	struct device *d;
 343	int status;
 344
 345	/* Chipselects are numbered 0..max; validate. */
 346	if (spi->chip_select >= spi->master->num_chipselect) {
 347		dev_err(dev, "cs%d >= max %d\n",
 348			spi->chip_select,
 349			spi->master->num_chipselect);
 350		return -EINVAL;
 351	}
 352
 353	/* Set the bus ID string */
 354	dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->master->dev),
 355			spi->chip_select);
 356
 
 
 
 
 357
 358	/* We need to make sure there's no other device with this
 359	 * chipselect **BEFORE** we call setup(), else we'll trash
 360	 * its configuration.  Lock against concurrent add() calls.
 361	 */
 362	mutex_lock(&spi_add_lock);
 
 
 
 
 
 
 
 
 
 
 
 
 363
 364	d = bus_find_device_by_name(&spi_bus_type, NULL, dev_name(&spi->dev));
 365	if (d != NULL) {
 366		dev_err(dev, "chipselect %d already in use\n",
 367				spi->chip_select);
 368		put_device(d);
 369		status = -EBUSY;
 370		goto done;
 371	}
 372
 
 
 
 
 
 
 
 
 
 
 
 
 373	/* Drivers may modify this initial i/o setup, but will
 374	 * normally rely on the device being setup.  Devices
 375	 * using SPI_CS_HIGH can't coexist well otherwise...
 376	 */
 377	status = spi_setup(spi);
 378	if (status < 0) {
 379		dev_err(dev, "can't setup %s, status %d\n",
 380				dev_name(&spi->dev), status);
 381		goto done;
 382	}
 383
 384	/* Device may be bound to an active driver when this returns */
 385	status = device_add(&spi->dev);
 386	if (status < 0)
 387		dev_err(dev, "can't add %s, status %d\n",
 388				dev_name(&spi->dev), status);
 389	else
 
 390		dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
 
 391
 392done:
 393	mutex_unlock(&spi_add_lock);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 394	return status;
 395}
 396EXPORT_SYMBOL_GPL(spi_add_device);
 397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 398/**
 399 * spi_new_device - instantiate one new SPI device
 400 * @master: Controller to which device is connected
 401 * @chip: Describes the SPI device
 402 * Context: can sleep
 403 *
 404 * On typical mainboards, this is purely internal; and it's not needed
 405 * after board init creates the hard-wired devices.  Some development
 406 * platforms may not be able to use spi_register_board_info though, and
 407 * this is exported so that for example a USB or parport based adapter
 408 * driver could add devices (which it would learn about out-of-band).
 409 *
 410 * Returns the new device, or NULL.
 411 */
 412struct spi_device *spi_new_device(struct spi_master *master,
 413				  struct spi_board_info *chip)
 414{
 415	struct spi_device	*proxy;
 416	int			status;
 417
 418	/* NOTE:  caller did any chip->bus_num checks necessary.
 419	 *
 420	 * Also, unless we change the return value convention to use
 421	 * error-or-pointer (not NULL-or-pointer), troubleshootability
 422	 * suggests syslogged diagnostics are best here (ugh).
 423	 */
 424
 425	proxy = spi_alloc_device(master);
 426	if (!proxy)
 427		return NULL;
 428
 429	WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
 430
 431	proxy->chip_select = chip->chip_select;
 432	proxy->max_speed_hz = chip->max_speed_hz;
 433	proxy->mode = chip->mode;
 434	proxy->irq = chip->irq;
 435	strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
 436	proxy->dev.platform_data = (void *) chip->platform_data;
 437	proxy->controller_data = chip->controller_data;
 438	proxy->controller_state = NULL;
 439
 440	status = spi_add_device(proxy);
 441	if (status < 0) {
 442		spi_dev_put(proxy);
 443		return NULL;
 
 
 
 444	}
 445
 
 
 
 
 446	return proxy;
 
 
 
 
 
 447}
 448EXPORT_SYMBOL_GPL(spi_new_device);
 449
 450static void spi_match_master_to_boardinfo(struct spi_master *master,
 451				struct spi_board_info *bi)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 452{
 453	struct spi_device *dev;
 454
 455	if (master->bus_num != bi->bus_num)
 456		return;
 457
 458	dev = spi_new_device(master, bi);
 459	if (!dev)
 460		dev_err(master->dev.parent, "can't create new device for %s\n",
 461			bi->modalias);
 462}
 463
 464/**
 465 * spi_register_board_info - register SPI devices for a given board
 466 * @info: array of chip descriptors
 467 * @n: how many descriptors are provided
 468 * Context: can sleep
 469 *
 470 * Board-specific early init code calls this (probably during arch_initcall)
 471 * with segments of the SPI device table.  Any device nodes are created later,
 472 * after the relevant parent SPI controller (bus_num) is defined.  We keep
 473 * this table of devices forever, so that reloading a controller driver will
 474 * not make Linux forget about these hard-wired devices.
 475 *
 476 * Other code can also call this, e.g. a particular add-on board might provide
 477 * SPI devices through its expansion connector, so code initializing that board
 478 * would naturally declare its SPI devices.
 479 *
 480 * The board info passed can safely be __initdata ... but be careful of
 481 * any embedded pointers (platform_data, etc), they're copied as-is.
 
 
 482 */
 483int __init
 484spi_register_board_info(struct spi_board_info const *info, unsigned n)
 485{
 486	struct boardinfo *bi;
 487	int i;
 488
 489	bi = kzalloc(n * sizeof(*bi), GFP_KERNEL);
 
 
 
 490	if (!bi)
 491		return -ENOMEM;
 492
 493	for (i = 0; i < n; i++, bi++, info++) {
 494		struct spi_master *master;
 495
 496		memcpy(&bi->board_info, info, sizeof(*info));
 
 497		mutex_lock(&board_lock);
 498		list_add_tail(&bi->list, &board_list);
 499		list_for_each_entry(master, &spi_master_list, list)
 500			spi_match_master_to_boardinfo(master, &bi->board_info);
 
 501		mutex_unlock(&board_lock);
 502	}
 503
 504	return 0;
 505}
 506
 507/*-------------------------------------------------------------------------*/
 508
 509static void spi_master_release(struct device *dev)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 510{
 511	struct spi_master *master;
 
 
 
 512
 513	master = container_of(dev, struct spi_master, dev);
 514	kfree(master);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 515}
 516
 517static struct class spi_master_class = {
 518	.name		= "spi_master",
 519	.owner		= THIS_MODULE,
 520	.dev_release	= spi_master_release,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 521};
 522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 523
 524/**
 525 * spi_alloc_master - allocate SPI master controller
 526 * @dev: the controller, possibly using the platform_bus
 527 * @size: how much zeroed driver-private data to allocate; the pointer to this
 528 *	memory is in the driver_data field of the returned device,
 529 *	accessible with spi_master_get_devdata().
 
 
 
 
 530 * Context: can sleep
 531 *
 532 * This call is used only by SPI master controller drivers, which are the
 533 * only ones directly touching chip registers.  It's how they allocate
 534 * an spi_master structure, prior to calling spi_register_master().
 535 *
 536 * This must be called from context that can sleep.  It returns the SPI
 537 * master structure on success, else NULL.
 
 
 
 
 538 *
 539 * The caller is responsible for assigning the bus number and initializing
 540 * the master's methods before calling spi_register_master(); and (after errors
 541 * adding the device) calling spi_master_put() to prevent a memory leak.
 542 */
 543struct spi_master *spi_alloc_master(struct device *dev, unsigned size)
 
 544{
 545	struct spi_master	*master;
 
 546
 547	if (!dev)
 548		return NULL;
 549
 550	master = kzalloc(size + sizeof *master, GFP_KERNEL);
 551	if (!master)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 552		return NULL;
 553
 554	device_initialize(&master->dev);
 555	master->dev.class = &spi_master_class;
 556	master->dev.parent = get_device(dev);
 557	spi_master_set_devdata(master, &master[1]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 558
 559	return master;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 560}
 561EXPORT_SYMBOL_GPL(spi_alloc_master);
 562
 563/**
 564 * spi_register_master - register SPI master controller
 565 * @master: initialized master, originally from spi_alloc_master()
 
 566 * Context: can sleep
 567 *
 568 * SPI master controllers connect to their drivers using some non-SPI bus,
 569 * such as the platform bus.  The final stage of probe() in that code
 570 * includes calling spi_register_master() to hook up to this SPI bus glue.
 571 *
 572 * SPI controllers use board specific (often SOC specific) bus numbers,
 573 * and board-specific addressing for SPI devices combines those numbers
 574 * with chip select numbers.  Since SPI does not directly support dynamic
 575 * device identification, boards need configuration tables telling which
 576 * chip is at which address.
 577 *
 578 * This must be called from context that can sleep.  It returns zero on
 579 * success, else a negative error code (dropping the master's refcount).
 580 * After a successful return, the caller is responsible for calling
 581 * spi_unregister_master().
 
 
 582 */
 583int spi_register_master(struct spi_master *master)
 584{
 585	static atomic_t		dyn_bus_id = ATOMIC_INIT((1<<15) - 1);
 586	struct device		*dev = master->dev.parent;
 587	struct boardinfo	*bi;
 588	int			status = -ENODEV;
 589	int			dynamic = 0;
 590
 591	if (!dev)
 592		return -ENODEV;
 593
 594	/* even if it's just one always-selected device, there must
 595	 * be at least one chipselect
 
 596	 */
 597	if (master->num_chipselect == 0)
 598		return -EINVAL;
 
 599
 600	/* convention:  dynamically assigned bus IDs count down from the max */
 601	if (master->bus_num < 0) {
 602		/* FIXME switch to an IDR based scheme, something like
 603		 * I2C now uses, so we can't run out of "dynamic" IDs
 604		 */
 605		master->bus_num = atomic_dec_return(&dyn_bus_id);
 606		dynamic = 1;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 607	}
 
 
 
 
 
 
 608
 609	spin_lock_init(&master->bus_lock_spinlock);
 610	mutex_init(&master->bus_lock_mutex);
 611	master->bus_lock_flag = 0;
 
 
 
 
 
 
 
 
 
 612
 613	/* register the device, then userspace will see it.
 614	 * registration fails if the bus ID is in use.
 615	 */
 616	dev_set_name(&master->dev, "spi%u", master->bus_num);
 617	status = device_add(&master->dev);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 618	if (status < 0)
 619		goto done;
 620	dev_dbg(dev, "registered master %s%s\n", dev_name(&master->dev),
 621			dynamic ? " (dynamic)" : "");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 622
 623	mutex_lock(&board_lock);
 624	list_add_tail(&master->list, &spi_master_list);
 625	list_for_each_entry(bi, &board_list, list)
 626		spi_match_master_to_boardinfo(master, &bi->board_info);
 627	mutex_unlock(&board_lock);
 628
 629	status = 0;
 
 
 
 630
 631	/* Register devices from the device tree */
 632	of_register_spi_devices(master);
 633done:
 
 634	return status;
 635}
 636EXPORT_SYMBOL_GPL(spi_register_master);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 637
 
 
 
 638
 639static int __unregister(struct device *dev, void *null)
 640{
 641	spi_unregister_device(to_spi_device(dev));
 642	return 0;
 643}
 644
 645/**
 646 * spi_unregister_master - unregister SPI master controller
 647 * @master: the master being unregistered
 648 * Context: can sleep
 649 *
 650 * This call is used only by SPI master controller drivers, which are the
 651 * only ones directly touching chip registers.
 652 *
 653 * This must be called from context that can sleep.
 
 
 654 */
 655void spi_unregister_master(struct spi_master *master)
 656{
 657	int dummy;
 
 
 
 
 
 658
 
 
 
 659	mutex_lock(&board_lock);
 660	list_del(&master->list);
 
 
 
 
 
 
 
 661	mutex_unlock(&board_lock);
 662
 663	dummy = device_for_each_child(&master->dev, NULL, __unregister);
 664	device_unregister(&master->dev);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 665}
 666EXPORT_SYMBOL_GPL(spi_unregister_master);
 667
 668static int __spi_master_match(struct device *dev, void *data)
 669{
 670	struct spi_master *m;
 671	u16 *bus_num = data;
 
 
 
 
 
 
 
 672
 673	m = container_of(dev, struct spi_master, dev);
 674	return m->bus_num == *bus_num;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 675}
 676
 677/**
 678 * spi_busnum_to_master - look up master associated with bus_num
 679 * @bus_num: the master's bus number
 680 * Context: can sleep
 681 *
 682 * This call may be used with devices that are registered after
 683 * arch init time.  It returns a refcounted pointer to the relevant
 684 * spi_master (which the caller must release), or NULL if there is
 685 * no such master registered.
 
 
 686 */
 687struct spi_master *spi_busnum_to_master(u16 bus_num)
 688{
 689	struct device		*dev;
 690	struct spi_master	*master = NULL;
 691
 692	dev = class_find_device(&spi_master_class, NULL, &bus_num,
 693				__spi_master_match);
 694	if (dev)
 695		master = container_of(dev, struct spi_master, dev);
 696	/* reference got in class_find_device */
 697	return master;
 698}
 699EXPORT_SYMBOL_GPL(spi_busnum_to_master);
 700
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 701
 702/*-------------------------------------------------------------------------*/
 703
 704/* Core methods for SPI master protocol drivers.  Some of the
 705 * other core methods are currently defined as inline functions.
 706 */
 707
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 708/**
 709 * spi_setup - setup SPI mode and clock rate
 710 * @spi: the device whose settings are being modified
 711 * Context: can sleep, and no requests are queued to the device
 712 *
 713 * SPI protocol drivers may need to update the transfer mode if the
 714 * device doesn't work with its default.  They may likewise need
 715 * to update clock rates or word sizes from initial values.  This function
 716 * changes those settings, and must be called from a context that can sleep.
 717 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
 718 * effect the next time the device is selected and data is transferred to
 719 * or from it.  When this function returns, the spi device is deselected.
 720 *
 721 * Note that this call will fail if the protocol driver specifies an option
 722 * that the underlying controller or its driver does not support.  For
 723 * example, not all hardware supports wire transfers using nine bit words,
 724 * LSB-first wire encoding, or active-high chipselects.
 
 
 725 */
 726int spi_setup(struct spi_device *spi)
 727{
 728	unsigned	bad_bits;
 729	int		status;
 730
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 731	/* help drivers fail *cleanly* when they need options
 732	 * that aren't supported with their current master
 
 
 733	 */
 734	bad_bits = spi->mode & ~spi->master->mode_bits;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 735	if (bad_bits) {
 736		dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
 737			bad_bits);
 738		return -EINVAL;
 739	}
 740
 741	if (!spi->bits_per_word)
 742		spi->bits_per_word = 8;
 743
 744	status = spi->master->setup(spi);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 745
 746	dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s"
 747				"%u bits/w, %u Hz max --> %d\n",
 748			(int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 749			(spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
 750			(spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
 751			(spi->mode & SPI_3WIRE) ? "3wire, " : "",
 752			(spi->mode & SPI_LOOP) ? "loopback, " : "",
 753			spi->bits_per_word, spi->max_speed_hz,
 754			status);
 755
 756	return status;
 757}
 758EXPORT_SYMBOL_GPL(spi_setup);
 759
 760static int __spi_async(struct spi_device *spi, struct spi_message *message)
 
 761{
 762	struct spi_master *master = spi->master;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 763
 764	/* Half-duplex links include original MicroWire, and ones with
 765	 * only one data pin like SPI_3WIRE (switches direction) or where
 766	 * either MOSI or MISO is missing.  They can also be caused by
 767	 * software limitations.
 768	 */
 769	if ((master->flags & SPI_MASTER_HALF_DUPLEX)
 770			|| (spi->mode & SPI_3WIRE)) {
 771		struct spi_transfer *xfer;
 772		unsigned flags = master->flags;
 773
 774		list_for_each_entry(xfer, &message->transfers, transfer_list) {
 775			if (xfer->rx_buf && xfer->tx_buf)
 776				return -EINVAL;
 777			if ((flags & SPI_MASTER_NO_TX) && xfer->tx_buf)
 778				return -EINVAL;
 779			if ((flags & SPI_MASTER_NO_RX) && xfer->rx_buf)
 780				return -EINVAL;
 781		}
 782	}
 783
 784	message->spi = spi;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 785	message->status = -EINPROGRESS;
 786	return master->transfer(spi, message);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 787}
 788
 789/**
 790 * spi_async - asynchronous SPI transfer
 791 * @spi: device with which data will be exchanged
 792 * @message: describes the data transfers, including completion callback
 793 * Context: any (irqs may be blocked, etc)
 794 *
 795 * This call may be used in_irq and other contexts which can't sleep,
 796 * as well as from task contexts which can sleep.
 797 *
 798 * The completion callback is invoked in a context which can't sleep.
 799 * Before that invocation, the value of message->status is undefined.
 800 * When the callback is issued, message->status holds either zero (to
 801 * indicate complete success) or a negative error code.  After that
 802 * callback returns, the driver which issued the transfer request may
 803 * deallocate the associated memory; it's no longer in use by any SPI
 804 * core or controller driver code.
 805 *
 806 * Note that although all messages to a spi_device are handled in
 807 * FIFO order, messages may go to different devices in other orders.
 808 * Some device might be higher priority, or have various "hard" access
 809 * time requirements, for example.
 810 *
 811 * On detection of any fault during the transfer, processing of
 812 * the entire message is aborted, and the device is deselected.
 813 * Until returning from the associated message completion callback,
 814 * no other spi_message queued to that device will be processed.
 815 * (This rule applies equally to all the synchronous transfer calls,
 816 * which are wrappers around this core asynchronous primitive.)
 
 
 817 */
 818int spi_async(struct spi_device *spi, struct spi_message *message)
 819{
 820	struct spi_master *master = spi->master;
 821	int ret;
 822	unsigned long flags;
 823
 824	spin_lock_irqsave(&master->bus_lock_spinlock, flags);
 
 
 825
 826	if (master->bus_lock_flag)
 
 
 827		ret = -EBUSY;
 828	else
 829		ret = __spi_async(spi, message);
 830
 831	spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
 832
 833	return ret;
 834}
 835EXPORT_SYMBOL_GPL(spi_async);
 836
 837/**
 838 * spi_async_locked - version of spi_async with exclusive bus usage
 839 * @spi: device with which data will be exchanged
 840 * @message: describes the data transfers, including completion callback
 841 * Context: any (irqs may be blocked, etc)
 842 *
 843 * This call may be used in_irq and other contexts which can't sleep,
 844 * as well as from task contexts which can sleep.
 845 *
 846 * The completion callback is invoked in a context which can't sleep.
 847 * Before that invocation, the value of message->status is undefined.
 848 * When the callback is issued, message->status holds either zero (to
 849 * indicate complete success) or a negative error code.  After that
 850 * callback returns, the driver which issued the transfer request may
 851 * deallocate the associated memory; it's no longer in use by any SPI
 852 * core or controller driver code.
 853 *
 854 * Note that although all messages to a spi_device are handled in
 855 * FIFO order, messages may go to different devices in other orders.
 856 * Some device might be higher priority, or have various "hard" access
 857 * time requirements, for example.
 858 *
 859 * On detection of any fault during the transfer, processing of
 860 * the entire message is aborted, and the device is deselected.
 861 * Until returning from the associated message completion callback,
 862 * no other spi_message queued to that device will be processed.
 863 * (This rule applies equally to all the synchronous transfer calls,
 864 * which are wrappers around this core asynchronous primitive.)
 
 
 865 */
 866int spi_async_locked(struct spi_device *spi, struct spi_message *message)
 867{
 868	struct spi_master *master = spi->master;
 869	int ret;
 870	unsigned long flags;
 871
 872	spin_lock_irqsave(&master->bus_lock_spinlock, flags);
 
 
 
 
 873
 874	ret = __spi_async(spi, message);
 875
 876	spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
 877
 878	return ret;
 879
 880}
 881EXPORT_SYMBOL_GPL(spi_async_locked);
 882
 883
 884/*-------------------------------------------------------------------------*/
 885
 886/* Utility methods for SPI master protocol drivers, layered on
 887 * top of the core.  Some other utility methods are defined as
 888 * inline functions.
 889 */
 890
 891static void spi_complete(void *arg)
 892{
 893	complete(arg);
 894}
 895
 896static int __spi_sync(struct spi_device *spi, struct spi_message *message,
 897		      int bus_locked)
 898{
 899	DECLARE_COMPLETION_ONSTACK(done);
 900	int status;
 901	struct spi_master *master = spi->master;
 
 
 
 
 
 902
 903	message->complete = spi_complete;
 904	message->context = &done;
 
 905
 906	if (!bus_locked)
 907		mutex_lock(&master->bus_lock_mutex);
 908
 909	status = spi_async_locked(spi, message);
 
 
 
 
 
 
 
 
 910
 911	if (!bus_locked)
 912		mutex_unlock(&master->bus_lock_mutex);
 
 
 
 
 913
 914	if (status == 0) {
 
 
 
 
 
 
 
 
 
 
 
 915		wait_for_completion(&done);
 916		status = message->status;
 917	}
 918	message->context = NULL;
 919	return status;
 920}
 921
 922/**
 923 * spi_sync - blocking/synchronous SPI data transfers
 924 * @spi: device with which data will be exchanged
 925 * @message: describes the data transfers
 926 * Context: can sleep
 927 *
 928 * This call may only be used from a context that may sleep.  The sleep
 929 * is non-interruptible, and has no timeout.  Low-overhead controller
 930 * drivers may DMA directly into and out of the message buffers.
 931 *
 932 * Note that the SPI device's chip select is active during the message,
 933 * and then is normally disabled between messages.  Drivers for some
 934 * frequently-used devices may want to minimize costs of selecting a chip,
 935 * by leaving it selected in anticipation that the next message will go
 936 * to the same chip.  (That may increase power usage.)
 937 *
 938 * Also, the caller is guaranteeing that the memory associated with the
 939 * message will not be freed before this call returns.
 940 *
 941 * It returns zero on success, else a negative error code.
 942 */
 943int spi_sync(struct spi_device *spi, struct spi_message *message)
 944{
 945	return __spi_sync(spi, message, 0);
 
 
 
 
 
 
 946}
 947EXPORT_SYMBOL_GPL(spi_sync);
 948
 949/**
 950 * spi_sync_locked - version of spi_sync with exclusive bus usage
 951 * @spi: device with which data will be exchanged
 952 * @message: describes the data transfers
 953 * Context: can sleep
 954 *
 955 * This call may only be used from a context that may sleep.  The sleep
 956 * is non-interruptible, and has no timeout.  Low-overhead controller
 957 * drivers may DMA directly into and out of the message buffers.
 958 *
 959 * This call should be used by drivers that require exclusive access to the
 960 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
 961 * be released by a spi_bus_unlock call when the exclusive access is over.
 962 *
 963 * It returns zero on success, else a negative error code.
 964 */
 965int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
 966{
 967	return __spi_sync(spi, message, 1);
 968}
 969EXPORT_SYMBOL_GPL(spi_sync_locked);
 970
 971/**
 972 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
 973 * @master: SPI bus master that should be locked for exclusive bus access
 974 * Context: can sleep
 975 *
 976 * This call may only be used from a context that may sleep.  The sleep
 977 * is non-interruptible, and has no timeout.
 978 *
 979 * This call should be used by drivers that require exclusive access to the
 980 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
 981 * exclusive access is over. Data transfer must be done by spi_sync_locked
 982 * and spi_async_locked calls when the SPI bus lock is held.
 983 *
 984 * It returns zero on success, else a negative error code.
 985 */
 986int spi_bus_lock(struct spi_master *master)
 987{
 988	unsigned long flags;
 989
 990	mutex_lock(&master->bus_lock_mutex);
 991
 992	spin_lock_irqsave(&master->bus_lock_spinlock, flags);
 993	master->bus_lock_flag = 1;
 994	spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
 995
 996	/* mutex remains locked until spi_bus_unlock is called */
 997
 998	return 0;
 999}
1000EXPORT_SYMBOL_GPL(spi_bus_lock);
1001
1002/**
1003 * spi_bus_unlock - release the lock for exclusive SPI bus usage
1004 * @master: SPI bus master that was locked for exclusive bus access
1005 * Context: can sleep
1006 *
1007 * This call may only be used from a context that may sleep.  The sleep
1008 * is non-interruptible, and has no timeout.
1009 *
1010 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
1011 * call.
1012 *
1013 * It returns zero on success, else a negative error code.
1014 */
1015int spi_bus_unlock(struct spi_master *master)
1016{
1017	master->bus_lock_flag = 0;
1018
1019	mutex_unlock(&master->bus_lock_mutex);
1020
1021	return 0;
1022}
1023EXPORT_SYMBOL_GPL(spi_bus_unlock);
1024
1025/* portable code must never pass more than 32 bytes */
1026#define	SPI_BUFSIZ	max(32,SMP_CACHE_BYTES)
1027
1028static u8	*buf;
1029
1030/**
1031 * spi_write_then_read - SPI synchronous write followed by read
1032 * @spi: device with which data will be exchanged
1033 * @txbuf: data to be written (need not be dma-safe)
1034 * @n_tx: size of txbuf, in bytes
1035 * @rxbuf: buffer into which data will be read (need not be dma-safe)
1036 * @n_rx: size of rxbuf, in bytes
1037 * Context: can sleep
1038 *
1039 * This performs a half duplex MicroWire style transaction with the
1040 * device, sending txbuf and then reading rxbuf.  The return value
1041 * is zero for success, else a negative errno status code.
1042 * This call may only be used from a context that may sleep.
1043 *
1044 * Parameters to this routine are always copied using a small buffer;
1045 * portable code should never use this for more than 32 bytes.
1046 * Performance-sensitive or bulk transfer code should instead use
1047 * spi_{async,sync}() calls with dma-safe buffers.
 
 
1048 */
1049int spi_write_then_read(struct spi_device *spi,
1050		const void *txbuf, unsigned n_tx,
1051		void *rxbuf, unsigned n_rx)
1052{
1053	static DEFINE_MUTEX(lock);
1054
1055	int			status;
1056	struct spi_message	message;
1057	struct spi_transfer	x[2];
1058	u8			*local_buf;
1059
1060	/* Use preallocated DMA-safe buffer.  We can't avoid copying here,
1061	 * (as a pure convenience thing), but we can keep heap costs
1062	 * out of the hot path ...
 
1063	 */
1064	if ((n_tx + n_rx) > SPI_BUFSIZ)
1065		return -EINVAL;
 
 
 
 
 
 
1066
1067	spi_message_init(&message);
1068	memset(x, 0, sizeof x);
1069	if (n_tx) {
1070		x[0].len = n_tx;
1071		spi_message_add_tail(&x[0], &message);
1072	}
1073	if (n_rx) {
1074		x[1].len = n_rx;
1075		spi_message_add_tail(&x[1], &message);
1076	}
1077
1078	/* ... unless someone else is using the pre-allocated buffer */
1079	if (!mutex_trylock(&lock)) {
1080		local_buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
1081		if (!local_buf)
1082			return -ENOMEM;
1083	} else
1084		local_buf = buf;
1085
1086	memcpy(local_buf, txbuf, n_tx);
1087	x[0].tx_buf = local_buf;
1088	x[1].rx_buf = local_buf + n_tx;
1089
1090	/* do the i/o */
1091	status = spi_sync(spi, &message);
1092	if (status == 0)
1093		memcpy(rxbuf, x[1].rx_buf, n_rx);
1094
1095	if (x[0].tx_buf == buf)
1096		mutex_unlock(&lock);
1097	else
1098		kfree(local_buf);
1099
1100	return status;
1101}
1102EXPORT_SYMBOL_GPL(spi_write_then_read);
1103
1104/*-------------------------------------------------------------------------*/
1105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1106static int __init spi_init(void)
1107{
1108	int	status;
1109
1110	buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
1111	if (!buf) {
1112		status = -ENOMEM;
1113		goto err0;
1114	}
1115
1116	status = bus_register(&spi_bus_type);
1117	if (status < 0)
1118		goto err1;
1119
1120	status = class_register(&spi_master_class);
1121	if (status < 0)
1122		goto err2;
 
 
 
 
 
 
 
 
 
 
 
 
1123	return 0;
1124
 
 
1125err2:
1126	bus_unregister(&spi_bus_type);
1127err1:
1128	kfree(buf);
1129	buf = NULL;
1130err0:
1131	return status;
1132}
1133
1134/* board_info is normally registered in arch_initcall(),
1135 * but even essential drivers wait till later
1136 *
1137 * REVISIT only boardinfo really needs static linking. the rest (device and
1138 * driver registration) _could_ be dynamically linked (modular) ... costs
1139 * include needing to have boardinfo data structures be much more public.
1140 */
1141postcore_initcall(spi_init);
1142
v5.14.15
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2// SPI init/core code
   3//
   4// Copyright (C) 2005 David Brownell
   5// Copyright (C) 2008 Secret Lab Technologies Ltd.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
   6
   7#include <linux/kernel.h>
   8#include <linux/device.h>
   9#include <linux/init.h>
  10#include <linux/cache.h>
  11#include <linux/dma-mapping.h>
  12#include <linux/dmaengine.h>
  13#include <linux/mutex.h>
  14#include <linux/of_device.h>
  15#include <linux/of_irq.h>
  16#include <linux/clk/clk-conf.h>
  17#include <linux/slab.h>
  18#include <linux/mod_devicetable.h>
  19#include <linux/spi/spi.h>
  20#include <linux/spi/spi-mem.h>
  21#include <linux/of_gpio.h>
  22#include <linux/gpio/consumer.h>
  23#include <linux/pm_runtime.h>
  24#include <linux/pm_domain.h>
  25#include <linux/property.h>
  26#include <linux/export.h>
  27#include <linux/sched/rt.h>
  28#include <uapi/linux/sched/types.h>
  29#include <linux/delay.h>
  30#include <linux/kthread.h>
  31#include <linux/ioport.h>
  32#include <linux/acpi.h>
  33#include <linux/highmem.h>
  34#include <linux/idr.h>
  35#include <linux/platform_data/x86/apple.h>
  36
  37#define CREATE_TRACE_POINTS
  38#include <trace/events/spi.h>
  39EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
  40EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
  41
  42#include "internals.h"
  43
  44static DEFINE_IDR(spi_master_idr);
  45
  46static void spidev_release(struct device *dev)
  47{
  48	struct spi_device	*spi = to_spi_device(dev);
  49
  50	spi_controller_put(spi->controller);
  51	kfree(spi->driver_override);
 
 
 
  52	kfree(spi);
  53}
  54
  55static ssize_t
  56modalias_show(struct device *dev, struct device_attribute *a, char *buf)
  57{
  58	const struct spi_device	*spi = to_spi_device(dev);
  59	int len;
  60
  61	len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
  62	if (len != -ENODEV)
  63		return len;
  64
  65	return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
  66}
  67static DEVICE_ATTR_RO(modalias);
  68
  69static ssize_t driver_override_store(struct device *dev,
  70				     struct device_attribute *a,
  71				     const char *buf, size_t count)
  72{
  73	struct spi_device *spi = to_spi_device(dev);
  74	const char *end = memchr(buf, '\n', count);
  75	const size_t len = end ? end - buf : count;
  76	const char *driver_override, *old;
  77
  78	/* We need to keep extra room for a newline when displaying value */
  79	if (len >= (PAGE_SIZE - 1))
  80		return -EINVAL;
  81
  82	driver_override = kstrndup(buf, len, GFP_KERNEL);
  83	if (!driver_override)
  84		return -ENOMEM;
  85
  86	device_lock(dev);
  87	old = spi->driver_override;
  88	if (len) {
  89		spi->driver_override = driver_override;
  90	} else {
  91		/* Empty string, disable driver override */
  92		spi->driver_override = NULL;
  93		kfree(driver_override);
  94	}
  95	device_unlock(dev);
  96	kfree(old);
  97
  98	return count;
  99}
 100
 101static ssize_t driver_override_show(struct device *dev,
 102				    struct device_attribute *a, char *buf)
 103{
 104	const struct spi_device *spi = to_spi_device(dev);
 105	ssize_t len;
 106
 107	device_lock(dev);
 108	len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
 109	device_unlock(dev);
 110	return len;
 111}
 112static DEVICE_ATTR_RW(driver_override);
 113
 114#define SPI_STATISTICS_ATTRS(field, file)				\
 115static ssize_t spi_controller_##field##_show(struct device *dev,	\
 116					     struct device_attribute *attr, \
 117					     char *buf)			\
 118{									\
 119	struct spi_controller *ctlr = container_of(dev,			\
 120					 struct spi_controller, dev);	\
 121	return spi_statistics_##field##_show(&ctlr->statistics, buf);	\
 122}									\
 123static struct device_attribute dev_attr_spi_controller_##field = {	\
 124	.attr = { .name = file, .mode = 0444 },				\
 125	.show = spi_controller_##field##_show,				\
 126};									\
 127static ssize_t spi_device_##field##_show(struct device *dev,		\
 128					 struct device_attribute *attr,	\
 129					char *buf)			\
 130{									\
 131	struct spi_device *spi = to_spi_device(dev);			\
 132	return spi_statistics_##field##_show(&spi->statistics, buf);	\
 133}									\
 134static struct device_attribute dev_attr_spi_device_##field = {		\
 135	.attr = { .name = file, .mode = 0444 },				\
 136	.show = spi_device_##field##_show,				\
 137}
 138
 139#define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string)	\
 140static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
 141					    char *buf)			\
 142{									\
 143	unsigned long flags;						\
 144	ssize_t len;							\
 145	spin_lock_irqsave(&stat->lock, flags);				\
 146	len = sprintf(buf, format_string, stat->field);			\
 147	spin_unlock_irqrestore(&stat->lock, flags);			\
 148	return len;							\
 149}									\
 150SPI_STATISTICS_ATTRS(name, file)
 151
 152#define SPI_STATISTICS_SHOW(field, format_string)			\
 153	SPI_STATISTICS_SHOW_NAME(field, __stringify(field),		\
 154				 field, format_string)
 155
 156SPI_STATISTICS_SHOW(messages, "%lu");
 157SPI_STATISTICS_SHOW(transfers, "%lu");
 158SPI_STATISTICS_SHOW(errors, "%lu");
 159SPI_STATISTICS_SHOW(timedout, "%lu");
 160
 161SPI_STATISTICS_SHOW(spi_sync, "%lu");
 162SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
 163SPI_STATISTICS_SHOW(spi_async, "%lu");
 164
 165SPI_STATISTICS_SHOW(bytes, "%llu");
 166SPI_STATISTICS_SHOW(bytes_rx, "%llu");
 167SPI_STATISTICS_SHOW(bytes_tx, "%llu");
 168
 169#define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number)		\
 170	SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index,		\
 171				 "transfer_bytes_histo_" number,	\
 172				 transfer_bytes_histo[index],  "%lu")
 173SPI_STATISTICS_TRANSFER_BYTES_HISTO(0,  "0-1");
 174SPI_STATISTICS_TRANSFER_BYTES_HISTO(1,  "2-3");
 175SPI_STATISTICS_TRANSFER_BYTES_HISTO(2,  "4-7");
 176SPI_STATISTICS_TRANSFER_BYTES_HISTO(3,  "8-15");
 177SPI_STATISTICS_TRANSFER_BYTES_HISTO(4,  "16-31");
 178SPI_STATISTICS_TRANSFER_BYTES_HISTO(5,  "32-63");
 179SPI_STATISTICS_TRANSFER_BYTES_HISTO(6,  "64-127");
 180SPI_STATISTICS_TRANSFER_BYTES_HISTO(7,  "128-255");
 181SPI_STATISTICS_TRANSFER_BYTES_HISTO(8,  "256-511");
 182SPI_STATISTICS_TRANSFER_BYTES_HISTO(9,  "512-1023");
 183SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
 184SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
 185SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
 186SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
 187SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
 188SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
 189SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
 190
 191SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
 192
 193static struct attribute *spi_dev_attrs[] = {
 194	&dev_attr_modalias.attr,
 195	&dev_attr_driver_override.attr,
 196	NULL,
 197};
 198
 199static const struct attribute_group spi_dev_group = {
 200	.attrs  = spi_dev_attrs,
 201};
 202
 203static struct attribute *spi_device_statistics_attrs[] = {
 204	&dev_attr_spi_device_messages.attr,
 205	&dev_attr_spi_device_transfers.attr,
 206	&dev_attr_spi_device_errors.attr,
 207	&dev_attr_spi_device_timedout.attr,
 208	&dev_attr_spi_device_spi_sync.attr,
 209	&dev_attr_spi_device_spi_sync_immediate.attr,
 210	&dev_attr_spi_device_spi_async.attr,
 211	&dev_attr_spi_device_bytes.attr,
 212	&dev_attr_spi_device_bytes_rx.attr,
 213	&dev_attr_spi_device_bytes_tx.attr,
 214	&dev_attr_spi_device_transfer_bytes_histo0.attr,
 215	&dev_attr_spi_device_transfer_bytes_histo1.attr,
 216	&dev_attr_spi_device_transfer_bytes_histo2.attr,
 217	&dev_attr_spi_device_transfer_bytes_histo3.attr,
 218	&dev_attr_spi_device_transfer_bytes_histo4.attr,
 219	&dev_attr_spi_device_transfer_bytes_histo5.attr,
 220	&dev_attr_spi_device_transfer_bytes_histo6.attr,
 221	&dev_attr_spi_device_transfer_bytes_histo7.attr,
 222	&dev_attr_spi_device_transfer_bytes_histo8.attr,
 223	&dev_attr_spi_device_transfer_bytes_histo9.attr,
 224	&dev_attr_spi_device_transfer_bytes_histo10.attr,
 225	&dev_attr_spi_device_transfer_bytes_histo11.attr,
 226	&dev_attr_spi_device_transfer_bytes_histo12.attr,
 227	&dev_attr_spi_device_transfer_bytes_histo13.attr,
 228	&dev_attr_spi_device_transfer_bytes_histo14.attr,
 229	&dev_attr_spi_device_transfer_bytes_histo15.attr,
 230	&dev_attr_spi_device_transfer_bytes_histo16.attr,
 231	&dev_attr_spi_device_transfers_split_maxsize.attr,
 232	NULL,
 233};
 234
 235static const struct attribute_group spi_device_statistics_group = {
 236	.name  = "statistics",
 237	.attrs  = spi_device_statistics_attrs,
 238};
 239
 240static const struct attribute_group *spi_dev_groups[] = {
 241	&spi_dev_group,
 242	&spi_device_statistics_group,
 243	NULL,
 244};
 245
 246static struct attribute *spi_controller_statistics_attrs[] = {
 247	&dev_attr_spi_controller_messages.attr,
 248	&dev_attr_spi_controller_transfers.attr,
 249	&dev_attr_spi_controller_errors.attr,
 250	&dev_attr_spi_controller_timedout.attr,
 251	&dev_attr_spi_controller_spi_sync.attr,
 252	&dev_attr_spi_controller_spi_sync_immediate.attr,
 253	&dev_attr_spi_controller_spi_async.attr,
 254	&dev_attr_spi_controller_bytes.attr,
 255	&dev_attr_spi_controller_bytes_rx.attr,
 256	&dev_attr_spi_controller_bytes_tx.attr,
 257	&dev_attr_spi_controller_transfer_bytes_histo0.attr,
 258	&dev_attr_spi_controller_transfer_bytes_histo1.attr,
 259	&dev_attr_spi_controller_transfer_bytes_histo2.attr,
 260	&dev_attr_spi_controller_transfer_bytes_histo3.attr,
 261	&dev_attr_spi_controller_transfer_bytes_histo4.attr,
 262	&dev_attr_spi_controller_transfer_bytes_histo5.attr,
 263	&dev_attr_spi_controller_transfer_bytes_histo6.attr,
 264	&dev_attr_spi_controller_transfer_bytes_histo7.attr,
 265	&dev_attr_spi_controller_transfer_bytes_histo8.attr,
 266	&dev_attr_spi_controller_transfer_bytes_histo9.attr,
 267	&dev_attr_spi_controller_transfer_bytes_histo10.attr,
 268	&dev_attr_spi_controller_transfer_bytes_histo11.attr,
 269	&dev_attr_spi_controller_transfer_bytes_histo12.attr,
 270	&dev_attr_spi_controller_transfer_bytes_histo13.attr,
 271	&dev_attr_spi_controller_transfer_bytes_histo14.attr,
 272	&dev_attr_spi_controller_transfer_bytes_histo15.attr,
 273	&dev_attr_spi_controller_transfer_bytes_histo16.attr,
 274	&dev_attr_spi_controller_transfers_split_maxsize.attr,
 275	NULL,
 276};
 277
 278static const struct attribute_group spi_controller_statistics_group = {
 279	.name  = "statistics",
 280	.attrs  = spi_controller_statistics_attrs,
 281};
 282
 283static const struct attribute_group *spi_master_groups[] = {
 284	&spi_controller_statistics_group,
 285	NULL,
 286};
 287
 288void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
 289				       struct spi_transfer *xfer,
 290				       struct spi_controller *ctlr)
 291{
 292	unsigned long flags;
 293	int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
 294
 295	if (l2len < 0)
 296		l2len = 0;
 297
 298	spin_lock_irqsave(&stats->lock, flags);
 299
 300	stats->transfers++;
 301	stats->transfer_bytes_histo[l2len]++;
 302
 303	stats->bytes += xfer->len;
 304	if ((xfer->tx_buf) &&
 305	    (xfer->tx_buf != ctlr->dummy_tx))
 306		stats->bytes_tx += xfer->len;
 307	if ((xfer->rx_buf) &&
 308	    (xfer->rx_buf != ctlr->dummy_rx))
 309		stats->bytes_rx += xfer->len;
 310
 311	spin_unlock_irqrestore(&stats->lock, flags);
 312}
 313EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
 314
 315/* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
 316 * and the sysfs version makes coldplug work too.
 317 */
 318
 319static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
 320						const struct spi_device *sdev)
 321{
 322	while (id->name[0]) {
 323		if (!strcmp(sdev->modalias, id->name))
 324			return id;
 325		id++;
 326	}
 327	return NULL;
 328}
 329
 330const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
 331{
 332	const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
 333
 334	return spi_match_id(sdrv->id_table, sdev);
 335}
 336EXPORT_SYMBOL_GPL(spi_get_device_id);
 337
 338static int spi_match_device(struct device *dev, struct device_driver *drv)
 339{
 340	const struct spi_device	*spi = to_spi_device(dev);
 341	const struct spi_driver	*sdrv = to_spi_driver(drv);
 342
 343	/* Check override first, and if set, only use the named driver */
 344	if (spi->driver_override)
 345		return strcmp(spi->driver_override, drv->name) == 0;
 346
 347	/* Attempt an OF style match */
 348	if (of_driver_match_device(dev, drv))
 349		return 1;
 350
 351	/* Then try ACPI */
 352	if (acpi_driver_match_device(dev, drv))
 353		return 1;
 354
 355	if (sdrv->id_table)
 356		return !!spi_match_id(sdrv->id_table, spi);
 357
 358	return strcmp(spi->modalias, drv->name) == 0;
 359}
 360
 361static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
 362{
 363	const struct spi_device		*spi = to_spi_device(dev);
 364	int rc;
 365
 366	rc = acpi_device_uevent_modalias(dev, env);
 367	if (rc != -ENODEV)
 368		return rc;
 
 
 
 
 
 
 369
 370	return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
 
 
 
 
 
 
 
 371}
 372
 373static int spi_probe(struct device *dev)
 374{
 375	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
 376	struct spi_device		*spi = to_spi_device(dev);
 377	int ret;
 378
 379	ret = of_clk_set_defaults(dev->of_node, false);
 380	if (ret)
 381		return ret;
 382
 383	if (dev->of_node) {
 384		spi->irq = of_irq_get(dev->of_node, 0);
 385		if (spi->irq == -EPROBE_DEFER)
 386			return -EPROBE_DEFER;
 387		if (spi->irq < 0)
 388			spi->irq = 0;
 389	}
 
 
 
 
 
 
 
 
 
 
 
 
 390
 391	ret = dev_pm_domain_attach(dev, true);
 392	if (ret)
 393		return ret;
 394
 395	if (sdrv->probe) {
 396		ret = sdrv->probe(spi);
 397		if (ret)
 398			dev_pm_domain_detach(dev, true);
 399	}
 400
 401	return ret;
 
 
 
 402}
 403
 404static int spi_remove(struct device *dev)
 405{
 406	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
 
 
 
 
 
 
 407
 408	if (sdrv->remove) {
 409		int ret;
 
 410
 411		ret = sdrv->remove(to_spi_device(dev));
 412		if (ret)
 413			dev_warn(dev,
 414				 "Failed to unbind driver (%pe), ignoring\n",
 415				 ERR_PTR(ret));
 416	}
 417
 418	dev_pm_domain_detach(dev, true);
 
 
 419
 420	return 0;
 
 
 
 421}
 422
 423static void spi_shutdown(struct device *dev)
 424{
 425	if (dev->driver) {
 426		const struct spi_driver	*sdrv = to_spi_driver(dev->driver);
 427
 428		if (sdrv->shutdown)
 429			sdrv->shutdown(to_spi_device(dev));
 430	}
 
 431}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 432
 433struct bus_type spi_bus_type = {
 434	.name		= "spi",
 435	.dev_groups	= spi_dev_groups,
 436	.match		= spi_match_device,
 437	.uevent		= spi_uevent,
 438	.probe		= spi_probe,
 439	.remove		= spi_remove,
 440	.shutdown	= spi_shutdown,
 441};
 442EXPORT_SYMBOL_GPL(spi_bus_type);
 443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 444/**
 445 * __spi_register_driver - register a SPI driver
 446 * @owner: owner module of the driver to register
 447 * @sdrv: the driver to register
 448 * Context: can sleep
 449 *
 450 * Return: zero on success, else a negative error code.
 451 */
 452int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
 453{
 454	sdrv->driver.owner = owner;
 455	sdrv->driver.bus = &spi_bus_type;
 
 
 
 
 
 
 456	return driver_register(&sdrv->driver);
 457}
 458EXPORT_SYMBOL_GPL(__spi_register_driver);
 459
 460/*-------------------------------------------------------------------------*/
 461
 462/* SPI devices should normally not be created by SPI device drivers; that
 463 * would make them board-specific.  Similarly with SPI controller drivers.
 464 * Device registration normally goes into like arch/.../mach.../board-YYY.c
 465 * with other readonly (flashable) information about mainboard devices.
 466 */
 467
 468struct boardinfo {
 469	struct list_head	list;
 470	struct spi_board_info	board_info;
 471};
 472
 473static LIST_HEAD(board_list);
 474static LIST_HEAD(spi_controller_list);
 475
 476/*
 477 * Used to protect add/del operation for board_info list and
 478 * spi_controller list, and their matching process
 479 * also used to protect object of type struct idr
 480 */
 481static DEFINE_MUTEX(board_lock);
 482
 483/**
 484 * spi_alloc_device - Allocate a new SPI device
 485 * @ctlr: Controller to which device is connected
 486 * Context: can sleep
 487 *
 488 * Allows a driver to allocate and initialize a spi_device without
 489 * registering it immediately.  This allows a driver to directly
 490 * fill the spi_device with device parameters before calling
 491 * spi_add_device() on it.
 492 *
 493 * Caller is responsible to call spi_add_device() on the returned
 494 * spi_device structure to add it to the SPI controller.  If the caller
 495 * needs to discard the spi_device without adding it, then it should
 496 * call spi_dev_put() on it.
 497 *
 498 * Return: a pointer to the new device, or NULL.
 499 */
 500struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
 501{
 502	struct spi_device	*spi;
 
 503
 504	if (!spi_controller_get(ctlr))
 505		return NULL;
 506
 507	spi = kzalloc(sizeof(*spi), GFP_KERNEL);
 508	if (!spi) {
 509		spi_controller_put(ctlr);
 
 510		return NULL;
 511	}
 512
 513	spi->master = spi->controller = ctlr;
 514	spi->dev.parent = &ctlr->dev;
 515	spi->dev.bus = &spi_bus_type;
 516	spi->dev.release = spidev_release;
 517	spi->cs_gpio = -ENOENT;
 518	spi->mode = ctlr->buswidth_override_bits;
 519
 520	spin_lock_init(&spi->statistics.lock);
 521
 522	device_initialize(&spi->dev);
 523	return spi;
 524}
 525EXPORT_SYMBOL_GPL(spi_alloc_device);
 526
 527static void spi_dev_set_name(struct spi_device *spi)
 
 
 
 
 
 
 
 
 
 528{
 529	struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
 
 
 
 530
 531	if (adev) {
 532		dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
 533		return;
 
 
 
 534	}
 535
 536	dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
 537		     spi->chip_select);
 538}
 539
 540static int spi_dev_check(struct device *dev, void *data)
 541{
 542	struct spi_device *spi = to_spi_device(dev);
 543	struct spi_device *new_spi = data;
 544
 545	if (spi->controller == new_spi->controller &&
 546	    spi->chip_select == new_spi->chip_select)
 547		return -EBUSY;
 548	return 0;
 549}
 550
 551static void spi_cleanup(struct spi_device *spi)
 552{
 553	if (spi->controller->cleanup)
 554		spi->controller->cleanup(spi);
 555}
 556
 557static int __spi_add_device(struct spi_device *spi)
 558{
 559	struct spi_controller *ctlr = spi->controller;
 560	struct device *dev = ctlr->dev.parent;
 561	int status;
 562
 563	status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
 564	if (status) {
 565		dev_err(dev, "chipselect %d already in use\n",
 566				spi->chip_select);
 567		return status;
 
 
 568	}
 569
 570	/* Controller may unregister concurrently */
 571	if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
 572	    !device_is_registered(&ctlr->dev)) {
 573		return -ENODEV;
 574	}
 575
 576	/* Descriptors take precedence */
 577	if (ctlr->cs_gpiods)
 578		spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
 579	else if (ctlr->cs_gpios)
 580		spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
 581
 582	/* Drivers may modify this initial i/o setup, but will
 583	 * normally rely on the device being setup.  Devices
 584	 * using SPI_CS_HIGH can't coexist well otherwise...
 585	 */
 586	status = spi_setup(spi);
 587	if (status < 0) {
 588		dev_err(dev, "can't setup %s, status %d\n",
 589				dev_name(&spi->dev), status);
 590		return status;
 591	}
 592
 593	/* Device may be bound to an active driver when this returns */
 594	status = device_add(&spi->dev);
 595	if (status < 0) {
 596		dev_err(dev, "can't add %s, status %d\n",
 597				dev_name(&spi->dev), status);
 598		spi_cleanup(spi);
 599	} else {
 600		dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
 601	}
 602
 603	return status;
 604}
 605
 606/**
 607 * spi_add_device - Add spi_device allocated with spi_alloc_device
 608 * @spi: spi_device to register
 609 *
 610 * Companion function to spi_alloc_device.  Devices allocated with
 611 * spi_alloc_device can be added onto the spi bus with this function.
 612 *
 613 * Return: 0 on success; negative errno on failure
 614 */
 615int spi_add_device(struct spi_device *spi)
 616{
 617	struct spi_controller *ctlr = spi->controller;
 618	struct device *dev = ctlr->dev.parent;
 619	int status;
 620
 621	/* Chipselects are numbered 0..max; validate. */
 622	if (spi->chip_select >= ctlr->num_chipselect) {
 623		dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
 624			ctlr->num_chipselect);
 625		return -EINVAL;
 626	}
 627
 628	/* Set the bus ID string */
 629	spi_dev_set_name(spi);
 630
 631	/* We need to make sure there's no other device with this
 632	 * chipselect **BEFORE** we call setup(), else we'll trash
 633	 * its configuration.  Lock against concurrent add() calls.
 634	 */
 635	mutex_lock(&ctlr->add_lock);
 636	status = __spi_add_device(spi);
 637	mutex_unlock(&ctlr->add_lock);
 638	return status;
 639}
 640EXPORT_SYMBOL_GPL(spi_add_device);
 641
 642static int spi_add_device_locked(struct spi_device *spi)
 643{
 644	struct spi_controller *ctlr = spi->controller;
 645	struct device *dev = ctlr->dev.parent;
 646
 647	/* Chipselects are numbered 0..max; validate. */
 648	if (spi->chip_select >= ctlr->num_chipselect) {
 649		dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
 650			ctlr->num_chipselect);
 651		return -EINVAL;
 652	}
 653
 654	/* Set the bus ID string */
 655	spi_dev_set_name(spi);
 656
 657	WARN_ON(!mutex_is_locked(&ctlr->add_lock));
 658	return __spi_add_device(spi);
 659}
 660
 661/**
 662 * spi_new_device - instantiate one new SPI device
 663 * @ctlr: Controller to which device is connected
 664 * @chip: Describes the SPI device
 665 * Context: can sleep
 666 *
 667 * On typical mainboards, this is purely internal; and it's not needed
 668 * after board init creates the hard-wired devices.  Some development
 669 * platforms may not be able to use spi_register_board_info though, and
 670 * this is exported so that for example a USB or parport based adapter
 671 * driver could add devices (which it would learn about out-of-band).
 672 *
 673 * Return: the new device, or NULL.
 674 */
 675struct spi_device *spi_new_device(struct spi_controller *ctlr,
 676				  struct spi_board_info *chip)
 677{
 678	struct spi_device	*proxy;
 679	int			status;
 680
 681	/* NOTE:  caller did any chip->bus_num checks necessary.
 682	 *
 683	 * Also, unless we change the return value convention to use
 684	 * error-or-pointer (not NULL-or-pointer), troubleshootability
 685	 * suggests syslogged diagnostics are best here (ugh).
 686	 */
 687
 688	proxy = spi_alloc_device(ctlr);
 689	if (!proxy)
 690		return NULL;
 691
 692	WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
 693
 694	proxy->chip_select = chip->chip_select;
 695	proxy->max_speed_hz = chip->max_speed_hz;
 696	proxy->mode = chip->mode;
 697	proxy->irq = chip->irq;
 698	strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
 699	proxy->dev.platform_data = (void *) chip->platform_data;
 700	proxy->controller_data = chip->controller_data;
 701	proxy->controller_state = NULL;
 702
 703	if (chip->swnode) {
 704		status = device_add_software_node(&proxy->dev, chip->swnode);
 705		if (status) {
 706			dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
 707				chip->modalias, status);
 708			goto err_dev_put;
 709		}
 710	}
 711
 712	status = spi_add_device(proxy);
 713	if (status < 0)
 714		goto err_dev_put;
 715
 716	return proxy;
 717
 718err_dev_put:
 719	device_remove_software_node(&proxy->dev);
 720	spi_dev_put(proxy);
 721	return NULL;
 722}
 723EXPORT_SYMBOL_GPL(spi_new_device);
 724
 725/**
 726 * spi_unregister_device - unregister a single SPI device
 727 * @spi: spi_device to unregister
 728 *
 729 * Start making the passed SPI device vanish. Normally this would be handled
 730 * by spi_unregister_controller().
 731 */
 732void spi_unregister_device(struct spi_device *spi)
 733{
 734	if (!spi)
 735		return;
 736
 737	if (spi->dev.of_node) {
 738		of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
 739		of_node_put(spi->dev.of_node);
 740	}
 741	if (ACPI_COMPANION(&spi->dev))
 742		acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
 743	device_remove_software_node(&spi->dev);
 744	device_del(&spi->dev);
 745	spi_cleanup(spi);
 746	put_device(&spi->dev);
 747}
 748EXPORT_SYMBOL_GPL(spi_unregister_device);
 749
 750static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
 751					      struct spi_board_info *bi)
 752{
 753	struct spi_device *dev;
 754
 755	if (ctlr->bus_num != bi->bus_num)
 756		return;
 757
 758	dev = spi_new_device(ctlr, bi);
 759	if (!dev)
 760		dev_err(ctlr->dev.parent, "can't create new device for %s\n",
 761			bi->modalias);
 762}
 763
 764/**
 765 * spi_register_board_info - register SPI devices for a given board
 766 * @info: array of chip descriptors
 767 * @n: how many descriptors are provided
 768 * Context: can sleep
 769 *
 770 * Board-specific early init code calls this (probably during arch_initcall)
 771 * with segments of the SPI device table.  Any device nodes are created later,
 772 * after the relevant parent SPI controller (bus_num) is defined.  We keep
 773 * this table of devices forever, so that reloading a controller driver will
 774 * not make Linux forget about these hard-wired devices.
 775 *
 776 * Other code can also call this, e.g. a particular add-on board might provide
 777 * SPI devices through its expansion connector, so code initializing that board
 778 * would naturally declare its SPI devices.
 779 *
 780 * The board info passed can safely be __initdata ... but be careful of
 781 * any embedded pointers (platform_data, etc), they're copied as-is.
 782 *
 783 * Return: zero on success, else a negative error code.
 784 */
 785int spi_register_board_info(struct spi_board_info const *info, unsigned n)
 
 786{
 787	struct boardinfo *bi;
 788	int i;
 789
 790	if (!n)
 791		return 0;
 792
 793	bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
 794	if (!bi)
 795		return -ENOMEM;
 796
 797	for (i = 0; i < n; i++, bi++, info++) {
 798		struct spi_controller *ctlr;
 799
 800		memcpy(&bi->board_info, info, sizeof(*info));
 801
 802		mutex_lock(&board_lock);
 803		list_add_tail(&bi->list, &board_list);
 804		list_for_each_entry(ctlr, &spi_controller_list, list)
 805			spi_match_controller_to_boardinfo(ctlr,
 806							  &bi->board_info);
 807		mutex_unlock(&board_lock);
 808	}
 809
 810	return 0;
 811}
 812
 813/*-------------------------------------------------------------------------*/
 814
 815static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
 816{
 817	bool activate = enable;
 818
 819	/*
 820	 * Avoid calling into the driver (or doing delays) if the chip select
 821	 * isn't actually changing from the last time this was called.
 822	 */
 823	if (!force && (spi->controller->last_cs_enable == enable) &&
 824	    (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
 825		return;
 826
 827	trace_spi_set_cs(spi, activate);
 828
 829	spi->controller->last_cs_enable = enable;
 830	spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
 831
 832	if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
 833	    !spi->controller->set_cs_timing) {
 834		if (activate)
 835			spi_delay_exec(&spi->controller->cs_setup, NULL);
 836		else
 837			spi_delay_exec(&spi->controller->cs_hold, NULL);
 838	}
 839
 840	if (spi->mode & SPI_CS_HIGH)
 841		enable = !enable;
 842
 843	if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio)) {
 844		if (!(spi->mode & SPI_NO_CS)) {
 845			if (spi->cs_gpiod) {
 846				/*
 847				 * Historically ACPI has no means of the GPIO polarity and
 848				 * thus the SPISerialBus() resource defines it on the per-chip
 849				 * basis. In order to avoid a chain of negations, the GPIO
 850				 * polarity is considered being Active High. Even for the cases
 851				 * when _DSD() is involved (in the updated versions of ACPI)
 852				 * the GPIO CS polarity must be defined Active High to avoid
 853				 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
 854				 * into account.
 855				 */
 856				if (has_acpi_companion(&spi->dev))
 857					gpiod_set_value_cansleep(spi->cs_gpiod, !enable);
 858				else
 859					/* Polarity handled by GPIO library */
 860					gpiod_set_value_cansleep(spi->cs_gpiod, activate);
 861			} else {
 862				/*
 863				 * invert the enable line, as active low is
 864				 * default for SPI.
 865				 */
 866				gpio_set_value_cansleep(spi->cs_gpio, !enable);
 867			}
 868		}
 869		/* Some SPI masters need both GPIO CS & slave_select */
 870		if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
 871		    spi->controller->set_cs)
 872			spi->controller->set_cs(spi, !enable);
 873	} else if (spi->controller->set_cs) {
 874		spi->controller->set_cs(spi, !enable);
 875	}
 876
 877	if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
 878	    !spi->controller->set_cs_timing) {
 879		if (!activate)
 880			spi_delay_exec(&spi->controller->cs_inactive, NULL);
 881	}
 882}
 883
 884#ifdef CONFIG_HAS_DMA
 885int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
 886		struct sg_table *sgt, void *buf, size_t len,
 887		enum dma_data_direction dir)
 888{
 889	const bool vmalloced_buf = is_vmalloc_addr(buf);
 890	unsigned int max_seg_size = dma_get_max_seg_size(dev);
 891#ifdef CONFIG_HIGHMEM
 892	const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
 893				(unsigned long)buf < (PKMAP_BASE +
 894					(LAST_PKMAP * PAGE_SIZE)));
 895#else
 896	const bool kmap_buf = false;
 897#endif
 898	int desc_len;
 899	int sgs;
 900	struct page *vm_page;
 901	struct scatterlist *sg;
 902	void *sg_buf;
 903	size_t min;
 904	int i, ret;
 905
 906	if (vmalloced_buf || kmap_buf) {
 907		desc_len = min_t(int, max_seg_size, PAGE_SIZE);
 908		sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
 909	} else if (virt_addr_valid(buf)) {
 910		desc_len = min_t(int, max_seg_size, ctlr->max_dma_len);
 911		sgs = DIV_ROUND_UP(len, desc_len);
 912	} else {
 913		return -EINVAL;
 914	}
 915
 916	ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
 917	if (ret != 0)
 918		return ret;
 919
 920	sg = &sgt->sgl[0];
 921	for (i = 0; i < sgs; i++) {
 922
 923		if (vmalloced_buf || kmap_buf) {
 924			/*
 925			 * Next scatterlist entry size is the minimum between
 926			 * the desc_len and the remaining buffer length that
 927			 * fits in a page.
 928			 */
 929			min = min_t(size_t, desc_len,
 930				    min_t(size_t, len,
 931					  PAGE_SIZE - offset_in_page(buf)));
 932			if (vmalloced_buf)
 933				vm_page = vmalloc_to_page(buf);
 934			else
 935				vm_page = kmap_to_page(buf);
 936			if (!vm_page) {
 937				sg_free_table(sgt);
 938				return -ENOMEM;
 939			}
 940			sg_set_page(sg, vm_page,
 941				    min, offset_in_page(buf));
 942		} else {
 943			min = min_t(size_t, len, desc_len);
 944			sg_buf = buf;
 945			sg_set_buf(sg, sg_buf, min);
 946		}
 947
 948		buf += min;
 949		len -= min;
 950		sg = sg_next(sg);
 951	}
 952
 953	ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
 954	if (!ret)
 955		ret = -ENOMEM;
 956	if (ret < 0) {
 957		sg_free_table(sgt);
 958		return ret;
 959	}
 960
 961	sgt->nents = ret;
 962
 963	return 0;
 964}
 965
 966void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
 967		   struct sg_table *sgt, enum dma_data_direction dir)
 968{
 969	if (sgt->orig_nents) {
 970		dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
 971		sg_free_table(sgt);
 972	}
 973}
 974
 975static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
 976{
 977	struct device *tx_dev, *rx_dev;
 978	struct spi_transfer *xfer;
 979	int ret;
 980
 981	if (!ctlr->can_dma)
 982		return 0;
 983
 984	if (ctlr->dma_tx)
 985		tx_dev = ctlr->dma_tx->device->dev;
 986	else if (ctlr->dma_map_dev)
 987		tx_dev = ctlr->dma_map_dev;
 988	else
 989		tx_dev = ctlr->dev.parent;
 990
 991	if (ctlr->dma_rx)
 992		rx_dev = ctlr->dma_rx->device->dev;
 993	else if (ctlr->dma_map_dev)
 994		rx_dev = ctlr->dma_map_dev;
 995	else
 996		rx_dev = ctlr->dev.parent;
 997
 998	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
 999		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1000			continue;
1001
1002		if (xfer->tx_buf != NULL) {
1003			ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
1004					  (void *)xfer->tx_buf, xfer->len,
1005					  DMA_TO_DEVICE);
1006			if (ret != 0)
1007				return ret;
1008		}
1009
1010		if (xfer->rx_buf != NULL) {
1011			ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
1012					  xfer->rx_buf, xfer->len,
1013					  DMA_FROM_DEVICE);
1014			if (ret != 0) {
1015				spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
1016					      DMA_TO_DEVICE);
1017				return ret;
1018			}
1019		}
1020	}
1021
1022	ctlr->cur_msg_mapped = true;
1023
1024	return 0;
1025}
1026
1027static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
1028{
1029	struct spi_transfer *xfer;
1030	struct device *tx_dev, *rx_dev;
1031
1032	if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
1033		return 0;
1034
1035	if (ctlr->dma_tx)
1036		tx_dev = ctlr->dma_tx->device->dev;
1037	else
1038		tx_dev = ctlr->dev.parent;
1039
1040	if (ctlr->dma_rx)
1041		rx_dev = ctlr->dma_rx->device->dev;
1042	else
1043		rx_dev = ctlr->dev.parent;
1044
1045	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1046		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1047			continue;
1048
1049		spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1050		spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1051	}
1052
1053	ctlr->cur_msg_mapped = false;
1054
1055	return 0;
1056}
1057#else /* !CONFIG_HAS_DMA */
1058static inline int __spi_map_msg(struct spi_controller *ctlr,
1059				struct spi_message *msg)
1060{
1061	return 0;
1062}
1063
1064static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1065				  struct spi_message *msg)
1066{
1067	return 0;
1068}
1069#endif /* !CONFIG_HAS_DMA */
1070
1071static inline int spi_unmap_msg(struct spi_controller *ctlr,
1072				struct spi_message *msg)
1073{
1074	struct spi_transfer *xfer;
1075
1076	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1077		/*
1078		 * Restore the original value of tx_buf or rx_buf if they are
1079		 * NULL.
1080		 */
1081		if (xfer->tx_buf == ctlr->dummy_tx)
1082			xfer->tx_buf = NULL;
1083		if (xfer->rx_buf == ctlr->dummy_rx)
1084			xfer->rx_buf = NULL;
1085	}
1086
1087	return __spi_unmap_msg(ctlr, msg);
1088}
1089
1090static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1091{
1092	struct spi_transfer *xfer;
1093	void *tmp;
1094	unsigned int max_tx, max_rx;
1095
1096	if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1097		&& !(msg->spi->mode & SPI_3WIRE)) {
1098		max_tx = 0;
1099		max_rx = 0;
1100
1101		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1102			if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1103			    !xfer->tx_buf)
1104				max_tx = max(xfer->len, max_tx);
1105			if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1106			    !xfer->rx_buf)
1107				max_rx = max(xfer->len, max_rx);
1108		}
1109
1110		if (max_tx) {
1111			tmp = krealloc(ctlr->dummy_tx, max_tx,
1112				       GFP_KERNEL | GFP_DMA);
1113			if (!tmp)
1114				return -ENOMEM;
1115			ctlr->dummy_tx = tmp;
1116			memset(tmp, 0, max_tx);
1117		}
1118
1119		if (max_rx) {
1120			tmp = krealloc(ctlr->dummy_rx, max_rx,
1121				       GFP_KERNEL | GFP_DMA);
1122			if (!tmp)
1123				return -ENOMEM;
1124			ctlr->dummy_rx = tmp;
1125		}
1126
1127		if (max_tx || max_rx) {
1128			list_for_each_entry(xfer, &msg->transfers,
1129					    transfer_list) {
1130				if (!xfer->len)
1131					continue;
1132				if (!xfer->tx_buf)
1133					xfer->tx_buf = ctlr->dummy_tx;
1134				if (!xfer->rx_buf)
1135					xfer->rx_buf = ctlr->dummy_rx;
1136			}
1137		}
1138	}
1139
1140	return __spi_map_msg(ctlr, msg);
1141}
1142
1143static int spi_transfer_wait(struct spi_controller *ctlr,
1144			     struct spi_message *msg,
1145			     struct spi_transfer *xfer)
1146{
1147	struct spi_statistics *statm = &ctlr->statistics;
1148	struct spi_statistics *stats = &msg->spi->statistics;
1149	u32 speed_hz = xfer->speed_hz;
1150	unsigned long long ms;
1151
1152	if (spi_controller_is_slave(ctlr)) {
1153		if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1154			dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1155			return -EINTR;
1156		}
1157	} else {
1158		if (!speed_hz)
1159			speed_hz = 100000;
1160
1161		/*
1162		 * For each byte we wait for 8 cycles of the SPI clock.
1163		 * Since speed is defined in Hz and we want milliseconds,
1164		 * use respective multiplier, but before the division,
1165		 * otherwise we may get 0 for short transfers.
1166		 */
1167		ms = 8LL * MSEC_PER_SEC * xfer->len;
1168		do_div(ms, speed_hz);
1169
1170		/*
1171		 * Increase it twice and add 200 ms tolerance, use
1172		 * predefined maximum in case of overflow.
1173		 */
1174		ms += ms + 200;
1175		if (ms > UINT_MAX)
1176			ms = UINT_MAX;
1177
1178		ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1179						 msecs_to_jiffies(ms));
1180
1181		if (ms == 0) {
1182			SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1183			SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1184			dev_err(&msg->spi->dev,
1185				"SPI transfer timed out\n");
1186			return -ETIMEDOUT;
1187		}
1188	}
1189
1190	return 0;
1191}
1192
1193static void _spi_transfer_delay_ns(u32 ns)
1194{
1195	if (!ns)
1196		return;
1197	if (ns <= NSEC_PER_USEC) {
1198		ndelay(ns);
1199	} else {
1200		u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
1201
1202		if (us <= 10)
1203			udelay(us);
1204		else
1205			usleep_range(us, us + DIV_ROUND_UP(us, 10));
1206	}
1207}
1208
1209int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1210{
1211	u32 delay = _delay->value;
1212	u32 unit = _delay->unit;
1213	u32 hz;
1214
1215	if (!delay)
1216		return 0;
1217
1218	switch (unit) {
1219	case SPI_DELAY_UNIT_USECS:
1220		delay *= NSEC_PER_USEC;
1221		break;
1222	case SPI_DELAY_UNIT_NSECS:
1223		/* Nothing to do here */
1224		break;
1225	case SPI_DELAY_UNIT_SCK:
1226		/* clock cycles need to be obtained from spi_transfer */
1227		if (!xfer)
1228			return -EINVAL;
1229		/*
1230		 * If there is unknown effective speed, approximate it
1231		 * by underestimating with half of the requested hz.
1232		 */
1233		hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1234		if (!hz)
1235			return -EINVAL;
1236
1237		/* Convert delay to nanoseconds */
1238		delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
1239		break;
1240	default:
1241		return -EINVAL;
1242	}
1243
1244	return delay;
1245}
1246EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1247
1248int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1249{
1250	int delay;
1251
1252	might_sleep();
1253
1254	if (!_delay)
1255		return -EINVAL;
1256
1257	delay = spi_delay_to_ns(_delay, xfer);
1258	if (delay < 0)
1259		return delay;
1260
1261	_spi_transfer_delay_ns(delay);
1262
1263	return 0;
1264}
1265EXPORT_SYMBOL_GPL(spi_delay_exec);
1266
1267static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1268					  struct spi_transfer *xfer)
1269{
1270	u32 default_delay_ns = 10 * NSEC_PER_USEC;
1271	u32 delay = xfer->cs_change_delay.value;
1272	u32 unit = xfer->cs_change_delay.unit;
1273	int ret;
1274
1275	/* return early on "fast" mode - for everything but USECS */
1276	if (!delay) {
1277		if (unit == SPI_DELAY_UNIT_USECS)
1278			_spi_transfer_delay_ns(default_delay_ns);
1279		return;
1280	}
1281
1282	ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1283	if (ret) {
1284		dev_err_once(&msg->spi->dev,
1285			     "Use of unsupported delay unit %i, using default of %luus\n",
1286			     unit, default_delay_ns / NSEC_PER_USEC);
1287		_spi_transfer_delay_ns(default_delay_ns);
1288	}
1289}
1290
1291/*
1292 * spi_transfer_one_message - Default implementation of transfer_one_message()
1293 *
1294 * This is a standard implementation of transfer_one_message() for
1295 * drivers which implement a transfer_one() operation.  It provides
1296 * standard handling of delays and chip select management.
1297 */
1298static int spi_transfer_one_message(struct spi_controller *ctlr,
1299				    struct spi_message *msg)
1300{
1301	struct spi_transfer *xfer;
1302	bool keep_cs = false;
1303	int ret = 0;
1304	struct spi_statistics *statm = &ctlr->statistics;
1305	struct spi_statistics *stats = &msg->spi->statistics;
1306
1307	spi_set_cs(msg->spi, true, false);
1308
1309	SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1310	SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1311
1312	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1313		trace_spi_transfer_start(msg, xfer);
1314
1315		spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1316		spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1317
1318		if (!ctlr->ptp_sts_supported) {
1319			xfer->ptp_sts_word_pre = 0;
1320			ptp_read_system_prets(xfer->ptp_sts);
1321		}
1322
1323		if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1324			reinit_completion(&ctlr->xfer_completion);
1325
1326fallback_pio:
1327			ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1328			if (ret < 0) {
1329				if (ctlr->cur_msg_mapped &&
1330				   (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1331					__spi_unmap_msg(ctlr, msg);
1332					ctlr->fallback = true;
1333					xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1334					goto fallback_pio;
1335				}
1336
1337				SPI_STATISTICS_INCREMENT_FIELD(statm,
1338							       errors);
1339				SPI_STATISTICS_INCREMENT_FIELD(stats,
1340							       errors);
1341				dev_err(&msg->spi->dev,
1342					"SPI transfer failed: %d\n", ret);
1343				goto out;
1344			}
1345
1346			if (ret > 0) {
1347				ret = spi_transfer_wait(ctlr, msg, xfer);
1348				if (ret < 0)
1349					msg->status = ret;
1350			}
1351		} else {
1352			if (xfer->len)
1353				dev_err(&msg->spi->dev,
1354					"Bufferless transfer has length %u\n",
1355					xfer->len);
1356		}
1357
1358		if (!ctlr->ptp_sts_supported) {
1359			ptp_read_system_postts(xfer->ptp_sts);
1360			xfer->ptp_sts_word_post = xfer->len;
1361		}
1362
1363		trace_spi_transfer_stop(msg, xfer);
1364
1365		if (msg->status != -EINPROGRESS)
1366			goto out;
1367
1368		spi_transfer_delay_exec(xfer);
1369
1370		if (xfer->cs_change) {
1371			if (list_is_last(&xfer->transfer_list,
1372					 &msg->transfers)) {
1373				keep_cs = true;
1374			} else {
1375				spi_set_cs(msg->spi, false, false);
1376				_spi_transfer_cs_change_delay(msg, xfer);
1377				spi_set_cs(msg->spi, true, false);
1378			}
1379		}
1380
1381		msg->actual_length += xfer->len;
1382	}
1383
1384out:
1385	if (ret != 0 || !keep_cs)
1386		spi_set_cs(msg->spi, false, false);
1387
1388	if (msg->status == -EINPROGRESS)
1389		msg->status = ret;
1390
1391	if (msg->status && ctlr->handle_err)
1392		ctlr->handle_err(ctlr, msg);
1393
1394	spi_finalize_current_message(ctlr);
1395
1396	return ret;
1397}
1398
1399/**
1400 * spi_finalize_current_transfer - report completion of a transfer
1401 * @ctlr: the controller reporting completion
1402 *
1403 * Called by SPI drivers using the core transfer_one_message()
1404 * implementation to notify it that the current interrupt driven
1405 * transfer has finished and the next one may be scheduled.
1406 */
1407void spi_finalize_current_transfer(struct spi_controller *ctlr)
1408{
1409	complete(&ctlr->xfer_completion);
1410}
1411EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1412
1413static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1414{
1415	if (ctlr->auto_runtime_pm) {
1416		pm_runtime_mark_last_busy(ctlr->dev.parent);
1417		pm_runtime_put_autosuspend(ctlr->dev.parent);
1418	}
1419}
1420
1421/**
1422 * __spi_pump_messages - function which processes spi message queue
1423 * @ctlr: controller to process queue for
1424 * @in_kthread: true if we are in the context of the message pump thread
1425 *
1426 * This function checks if there is any spi message in the queue that
1427 * needs processing and if so call out to the driver to initialize hardware
1428 * and transfer each message.
1429 *
1430 * Note that it is called both from the kthread itself and also from
1431 * inside spi_sync(); the queue extraction handling at the top of the
1432 * function should deal with this safely.
1433 */
1434static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1435{
1436	struct spi_transfer *xfer;
1437	struct spi_message *msg;
1438	bool was_busy = false;
1439	unsigned long flags;
1440	int ret;
1441
1442	/* Lock queue */
1443	spin_lock_irqsave(&ctlr->queue_lock, flags);
1444
1445	/* Make sure we are not already running a message */
1446	if (ctlr->cur_msg) {
1447		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1448		return;
1449	}
1450
1451	/* If another context is idling the device then defer */
1452	if (ctlr->idling) {
1453		kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1454		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1455		return;
1456	}
1457
1458	/* Check if the queue is idle */
1459	if (list_empty(&ctlr->queue) || !ctlr->running) {
1460		if (!ctlr->busy) {
1461			spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1462			return;
1463		}
1464
1465		/* Defer any non-atomic teardown to the thread */
1466		if (!in_kthread) {
1467			if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1468			    !ctlr->unprepare_transfer_hardware) {
1469				spi_idle_runtime_pm(ctlr);
1470				ctlr->busy = false;
1471				trace_spi_controller_idle(ctlr);
1472			} else {
1473				kthread_queue_work(ctlr->kworker,
1474						   &ctlr->pump_messages);
1475			}
1476			spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1477			return;
1478		}
1479
1480		ctlr->busy = false;
1481		ctlr->idling = true;
1482		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1483
1484		kfree(ctlr->dummy_rx);
1485		ctlr->dummy_rx = NULL;
1486		kfree(ctlr->dummy_tx);
1487		ctlr->dummy_tx = NULL;
1488		if (ctlr->unprepare_transfer_hardware &&
1489		    ctlr->unprepare_transfer_hardware(ctlr))
1490			dev_err(&ctlr->dev,
1491				"failed to unprepare transfer hardware\n");
1492		spi_idle_runtime_pm(ctlr);
1493		trace_spi_controller_idle(ctlr);
1494
1495		spin_lock_irqsave(&ctlr->queue_lock, flags);
1496		ctlr->idling = false;
1497		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1498		return;
1499	}
1500
1501	/* Extract head of queue */
1502	msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1503	ctlr->cur_msg = msg;
1504
1505	list_del_init(&msg->queue);
1506	if (ctlr->busy)
1507		was_busy = true;
1508	else
1509		ctlr->busy = true;
1510	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1511
1512	mutex_lock(&ctlr->io_mutex);
1513
1514	if (!was_busy && ctlr->auto_runtime_pm) {
1515		ret = pm_runtime_get_sync(ctlr->dev.parent);
1516		if (ret < 0) {
1517			pm_runtime_put_noidle(ctlr->dev.parent);
1518			dev_err(&ctlr->dev, "Failed to power device: %d\n",
1519				ret);
1520			mutex_unlock(&ctlr->io_mutex);
1521			return;
1522		}
1523	}
1524
1525	if (!was_busy)
1526		trace_spi_controller_busy(ctlr);
1527
1528	if (!was_busy && ctlr->prepare_transfer_hardware) {
1529		ret = ctlr->prepare_transfer_hardware(ctlr);
1530		if (ret) {
1531			dev_err(&ctlr->dev,
1532				"failed to prepare transfer hardware: %d\n",
1533				ret);
1534
1535			if (ctlr->auto_runtime_pm)
1536				pm_runtime_put(ctlr->dev.parent);
1537
1538			msg->status = ret;
1539			spi_finalize_current_message(ctlr);
1540
1541			mutex_unlock(&ctlr->io_mutex);
1542			return;
1543		}
1544	}
1545
1546	trace_spi_message_start(msg);
1547
1548	if (ctlr->prepare_message) {
1549		ret = ctlr->prepare_message(ctlr, msg);
1550		if (ret) {
1551			dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1552				ret);
1553			msg->status = ret;
1554			spi_finalize_current_message(ctlr);
1555			goto out;
1556		}
1557		ctlr->cur_msg_prepared = true;
1558	}
1559
1560	ret = spi_map_msg(ctlr, msg);
1561	if (ret) {
1562		msg->status = ret;
1563		spi_finalize_current_message(ctlr);
1564		goto out;
1565	}
1566
1567	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1568		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1569			xfer->ptp_sts_word_pre = 0;
1570			ptp_read_system_prets(xfer->ptp_sts);
1571		}
1572	}
1573
1574	ret = ctlr->transfer_one_message(ctlr, msg);
1575	if (ret) {
1576		dev_err(&ctlr->dev,
1577			"failed to transfer one message from queue\n");
1578		goto out;
1579	}
1580
1581out:
1582	mutex_unlock(&ctlr->io_mutex);
1583
1584	/* Prod the scheduler in case transfer_one() was busy waiting */
1585	if (!ret)
1586		cond_resched();
1587}
1588
1589/**
1590 * spi_pump_messages - kthread work function which processes spi message queue
1591 * @work: pointer to kthread work struct contained in the controller struct
1592 */
1593static void spi_pump_messages(struct kthread_work *work)
1594{
1595	struct spi_controller *ctlr =
1596		container_of(work, struct spi_controller, pump_messages);
1597
1598	__spi_pump_messages(ctlr, true);
1599}
1600
1601/**
1602 * spi_take_timestamp_pre - helper for drivers to collect the beginning of the
1603 *			    TX timestamp for the requested byte from the SPI
1604 *			    transfer. The frequency with which this function
1605 *			    must be called (once per word, once for the whole
1606 *			    transfer, once per batch of words etc) is arbitrary
1607 *			    as long as the @tx buffer offset is greater than or
1608 *			    equal to the requested byte at the time of the
1609 *			    call. The timestamp is only taken once, at the
1610 *			    first such call. It is assumed that the driver
1611 *			    advances its @tx buffer pointer monotonically.
1612 * @ctlr: Pointer to the spi_controller structure of the driver
1613 * @xfer: Pointer to the transfer being timestamped
1614 * @progress: How many words (not bytes) have been transferred so far
1615 * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1616 *	      transfer, for less jitter in time measurement. Only compatible
1617 *	      with PIO drivers. If true, must follow up with
1618 *	      spi_take_timestamp_post or otherwise system will crash.
1619 *	      WARNING: for fully predictable results, the CPU frequency must
1620 *	      also be under control (governor).
1621 */
1622void spi_take_timestamp_pre(struct spi_controller *ctlr,
1623			    struct spi_transfer *xfer,
1624			    size_t progress, bool irqs_off)
1625{
1626	if (!xfer->ptp_sts)
1627		return;
1628
1629	if (xfer->timestamped)
1630		return;
1631
1632	if (progress > xfer->ptp_sts_word_pre)
1633		return;
1634
1635	/* Capture the resolution of the timestamp */
1636	xfer->ptp_sts_word_pre = progress;
1637
1638	if (irqs_off) {
1639		local_irq_save(ctlr->irq_flags);
1640		preempt_disable();
1641	}
1642
1643	ptp_read_system_prets(xfer->ptp_sts);
1644}
1645EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1646
1647/**
1648 * spi_take_timestamp_post - helper for drivers to collect the end of the
1649 *			     TX timestamp for the requested byte from the SPI
1650 *			     transfer. Can be called with an arbitrary
1651 *			     frequency: only the first call where @tx exceeds
1652 *			     or is equal to the requested word will be
1653 *			     timestamped.
1654 * @ctlr: Pointer to the spi_controller structure of the driver
1655 * @xfer: Pointer to the transfer being timestamped
1656 * @progress: How many words (not bytes) have been transferred so far
1657 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1658 */
1659void spi_take_timestamp_post(struct spi_controller *ctlr,
1660			     struct spi_transfer *xfer,
1661			     size_t progress, bool irqs_off)
1662{
1663	if (!xfer->ptp_sts)
1664		return;
1665
1666	if (xfer->timestamped)
1667		return;
1668
1669	if (progress < xfer->ptp_sts_word_post)
1670		return;
1671
1672	ptp_read_system_postts(xfer->ptp_sts);
1673
1674	if (irqs_off) {
1675		local_irq_restore(ctlr->irq_flags);
1676		preempt_enable();
1677	}
1678
1679	/* Capture the resolution of the timestamp */
1680	xfer->ptp_sts_word_post = progress;
1681
1682	xfer->timestamped = true;
1683}
1684EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1685
1686/**
1687 * spi_set_thread_rt - set the controller to pump at realtime priority
1688 * @ctlr: controller to boost priority of
1689 *
1690 * This can be called because the controller requested realtime priority
1691 * (by setting the ->rt value before calling spi_register_controller()) or
1692 * because a device on the bus said that its transfers needed realtime
1693 * priority.
1694 *
1695 * NOTE: at the moment if any device on a bus says it needs realtime then
1696 * the thread will be at realtime priority for all transfers on that
1697 * controller.  If this eventually becomes a problem we may see if we can
1698 * find a way to boost the priority only temporarily during relevant
1699 * transfers.
1700 */
1701static void spi_set_thread_rt(struct spi_controller *ctlr)
1702{
1703	dev_info(&ctlr->dev,
1704		"will run message pump with realtime priority\n");
1705	sched_set_fifo(ctlr->kworker->task);
1706}
1707
1708static int spi_init_queue(struct spi_controller *ctlr)
1709{
1710	ctlr->running = false;
1711	ctlr->busy = false;
1712
1713	ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
1714	if (IS_ERR(ctlr->kworker)) {
1715		dev_err(&ctlr->dev, "failed to create message pump kworker\n");
1716		return PTR_ERR(ctlr->kworker);
1717	}
1718
1719	kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1720
1721	/*
1722	 * Controller config will indicate if this controller should run the
1723	 * message pump with high (realtime) priority to reduce the transfer
1724	 * latency on the bus by minimising the delay between a transfer
1725	 * request and the scheduling of the message pump thread. Without this
1726	 * setting the message pump thread will remain at default priority.
1727	 */
1728	if (ctlr->rt)
1729		spi_set_thread_rt(ctlr);
1730
1731	return 0;
1732}
1733
1734/**
1735 * spi_get_next_queued_message() - called by driver to check for queued
1736 * messages
1737 * @ctlr: the controller to check for queued messages
1738 *
1739 * If there are more messages in the queue, the next message is returned from
1740 * this call.
1741 *
1742 * Return: the next message in the queue, else NULL if the queue is empty.
1743 */
1744struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1745{
1746	struct spi_message *next;
1747	unsigned long flags;
1748
1749	/* get a pointer to the next message, if any */
1750	spin_lock_irqsave(&ctlr->queue_lock, flags);
1751	next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1752					queue);
1753	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1754
1755	return next;
1756}
1757EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1758
1759/**
1760 * spi_finalize_current_message() - the current message is complete
1761 * @ctlr: the controller to return the message to
1762 *
1763 * Called by the driver to notify the core that the message in the front of the
1764 * queue is complete and can be removed from the queue.
1765 */
1766void spi_finalize_current_message(struct spi_controller *ctlr)
1767{
1768	struct spi_transfer *xfer;
1769	struct spi_message *mesg;
1770	unsigned long flags;
1771	int ret;
1772
1773	spin_lock_irqsave(&ctlr->queue_lock, flags);
1774	mesg = ctlr->cur_msg;
1775	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1776
1777	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1778		list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1779			ptp_read_system_postts(xfer->ptp_sts);
1780			xfer->ptp_sts_word_post = xfer->len;
1781		}
1782	}
1783
1784	if (unlikely(ctlr->ptp_sts_supported))
1785		list_for_each_entry(xfer, &mesg->transfers, transfer_list)
1786			WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1787
1788	spi_unmap_msg(ctlr, mesg);
1789
1790	/* In the prepare_messages callback the spi bus has the opportunity to
1791	 * split a transfer to smaller chunks.
1792	 * Release splited transfers here since spi_map_msg is done on the
1793	 * splited transfers.
1794	 */
1795	spi_res_release(ctlr, mesg);
1796
1797	if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1798		ret = ctlr->unprepare_message(ctlr, mesg);
1799		if (ret) {
1800			dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1801				ret);
1802		}
1803	}
1804
1805	spin_lock_irqsave(&ctlr->queue_lock, flags);
1806	ctlr->cur_msg = NULL;
1807	ctlr->cur_msg_prepared = false;
1808	ctlr->fallback = false;
1809	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1810	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1811
1812	trace_spi_message_done(mesg);
1813
1814	mesg->state = NULL;
1815	if (mesg->complete)
1816		mesg->complete(mesg->context);
1817}
1818EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1819
1820static int spi_start_queue(struct spi_controller *ctlr)
1821{
1822	unsigned long flags;
1823
1824	spin_lock_irqsave(&ctlr->queue_lock, flags);
1825
1826	if (ctlr->running || ctlr->busy) {
1827		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1828		return -EBUSY;
1829	}
1830
1831	ctlr->running = true;
1832	ctlr->cur_msg = NULL;
1833	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1834
1835	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1836
1837	return 0;
1838}
1839
1840static int spi_stop_queue(struct spi_controller *ctlr)
1841{
1842	unsigned long flags;
1843	unsigned limit = 500;
1844	int ret = 0;
1845
1846	spin_lock_irqsave(&ctlr->queue_lock, flags);
1847
1848	/*
1849	 * This is a bit lame, but is optimized for the common execution path.
1850	 * A wait_queue on the ctlr->busy could be used, but then the common
1851	 * execution path (pump_messages) would be required to call wake_up or
1852	 * friends on every SPI message. Do this instead.
1853	 */
1854	while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1855		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1856		usleep_range(10000, 11000);
1857		spin_lock_irqsave(&ctlr->queue_lock, flags);
1858	}
1859
1860	if (!list_empty(&ctlr->queue) || ctlr->busy)
1861		ret = -EBUSY;
1862	else
1863		ctlr->running = false;
1864
1865	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1866
1867	if (ret) {
1868		dev_warn(&ctlr->dev, "could not stop message queue\n");
1869		return ret;
1870	}
1871	return ret;
1872}
1873
1874static int spi_destroy_queue(struct spi_controller *ctlr)
1875{
1876	int ret;
1877
1878	ret = spi_stop_queue(ctlr);
1879
1880	/*
1881	 * kthread_flush_worker will block until all work is done.
1882	 * If the reason that stop_queue timed out is that the work will never
1883	 * finish, then it does no good to call flush/stop thread, so
1884	 * return anyway.
1885	 */
1886	if (ret) {
1887		dev_err(&ctlr->dev, "problem destroying queue\n");
1888		return ret;
1889	}
1890
1891	kthread_destroy_worker(ctlr->kworker);
1892
1893	return 0;
1894}
1895
1896static int __spi_queued_transfer(struct spi_device *spi,
1897				 struct spi_message *msg,
1898				 bool need_pump)
1899{
1900	struct spi_controller *ctlr = spi->controller;
1901	unsigned long flags;
1902
1903	spin_lock_irqsave(&ctlr->queue_lock, flags);
1904
1905	if (!ctlr->running) {
1906		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1907		return -ESHUTDOWN;
1908	}
1909	msg->actual_length = 0;
1910	msg->status = -EINPROGRESS;
1911
1912	list_add_tail(&msg->queue, &ctlr->queue);
1913	if (!ctlr->busy && need_pump)
1914		kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1915
1916	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1917	return 0;
1918}
1919
1920/**
1921 * spi_queued_transfer - transfer function for queued transfers
1922 * @spi: spi device which is requesting transfer
1923 * @msg: spi message which is to handled is queued to driver queue
1924 *
1925 * Return: zero on success, else a negative error code.
1926 */
1927static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1928{
1929	return __spi_queued_transfer(spi, msg, true);
1930}
1931
1932static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1933{
1934	int ret;
1935
1936	ctlr->transfer = spi_queued_transfer;
1937	if (!ctlr->transfer_one_message)
1938		ctlr->transfer_one_message = spi_transfer_one_message;
1939
1940	/* Initialize and start queue */
1941	ret = spi_init_queue(ctlr);
1942	if (ret) {
1943		dev_err(&ctlr->dev, "problem initializing queue\n");
1944		goto err_init_queue;
1945	}
1946	ctlr->queued = true;
1947	ret = spi_start_queue(ctlr);
1948	if (ret) {
1949		dev_err(&ctlr->dev, "problem starting queue\n");
1950		goto err_start_queue;
1951	}
1952
1953	return 0;
1954
1955err_start_queue:
1956	spi_destroy_queue(ctlr);
1957err_init_queue:
1958	return ret;
1959}
1960
1961/**
1962 * spi_flush_queue - Send all pending messages in the queue from the callers'
1963 *		     context
1964 * @ctlr: controller to process queue for
1965 *
1966 * This should be used when one wants to ensure all pending messages have been
1967 * sent before doing something. Is used by the spi-mem code to make sure SPI
1968 * memory operations do not preempt regular SPI transfers that have been queued
1969 * before the spi-mem operation.
1970 */
1971void spi_flush_queue(struct spi_controller *ctlr)
1972{
1973	if (ctlr->transfer == spi_queued_transfer)
1974		__spi_pump_messages(ctlr, false);
1975}
1976
1977/*-------------------------------------------------------------------------*/
1978
1979#if defined(CONFIG_OF)
1980static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
1981			   struct device_node *nc)
1982{
1983	u32 value;
1984	int rc;
1985
1986	/* Mode (clock phase/polarity/etc.) */
1987	if (of_property_read_bool(nc, "spi-cpha"))
1988		spi->mode |= SPI_CPHA;
1989	if (of_property_read_bool(nc, "spi-cpol"))
1990		spi->mode |= SPI_CPOL;
1991	if (of_property_read_bool(nc, "spi-3wire"))
1992		spi->mode |= SPI_3WIRE;
1993	if (of_property_read_bool(nc, "spi-lsb-first"))
1994		spi->mode |= SPI_LSB_FIRST;
1995	if (of_property_read_bool(nc, "spi-cs-high"))
1996		spi->mode |= SPI_CS_HIGH;
1997
1998	/* Device DUAL/QUAD mode */
1999	if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
2000		switch (value) {
2001		case 0:
2002			spi->mode |= SPI_NO_TX;
2003			break;
2004		case 1:
2005			break;
2006		case 2:
2007			spi->mode |= SPI_TX_DUAL;
2008			break;
2009		case 4:
2010			spi->mode |= SPI_TX_QUAD;
2011			break;
2012		case 8:
2013			spi->mode |= SPI_TX_OCTAL;
2014			break;
2015		default:
2016			dev_warn(&ctlr->dev,
2017				"spi-tx-bus-width %d not supported\n",
2018				value);
2019			break;
2020		}
2021	}
2022
2023	if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
2024		switch (value) {
2025		case 0:
2026			spi->mode |= SPI_NO_RX;
2027			break;
2028		case 1:
2029			break;
2030		case 2:
2031			spi->mode |= SPI_RX_DUAL;
2032			break;
2033		case 4:
2034			spi->mode |= SPI_RX_QUAD;
2035			break;
2036		case 8:
2037			spi->mode |= SPI_RX_OCTAL;
2038			break;
2039		default:
2040			dev_warn(&ctlr->dev,
2041				"spi-rx-bus-width %d not supported\n",
2042				value);
2043			break;
2044		}
2045	}
2046
2047	if (spi_controller_is_slave(ctlr)) {
2048		if (!of_node_name_eq(nc, "slave")) {
2049			dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
2050				nc);
2051			return -EINVAL;
2052		}
2053		return 0;
2054	}
2055
2056	/* Device address */
2057	rc = of_property_read_u32(nc, "reg", &value);
2058	if (rc) {
2059		dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2060			nc, rc);
2061		return rc;
2062	}
2063	spi->chip_select = value;
2064
2065	/* Device speed */
2066	if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2067		spi->max_speed_hz = value;
2068
2069	return 0;
2070}
2071
2072static struct spi_device *
2073of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2074{
2075	struct spi_device *spi;
2076	int rc;
2077
2078	/* Alloc an spi_device */
2079	spi = spi_alloc_device(ctlr);
2080	if (!spi) {
2081		dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2082		rc = -ENOMEM;
2083		goto err_out;
2084	}
2085
2086	/* Select device driver */
2087	rc = of_modalias_node(nc, spi->modalias,
2088				sizeof(spi->modalias));
2089	if (rc < 0) {
2090		dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2091		goto err_out;
2092	}
2093
2094	rc = of_spi_parse_dt(ctlr, spi, nc);
2095	if (rc)
2096		goto err_out;
2097
2098	/* Store a pointer to the node in the device structure */
2099	of_node_get(nc);
2100	spi->dev.of_node = nc;
2101	spi->dev.fwnode = of_fwnode_handle(nc);
2102
2103	/* Register the new device */
2104	rc = spi_add_device(spi);
2105	if (rc) {
2106		dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2107		goto err_of_node_put;
2108	}
2109
2110	return spi;
2111
2112err_of_node_put:
2113	of_node_put(nc);
2114err_out:
2115	spi_dev_put(spi);
2116	return ERR_PTR(rc);
2117}
2118
2119/**
2120 * of_register_spi_devices() - Register child devices onto the SPI bus
2121 * @ctlr:	Pointer to spi_controller device
2122 *
2123 * Registers an spi_device for each child node of controller node which
2124 * represents a valid SPI slave.
2125 */
2126static void of_register_spi_devices(struct spi_controller *ctlr)
2127{
2128	struct spi_device *spi;
2129	struct device_node *nc;
2130
2131	if (!ctlr->dev.of_node)
2132		return;
2133
2134	for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2135		if (of_node_test_and_set_flag(nc, OF_POPULATED))
2136			continue;
2137		spi = of_register_spi_device(ctlr, nc);
2138		if (IS_ERR(spi)) {
2139			dev_warn(&ctlr->dev,
2140				 "Failed to create SPI device for %pOF\n", nc);
2141			of_node_clear_flag(nc, OF_POPULATED);
2142		}
2143	}
2144}
2145#else
2146static void of_register_spi_devices(struct spi_controller *ctlr) { }
2147#endif
2148
2149/**
2150 * spi_new_ancillary_device() - Register ancillary SPI device
2151 * @spi:         Pointer to the main SPI device registering the ancillary device
2152 * @chip_select: Chip Select of the ancillary device
2153 *
2154 * Register an ancillary SPI device; for example some chips have a chip-select
2155 * for normal device usage and another one for setup/firmware upload.
2156 *
2157 * This may only be called from main SPI device's probe routine.
2158 *
2159 * Return: 0 on success; negative errno on failure
2160 */
2161struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
2162					     u8 chip_select)
2163{
2164	struct spi_device *ancillary;
2165	int rc = 0;
2166
2167	/* Alloc an spi_device */
2168	ancillary = spi_alloc_device(spi->controller);
2169	if (!ancillary) {
2170		rc = -ENOMEM;
2171		goto err_out;
2172	}
2173
2174	strlcpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
2175
2176	/* Use provided chip-select for ancillary device */
2177	ancillary->chip_select = chip_select;
2178
2179	/* Take over SPI mode/speed from SPI main device */
2180	ancillary->max_speed_hz = spi->max_speed_hz;
2181	ancillary->mode = spi->mode;
2182
2183	/* Register the new device */
2184	rc = spi_add_device_locked(ancillary);
2185	if (rc) {
2186		dev_err(&spi->dev, "failed to register ancillary device\n");
2187		goto err_out;
2188	}
2189
2190	return ancillary;
2191
2192err_out:
2193	spi_dev_put(ancillary);
2194	return ERR_PTR(rc);
2195}
2196EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
2197
2198#ifdef CONFIG_ACPI
2199struct acpi_spi_lookup {
2200	struct spi_controller 	*ctlr;
2201	u32			max_speed_hz;
2202	u32			mode;
2203	int			irq;
2204	u8			bits_per_word;
2205	u8			chip_select;
2206};
2207
2208static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2209					    struct acpi_spi_lookup *lookup)
2210{
2211	const union acpi_object *obj;
2212
2213	if (!x86_apple_machine)
2214		return;
2215
2216	if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2217	    && obj->buffer.length >= 4)
2218		lookup->max_speed_hz  = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2219
2220	if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2221	    && obj->buffer.length == 8)
2222		lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2223
2224	if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2225	    && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2226		lookup->mode |= SPI_LSB_FIRST;
2227
2228	if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2229	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
2230		lookup->mode |= SPI_CPOL;
2231
2232	if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2233	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
2234		lookup->mode |= SPI_CPHA;
2235}
2236
2237static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2238{
2239	struct acpi_spi_lookup *lookup = data;
2240	struct spi_controller *ctlr = lookup->ctlr;
2241
2242	if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2243		struct acpi_resource_spi_serialbus *sb;
2244		acpi_handle parent_handle;
2245		acpi_status status;
2246
2247		sb = &ares->data.spi_serial_bus;
2248		if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2249
2250			status = acpi_get_handle(NULL,
2251						 sb->resource_source.string_ptr,
2252						 &parent_handle);
2253
2254			if (ACPI_FAILURE(status) ||
2255			    ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2256				return -ENODEV;
2257
2258			/*
2259			 * ACPI DeviceSelection numbering is handled by the
2260			 * host controller driver in Windows and can vary
2261			 * from driver to driver. In Linux we always expect
2262			 * 0 .. max - 1 so we need to ask the driver to
2263			 * translate between the two schemes.
2264			 */
2265			if (ctlr->fw_translate_cs) {
2266				int cs = ctlr->fw_translate_cs(ctlr,
2267						sb->device_selection);
2268				if (cs < 0)
2269					return cs;
2270				lookup->chip_select = cs;
2271			} else {
2272				lookup->chip_select = sb->device_selection;
2273			}
2274
2275			lookup->max_speed_hz = sb->connection_speed;
2276			lookup->bits_per_word = sb->data_bit_length;
2277
2278			if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2279				lookup->mode |= SPI_CPHA;
2280			if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2281				lookup->mode |= SPI_CPOL;
2282			if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2283				lookup->mode |= SPI_CS_HIGH;
2284		}
2285	} else if (lookup->irq < 0) {
2286		struct resource r;
2287
2288		if (acpi_dev_resource_interrupt(ares, 0, &r))
2289			lookup->irq = r.start;
2290	}
2291
2292	/* Always tell the ACPI core to skip this resource */
2293	return 1;
2294}
2295
2296static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2297					    struct acpi_device *adev)
2298{
2299	acpi_handle parent_handle = NULL;
2300	struct list_head resource_list;
2301	struct acpi_spi_lookup lookup = {};
2302	struct spi_device *spi;
2303	int ret;
2304
2305	if (acpi_bus_get_status(adev) || !adev->status.present ||
2306	    acpi_device_enumerated(adev))
2307		return AE_OK;
2308
2309	lookup.ctlr		= ctlr;
2310	lookup.irq		= -1;
2311
2312	INIT_LIST_HEAD(&resource_list);
2313	ret = acpi_dev_get_resources(adev, &resource_list,
2314				     acpi_spi_add_resource, &lookup);
2315	acpi_dev_free_resource_list(&resource_list);
2316
2317	if (ret < 0)
2318		/* found SPI in _CRS but it points to another controller */
2319		return AE_OK;
2320
2321	if (!lookup.max_speed_hz &&
2322	    ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
2323	    ACPI_HANDLE(ctlr->dev.parent) == parent_handle) {
2324		/* Apple does not use _CRS but nested devices for SPI slaves */
2325		acpi_spi_parse_apple_properties(adev, &lookup);
2326	}
2327
2328	if (!lookup.max_speed_hz)
2329		return AE_OK;
2330
2331	spi = spi_alloc_device(ctlr);
2332	if (!spi) {
2333		dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
2334			dev_name(&adev->dev));
2335		return AE_NO_MEMORY;
2336	}
2337
2338
2339	ACPI_COMPANION_SET(&spi->dev, adev);
2340	spi->max_speed_hz	= lookup.max_speed_hz;
2341	spi->mode		|= lookup.mode;
2342	spi->irq		= lookup.irq;
2343	spi->bits_per_word	= lookup.bits_per_word;
2344	spi->chip_select	= lookup.chip_select;
2345
2346	acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2347			  sizeof(spi->modalias));
2348
2349	if (spi->irq < 0)
2350		spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2351
2352	acpi_device_set_enumerated(adev);
2353
2354	adev->power.flags.ignore_parent = true;
2355	if (spi_add_device(spi)) {
2356		adev->power.flags.ignore_parent = false;
2357		dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2358			dev_name(&adev->dev));
2359		spi_dev_put(spi);
2360	}
2361
2362	return AE_OK;
2363}
2364
2365static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2366				       void *data, void **return_value)
2367{
2368	struct spi_controller *ctlr = data;
2369	struct acpi_device *adev;
2370
2371	if (acpi_bus_get_device(handle, &adev))
2372		return AE_OK;
2373
2374	return acpi_register_spi_device(ctlr, adev);
2375}
2376
2377#define SPI_ACPI_ENUMERATE_MAX_DEPTH		32
2378
2379static void acpi_register_spi_devices(struct spi_controller *ctlr)
2380{
2381	acpi_status status;
2382	acpi_handle handle;
2383
2384	handle = ACPI_HANDLE(ctlr->dev.parent);
2385	if (!handle)
2386		return;
2387
2388	status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2389				     SPI_ACPI_ENUMERATE_MAX_DEPTH,
2390				     acpi_spi_add_device, NULL, ctlr, NULL);
2391	if (ACPI_FAILURE(status))
2392		dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2393}
2394#else
2395static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2396#endif /* CONFIG_ACPI */
2397
2398static void spi_controller_release(struct device *dev)
2399{
2400	struct spi_controller *ctlr;
2401
2402	ctlr = container_of(dev, struct spi_controller, dev);
2403	kfree(ctlr);
2404}
2405
2406static struct class spi_master_class = {
2407	.name		= "spi_master",
2408	.owner		= THIS_MODULE,
2409	.dev_release	= spi_controller_release,
2410	.dev_groups	= spi_master_groups,
2411};
2412
2413#ifdef CONFIG_SPI_SLAVE
2414/**
2415 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2416 *		     controller
2417 * @spi: device used for the current transfer
2418 */
2419int spi_slave_abort(struct spi_device *spi)
2420{
2421	struct spi_controller *ctlr = spi->controller;
2422
2423	if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2424		return ctlr->slave_abort(ctlr);
2425
2426	return -ENOTSUPP;
2427}
2428EXPORT_SYMBOL_GPL(spi_slave_abort);
2429
2430static int match_true(struct device *dev, void *data)
2431{
2432	return 1;
2433}
2434
2435static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2436			  char *buf)
2437{
2438	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2439						   dev);
2440	struct device *child;
2441
2442	child = device_find_child(&ctlr->dev, NULL, match_true);
2443	return sprintf(buf, "%s\n",
2444		       child ? to_spi_device(child)->modalias : NULL);
2445}
2446
2447static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2448			   const char *buf, size_t count)
2449{
2450	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2451						   dev);
2452	struct spi_device *spi;
2453	struct device *child;
2454	char name[32];
2455	int rc;
2456
2457	rc = sscanf(buf, "%31s", name);
2458	if (rc != 1 || !name[0])
2459		return -EINVAL;
2460
2461	child = device_find_child(&ctlr->dev, NULL, match_true);
2462	if (child) {
2463		/* Remove registered slave */
2464		device_unregister(child);
2465		put_device(child);
2466	}
2467
2468	if (strcmp(name, "(null)")) {
2469		/* Register new slave */
2470		spi = spi_alloc_device(ctlr);
2471		if (!spi)
2472			return -ENOMEM;
2473
2474		strlcpy(spi->modalias, name, sizeof(spi->modalias));
2475
2476		rc = spi_add_device(spi);
2477		if (rc) {
2478			spi_dev_put(spi);
2479			return rc;
2480		}
2481	}
2482
2483	return count;
2484}
2485
2486static DEVICE_ATTR_RW(slave);
2487
2488static struct attribute *spi_slave_attrs[] = {
2489	&dev_attr_slave.attr,
2490	NULL,
2491};
2492
2493static const struct attribute_group spi_slave_group = {
2494	.attrs = spi_slave_attrs,
2495};
2496
2497static const struct attribute_group *spi_slave_groups[] = {
2498	&spi_controller_statistics_group,
2499	&spi_slave_group,
2500	NULL,
2501};
2502
2503static struct class spi_slave_class = {
2504	.name		= "spi_slave",
2505	.owner		= THIS_MODULE,
2506	.dev_release	= spi_controller_release,
2507	.dev_groups	= spi_slave_groups,
2508};
2509#else
2510extern struct class spi_slave_class;	/* dummy */
2511#endif
2512
2513/**
2514 * __spi_alloc_controller - allocate an SPI master or slave controller
2515 * @dev: the controller, possibly using the platform_bus
2516 * @size: how much zeroed driver-private data to allocate; the pointer to this
2517 *	memory is in the driver_data field of the returned device, accessible
2518 *	with spi_controller_get_devdata(); the memory is cacheline aligned;
2519 *	drivers granting DMA access to portions of their private data need to
2520 *	round up @size using ALIGN(size, dma_get_cache_alignment()).
2521 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2522 *	slave (true) controller
2523 * Context: can sleep
2524 *
2525 * This call is used only by SPI controller drivers, which are the
2526 * only ones directly touching chip registers.  It's how they allocate
2527 * an spi_controller structure, prior to calling spi_register_controller().
2528 *
2529 * This must be called from context that can sleep.
2530 *
2531 * The caller is responsible for assigning the bus number and initializing the
2532 * controller's methods before calling spi_register_controller(); and (after
2533 * errors adding the device) calling spi_controller_put() to prevent a memory
2534 * leak.
2535 *
2536 * Return: the SPI controller structure on success, else NULL.
 
 
2537 */
2538struct spi_controller *__spi_alloc_controller(struct device *dev,
2539					      unsigned int size, bool slave)
2540{
2541	struct spi_controller	*ctlr;
2542	size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2543
2544	if (!dev)
2545		return NULL;
2546
2547	ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2548	if (!ctlr)
2549		return NULL;
2550
2551	device_initialize(&ctlr->dev);
2552	INIT_LIST_HEAD(&ctlr->queue);
2553	spin_lock_init(&ctlr->queue_lock);
2554	spin_lock_init(&ctlr->bus_lock_spinlock);
2555	mutex_init(&ctlr->bus_lock_mutex);
2556	mutex_init(&ctlr->io_mutex);
2557	mutex_init(&ctlr->add_lock);
2558	ctlr->bus_num = -1;
2559	ctlr->num_chipselect = 1;
2560	ctlr->slave = slave;
2561	if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2562		ctlr->dev.class = &spi_slave_class;
2563	else
2564		ctlr->dev.class = &spi_master_class;
2565	ctlr->dev.parent = dev;
2566	pm_suspend_ignore_children(&ctlr->dev, true);
2567	spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2568
2569	return ctlr;
2570}
2571EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2572
2573static void devm_spi_release_controller(struct device *dev, void *ctlr)
2574{
2575	spi_controller_put(*(struct spi_controller **)ctlr);
2576}
2577
2578/**
2579 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2580 * @dev: physical device of SPI controller
2581 * @size: how much zeroed driver-private data to allocate
2582 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2583 * Context: can sleep
2584 *
2585 * Allocate an SPI controller and automatically release a reference on it
2586 * when @dev is unbound from its driver.  Drivers are thus relieved from
2587 * having to call spi_controller_put().
2588 *
2589 * The arguments to this function are identical to __spi_alloc_controller().
2590 *
2591 * Return: the SPI controller structure on success, else NULL.
2592 */
2593struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2594						   unsigned int size,
2595						   bool slave)
2596{
2597	struct spi_controller **ptr, *ctlr;
2598
2599	ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2600			   GFP_KERNEL);
2601	if (!ptr)
2602		return NULL;
2603
2604	ctlr = __spi_alloc_controller(dev, size, slave);
2605	if (ctlr) {
2606		ctlr->devm_allocated = true;
2607		*ptr = ctlr;
2608		devres_add(dev, ptr);
2609	} else {
2610		devres_free(ptr);
2611	}
2612
2613	return ctlr;
2614}
2615EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2616
2617#ifdef CONFIG_OF
2618static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2619{
2620	int nb, i, *cs;
2621	struct device_node *np = ctlr->dev.of_node;
2622
2623	if (!np)
2624		return 0;
2625
2626	nb = of_gpio_named_count(np, "cs-gpios");
2627	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2628
2629	/* Return error only for an incorrectly formed cs-gpios property */
2630	if (nb == 0 || nb == -ENOENT)
2631		return 0;
2632	else if (nb < 0)
2633		return nb;
2634
2635	cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
2636			  GFP_KERNEL);
2637	ctlr->cs_gpios = cs;
2638
2639	if (!ctlr->cs_gpios)
2640		return -ENOMEM;
2641
2642	for (i = 0; i < ctlr->num_chipselect; i++)
2643		cs[i] = -ENOENT;
2644
2645	for (i = 0; i < nb; i++)
2646		cs[i] = of_get_named_gpio(np, "cs-gpios", i);
2647
2648	return 0;
2649}
2650#else
2651static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2652{
2653	return 0;
2654}
2655#endif
2656
2657/**
2658 * spi_get_gpio_descs() - grab chip select GPIOs for the master
2659 * @ctlr: The SPI master to grab GPIO descriptors for
2660 */
2661static int spi_get_gpio_descs(struct spi_controller *ctlr)
2662{
2663	int nb, i;
2664	struct gpio_desc **cs;
2665	struct device *dev = &ctlr->dev;
2666	unsigned long native_cs_mask = 0;
2667	unsigned int num_cs_gpios = 0;
2668
2669	nb = gpiod_count(dev, "cs");
2670	if (nb < 0) {
2671		/* No GPIOs at all is fine, else return the error */
2672		if (nb == -ENOENT)
2673			return 0;
2674		return nb;
2675	}
2676
2677	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2678
2679	cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2680			  GFP_KERNEL);
2681	if (!cs)
2682		return -ENOMEM;
2683	ctlr->cs_gpiods = cs;
2684
2685	for (i = 0; i < nb; i++) {
2686		/*
2687		 * Most chipselects are active low, the inverted
2688		 * semantics are handled by special quirks in gpiolib,
2689		 * so initializing them GPIOD_OUT_LOW here means
2690		 * "unasserted", in most cases this will drive the physical
2691		 * line high.
2692		 */
2693		cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2694						      GPIOD_OUT_LOW);
2695		if (IS_ERR(cs[i]))
2696			return PTR_ERR(cs[i]);
2697
2698		if (cs[i]) {
2699			/*
2700			 * If we find a CS GPIO, name it after the device and
2701			 * chip select line.
2702			 */
2703			char *gpioname;
2704
2705			gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2706						  dev_name(dev), i);
2707			if (!gpioname)
2708				return -ENOMEM;
2709			gpiod_set_consumer_name(cs[i], gpioname);
2710			num_cs_gpios++;
2711			continue;
2712		}
2713
2714		if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
2715			dev_err(dev, "Invalid native chip select %d\n", i);
2716			return -EINVAL;
2717		}
2718		native_cs_mask |= BIT(i);
2719	}
2720
2721	ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
2722
2723	if ((ctlr->flags & SPI_MASTER_GPIO_SS) && num_cs_gpios &&
2724	    ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
2725		dev_err(dev, "No unused native chip select available\n");
2726		return -EINVAL;
2727	}
2728
2729	return 0;
2730}
2731
2732static int spi_controller_check_ops(struct spi_controller *ctlr)
2733{
2734	/*
2735	 * The controller may implement only the high-level SPI-memory like
2736	 * operations if it does not support regular SPI transfers, and this is
2737	 * valid use case.
2738	 * If ->mem_ops is NULL, we request that at least one of the
2739	 * ->transfer_xxx() method be implemented.
2740	 */
2741	if (ctlr->mem_ops) {
2742		if (!ctlr->mem_ops->exec_op)
2743			return -EINVAL;
2744	} else if (!ctlr->transfer && !ctlr->transfer_one &&
2745		   !ctlr->transfer_one_message) {
2746		return -EINVAL;
2747	}
2748
2749	return 0;
2750}
 
2751
2752/**
2753 * spi_register_controller - register SPI master or slave controller
2754 * @ctlr: initialized master, originally from spi_alloc_master() or
2755 *	spi_alloc_slave()
2756 * Context: can sleep
2757 *
2758 * SPI controllers connect to their drivers using some non-SPI bus,
2759 * such as the platform bus.  The final stage of probe() in that code
2760 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2761 *
2762 * SPI controllers use board specific (often SOC specific) bus numbers,
2763 * and board-specific addressing for SPI devices combines those numbers
2764 * with chip select numbers.  Since SPI does not directly support dynamic
2765 * device identification, boards need configuration tables telling which
2766 * chip is at which address.
2767 *
2768 * This must be called from context that can sleep.  It returns zero on
2769 * success, else a negative error code (dropping the controller's refcount).
2770 * After a successful return, the caller is responsible for calling
2771 * spi_unregister_controller().
2772 *
2773 * Return: zero on success, else a negative error code.
2774 */
2775int spi_register_controller(struct spi_controller *ctlr)
2776{
2777	struct device		*dev = ctlr->dev.parent;
 
2778	struct boardinfo	*bi;
2779	int			status;
2780	int			id, first_dynamic;
2781
2782	if (!dev)
2783		return -ENODEV;
2784
2785	/*
2786	 * Make sure all necessary hooks are implemented before registering
2787	 * the SPI controller.
2788	 */
2789	status = spi_controller_check_ops(ctlr);
2790	if (status)
2791		return status;
2792
2793	if (ctlr->bus_num >= 0) {
2794		/* devices with a fixed bus num must check-in with the num */
2795		mutex_lock(&board_lock);
2796		id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2797			ctlr->bus_num + 1, GFP_KERNEL);
2798		mutex_unlock(&board_lock);
2799		if (WARN(id < 0, "couldn't get idr"))
2800			return id == -ENOSPC ? -EBUSY : id;
2801		ctlr->bus_num = id;
2802	} else if (ctlr->dev.of_node) {
2803		/* allocate dynamic bus number using Linux idr */
2804		id = of_alias_get_id(ctlr->dev.of_node, "spi");
2805		if (id >= 0) {
2806			ctlr->bus_num = id;
2807			mutex_lock(&board_lock);
2808			id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2809				       ctlr->bus_num + 1, GFP_KERNEL);
2810			mutex_unlock(&board_lock);
2811			if (WARN(id < 0, "couldn't get idr"))
2812				return id == -ENOSPC ? -EBUSY : id;
2813		}
2814	}
2815	if (ctlr->bus_num < 0) {
2816		first_dynamic = of_alias_get_highest_id("spi");
2817		if (first_dynamic < 0)
2818			first_dynamic = 0;
2819		else
2820			first_dynamic++;
2821
2822		mutex_lock(&board_lock);
2823		id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2824			       0, GFP_KERNEL);
2825		mutex_unlock(&board_lock);
2826		if (WARN(id < 0, "couldn't get idr"))
2827			return id;
2828		ctlr->bus_num = id;
2829	}
2830	ctlr->bus_lock_flag = 0;
2831	init_completion(&ctlr->xfer_completion);
2832	if (!ctlr->max_dma_len)
2833		ctlr->max_dma_len = INT_MAX;
2834
2835	/* register the device, then userspace will see it.
2836	 * registration fails if the bus ID is in use.
2837	 */
2838	dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
2839
2840	if (!spi_controller_is_slave(ctlr)) {
2841		if (ctlr->use_gpio_descriptors) {
2842			status = spi_get_gpio_descs(ctlr);
2843			if (status)
2844				goto free_bus_id;
2845			/*
2846			 * A controller using GPIO descriptors always
2847			 * supports SPI_CS_HIGH if need be.
2848			 */
2849			ctlr->mode_bits |= SPI_CS_HIGH;
2850		} else {
2851			/* Legacy code path for GPIOs from DT */
2852			status = of_spi_get_gpio_numbers(ctlr);
2853			if (status)
2854				goto free_bus_id;
2855		}
2856	}
2857
2858	/*
2859	 * Even if it's just one always-selected device, there must
2860	 * be at least one chipselect.
2861	 */
2862	if (!ctlr->num_chipselect) {
2863		status = -EINVAL;
2864		goto free_bus_id;
2865	}
2866
2867	status = device_add(&ctlr->dev);
2868	if (status < 0)
2869		goto free_bus_id;
2870	dev_dbg(dev, "registered %s %s\n",
2871			spi_controller_is_slave(ctlr) ? "slave" : "master",
2872			dev_name(&ctlr->dev));
2873
2874	/*
2875	 * If we're using a queued driver, start the queue. Note that we don't
2876	 * need the queueing logic if the driver is only supporting high-level
2877	 * memory operations.
2878	 */
2879	if (ctlr->transfer) {
2880		dev_info(dev, "controller is unqueued, this is deprecated\n");
2881	} else if (ctlr->transfer_one || ctlr->transfer_one_message) {
2882		status = spi_controller_initialize_queue(ctlr);
2883		if (status) {
2884			device_del(&ctlr->dev);
2885			goto free_bus_id;
2886		}
2887	}
2888	/* add statistics */
2889	spin_lock_init(&ctlr->statistics.lock);
2890
2891	mutex_lock(&board_lock);
2892	list_add_tail(&ctlr->list, &spi_controller_list);
2893	list_for_each_entry(bi, &board_list, list)
2894		spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
2895	mutex_unlock(&board_lock);
2896
2897	/* Register devices from the device tree and ACPI */
2898	of_register_spi_devices(ctlr);
2899	acpi_register_spi_devices(ctlr);
2900	return status;
2901
2902free_bus_id:
2903	mutex_lock(&board_lock);
2904	idr_remove(&spi_master_idr, ctlr->bus_num);
2905	mutex_unlock(&board_lock);
2906	return status;
2907}
2908EXPORT_SYMBOL_GPL(spi_register_controller);
2909
2910static void devm_spi_unregister(void *ctlr)
2911{
2912	spi_unregister_controller(ctlr);
2913}
2914
2915/**
2916 * devm_spi_register_controller - register managed SPI master or slave
2917 *	controller
2918 * @dev:    device managing SPI controller
2919 * @ctlr: initialized controller, originally from spi_alloc_master() or
2920 *	spi_alloc_slave()
2921 * Context: can sleep
2922 *
2923 * Register a SPI device as with spi_register_controller() which will
2924 * automatically be unregistered and freed.
2925 *
2926 * Return: zero on success, else a negative error code.
2927 */
2928int devm_spi_register_controller(struct device *dev,
2929				 struct spi_controller *ctlr)
2930{
2931	int ret;
2932
2933	ret = spi_register_controller(ctlr);
2934	if (ret)
2935		return ret;
2936
2937	return devm_add_action_or_reset(dev, devm_spi_unregister, ctlr);
2938}
2939EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2940
2941static int __unregister(struct device *dev, void *null)
2942{
2943	spi_unregister_device(to_spi_device(dev));
2944	return 0;
2945}
2946
2947/**
2948 * spi_unregister_controller - unregister SPI master or slave controller
2949 * @ctlr: the controller being unregistered
2950 * Context: can sleep
2951 *
2952 * This call is used only by SPI controller drivers, which are the
2953 * only ones directly touching chip registers.
2954 *
2955 * This must be called from context that can sleep.
2956 *
2957 * Note that this function also drops a reference to the controller.
2958 */
2959void spi_unregister_controller(struct spi_controller *ctlr)
2960{
2961	struct spi_controller *found;
2962	int id = ctlr->bus_num;
2963
2964	/* Prevent addition of new devices, unregister existing ones */
2965	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2966		mutex_lock(&ctlr->add_lock);
2967
2968	device_for_each_child(&ctlr->dev, NULL, __unregister);
2969
2970	/* First make sure that this controller was ever added */
2971	mutex_lock(&board_lock);
2972	found = idr_find(&spi_master_idr, id);
2973	mutex_unlock(&board_lock);
2974	if (ctlr->queued) {
2975		if (spi_destroy_queue(ctlr))
2976			dev_err(&ctlr->dev, "queue remove failed\n");
2977	}
2978	mutex_lock(&board_lock);
2979	list_del(&ctlr->list);
2980	mutex_unlock(&board_lock);
2981
2982	device_del(&ctlr->dev);
2983
2984	/* Release the last reference on the controller if its driver
2985	 * has not yet been converted to devm_spi_alloc_master/slave().
2986	 */
2987	if (!ctlr->devm_allocated)
2988		put_device(&ctlr->dev);
2989
2990	/* free bus id */
2991	mutex_lock(&board_lock);
2992	if (found == ctlr)
2993		idr_remove(&spi_master_idr, id);
2994	mutex_unlock(&board_lock);
2995
2996	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2997		mutex_unlock(&ctlr->add_lock);
2998}
2999EXPORT_SYMBOL_GPL(spi_unregister_controller);
3000
3001int spi_controller_suspend(struct spi_controller *ctlr)
3002{
3003	int ret;
3004
3005	/* Basically no-ops for non-queued controllers */
3006	if (!ctlr->queued)
3007		return 0;
3008
3009	ret = spi_stop_queue(ctlr);
3010	if (ret)
3011		dev_err(&ctlr->dev, "queue stop failed\n");
3012
3013	return ret;
3014}
3015EXPORT_SYMBOL_GPL(spi_controller_suspend);
3016
3017int spi_controller_resume(struct spi_controller *ctlr)
3018{
3019	int ret;
3020
3021	if (!ctlr->queued)
3022		return 0;
3023
3024	ret = spi_start_queue(ctlr);
3025	if (ret)
3026		dev_err(&ctlr->dev, "queue restart failed\n");
3027
3028	return ret;
3029}
3030EXPORT_SYMBOL_GPL(spi_controller_resume);
3031
3032static int __spi_controller_match(struct device *dev, const void *data)
3033{
3034	struct spi_controller *ctlr;
3035	const u16 *bus_num = data;
3036
3037	ctlr = container_of(dev, struct spi_controller, dev);
3038	return ctlr->bus_num == *bus_num;
3039}
3040
3041/**
3042 * spi_busnum_to_master - look up master associated with bus_num
3043 * @bus_num: the master's bus number
3044 * Context: can sleep
3045 *
3046 * This call may be used with devices that are registered after
3047 * arch init time.  It returns a refcounted pointer to the relevant
3048 * spi_controller (which the caller must release), or NULL if there is
3049 * no such master registered.
3050 *
3051 * Return: the SPI master structure on success, else NULL.
3052 */
3053struct spi_controller *spi_busnum_to_master(u16 bus_num)
3054{
3055	struct device		*dev;
3056	struct spi_controller	*ctlr = NULL;
3057
3058	dev = class_find_device(&spi_master_class, NULL, &bus_num,
3059				__spi_controller_match);
3060	if (dev)
3061		ctlr = container_of(dev, struct spi_controller, dev);
3062	/* reference got in class_find_device */
3063	return ctlr;
3064}
3065EXPORT_SYMBOL_GPL(spi_busnum_to_master);
3066
3067/*-------------------------------------------------------------------------*/
3068
3069/* Core methods for SPI resource management */
3070
3071/**
3072 * spi_res_alloc - allocate a spi resource that is life-cycle managed
3073 *                 during the processing of a spi_message while using
3074 *                 spi_transfer_one
3075 * @spi:     the spi device for which we allocate memory
3076 * @release: the release code to execute for this resource
3077 * @size:    size to alloc and return
3078 * @gfp:     GFP allocation flags
3079 *
3080 * Return: the pointer to the allocated data
3081 *
3082 * This may get enhanced in the future to allocate from a memory pool
3083 * of the @spi_device or @spi_controller to avoid repeated allocations.
3084 */
3085void *spi_res_alloc(struct spi_device *spi,
3086		    spi_res_release_t release,
3087		    size_t size, gfp_t gfp)
3088{
3089	struct spi_res *sres;
3090
3091	sres = kzalloc(sizeof(*sres) + size, gfp);
3092	if (!sres)
3093		return NULL;
3094
3095	INIT_LIST_HEAD(&sres->entry);
3096	sres->release = release;
3097
3098	return sres->data;
3099}
3100EXPORT_SYMBOL_GPL(spi_res_alloc);
3101
3102/**
3103 * spi_res_free - free an spi resource
3104 * @res: pointer to the custom data of a resource
3105 *
3106 */
3107void spi_res_free(void *res)
3108{
3109	struct spi_res *sres = container_of(res, struct spi_res, data);
3110
3111	if (!res)
3112		return;
3113
3114	WARN_ON(!list_empty(&sres->entry));
3115	kfree(sres);
3116}
3117EXPORT_SYMBOL_GPL(spi_res_free);
3118
3119/**
3120 * spi_res_add - add a spi_res to the spi_message
3121 * @message: the spi message
3122 * @res:     the spi_resource
3123 */
3124void spi_res_add(struct spi_message *message, void *res)
3125{
3126	struct spi_res *sres = container_of(res, struct spi_res, data);
3127
3128	WARN_ON(!list_empty(&sres->entry));
3129	list_add_tail(&sres->entry, &message->resources);
3130}
3131EXPORT_SYMBOL_GPL(spi_res_add);
3132
3133/**
3134 * spi_res_release - release all spi resources for this message
3135 * @ctlr:  the @spi_controller
3136 * @message: the @spi_message
3137 */
3138void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
3139{
3140	struct spi_res *res, *tmp;
3141
3142	list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
3143		if (res->release)
3144			res->release(ctlr, message, res->data);
3145
3146		list_del(&res->entry);
3147
3148		kfree(res);
3149	}
3150}
3151EXPORT_SYMBOL_GPL(spi_res_release);
3152
3153/*-------------------------------------------------------------------------*/
3154
3155/* Core methods for spi_message alterations */
3156
3157static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3158					    struct spi_message *msg,
3159					    void *res)
3160{
3161	struct spi_replaced_transfers *rxfer = res;
3162	size_t i;
3163
3164	/* call extra callback if requested */
3165	if (rxfer->release)
3166		rxfer->release(ctlr, msg, res);
3167
3168	/* insert replaced transfers back into the message */
3169	list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3170
3171	/* remove the formerly inserted entries */
3172	for (i = 0; i < rxfer->inserted; i++)
3173		list_del(&rxfer->inserted_transfers[i].transfer_list);
3174}
3175
3176/**
3177 * spi_replace_transfers - replace transfers with several transfers
3178 *                         and register change with spi_message.resources
3179 * @msg:           the spi_message we work upon
3180 * @xfer_first:    the first spi_transfer we want to replace
3181 * @remove:        number of transfers to remove
3182 * @insert:        the number of transfers we want to insert instead
3183 * @release:       extra release code necessary in some circumstances
3184 * @extradatasize: extra data to allocate (with alignment guarantees
3185 *                 of struct @spi_transfer)
3186 * @gfp:           gfp flags
3187 *
3188 * Returns: pointer to @spi_replaced_transfers,
3189 *          PTR_ERR(...) in case of errors.
3190 */
3191struct spi_replaced_transfers *spi_replace_transfers(
3192	struct spi_message *msg,
3193	struct spi_transfer *xfer_first,
3194	size_t remove,
3195	size_t insert,
3196	spi_replaced_release_t release,
3197	size_t extradatasize,
3198	gfp_t gfp)
3199{
3200	struct spi_replaced_transfers *rxfer;
3201	struct spi_transfer *xfer;
3202	size_t i;
3203
3204	/* allocate the structure using spi_res */
3205	rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3206			      struct_size(rxfer, inserted_transfers, insert)
3207			      + extradatasize,
3208			      gfp);
3209	if (!rxfer)
3210		return ERR_PTR(-ENOMEM);
3211
3212	/* the release code to invoke before running the generic release */
3213	rxfer->release = release;
3214
3215	/* assign extradata */
3216	if (extradatasize)
3217		rxfer->extradata =
3218			&rxfer->inserted_transfers[insert];
3219
3220	/* init the replaced_transfers list */
3221	INIT_LIST_HEAD(&rxfer->replaced_transfers);
3222
3223	/* assign the list_entry after which we should reinsert
3224	 * the @replaced_transfers - it may be spi_message.messages!
3225	 */
3226	rxfer->replaced_after = xfer_first->transfer_list.prev;
3227
3228	/* remove the requested number of transfers */
3229	for (i = 0; i < remove; i++) {
3230		/* if the entry after replaced_after it is msg->transfers
3231		 * then we have been requested to remove more transfers
3232		 * than are in the list
3233		 */
3234		if (rxfer->replaced_after->next == &msg->transfers) {
3235			dev_err(&msg->spi->dev,
3236				"requested to remove more spi_transfers than are available\n");
3237			/* insert replaced transfers back into the message */
3238			list_splice(&rxfer->replaced_transfers,
3239				    rxfer->replaced_after);
3240
3241			/* free the spi_replace_transfer structure */
3242			spi_res_free(rxfer);
3243
3244			/* and return with an error */
3245			return ERR_PTR(-EINVAL);
3246		}
3247
3248		/* remove the entry after replaced_after from list of
3249		 * transfers and add it to list of replaced_transfers
3250		 */
3251		list_move_tail(rxfer->replaced_after->next,
3252			       &rxfer->replaced_transfers);
3253	}
3254
3255	/* create copy of the given xfer with identical settings
3256	 * based on the first transfer to get removed
3257	 */
3258	for (i = 0; i < insert; i++) {
3259		/* we need to run in reverse order */
3260		xfer = &rxfer->inserted_transfers[insert - 1 - i];
3261
3262		/* copy all spi_transfer data */
3263		memcpy(xfer, xfer_first, sizeof(*xfer));
3264
3265		/* add to list */
3266		list_add(&xfer->transfer_list, rxfer->replaced_after);
3267
3268		/* clear cs_change and delay for all but the last */
3269		if (i) {
3270			xfer->cs_change = false;
3271			xfer->delay.value = 0;
3272		}
3273	}
3274
3275	/* set up inserted */
3276	rxfer->inserted = insert;
3277
3278	/* and register it with spi_res/spi_message */
3279	spi_res_add(msg, rxfer);
3280
3281	return rxfer;
3282}
3283EXPORT_SYMBOL_GPL(spi_replace_transfers);
3284
3285static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3286					struct spi_message *msg,
3287					struct spi_transfer **xferp,
3288					size_t maxsize,
3289					gfp_t gfp)
3290{
3291	struct spi_transfer *xfer = *xferp, *xfers;
3292	struct spi_replaced_transfers *srt;
3293	size_t offset;
3294	size_t count, i;
3295
3296	/* calculate how many we have to replace */
3297	count = DIV_ROUND_UP(xfer->len, maxsize);
3298
3299	/* create replacement */
3300	srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3301	if (IS_ERR(srt))
3302		return PTR_ERR(srt);
3303	xfers = srt->inserted_transfers;
3304
3305	/* now handle each of those newly inserted spi_transfers
3306	 * note that the replacements spi_transfers all are preset
3307	 * to the same values as *xferp, so tx_buf, rx_buf and len
3308	 * are all identical (as well as most others)
3309	 * so we just have to fix up len and the pointers.
3310	 *
3311	 * this also includes support for the depreciated
3312	 * spi_message.is_dma_mapped interface
3313	 */
3314
3315	/* the first transfer just needs the length modified, so we
3316	 * run it outside the loop
3317	 */
3318	xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3319
3320	/* all the others need rx_buf/tx_buf also set */
3321	for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3322		/* update rx_buf, tx_buf and dma */
3323		if (xfers[i].rx_buf)
3324			xfers[i].rx_buf += offset;
3325		if (xfers[i].rx_dma)
3326			xfers[i].rx_dma += offset;
3327		if (xfers[i].tx_buf)
3328			xfers[i].tx_buf += offset;
3329		if (xfers[i].tx_dma)
3330			xfers[i].tx_dma += offset;
3331
3332		/* update length */
3333		xfers[i].len = min(maxsize, xfers[i].len - offset);
3334	}
3335
3336	/* we set up xferp to the last entry we have inserted,
3337	 * so that we skip those already split transfers
3338	 */
3339	*xferp = &xfers[count - 1];
3340
3341	/* increment statistics counters */
3342	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3343				       transfers_split_maxsize);
3344	SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3345				       transfers_split_maxsize);
3346
3347	return 0;
3348}
3349
3350/**
3351 * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3352 *                               when an individual transfer exceeds a
3353 *                               certain size
3354 * @ctlr:    the @spi_controller for this transfer
3355 * @msg:   the @spi_message to transform
3356 * @maxsize:  the maximum when to apply this
3357 * @gfp: GFP allocation flags
3358 *
3359 * Return: status of transformation
3360 */
3361int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3362				struct spi_message *msg,
3363				size_t maxsize,
3364				gfp_t gfp)
3365{
3366	struct spi_transfer *xfer;
3367	int ret;
3368
3369	/* iterate over the transfer_list,
3370	 * but note that xfer is advanced to the last transfer inserted
3371	 * to avoid checking sizes again unnecessarily (also xfer does
3372	 * potentiall belong to a different list by the time the
3373	 * replacement has happened
3374	 */
3375	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3376		if (xfer->len > maxsize) {
3377			ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3378							   maxsize, gfp);
3379			if (ret)
3380				return ret;
3381		}
3382	}
3383
3384	return 0;
3385}
3386EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3387
3388/*-------------------------------------------------------------------------*/
3389
3390/* Core methods for SPI controller protocol drivers.  Some of the
3391 * other core methods are currently defined as inline functions.
3392 */
3393
3394static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3395					u8 bits_per_word)
3396{
3397	if (ctlr->bits_per_word_mask) {
3398		/* Only 32 bits fit in the mask */
3399		if (bits_per_word > 32)
3400			return -EINVAL;
3401		if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3402			return -EINVAL;
3403	}
3404
3405	return 0;
3406}
3407
3408/**
3409 * spi_setup - setup SPI mode and clock rate
3410 * @spi: the device whose settings are being modified
3411 * Context: can sleep, and no requests are queued to the device
3412 *
3413 * SPI protocol drivers may need to update the transfer mode if the
3414 * device doesn't work with its default.  They may likewise need
3415 * to update clock rates or word sizes from initial values.  This function
3416 * changes those settings, and must be called from a context that can sleep.
3417 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3418 * effect the next time the device is selected and data is transferred to
3419 * or from it.  When this function returns, the spi device is deselected.
3420 *
3421 * Note that this call will fail if the protocol driver specifies an option
3422 * that the underlying controller or its driver does not support.  For
3423 * example, not all hardware supports wire transfers using nine bit words,
3424 * LSB-first wire encoding, or active-high chipselects.
3425 *
3426 * Return: zero on success, else a negative error code.
3427 */
3428int spi_setup(struct spi_device *spi)
3429{
3430	unsigned	bad_bits, ugly_bits;
3431	int		status;
3432
3433	/*
3434	 * check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3435	 * are set at the same time
3436	 */
3437	if ((hweight_long(spi->mode &
3438		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3439	    (hweight_long(spi->mode &
3440		(SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3441		dev_err(&spi->dev,
3442		"setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3443		return -EINVAL;
3444	}
3445	/* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
3446	 */
3447	if ((spi->mode & SPI_3WIRE) && (spi->mode &
3448		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3449		 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3450		return -EINVAL;
3451	/* help drivers fail *cleanly* when they need options
3452	 * that aren't supported with their current controller
3453	 * SPI_CS_WORD has a fallback software implementation,
3454	 * so it is ignored here.
3455	 */
3456	bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3457				 SPI_NO_TX | SPI_NO_RX);
3458	/* nothing prevents from working with active-high CS in case if it
3459	 * is driven by GPIO.
3460	 */
3461	if (gpio_is_valid(spi->cs_gpio))
3462		bad_bits &= ~SPI_CS_HIGH;
3463	ugly_bits = bad_bits &
3464		    (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3465		     SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3466	if (ugly_bits) {
3467		dev_warn(&spi->dev,
3468			 "setup: ignoring unsupported mode bits %x\n",
3469			 ugly_bits);
3470		spi->mode &= ~ugly_bits;
3471		bad_bits &= ~ugly_bits;
3472	}
3473	if (bad_bits) {
3474		dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3475			bad_bits);
3476		return -EINVAL;
3477	}
3478
3479	if (!spi->bits_per_word)
3480		spi->bits_per_word = 8;
3481
3482	status = __spi_validate_bits_per_word(spi->controller,
3483					      spi->bits_per_word);
3484	if (status)
3485		return status;
3486
3487	if (spi->controller->max_speed_hz &&
3488	    (!spi->max_speed_hz ||
3489	     spi->max_speed_hz > spi->controller->max_speed_hz))
3490		spi->max_speed_hz = spi->controller->max_speed_hz;
3491
3492	mutex_lock(&spi->controller->io_mutex);
3493
3494	if (spi->controller->setup) {
3495		status = spi->controller->setup(spi);
3496		if (status) {
3497			mutex_unlock(&spi->controller->io_mutex);
3498			dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3499				status);
3500			return status;
3501		}
3502	}
3503
3504	if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3505		status = pm_runtime_get_sync(spi->controller->dev.parent);
3506		if (status < 0) {
3507			mutex_unlock(&spi->controller->io_mutex);
3508			pm_runtime_put_noidle(spi->controller->dev.parent);
3509			dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3510				status);
3511			return status;
3512		}
3513
3514		/*
3515		 * We do not want to return positive value from pm_runtime_get,
3516		 * there are many instances of devices calling spi_setup() and
3517		 * checking for a non-zero return value instead of a negative
3518		 * return value.
3519		 */
3520		status = 0;
3521
3522		spi_set_cs(spi, false, true);
3523		pm_runtime_mark_last_busy(spi->controller->dev.parent);
3524		pm_runtime_put_autosuspend(spi->controller->dev.parent);
3525	} else {
3526		spi_set_cs(spi, false, true);
3527	}
3528
3529	mutex_unlock(&spi->controller->io_mutex);
3530
3531	if (spi->rt && !spi->controller->rt) {
3532		spi->controller->rt = true;
3533		spi_set_thread_rt(spi->controller);
3534	}
3535
3536	trace_spi_setup(spi, status);
3537
3538	dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3539			spi->mode & SPI_MODE_X_MASK,
3540			(spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3541			(spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3542			(spi->mode & SPI_3WIRE) ? "3wire, " : "",
3543			(spi->mode & SPI_LOOP) ? "loopback, " : "",
3544			spi->bits_per_word, spi->max_speed_hz,
3545			status);
3546
3547	return status;
3548}
3549EXPORT_SYMBOL_GPL(spi_setup);
3550
3551static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
3552				       struct spi_device *spi)
3553{
3554	int delay1, delay2;
3555
3556	delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
3557	if (delay1 < 0)
3558		return delay1;
3559
3560	delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
3561	if (delay2 < 0)
3562		return delay2;
3563
3564	if (delay1 < delay2)
3565		memcpy(&xfer->word_delay, &spi->word_delay,
3566		       sizeof(xfer->word_delay));
3567
3568	return 0;
3569}
3570
3571static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3572{
3573	struct spi_controller *ctlr = spi->controller;
3574	struct spi_transfer *xfer;
3575	int w_size;
3576
3577	if (list_empty(&message->transfers))
3578		return -EINVAL;
3579
3580	/* If an SPI controller does not support toggling the CS line on each
3581	 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3582	 * for the CS line, we can emulate the CS-per-word hardware function by
3583	 * splitting transfers into one-word transfers and ensuring that
3584	 * cs_change is set for each transfer.
3585	 */
3586	if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3587					  spi->cs_gpiod ||
3588					  gpio_is_valid(spi->cs_gpio))) {
3589		size_t maxsize;
3590		int ret;
3591
3592		maxsize = (spi->bits_per_word + 7) / 8;
3593
3594		/* spi_split_transfers_maxsize() requires message->spi */
3595		message->spi = spi;
3596
3597		ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3598						  GFP_KERNEL);
3599		if (ret)
3600			return ret;
3601
3602		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3603			/* don't change cs_change on the last entry in the list */
3604			if (list_is_last(&xfer->transfer_list, &message->transfers))
3605				break;
3606			xfer->cs_change = 1;
3607		}
3608	}
3609
3610	/* Half-duplex links include original MicroWire, and ones with
3611	 * only one data pin like SPI_3WIRE (switches direction) or where
3612	 * either MOSI or MISO is missing.  They can also be caused by
3613	 * software limitations.
3614	 */
3615	if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3616	    (spi->mode & SPI_3WIRE)) {
3617		unsigned flags = ctlr->flags;
 
3618
3619		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3620			if (xfer->rx_buf && xfer->tx_buf)
3621				return -EINVAL;
3622			if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3623				return -EINVAL;
3624			if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3625				return -EINVAL;
3626		}
3627	}
3628
3629	/**
3630	 * Set transfer bits_per_word and max speed as spi device default if
3631	 * it is not set for this transfer.
3632	 * Set transfer tx_nbits and rx_nbits as single transfer default
3633	 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3634	 * Ensure transfer word_delay is at least as long as that required by
3635	 * device itself.
3636	 */
3637	message->frame_length = 0;
3638	list_for_each_entry(xfer, &message->transfers, transfer_list) {
3639		xfer->effective_speed_hz = 0;
3640		message->frame_length += xfer->len;
3641		if (!xfer->bits_per_word)
3642			xfer->bits_per_word = spi->bits_per_word;
3643
3644		if (!xfer->speed_hz)
3645			xfer->speed_hz = spi->max_speed_hz;
3646
3647		if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3648			xfer->speed_hz = ctlr->max_speed_hz;
3649
3650		if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3651			return -EINVAL;
3652
3653		/*
3654		 * SPI transfer length should be multiple of SPI word size
3655		 * where SPI word size should be power-of-two multiple
3656		 */
3657		if (xfer->bits_per_word <= 8)
3658			w_size = 1;
3659		else if (xfer->bits_per_word <= 16)
3660			w_size = 2;
3661		else
3662			w_size = 4;
3663
3664		/* No partial transfers accepted */
3665		if (xfer->len % w_size)
3666			return -EINVAL;
3667
3668		if (xfer->speed_hz && ctlr->min_speed_hz &&
3669		    xfer->speed_hz < ctlr->min_speed_hz)
3670			return -EINVAL;
3671
3672		if (xfer->tx_buf && !xfer->tx_nbits)
3673			xfer->tx_nbits = SPI_NBITS_SINGLE;
3674		if (xfer->rx_buf && !xfer->rx_nbits)
3675			xfer->rx_nbits = SPI_NBITS_SINGLE;
3676		/* check transfer tx/rx_nbits:
3677		 * 1. check the value matches one of single, dual and quad
3678		 * 2. check tx/rx_nbits match the mode in spi_device
3679		 */
3680		if (xfer->tx_buf) {
3681			if (spi->mode & SPI_NO_TX)
3682				return -EINVAL;
3683			if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3684				xfer->tx_nbits != SPI_NBITS_DUAL &&
3685				xfer->tx_nbits != SPI_NBITS_QUAD)
3686				return -EINVAL;
3687			if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3688				!(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3689				return -EINVAL;
3690			if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3691				!(spi->mode & SPI_TX_QUAD))
3692				return -EINVAL;
3693		}
3694		/* check transfer rx_nbits */
3695		if (xfer->rx_buf) {
3696			if (spi->mode & SPI_NO_RX)
3697				return -EINVAL;
3698			if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3699				xfer->rx_nbits != SPI_NBITS_DUAL &&
3700				xfer->rx_nbits != SPI_NBITS_QUAD)
3701				return -EINVAL;
3702			if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3703				!(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3704				return -EINVAL;
3705			if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3706				!(spi->mode & SPI_RX_QUAD))
3707				return -EINVAL;
3708		}
3709
3710		if (_spi_xfer_word_delay_update(xfer, spi))
3711			return -EINVAL;
3712	}
3713
3714	message->status = -EINPROGRESS;
3715
3716	return 0;
3717}
3718
3719static int __spi_async(struct spi_device *spi, struct spi_message *message)
3720{
3721	struct spi_controller *ctlr = spi->controller;
3722	struct spi_transfer *xfer;
3723
3724	/*
3725	 * Some controllers do not support doing regular SPI transfers. Return
3726	 * ENOTSUPP when this is the case.
3727	 */
3728	if (!ctlr->transfer)
3729		return -ENOTSUPP;
3730
3731	message->spi = spi;
3732
3733	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3734	SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3735
3736	trace_spi_message_submit(message);
3737
3738	if (!ctlr->ptp_sts_supported) {
3739		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3740			xfer->ptp_sts_word_pre = 0;
3741			ptp_read_system_prets(xfer->ptp_sts);
3742		}
3743	}
3744
3745	return ctlr->transfer(spi, message);
3746}
3747
3748/**
3749 * spi_async - asynchronous SPI transfer
3750 * @spi: device with which data will be exchanged
3751 * @message: describes the data transfers, including completion callback
3752 * Context: any (irqs may be blocked, etc)
3753 *
3754 * This call may be used in_irq and other contexts which can't sleep,
3755 * as well as from task contexts which can sleep.
3756 *
3757 * The completion callback is invoked in a context which can't sleep.
3758 * Before that invocation, the value of message->status is undefined.
3759 * When the callback is issued, message->status holds either zero (to
3760 * indicate complete success) or a negative error code.  After that
3761 * callback returns, the driver which issued the transfer request may
3762 * deallocate the associated memory; it's no longer in use by any SPI
3763 * core or controller driver code.
3764 *
3765 * Note that although all messages to a spi_device are handled in
3766 * FIFO order, messages may go to different devices in other orders.
3767 * Some device might be higher priority, or have various "hard" access
3768 * time requirements, for example.
3769 *
3770 * On detection of any fault during the transfer, processing of
3771 * the entire message is aborted, and the device is deselected.
3772 * Until returning from the associated message completion callback,
3773 * no other spi_message queued to that device will be processed.
3774 * (This rule applies equally to all the synchronous transfer calls,
3775 * which are wrappers around this core asynchronous primitive.)
3776 *
3777 * Return: zero on success, else a negative error code.
3778 */
3779int spi_async(struct spi_device *spi, struct spi_message *message)
3780{
3781	struct spi_controller *ctlr = spi->controller;
3782	int ret;
3783	unsigned long flags;
3784
3785	ret = __spi_validate(spi, message);
3786	if (ret != 0)
3787		return ret;
3788
3789	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3790
3791	if (ctlr->bus_lock_flag)
3792		ret = -EBUSY;
3793	else
3794		ret = __spi_async(spi, message);
3795
3796	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3797
3798	return ret;
3799}
3800EXPORT_SYMBOL_GPL(spi_async);
3801
3802/**
3803 * spi_async_locked - version of spi_async with exclusive bus usage
3804 * @spi: device with which data will be exchanged
3805 * @message: describes the data transfers, including completion callback
3806 * Context: any (irqs may be blocked, etc)
3807 *
3808 * This call may be used in_irq and other contexts which can't sleep,
3809 * as well as from task contexts which can sleep.
3810 *
3811 * The completion callback is invoked in a context which can't sleep.
3812 * Before that invocation, the value of message->status is undefined.
3813 * When the callback is issued, message->status holds either zero (to
3814 * indicate complete success) or a negative error code.  After that
3815 * callback returns, the driver which issued the transfer request may
3816 * deallocate the associated memory; it's no longer in use by any SPI
3817 * core or controller driver code.
3818 *
3819 * Note that although all messages to a spi_device are handled in
3820 * FIFO order, messages may go to different devices in other orders.
3821 * Some device might be higher priority, or have various "hard" access
3822 * time requirements, for example.
3823 *
3824 * On detection of any fault during the transfer, processing of
3825 * the entire message is aborted, and the device is deselected.
3826 * Until returning from the associated message completion callback,
3827 * no other spi_message queued to that device will be processed.
3828 * (This rule applies equally to all the synchronous transfer calls,
3829 * which are wrappers around this core asynchronous primitive.)
3830 *
3831 * Return: zero on success, else a negative error code.
3832 */
3833int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3834{
3835	struct spi_controller *ctlr = spi->controller;
3836	int ret;
3837	unsigned long flags;
3838
3839	ret = __spi_validate(spi, message);
3840	if (ret != 0)
3841		return ret;
3842
3843	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3844
3845	ret = __spi_async(spi, message);
3846
3847	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3848
3849	return ret;
3850
3851}
3852EXPORT_SYMBOL_GPL(spi_async_locked);
3853
 
3854/*-------------------------------------------------------------------------*/
3855
3856/* Utility methods for SPI protocol drivers, layered on
3857 * top of the core.  Some other utility methods are defined as
3858 * inline functions.
3859 */
3860
3861static void spi_complete(void *arg)
3862{
3863	complete(arg);
3864}
3865
3866static int __spi_sync(struct spi_device *spi, struct spi_message *message)
 
3867{
3868	DECLARE_COMPLETION_ONSTACK(done);
3869	int status;
3870	struct spi_controller *ctlr = spi->controller;
3871	unsigned long flags;
3872
3873	status = __spi_validate(spi, message);
3874	if (status != 0)
3875		return status;
3876
3877	message->complete = spi_complete;
3878	message->context = &done;
3879	message->spi = spi;
3880
3881	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3882	SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3883
3884	/* If we're not using the legacy transfer method then we will
3885	 * try to transfer in the calling context so special case.
3886	 * This code would be less tricky if we could remove the
3887	 * support for driver implemented message queues.
3888	 */
3889	if (ctlr->transfer == spi_queued_transfer) {
3890		spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3891
3892		trace_spi_message_submit(message);
3893
3894		status = __spi_queued_transfer(spi, message, false);
3895
3896		spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3897	} else {
3898		status = spi_async_locked(spi, message);
3899	}
3900
3901	if (status == 0) {
3902		/* Push out the messages in the calling context if we
3903		 * can.
3904		 */
3905		if (ctlr->transfer == spi_queued_transfer) {
3906			SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3907						       spi_sync_immediate);
3908			SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3909						       spi_sync_immediate);
3910			__spi_pump_messages(ctlr, false);
3911		}
3912
3913		wait_for_completion(&done);
3914		status = message->status;
3915	}
3916	message->context = NULL;
3917	return status;
3918}
3919
3920/**
3921 * spi_sync - blocking/synchronous SPI data transfers
3922 * @spi: device with which data will be exchanged
3923 * @message: describes the data transfers
3924 * Context: can sleep
3925 *
3926 * This call may only be used from a context that may sleep.  The sleep
3927 * is non-interruptible, and has no timeout.  Low-overhead controller
3928 * drivers may DMA directly into and out of the message buffers.
3929 *
3930 * Note that the SPI device's chip select is active during the message,
3931 * and then is normally disabled between messages.  Drivers for some
3932 * frequently-used devices may want to minimize costs of selecting a chip,
3933 * by leaving it selected in anticipation that the next message will go
3934 * to the same chip.  (That may increase power usage.)
3935 *
3936 * Also, the caller is guaranteeing that the memory associated with the
3937 * message will not be freed before this call returns.
3938 *
3939 * Return: zero on success, else a negative error code.
3940 */
3941int spi_sync(struct spi_device *spi, struct spi_message *message)
3942{
3943	int ret;
3944
3945	mutex_lock(&spi->controller->bus_lock_mutex);
3946	ret = __spi_sync(spi, message);
3947	mutex_unlock(&spi->controller->bus_lock_mutex);
3948
3949	return ret;
3950}
3951EXPORT_SYMBOL_GPL(spi_sync);
3952
3953/**
3954 * spi_sync_locked - version of spi_sync with exclusive bus usage
3955 * @spi: device with which data will be exchanged
3956 * @message: describes the data transfers
3957 * Context: can sleep
3958 *
3959 * This call may only be used from a context that may sleep.  The sleep
3960 * is non-interruptible, and has no timeout.  Low-overhead controller
3961 * drivers may DMA directly into and out of the message buffers.
3962 *
3963 * This call should be used by drivers that require exclusive access to the
3964 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3965 * be released by a spi_bus_unlock call when the exclusive access is over.
3966 *
3967 * Return: zero on success, else a negative error code.
3968 */
3969int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3970{
3971	return __spi_sync(spi, message);
3972}
3973EXPORT_SYMBOL_GPL(spi_sync_locked);
3974
3975/**
3976 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
3977 * @ctlr: SPI bus master that should be locked for exclusive bus access
3978 * Context: can sleep
3979 *
3980 * This call may only be used from a context that may sleep.  The sleep
3981 * is non-interruptible, and has no timeout.
3982 *
3983 * This call should be used by drivers that require exclusive access to the
3984 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3985 * exclusive access is over. Data transfer must be done by spi_sync_locked
3986 * and spi_async_locked calls when the SPI bus lock is held.
3987 *
3988 * Return: always zero.
3989 */
3990int spi_bus_lock(struct spi_controller *ctlr)
3991{
3992	unsigned long flags;
3993
3994	mutex_lock(&ctlr->bus_lock_mutex);
3995
3996	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3997	ctlr->bus_lock_flag = 1;
3998	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3999
4000	/* mutex remains locked until spi_bus_unlock is called */
4001
4002	return 0;
4003}
4004EXPORT_SYMBOL_GPL(spi_bus_lock);
4005
4006/**
4007 * spi_bus_unlock - release the lock for exclusive SPI bus usage
4008 * @ctlr: SPI bus master that was locked for exclusive bus access
4009 * Context: can sleep
4010 *
4011 * This call may only be used from a context that may sleep.  The sleep
4012 * is non-interruptible, and has no timeout.
4013 *
4014 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
4015 * call.
4016 *
4017 * Return: always zero.
4018 */
4019int spi_bus_unlock(struct spi_controller *ctlr)
4020{
4021	ctlr->bus_lock_flag = 0;
4022
4023	mutex_unlock(&ctlr->bus_lock_mutex);
4024
4025	return 0;
4026}
4027EXPORT_SYMBOL_GPL(spi_bus_unlock);
4028
4029/* portable code must never pass more than 32 bytes */
4030#define	SPI_BUFSIZ	max(32, SMP_CACHE_BYTES)
4031
4032static u8	*buf;
4033
4034/**
4035 * spi_write_then_read - SPI synchronous write followed by read
4036 * @spi: device with which data will be exchanged
4037 * @txbuf: data to be written (need not be dma-safe)
4038 * @n_tx: size of txbuf, in bytes
4039 * @rxbuf: buffer into which data will be read (need not be dma-safe)
4040 * @n_rx: size of rxbuf, in bytes
4041 * Context: can sleep
4042 *
4043 * This performs a half duplex MicroWire style transaction with the
4044 * device, sending txbuf and then reading rxbuf.  The return value
4045 * is zero for success, else a negative errno status code.
4046 * This call may only be used from a context that may sleep.
4047 *
4048 * Parameters to this routine are always copied using a small buffer.
 
4049 * Performance-sensitive or bulk transfer code should instead use
4050 * spi_{async,sync}() calls with dma-safe buffers.
4051 *
4052 * Return: zero on success, else a negative error code.
4053 */
4054int spi_write_then_read(struct spi_device *spi,
4055		const void *txbuf, unsigned n_tx,
4056		void *rxbuf, unsigned n_rx)
4057{
4058	static DEFINE_MUTEX(lock);
4059
4060	int			status;
4061	struct spi_message	message;
4062	struct spi_transfer	x[2];
4063	u8			*local_buf;
4064
4065	/* Use preallocated DMA-safe buffer if we can.  We can't avoid
4066	 * copying here, (as a pure convenience thing), but we can
4067	 * keep heap costs out of the hot path unless someone else is
4068	 * using the pre-allocated buffer or the transfer is too large.
4069	 */
4070	if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4071		local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4072				    GFP_KERNEL | GFP_DMA);
4073		if (!local_buf)
4074			return -ENOMEM;
4075	} else {
4076		local_buf = buf;
4077	}
4078
4079	spi_message_init(&message);
4080	memset(x, 0, sizeof(x));
4081	if (n_tx) {
4082		x[0].len = n_tx;
4083		spi_message_add_tail(&x[0], &message);
4084	}
4085	if (n_rx) {
4086		x[1].len = n_rx;
4087		spi_message_add_tail(&x[1], &message);
4088	}
4089
 
 
 
 
 
 
 
 
4090	memcpy(local_buf, txbuf, n_tx);
4091	x[0].tx_buf = local_buf;
4092	x[1].rx_buf = local_buf + n_tx;
4093
4094	/* do the i/o */
4095	status = spi_sync(spi, &message);
4096	if (status == 0)
4097		memcpy(rxbuf, x[1].rx_buf, n_rx);
4098
4099	if (x[0].tx_buf == buf)
4100		mutex_unlock(&lock);
4101	else
4102		kfree(local_buf);
4103
4104	return status;
4105}
4106EXPORT_SYMBOL_GPL(spi_write_then_read);
4107
4108/*-------------------------------------------------------------------------*/
4109
4110#if IS_ENABLED(CONFIG_OF)
4111/* must call put_device() when done with returned spi_device device */
4112struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4113{
4114	struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4115
4116	return dev ? to_spi_device(dev) : NULL;
4117}
4118EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
4119#endif /* IS_ENABLED(CONFIG_OF) */
4120
4121#if IS_ENABLED(CONFIG_OF_DYNAMIC)
4122/* the spi controllers are not using spi_bus, so we find it with another way */
4123static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4124{
4125	struct device *dev;
4126
4127	dev = class_find_device_by_of_node(&spi_master_class, node);
4128	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4129		dev = class_find_device_by_of_node(&spi_slave_class, node);
4130	if (!dev)
4131		return NULL;
4132
4133	/* reference got in class_find_device */
4134	return container_of(dev, struct spi_controller, dev);
4135}
4136
4137static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4138			 void *arg)
4139{
4140	struct of_reconfig_data *rd = arg;
4141	struct spi_controller *ctlr;
4142	struct spi_device *spi;
4143
4144	switch (of_reconfig_get_state_change(action, arg)) {
4145	case OF_RECONFIG_CHANGE_ADD:
4146		ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4147		if (ctlr == NULL)
4148			return NOTIFY_OK;	/* not for us */
4149
4150		if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4151			put_device(&ctlr->dev);
4152			return NOTIFY_OK;
4153		}
4154
4155		spi = of_register_spi_device(ctlr, rd->dn);
4156		put_device(&ctlr->dev);
4157
4158		if (IS_ERR(spi)) {
4159			pr_err("%s: failed to create for '%pOF'\n",
4160					__func__, rd->dn);
4161			of_node_clear_flag(rd->dn, OF_POPULATED);
4162			return notifier_from_errno(PTR_ERR(spi));
4163		}
4164		break;
4165
4166	case OF_RECONFIG_CHANGE_REMOVE:
4167		/* already depopulated? */
4168		if (!of_node_check_flag(rd->dn, OF_POPULATED))
4169			return NOTIFY_OK;
4170
4171		/* find our device by node */
4172		spi = of_find_spi_device_by_node(rd->dn);
4173		if (spi == NULL)
4174			return NOTIFY_OK;	/* no? not meant for us */
4175
4176		/* unregister takes one ref away */
4177		spi_unregister_device(spi);
4178
4179		/* and put the reference of the find */
4180		put_device(&spi->dev);
4181		break;
4182	}
4183
4184	return NOTIFY_OK;
4185}
4186
4187static struct notifier_block spi_of_notifier = {
4188	.notifier_call = of_spi_notify,
4189};
4190#else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4191extern struct notifier_block spi_of_notifier;
4192#endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4193
4194#if IS_ENABLED(CONFIG_ACPI)
4195static int spi_acpi_controller_match(struct device *dev, const void *data)
4196{
4197	return ACPI_COMPANION(dev->parent) == data;
4198}
4199
4200static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4201{
4202	struct device *dev;
4203
4204	dev = class_find_device(&spi_master_class, NULL, adev,
4205				spi_acpi_controller_match);
4206	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4207		dev = class_find_device(&spi_slave_class, NULL, adev,
4208					spi_acpi_controller_match);
4209	if (!dev)
4210		return NULL;
4211
4212	return container_of(dev, struct spi_controller, dev);
4213}
4214
4215static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4216{
4217	struct device *dev;
4218
4219	dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4220	return to_spi_device(dev);
4221}
4222
4223static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4224			   void *arg)
4225{
4226	struct acpi_device *adev = arg;
4227	struct spi_controller *ctlr;
4228	struct spi_device *spi;
4229
4230	switch (value) {
4231	case ACPI_RECONFIG_DEVICE_ADD:
4232		ctlr = acpi_spi_find_controller_by_adev(adev->parent);
4233		if (!ctlr)
4234			break;
4235
4236		acpi_register_spi_device(ctlr, adev);
4237		put_device(&ctlr->dev);
4238		break;
4239	case ACPI_RECONFIG_DEVICE_REMOVE:
4240		if (!acpi_device_enumerated(adev))
4241			break;
4242
4243		spi = acpi_spi_find_device_by_adev(adev);
4244		if (!spi)
4245			break;
4246
4247		spi_unregister_device(spi);
4248		put_device(&spi->dev);
4249		break;
4250	}
4251
4252	return NOTIFY_OK;
4253}
4254
4255static struct notifier_block spi_acpi_notifier = {
4256	.notifier_call = acpi_spi_notify,
4257};
4258#else
4259extern struct notifier_block spi_acpi_notifier;
4260#endif
4261
4262static int __init spi_init(void)
4263{
4264	int	status;
4265
4266	buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4267	if (!buf) {
4268		status = -ENOMEM;
4269		goto err0;
4270	}
4271
4272	status = bus_register(&spi_bus_type);
4273	if (status < 0)
4274		goto err1;
4275
4276	status = class_register(&spi_master_class);
4277	if (status < 0)
4278		goto err2;
4279
4280	if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4281		status = class_register(&spi_slave_class);
4282		if (status < 0)
4283			goto err3;
4284	}
4285
4286	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4287		WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4288	if (IS_ENABLED(CONFIG_ACPI))
4289		WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4290
4291	return 0;
4292
4293err3:
4294	class_unregister(&spi_master_class);
4295err2:
4296	bus_unregister(&spi_bus_type);
4297err1:
4298	kfree(buf);
4299	buf = NULL;
4300err0:
4301	return status;
4302}
4303
4304/* board_info is normally registered in arch_initcall(),
4305 * but even essential drivers wait till later
4306 *
4307 * REVISIT only boardinfo really needs static linking. the rest (device and
4308 * driver registration) _could_ be dynamically linked (modular) ... costs
4309 * include needing to have boardinfo data structures be much more public.
4310 */
4311postcore_initcall(spi_init);