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