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