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