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