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