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 desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE); 1353 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len); 1354 } else if (virt_addr_valid(buf)) { 1355 desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len); 1356 sgs = DIV_ROUND_UP(len, desc_len); 1357 } else { 1358 return -EINVAL; 1359 } 1360 1361 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL); 1362 if (ret != 0) 1363 return ret; 1364 1365 sg = &sgt->sgl[0]; 1366 for (i = 0; i < sgs; i++) { 1367 1368 if (vmalloced_buf || kmap_buf) { 1369 /* 1370 * Next scatterlist entry size is the minimum between 1371 * the desc_len and the remaining buffer length that 1372 * fits in a page. 1373 */ 1374 min = min_t(size_t, desc_len, 1375 min_t(size_t, len, 1376 PAGE_SIZE - offset_in_page(buf))); 1377 if (vmalloced_buf) 1378 vm_page = vmalloc_to_page(buf); 1379 else 1380 vm_page = kmap_to_page(buf); 1381 if (!vm_page) { 1382 sg_free_table(sgt); 1383 return -ENOMEM; 1384 } 1385 sg_set_page(sg, vm_page, 1386 min, offset_in_page(buf)); 1387 } else { 1388 min = min_t(size_t, len, desc_len); 1389 sg_buf = buf; 1390 sg_set_buf(sg, sg_buf, min); 1391 } 1392 1393 buf += min; 1394 len -= min; 1395 sg = sg_next(sg); 1396 } 1397 1398 ret = dma_map_sgtable(dev, sgt, dir, attrs); 1399 if (ret < 0) { 1400 sg_free_table(sgt); 1401 return ret; 1402 } 1403 1404 return 0; 1405 } 1406 1407 int spi_map_buf(struct spi_controller *ctlr, struct device *dev, 1408 struct sg_table *sgt, void *buf, size_t len, 1409 enum dma_data_direction dir) 1410 { 1411 return spi_map_buf_attrs(ctlr, dev, sgt, buf, len, dir, 0); 1412 } 1413 1414 static void spi_unmap_buf_attrs(struct spi_controller *ctlr, 1415 struct device *dev, struct sg_table *sgt, 1416 enum dma_data_direction dir, 1417 unsigned long attrs) 1418 { 1419 dma_unmap_sgtable(dev, sgt, dir, attrs); 1420 sg_free_table(sgt); 1421 sgt->orig_nents = 0; 1422 sgt->nents = 0; 1423 } 1424 1425 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev, 1426 struct sg_table *sgt, enum dma_data_direction dir) 1427 { 1428 spi_unmap_buf_attrs(ctlr, dev, sgt, dir, 0); 1429 } 1430 1431 VISIBLE_IF_KUNIT 1432 int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg) 1433 { 1434 struct device *rx_dev = ctlr->cur_rx_dma_dev; 1435 struct device *tx_dev = ctlr->cur_tx_dma_dev; 1436 struct spi_transfer *xfer; 1437 1438 list_for_each_entry(xfer, &msg->transfers, transfer_list) { 1439 /* The sync has already been done after each transfer. */ 1440 unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC; 1441 1442 if (xfer->rx_sg_mapped) 1443 spi_unmap_buf_attrs(ctlr, rx_dev, &xfer->rx_sg, 1444 DMA_FROM_DEVICE, attrs); 1445 xfer->rx_sg_mapped = false; 1446 1447 if (xfer->tx_sg_mapped) 1448 spi_unmap_buf_attrs(ctlr, tx_dev, &xfer->tx_sg, 1449 DMA_TO_DEVICE, attrs); 1450 xfer->tx_sg_mapped = false; 1451 } 1452 1453 return 0; 1454 } 1455 EXPORT_SYMBOL_IF_KUNIT(__spi_unmap_msg); 1456 1457 VISIBLE_IF_KUNIT 1458 int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg) 1459 { 1460 struct device *tx_dev, *rx_dev; 1461 struct spi_transfer *xfer; 1462 int ret; 1463 1464 if (!ctlr->can_dma) 1465 return 0; 1466 1467 if (ctlr->dma_tx) 1468 tx_dev = dmaengine_get_dma_device(ctlr->dma_tx); 1469 else if (ctlr->dma_map_dev) 1470 tx_dev = ctlr->dma_map_dev; 1471 else 1472 tx_dev = ctlr->dev.parent; 1473 1474 if (ctlr->dma_rx) 1475 rx_dev = dmaengine_get_dma_device(ctlr->dma_rx); 1476 else if (ctlr->dma_map_dev) 1477 rx_dev = ctlr->dma_map_dev; 1478 else 1479 rx_dev = ctlr->dev.parent; 1480 1481 /* 1482 * Store the devices before mapping so partial failures can be unwound 1483 * with the device that created each mapping. 1484 */ 1485 ctlr->cur_tx_dma_dev = tx_dev; 1486 ctlr->cur_rx_dma_dev = rx_dev; 1487 1488 list_for_each_entry(xfer, &msg->transfers, transfer_list) { 1489 /* The sync is done before each transfer. */ 1490 unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC; 1491 1492 if (!ctlr->can_dma(ctlr, msg->spi, xfer)) 1493 continue; 1494 1495 if (xfer->tx_buf != NULL) { 1496 ret = spi_map_buf_attrs(ctlr, tx_dev, &xfer->tx_sg, 1497 (void *)xfer->tx_buf, 1498 xfer->len, DMA_TO_DEVICE, 1499 attrs); 1500 if (ret) 1501 goto unwind; 1502 1503 xfer->tx_sg_mapped = true; 1504 } 1505 1506 if (xfer->rx_buf != NULL) { 1507 ret = spi_map_buf_attrs(ctlr, rx_dev, &xfer->rx_sg, 1508 xfer->rx_buf, xfer->len, 1509 DMA_FROM_DEVICE, attrs); 1510 if (ret) 1511 goto unwind; 1512 1513 xfer->rx_sg_mapped = true; 1514 } 1515 } 1516 1517 return 0; 1518 1519 unwind: 1520 __spi_unmap_msg(ctlr, msg); 1521 1522 return ret; 1523 } 1524 EXPORT_SYMBOL_IF_KUNIT(__spi_map_msg); 1525 1526 static void spi_dma_sync_for_device(struct spi_controller *ctlr, 1527 struct spi_transfer *xfer) 1528 { 1529 struct device *rx_dev = ctlr->cur_rx_dma_dev; 1530 struct device *tx_dev = ctlr->cur_tx_dma_dev; 1531 1532 if (xfer->tx_sg_mapped) 1533 dma_sync_sgtable_for_device(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE); 1534 if (xfer->rx_sg_mapped) 1535 dma_sync_sgtable_for_device(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE); 1536 } 1537 1538 static void spi_dma_sync_for_cpu(struct spi_controller *ctlr, 1539 struct spi_transfer *xfer) 1540 { 1541 struct device *rx_dev = ctlr->cur_rx_dma_dev; 1542 struct device *tx_dev = ctlr->cur_tx_dma_dev; 1543 1544 if (xfer->rx_sg_mapped) 1545 dma_sync_sgtable_for_cpu(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE); 1546 if (xfer->tx_sg_mapped) 1547 dma_sync_sgtable_for_cpu(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE); 1548 } 1549 #else /* !CONFIG_HAS_DMA */ 1550 static inline int __spi_map_msg(struct spi_controller *ctlr, 1551 struct spi_message *msg) 1552 { 1553 return 0; 1554 } 1555 1556 static inline int __spi_unmap_msg(struct spi_controller *ctlr, 1557 struct spi_message *msg) 1558 { 1559 return 0; 1560 } 1561 1562 static void spi_dma_sync_for_device(struct spi_controller *ctrl, 1563 struct spi_transfer *xfer) 1564 { 1565 } 1566 1567 static void spi_dma_sync_for_cpu(struct spi_controller *ctrl, 1568 struct spi_transfer *xfer) 1569 { 1570 } 1571 #endif /* !CONFIG_HAS_DMA */ 1572 1573 static inline int spi_unmap_msg(struct spi_controller *ctlr, 1574 struct spi_message *msg) 1575 { 1576 struct spi_transfer *xfer; 1577 int ret; 1578 1579 list_for_each_entry(xfer, &msg->transfers, transfer_list) { 1580 /* 1581 * Restore the original value of tx_buf or rx_buf if they are 1582 * NULL. 1583 */ 1584 if (xfer->tx_buf == ctlr->dummy_tx) 1585 xfer->tx_buf = NULL; 1586 if (xfer->rx_buf == ctlr->dummy_rx) 1587 xfer->rx_buf = NULL; 1588 } 1589 1590 ret = __spi_unmap_msg(ctlr, msg); 1591 1592 ctlr->cur_rx_dma_dev = NULL; 1593 ctlr->cur_tx_dma_dev = NULL; 1594 1595 return ret; 1596 } 1597 1598 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg) 1599 { 1600 struct spi_transfer *xfer; 1601 void *tmp; 1602 unsigned int max_tx, max_rx; 1603 1604 if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX)) 1605 && !(msg->spi->mode & SPI_3WIRE)) { 1606 max_tx = 0; 1607 max_rx = 0; 1608 1609 list_for_each_entry(xfer, &msg->transfers, transfer_list) { 1610 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) && 1611 !xfer->tx_buf) 1612 max_tx = max(xfer->len, max_tx); 1613 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) && 1614 !xfer->rx_buf) 1615 max_rx = max(xfer->len, max_rx); 1616 } 1617 1618 if (max_tx) { 1619 tmp = krealloc(ctlr->dummy_tx, max_tx, 1620 GFP_KERNEL | GFP_DMA | __GFP_ZERO); 1621 if (!tmp) 1622 return -ENOMEM; 1623 ctlr->dummy_tx = tmp; 1624 } 1625 1626 if (max_rx) { 1627 tmp = krealloc(ctlr->dummy_rx, max_rx, 1628 GFP_KERNEL | GFP_DMA); 1629 if (!tmp) 1630 return -ENOMEM; 1631 ctlr->dummy_rx = tmp; 1632 } 1633 1634 if (max_tx || max_rx) { 1635 list_for_each_entry(xfer, &msg->transfers, 1636 transfer_list) { 1637 if (!xfer->len) 1638 continue; 1639 if (!xfer->tx_buf) 1640 xfer->tx_buf = ctlr->dummy_tx; 1641 if (!xfer->rx_buf) 1642 xfer->rx_buf = ctlr->dummy_rx; 1643 } 1644 } 1645 } 1646 1647 return __spi_map_msg(ctlr, msg); 1648 } 1649 1650 static int spi_transfer_wait(struct spi_controller *ctlr, 1651 struct spi_message *msg, 1652 struct spi_transfer *xfer) 1653 { 1654 struct spi_statistics __percpu *statm = ctlr->pcpu_statistics; 1655 struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics; 1656 u32 speed_hz = xfer->speed_hz; 1657 unsigned long long ms; 1658 1659 if (spi_controller_is_target(ctlr)) { 1660 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) { 1661 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n"); 1662 return -EINTR; 1663 } 1664 } else { 1665 if (!speed_hz) 1666 speed_hz = 100000; 1667 1668 /* 1669 * For each byte we wait for 8 cycles of the SPI clock. 1670 * Since speed is defined in Hz and we want milliseconds, 1671 * use respective multiplier, but before the division, 1672 * otherwise we may get 0 for short transfers. 1673 */ 1674 ms = 8LL * MSEC_PER_SEC * xfer->len; 1675 do_div(ms, speed_hz); 1676 1677 /* 1678 * Increase it twice and add 200 ms tolerance, use 1679 * predefined maximum in case of overflow. 1680 */ 1681 ms += ms + 200; 1682 if (ms > UINT_MAX) 1683 ms = UINT_MAX; 1684 1685 ms = wait_for_completion_timeout(&ctlr->xfer_completion, 1686 msecs_to_jiffies(ms)); 1687 1688 if (ms == 0) { 1689 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout); 1690 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout); 1691 dev_err(&msg->spi->dev, 1692 "SPI transfer timed out\n"); 1693 return -ETIMEDOUT; 1694 } 1695 1696 if (xfer->error & SPI_TRANS_FAIL_IO) 1697 return -EIO; 1698 } 1699 1700 return 0; 1701 } 1702 1703 static void _spi_transfer_delay_ns(u32 ns) 1704 { 1705 if (!ns) 1706 return; 1707 if (ns <= NSEC_PER_USEC) { 1708 ndelay(ns); 1709 } else { 1710 u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC); 1711 1712 fsleep(us); 1713 } 1714 } 1715 1716 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer) 1717 { 1718 u32 delay = _delay->value; 1719 u32 unit = _delay->unit; 1720 u32 hz; 1721 1722 if (!delay) 1723 return 0; 1724 1725 switch (unit) { 1726 case SPI_DELAY_UNIT_USECS: 1727 delay *= NSEC_PER_USEC; 1728 break; 1729 case SPI_DELAY_UNIT_NSECS: 1730 /* Nothing to do here */ 1731 break; 1732 case SPI_DELAY_UNIT_SCK: 1733 /* Clock cycles need to be obtained from spi_transfer */ 1734 if (!xfer) 1735 return -EINVAL; 1736 /* 1737 * If there is unknown effective speed, approximate it 1738 * by underestimating with half of the requested Hz. 1739 */ 1740 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2; 1741 if (!hz) 1742 return -EINVAL; 1743 1744 /* Convert delay to nanoseconds */ 1745 delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz); 1746 break; 1747 default: 1748 return -EINVAL; 1749 } 1750 1751 return delay; 1752 } 1753 EXPORT_SYMBOL_GPL(spi_delay_to_ns); 1754 1755 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer) 1756 { 1757 int delay; 1758 1759 might_sleep(); 1760 1761 if (!_delay) 1762 return -EINVAL; 1763 1764 delay = spi_delay_to_ns(_delay, xfer); 1765 if (delay < 0) 1766 return delay; 1767 1768 _spi_transfer_delay_ns(delay); 1769 1770 return 0; 1771 } 1772 EXPORT_SYMBOL_GPL(spi_delay_exec); 1773 1774 static void _spi_transfer_cs_change_delay(struct spi_message *msg, 1775 struct spi_transfer *xfer) 1776 { 1777 u32 default_delay_ns = 10 * NSEC_PER_USEC; 1778 u32 delay = xfer->cs_change_delay.value; 1779 u32 unit = xfer->cs_change_delay.unit; 1780 int ret; 1781 1782 /* Return early on "fast" mode - for everything but USECS */ 1783 if (!delay) { 1784 if (unit == SPI_DELAY_UNIT_USECS) 1785 _spi_transfer_delay_ns(default_delay_ns); 1786 return; 1787 } 1788 1789 ret = spi_delay_exec(&xfer->cs_change_delay, xfer); 1790 if (ret) { 1791 dev_err_once(&msg->spi->dev, 1792 "Use of unsupported delay unit %i, using default of %luus\n", 1793 unit, default_delay_ns / NSEC_PER_USEC); 1794 _spi_transfer_delay_ns(default_delay_ns); 1795 } 1796 } 1797 1798 void spi_transfer_cs_change_delay_exec(struct spi_message *msg, 1799 struct spi_transfer *xfer) 1800 { 1801 _spi_transfer_cs_change_delay(msg, xfer); 1802 } 1803 EXPORT_SYMBOL_GPL(spi_transfer_cs_change_delay_exec); 1804 1805 /* 1806 * spi_transfer_one_message - Default implementation of transfer_one_message() 1807 * 1808 * This is a standard implementation of transfer_one_message() for 1809 * drivers which implement a transfer_one() operation. It provides 1810 * standard handling of delays and chip select management. 1811 */ 1812 static int spi_transfer_one_message(struct spi_controller *ctlr, 1813 struct spi_message *msg) 1814 { 1815 struct spi_transfer *xfer; 1816 bool keep_cs = false; 1817 int ret = 0; 1818 struct spi_statistics __percpu *statm = ctlr->pcpu_statistics; 1819 struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics; 1820 1821 xfer = list_first_entry(&msg->transfers, struct spi_transfer, transfer_list); 1822 spi_set_cs(msg->spi, !xfer->cs_off, false); 1823 1824 SPI_STATISTICS_INCREMENT_FIELD(statm, messages); 1825 SPI_STATISTICS_INCREMENT_FIELD(stats, messages); 1826 1827 list_for_each_entry(xfer, &msg->transfers, transfer_list) { 1828 trace_spi_transfer_start(msg, xfer); 1829 1830 spi_statistics_add_transfer_stats(statm, xfer, msg); 1831 spi_statistics_add_transfer_stats(stats, xfer, msg); 1832 1833 if (!ctlr->ptp_sts_supported) { 1834 xfer->ptp_sts_word_pre = 0; 1835 ptp_read_system_prets(xfer->ptp_sts); 1836 } 1837 1838 if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) { 1839 reinit_completion(&ctlr->xfer_completion); 1840 1841 fallback_pio: 1842 spi_dma_sync_for_device(ctlr, xfer); 1843 ret = ctlr->transfer_one(ctlr, msg->spi, xfer); 1844 if (ret < 0) { 1845 spi_dma_sync_for_cpu(ctlr, xfer); 1846 1847 if ((xfer->tx_sg_mapped || xfer->rx_sg_mapped) && 1848 (xfer->error & SPI_TRANS_FAIL_NO_START)) { 1849 __spi_unmap_msg(ctlr, msg); 1850 ctlr->fallback = true; 1851 xfer->error &= ~SPI_TRANS_FAIL_NO_START; 1852 goto fallback_pio; 1853 } 1854 1855 SPI_STATISTICS_INCREMENT_FIELD(statm, 1856 errors); 1857 SPI_STATISTICS_INCREMENT_FIELD(stats, 1858 errors); 1859 dev_err(&msg->spi->dev, 1860 "SPI transfer failed: %d\n", ret); 1861 goto out; 1862 } 1863 1864 if (ret > 0) { 1865 ret = spi_transfer_wait(ctlr, msg, xfer); 1866 if (ret < 0) 1867 msg->status = ret; 1868 } 1869 1870 spi_dma_sync_for_cpu(ctlr, xfer); 1871 } else { 1872 if (xfer->len) 1873 dev_err(&msg->spi->dev, 1874 "Bufferless transfer has length %u\n", 1875 xfer->len); 1876 } 1877 1878 if (!ctlr->ptp_sts_supported) { 1879 ptp_read_system_postts(xfer->ptp_sts); 1880 xfer->ptp_sts_word_post = xfer->len; 1881 } 1882 1883 trace_spi_transfer_stop(msg, xfer); 1884 1885 if (msg->status != -EINPROGRESS) 1886 goto out; 1887 1888 spi_transfer_delay_exec(xfer); 1889 1890 if (xfer->cs_change) { 1891 if (list_is_last(&xfer->transfer_list, 1892 &msg->transfers)) { 1893 keep_cs = true; 1894 } else { 1895 if (!xfer->cs_off) 1896 spi_set_cs(msg->spi, false, false); 1897 _spi_transfer_cs_change_delay(msg, xfer); 1898 if (!list_next_entry(xfer, transfer_list)->cs_off) 1899 spi_set_cs(msg->spi, true, false); 1900 } 1901 } else if (!list_is_last(&xfer->transfer_list, &msg->transfers) && 1902 xfer->cs_off != list_next_entry(xfer, transfer_list)->cs_off) { 1903 spi_set_cs(msg->spi, xfer->cs_off, false); 1904 } 1905 1906 msg->actual_length += xfer->len; 1907 } 1908 1909 out: 1910 if (ret != 0 || !keep_cs) 1911 spi_set_cs(msg->spi, false, false); 1912 1913 if (msg->status == -EINPROGRESS) 1914 msg->status = ret; 1915 1916 if (msg->status && ctlr->handle_err) 1917 ctlr->handle_err(ctlr, msg); 1918 1919 spi_finalize_current_message(ctlr); 1920 1921 return ret; 1922 } 1923 1924 /** 1925 * spi_finalize_current_transfer - report completion of a transfer 1926 * @ctlr: the controller reporting completion 1927 * 1928 * Called by SPI drivers using the core transfer_one_message() 1929 * implementation to notify it that the current interrupt driven 1930 * transfer has finished and the next one may be scheduled. 1931 */ 1932 void spi_finalize_current_transfer(struct spi_controller *ctlr) 1933 { 1934 complete(&ctlr->xfer_completion); 1935 } 1936 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer); 1937 1938 static void spi_idle_runtime_pm(struct spi_controller *ctlr) 1939 { 1940 if (ctlr->auto_runtime_pm) { 1941 pm_runtime_put_autosuspend(ctlr->dev.parent); 1942 } 1943 } 1944 1945 static int __spi_pump_transfer_message(struct spi_controller *ctlr, 1946 struct spi_message *msg, bool was_busy) 1947 { 1948 struct spi_transfer *xfer; 1949 int ret; 1950 1951 if (!was_busy && ctlr->auto_runtime_pm) { 1952 ret = pm_runtime_get_sync(ctlr->dev.parent); 1953 if (ret < 0) { 1954 pm_runtime_put_noidle(ctlr->dev.parent); 1955 dev_err(&ctlr->dev, "Failed to power device: %d\n", 1956 ret); 1957 1958 msg->status = ret; 1959 spi_finalize_current_message(ctlr); 1960 1961 return ret; 1962 } 1963 } 1964 1965 if (!was_busy) 1966 trace_spi_controller_busy(ctlr); 1967 1968 if (!was_busy && ctlr->prepare_transfer_hardware) { 1969 ret = ctlr->prepare_transfer_hardware(ctlr); 1970 if (ret) { 1971 dev_err(&ctlr->dev, 1972 "failed to prepare transfer hardware: %d\n", 1973 ret); 1974 1975 if (ctlr->auto_runtime_pm) 1976 pm_runtime_put(ctlr->dev.parent); 1977 1978 msg->status = ret; 1979 spi_finalize_current_message(ctlr); 1980 1981 return ret; 1982 } 1983 } 1984 1985 trace_spi_message_start(msg); 1986 1987 if (ctlr->prepare_message) { 1988 ret = ctlr->prepare_message(ctlr, msg); 1989 if (ret) { 1990 dev_err(&ctlr->dev, "failed to prepare message: %d\n", 1991 ret); 1992 msg->status = ret; 1993 spi_finalize_current_message(ctlr); 1994 return ret; 1995 } 1996 msg->prepared = true; 1997 } 1998 1999 ret = spi_map_msg(ctlr, msg); 2000 if (ret) { 2001 msg->status = ret; 2002 spi_finalize_current_message(ctlr); 2003 return ret; 2004 } 2005 2006 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) { 2007 list_for_each_entry(xfer, &msg->transfers, transfer_list) { 2008 xfer->ptp_sts_word_pre = 0; 2009 ptp_read_system_prets(xfer->ptp_sts); 2010 } 2011 } 2012 2013 /* 2014 * Drivers implementation of transfer_one_message() must arrange for 2015 * spi_finalize_current_message() to get called. Most drivers will do 2016 * this in the calling context, but some don't. For those cases, a 2017 * completion is used to guarantee that this function does not return 2018 * until spi_finalize_current_message() is done accessing 2019 * ctlr->cur_msg. 2020 * Use of the following two flags enable to opportunistically skip the 2021 * use of the completion since its use involves expensive spin locks. 2022 * In case of a race with the context that calls 2023 * spi_finalize_current_message() the completion will always be used, 2024 * due to strict ordering of these flags using barriers. 2025 */ 2026 WRITE_ONCE(ctlr->cur_msg_incomplete, true); 2027 WRITE_ONCE(ctlr->cur_msg_need_completion, false); 2028 reinit_completion(&ctlr->cur_msg_completion); 2029 smp_wmb(); /* Make these available to spi_finalize_current_message() */ 2030 2031 ret = ctlr->transfer_one_message(ctlr, msg); 2032 if (ret) { 2033 dev_err(&ctlr->dev, 2034 "failed to transfer one message from queue\n"); 2035 return ret; 2036 } 2037 2038 WRITE_ONCE(ctlr->cur_msg_need_completion, true); 2039 smp_mb(); /* See spi_finalize_current_message()... */ 2040 if (READ_ONCE(ctlr->cur_msg_incomplete)) 2041 wait_for_completion(&ctlr->cur_msg_completion); 2042 2043 return 0; 2044 } 2045 2046 /** 2047 * __spi_pump_messages - function which processes SPI message queue 2048 * @ctlr: controller to process queue for 2049 * @in_kthread: true if we are in the context of the message pump thread 2050 * 2051 * This function checks if there is any SPI message in the queue that 2052 * needs processing and if so call out to the driver to initialize hardware 2053 * and transfer each message. 2054 * 2055 * Note that it is called both from the kthread itself and also from 2056 * inside spi_sync(); the queue extraction handling at the top of the 2057 * function should deal with this safely. 2058 */ 2059 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread) 2060 { 2061 struct spi_message *msg; 2062 bool was_busy = false; 2063 unsigned long flags; 2064 int ret; 2065 2066 /* Take the I/O mutex */ 2067 mutex_lock(&ctlr->io_mutex); 2068 2069 /* Lock queue */ 2070 spin_lock_irqsave(&ctlr->queue_lock, flags); 2071 2072 /* Make sure we are not already running a message */ 2073 if (ctlr->cur_msg) 2074 goto out_unlock; 2075 2076 /* Check if the queue is idle */ 2077 if (list_empty(&ctlr->queue) || !ctlr->running) { 2078 if (!ctlr->busy) 2079 goto out_unlock; 2080 2081 /* Defer any non-atomic teardown to the thread */ 2082 if (!in_kthread) { 2083 if (!ctlr->dummy_rx && !ctlr->dummy_tx && 2084 !ctlr->unprepare_transfer_hardware) { 2085 spi_idle_runtime_pm(ctlr); 2086 ctlr->busy = false; 2087 ctlr->queue_empty = true; 2088 trace_spi_controller_idle(ctlr); 2089 } else { 2090 kthread_queue_work(ctlr->kworker, 2091 &ctlr->pump_messages); 2092 } 2093 goto out_unlock; 2094 } 2095 2096 ctlr->busy = false; 2097 spin_unlock_irqrestore(&ctlr->queue_lock, flags); 2098 2099 kfree(ctlr->dummy_rx); 2100 ctlr->dummy_rx = NULL; 2101 kfree(ctlr->dummy_tx); 2102 ctlr->dummy_tx = NULL; 2103 if (ctlr->unprepare_transfer_hardware && 2104 ctlr->unprepare_transfer_hardware(ctlr)) 2105 dev_err(&ctlr->dev, 2106 "failed to unprepare transfer hardware\n"); 2107 spi_idle_runtime_pm(ctlr); 2108 trace_spi_controller_idle(ctlr); 2109 2110 spin_lock_irqsave(&ctlr->queue_lock, flags); 2111 ctlr->queue_empty = true; 2112 goto out_unlock; 2113 } 2114 2115 /* Extract head of queue */ 2116 msg = list_first_entry(&ctlr->queue, struct spi_message, queue); 2117 ctlr->cur_msg = msg; 2118 2119 list_del_init(&msg->queue); 2120 if (ctlr->busy) 2121 was_busy = true; 2122 else 2123 ctlr->busy = true; 2124 spin_unlock_irqrestore(&ctlr->queue_lock, flags); 2125 2126 ret = __spi_pump_transfer_message(ctlr, msg, was_busy); 2127 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages); 2128 2129 ctlr->cur_msg = NULL; 2130 ctlr->fallback = false; 2131 2132 mutex_unlock(&ctlr->io_mutex); 2133 2134 /* Prod the scheduler in case transfer_one() was busy waiting */ 2135 if (!ret) 2136 cond_resched(); 2137 return; 2138 2139 out_unlock: 2140 spin_unlock_irqrestore(&ctlr->queue_lock, flags); 2141 mutex_unlock(&ctlr->io_mutex); 2142 } 2143 2144 /** 2145 * spi_pump_messages - kthread work function which processes spi message queue 2146 * @work: pointer to kthread work struct contained in the controller struct 2147 */ 2148 static void spi_pump_messages(struct kthread_work *work) 2149 { 2150 struct spi_controller *ctlr = 2151 container_of(work, struct spi_controller, pump_messages); 2152 2153 __spi_pump_messages(ctlr, true); 2154 } 2155 2156 /** 2157 * spi_take_timestamp_pre - helper to collect the beginning of the TX timestamp 2158 * @ctlr: Pointer to the spi_controller structure of the driver 2159 * @xfer: Pointer to the transfer being timestamped 2160 * @progress: How many words (not bytes) have been transferred so far 2161 * @irqs_off: If true, will disable IRQs and preemption for the duration of the 2162 * transfer, for less jitter in time measurement. Only compatible 2163 * with PIO drivers. If true, must follow up with 2164 * spi_take_timestamp_post or otherwise system will crash. 2165 * WARNING: for fully predictable results, the CPU frequency must 2166 * also be under control (governor). 2167 * 2168 * This is a helper for drivers to collect the beginning of the TX timestamp 2169 * for the requested byte from the SPI transfer. The frequency with which this 2170 * function must be called (once per word, once for the whole transfer, once 2171 * per batch of words etc) is arbitrary as long as the @tx buffer offset is 2172 * greater than or equal to the requested byte at the time of the call. The 2173 * timestamp is only taken once, at the first such call. It is assumed that 2174 * the driver advances its @tx buffer pointer monotonically. 2175 */ 2176 void spi_take_timestamp_pre(struct spi_controller *ctlr, 2177 struct spi_transfer *xfer, 2178 size_t progress, bool irqs_off) 2179 { 2180 if (!xfer->ptp_sts) 2181 return; 2182 2183 if (xfer->timestamped) 2184 return; 2185 2186 if (progress > xfer->ptp_sts_word_pre) 2187 return; 2188 2189 /* Capture the resolution of the timestamp */ 2190 xfer->ptp_sts_word_pre = progress; 2191 2192 if (irqs_off) { 2193 local_irq_save(ctlr->irq_flags); 2194 preempt_disable(); 2195 } 2196 2197 ptp_read_system_prets(xfer->ptp_sts); 2198 } 2199 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre); 2200 2201 /** 2202 * spi_take_timestamp_post - helper to collect the end of the TX timestamp 2203 * @ctlr: Pointer to the spi_controller structure of the driver 2204 * @xfer: Pointer to the transfer being timestamped 2205 * @progress: How many words (not bytes) have been transferred so far 2206 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU. 2207 * 2208 * This is a helper for drivers to collect the end of the TX timestamp for 2209 * the requested byte from the SPI transfer. Can be called with an arbitrary 2210 * frequency: only the first call where @tx exceeds or is equal to the 2211 * requested word will be timestamped. 2212 */ 2213 void spi_take_timestamp_post(struct spi_controller *ctlr, 2214 struct spi_transfer *xfer, 2215 size_t progress, bool irqs_off) 2216 { 2217 if (!xfer->ptp_sts) 2218 return; 2219 2220 if (xfer->timestamped) 2221 return; 2222 2223 if (progress < xfer->ptp_sts_word_post) 2224 return; 2225 2226 ptp_read_system_postts(xfer->ptp_sts); 2227 2228 if (irqs_off) { 2229 local_irq_restore(ctlr->irq_flags); 2230 preempt_enable(); 2231 } 2232 2233 /* Capture the resolution of the timestamp */ 2234 xfer->ptp_sts_word_post = progress; 2235 2236 xfer->timestamped = 1; 2237 } 2238 EXPORT_SYMBOL_GPL(spi_take_timestamp_post); 2239 2240 /** 2241 * spi_set_thread_rt - set the controller to pump at realtime priority 2242 * @ctlr: controller to boost priority of 2243 * 2244 * This can be called because the controller requested realtime priority 2245 * (by setting the ->rt value before calling spi_register_controller()) or 2246 * because a device on the bus said that its transfers needed realtime 2247 * priority. 2248 * 2249 * NOTE: at the moment if any device on a bus says it needs realtime then 2250 * the thread will be at realtime priority for all transfers on that 2251 * controller. If this eventually becomes a problem we may see if we can 2252 * find a way to boost the priority only temporarily during relevant 2253 * transfers. 2254 */ 2255 static void spi_set_thread_rt(struct spi_controller *ctlr) 2256 { 2257 dev_info(&ctlr->dev, 2258 "will run message pump with realtime priority\n"); 2259 sched_set_fifo(ctlr->kworker->task); 2260 } 2261 2262 static int spi_init_queue(struct spi_controller *ctlr) 2263 { 2264 ctlr->running = false; 2265 ctlr->busy = false; 2266 ctlr->queue_empty = true; 2267 2268 ctlr->kworker = kthread_run_worker(0, dev_name(&ctlr->dev)); 2269 if (IS_ERR(ctlr->kworker)) { 2270 dev_err(&ctlr->dev, "failed to create message pump kworker\n"); 2271 return PTR_ERR(ctlr->kworker); 2272 } 2273 2274 kthread_init_work(&ctlr->pump_messages, spi_pump_messages); 2275 2276 /* 2277 * Controller config will indicate if this controller should run the 2278 * message pump with high (realtime) priority to reduce the transfer 2279 * latency on the bus by minimising the delay between a transfer 2280 * request and the scheduling of the message pump thread. Without this 2281 * setting the message pump thread will remain at default priority. 2282 */ 2283 if (ctlr->rt) 2284 spi_set_thread_rt(ctlr); 2285 2286 return 0; 2287 } 2288 2289 /** 2290 * spi_get_next_queued_message() - called by driver to check for queued 2291 * messages 2292 * @ctlr: the controller to check for queued messages 2293 * 2294 * If there are more messages in the queue, the next message is returned from 2295 * this call. 2296 * 2297 * Return: the next message in the queue, else NULL if the queue is empty. 2298 */ 2299 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr) 2300 { 2301 struct spi_message *next; 2302 unsigned long flags; 2303 2304 /* Get a pointer to the next message, if any */ 2305 spin_lock_irqsave(&ctlr->queue_lock, flags); 2306 next = list_first_entry_or_null(&ctlr->queue, struct spi_message, 2307 queue); 2308 spin_unlock_irqrestore(&ctlr->queue_lock, flags); 2309 2310 return next; 2311 } 2312 EXPORT_SYMBOL_GPL(spi_get_next_queued_message); 2313 2314 /* 2315 * __spi_unoptimize_message - shared implementation of spi_unoptimize_message() 2316 * and spi_maybe_unoptimize_message() 2317 * @msg: the message to unoptimize 2318 * 2319 * Peripheral drivers should use spi_unoptimize_message() and callers inside 2320 * core should use spi_maybe_unoptimize_message() rather than calling this 2321 * function directly. 2322 * 2323 * It is not valid to call this on a message that is not currently optimized. 2324 */ 2325 static void __spi_unoptimize_message(struct spi_message *msg) 2326 { 2327 struct spi_controller *ctlr = msg->spi->controller; 2328 2329 if (ctlr->unoptimize_message) 2330 ctlr->unoptimize_message(msg); 2331 2332 spi_res_release(ctlr, msg); 2333 2334 msg->optimized = false; 2335 msg->opt_state = NULL; 2336 } 2337 2338 /* 2339 * spi_maybe_unoptimize_message - unoptimize msg not managed by a peripheral 2340 * @msg: the message to unoptimize 2341 * 2342 * This function is used to unoptimize a message if and only if it was 2343 * optimized by the core (via spi_maybe_optimize_message()). 2344 */ 2345 static void spi_maybe_unoptimize_message(struct spi_message *msg) 2346 { 2347 if (!msg->pre_optimized && msg->optimized && 2348 !msg->spi->controller->defer_optimize_message) 2349 __spi_unoptimize_message(msg); 2350 } 2351 2352 /** 2353 * spi_finalize_current_message() - the current message is complete 2354 * @ctlr: the controller to return the message to 2355 * 2356 * Called by the driver to notify the core that the message in the front of the 2357 * queue is complete and can be removed from the queue. 2358 */ 2359 void spi_finalize_current_message(struct spi_controller *ctlr) 2360 { 2361 struct spi_transfer *xfer; 2362 struct spi_message *mesg; 2363 int ret; 2364 2365 mesg = ctlr->cur_msg; 2366 2367 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) { 2368 list_for_each_entry(xfer, &mesg->transfers, transfer_list) { 2369 ptp_read_system_postts(xfer->ptp_sts); 2370 xfer->ptp_sts_word_post = xfer->len; 2371 } 2372 } 2373 2374 if (unlikely(ctlr->ptp_sts_supported)) 2375 list_for_each_entry(xfer, &mesg->transfers, transfer_list) 2376 WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped); 2377 2378 spi_unmap_msg(ctlr, mesg); 2379 2380 if (mesg->prepared && ctlr->unprepare_message) { 2381 ret = ctlr->unprepare_message(ctlr, mesg); 2382 if (ret) { 2383 dev_err(&ctlr->dev, "failed to unprepare message: %d\n", 2384 ret); 2385 } 2386 } 2387 2388 mesg->prepared = false; 2389 2390 spi_maybe_unoptimize_message(mesg); 2391 2392 WRITE_ONCE(ctlr->cur_msg_incomplete, false); 2393 smp_mb(); /* See __spi_pump_transfer_message()... */ 2394 if (READ_ONCE(ctlr->cur_msg_need_completion)) 2395 complete(&ctlr->cur_msg_completion); 2396 2397 trace_spi_message_done(mesg); 2398 2399 mesg->state = NULL; 2400 if (mesg->complete) 2401 mesg->complete(mesg->context); 2402 } 2403 EXPORT_SYMBOL_GPL(spi_finalize_current_message); 2404 2405 static int spi_start_queue(struct spi_controller *ctlr) 2406 { 2407 unsigned long flags; 2408 2409 spin_lock_irqsave(&ctlr->queue_lock, flags); 2410 2411 if (ctlr->running || ctlr->busy) { 2412 spin_unlock_irqrestore(&ctlr->queue_lock, flags); 2413 return -EBUSY; 2414 } 2415 2416 ctlr->running = true; 2417 ctlr->cur_msg = NULL; 2418 spin_unlock_irqrestore(&ctlr->queue_lock, flags); 2419 2420 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages); 2421 2422 return 0; 2423 } 2424 2425 static int spi_stop_queue(struct spi_controller *ctlr) 2426 { 2427 unsigned int limit = 500; 2428 unsigned long flags; 2429 2430 /* 2431 * This is a bit lame, but is optimized for the common execution path. 2432 * A wait_queue on the ctlr->busy could be used, but then the common 2433 * execution path (pump_messages) would be required to call wake_up or 2434 * friends on every SPI message. Do this instead. 2435 */ 2436 do { 2437 spin_lock_irqsave(&ctlr->queue_lock, flags); 2438 if (list_empty(&ctlr->queue) && !ctlr->busy) { 2439 ctlr->running = false; 2440 spin_unlock_irqrestore(&ctlr->queue_lock, flags); 2441 return 0; 2442 } 2443 spin_unlock_irqrestore(&ctlr->queue_lock, flags); 2444 usleep_range(10000, 11000); 2445 } while (--limit); 2446 2447 return -EBUSY; 2448 } 2449 2450 static int spi_destroy_queue(struct spi_controller *ctlr) 2451 { 2452 int ret; 2453 2454 ret = spi_stop_queue(ctlr); 2455 2456 /* 2457 * kthread_flush_worker will block until all work is done. 2458 * If the reason that stop_queue timed out is that the work will never 2459 * finish, then it does no good to call flush/stop thread, so 2460 * return anyway. 2461 */ 2462 if (ret) { 2463 dev_err(&ctlr->dev, "problem destroying queue\n"); 2464 return ret; 2465 } 2466 2467 kthread_destroy_worker(ctlr->kworker); 2468 2469 return 0; 2470 } 2471 2472 static int __spi_queued_transfer(struct spi_device *spi, 2473 struct spi_message *msg, 2474 bool need_pump) 2475 { 2476 struct spi_controller *ctlr = spi->controller; 2477 unsigned long flags; 2478 2479 spin_lock_irqsave(&ctlr->queue_lock, flags); 2480 2481 if (!ctlr->running) { 2482 spin_unlock_irqrestore(&ctlr->queue_lock, flags); 2483 return -ESHUTDOWN; 2484 } 2485 msg->actual_length = 0; 2486 msg->status = -EINPROGRESS; 2487 2488 list_add_tail(&msg->queue, &ctlr->queue); 2489 ctlr->queue_empty = false; 2490 if (!ctlr->busy && need_pump) 2491 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages); 2492 2493 spin_unlock_irqrestore(&ctlr->queue_lock, flags); 2494 return 0; 2495 } 2496 2497 /** 2498 * spi_queued_transfer - transfer function for queued transfers 2499 * @spi: SPI device which is requesting transfer 2500 * @msg: SPI message which is to handled is queued to driver queue 2501 * 2502 * Return: zero on success, else a negative error code. 2503 */ 2504 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg) 2505 { 2506 return __spi_queued_transfer(spi, msg, true); 2507 } 2508 2509 static int spi_controller_initialize_queue(struct spi_controller *ctlr) 2510 { 2511 int ret; 2512 2513 ctlr->transfer = spi_queued_transfer; 2514 if (!ctlr->transfer_one_message) 2515 ctlr->transfer_one_message = spi_transfer_one_message; 2516 2517 /* Initialize and start queue */ 2518 ret = spi_init_queue(ctlr); 2519 if (ret) { 2520 dev_err(&ctlr->dev, "problem initializing queue\n"); 2521 goto err_init_queue; 2522 } 2523 ctlr->queued = true; 2524 ret = spi_start_queue(ctlr); 2525 if (ret) { 2526 dev_err(&ctlr->dev, "problem starting queue\n"); 2527 goto err_start_queue; 2528 } 2529 2530 return 0; 2531 2532 err_start_queue: 2533 spi_destroy_queue(ctlr); 2534 err_init_queue: 2535 return ret; 2536 } 2537 2538 /** 2539 * spi_flush_queue - Send all pending messages in the queue from the callers' 2540 * context 2541 * @ctlr: controller to process queue for 2542 * 2543 * This should be used when one wants to ensure all pending messages have been 2544 * sent before doing something. Is used by the spi-mem code to make sure SPI 2545 * memory operations do not preempt regular SPI transfers that have been queued 2546 * before the spi-mem operation. 2547 */ 2548 void spi_flush_queue(struct spi_controller *ctlr) 2549 { 2550 if (ctlr->transfer == spi_queued_transfer) 2551 __spi_pump_messages(ctlr, false); 2552 } 2553 2554 /*-------------------------------------------------------------------------*/ 2555 2556 #if defined(CONFIG_OF) 2557 static void of_spi_parse_dt_cs_delay(struct device_node *nc, 2558 struct spi_delay *delay, const char *prop) 2559 { 2560 u32 value; 2561 2562 if (!of_property_read_u32(nc, prop, &value)) { 2563 if (value > U16_MAX) { 2564 delay->value = DIV_ROUND_UP(value, 1000); 2565 delay->unit = SPI_DELAY_UNIT_USECS; 2566 } else { 2567 delay->value = value; 2568 delay->unit = SPI_DELAY_UNIT_NSECS; 2569 } 2570 } 2571 } 2572 2573 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi, 2574 struct device_node *nc) 2575 { 2576 u32 value, cs[SPI_DEVICE_CS_CNT_MAX], map[SPI_DEVICE_DATA_LANE_CNT_MAX]; 2577 int rc, idx, max_num_data_lanes; 2578 2579 /* Mode (clock phase/polarity/etc.) */ 2580 if (of_property_read_bool(nc, "spi-cpha")) 2581 spi->mode |= SPI_CPHA; 2582 if (of_property_read_bool(nc, "spi-cpol")) 2583 spi->mode |= SPI_CPOL; 2584 if (of_property_read_bool(nc, "spi-3wire")) 2585 spi->mode |= SPI_3WIRE; 2586 if (of_property_read_bool(nc, "spi-lsb-first")) 2587 spi->mode |= SPI_LSB_FIRST; 2588 if (of_property_read_bool(nc, "spi-cs-high")) 2589 spi->mode |= SPI_CS_HIGH; 2590 2591 /* Device DUAL/QUAD mode */ 2592 2593 rc = of_property_read_variable_u32_array(nc, "spi-tx-lane-map", map, 1, 2594 ARRAY_SIZE(map)); 2595 if (rc >= 0) { 2596 max_num_data_lanes = rc; 2597 for (idx = 0; idx < max_num_data_lanes; idx++) 2598 spi->tx_lane_map[idx] = map[idx]; 2599 } else if (rc == -EINVAL) { 2600 /* Default lane map is identity mapping. */ 2601 max_num_data_lanes = ARRAY_SIZE(spi->tx_lane_map); 2602 for (idx = 0; idx < max_num_data_lanes; idx++) 2603 spi->tx_lane_map[idx] = idx; 2604 } else { 2605 dev_err(&ctlr->dev, 2606 "failed to read spi-tx-lane-map property: %d\n", rc); 2607 return rc; 2608 } 2609 2610 rc = of_property_count_u32_elems(nc, "spi-tx-bus-width"); 2611 if (rc < 0 && rc != -EINVAL) { 2612 dev_err(&ctlr->dev, 2613 "failed to read spi-tx-bus-width property: %d\n", rc); 2614 return rc; 2615 } 2616 if (rc > max_num_data_lanes) { 2617 dev_err(&ctlr->dev, 2618 "spi-tx-bus-width has more elements (%d) than spi-tx-lane-map (%d)\n", 2619 rc, max_num_data_lanes); 2620 return -EINVAL; 2621 } 2622 2623 if (rc == -EINVAL) { 2624 /* Default when property is not present. */ 2625 spi->num_tx_lanes = 1; 2626 } else { 2627 u32 first_value; 2628 2629 spi->num_tx_lanes = rc; 2630 2631 for (idx = 0; idx < spi->num_tx_lanes; idx++) { 2632 rc = of_property_read_u32_index(nc, "spi-tx-bus-width", 2633 idx, &value); 2634 if (rc) 2635 return rc; 2636 2637 /* 2638 * For now, we only support all lanes having the same 2639 * width so we can keep using the existing mode flags. 2640 */ 2641 if (!idx) 2642 first_value = value; 2643 else if (first_value != value) { 2644 dev_err(&ctlr->dev, 2645 "spi-tx-bus-width has inconsistent values: first %d vs later %d\n", 2646 first_value, value); 2647 return -EINVAL; 2648 } 2649 } 2650 2651 switch (value) { 2652 case 0: 2653 spi->mode |= SPI_NO_TX; 2654 break; 2655 case 1: 2656 break; 2657 case 2: 2658 spi->mode |= SPI_TX_DUAL; 2659 break; 2660 case 4: 2661 spi->mode |= SPI_TX_QUAD; 2662 break; 2663 case 8: 2664 spi->mode |= SPI_TX_OCTAL; 2665 break; 2666 default: 2667 dev_warn(&ctlr->dev, 2668 "spi-tx-bus-width %d not supported\n", 2669 value); 2670 break; 2671 } 2672 } 2673 2674 for (idx = 0; idx < spi->num_tx_lanes; idx++) { 2675 if (spi->tx_lane_map[idx] >= spi->controller->num_data_lanes) { 2676 dev_err(&ctlr->dev, 2677 "spi-tx-lane-map has invalid value %d (num_data_lanes=%d)\n", 2678 spi->tx_lane_map[idx], 2679 spi->controller->num_data_lanes); 2680 return -EINVAL; 2681 } 2682 } 2683 2684 rc = of_property_read_variable_u32_array(nc, "spi-rx-lane-map", map, 1, 2685 ARRAY_SIZE(map)); 2686 if (rc >= 0) { 2687 max_num_data_lanes = rc; 2688 for (idx = 0; idx < max_num_data_lanes; idx++) 2689 spi->rx_lane_map[idx] = map[idx]; 2690 } else if (rc == -EINVAL) { 2691 /* Default lane map is identity mapping. */ 2692 max_num_data_lanes = ARRAY_SIZE(spi->rx_lane_map); 2693 for (idx = 0; idx < max_num_data_lanes; idx++) 2694 spi->rx_lane_map[idx] = idx; 2695 } else { 2696 dev_err(&ctlr->dev, 2697 "failed to read spi-rx-lane-map property: %d\n", rc); 2698 return rc; 2699 } 2700 2701 rc = of_property_count_u32_elems(nc, "spi-rx-bus-width"); 2702 if (rc < 0 && rc != -EINVAL) { 2703 dev_err(&ctlr->dev, 2704 "failed to read spi-rx-bus-width property: %d\n", rc); 2705 return rc; 2706 } 2707 if (rc > max_num_data_lanes) { 2708 dev_err(&ctlr->dev, 2709 "spi-rx-bus-width has more elements (%d) than spi-rx-lane-map (%d)\n", 2710 rc, max_num_data_lanes); 2711 return -EINVAL; 2712 } 2713 2714 if (rc == -EINVAL) { 2715 /* Default when property is not present. */ 2716 spi->num_rx_lanes = 1; 2717 } else { 2718 u32 first_value; 2719 2720 spi->num_rx_lanes = rc; 2721 2722 for (idx = 0; idx < spi->num_rx_lanes; idx++) { 2723 rc = of_property_read_u32_index(nc, "spi-rx-bus-width", 2724 idx, &value); 2725 if (rc) 2726 return rc; 2727 2728 /* 2729 * For now, we only support all lanes having the same 2730 * width so we can keep using the existing mode flags. 2731 */ 2732 if (!idx) 2733 first_value = value; 2734 else if (first_value != value) { 2735 dev_err(&ctlr->dev, 2736 "spi-rx-bus-width has inconsistent values: first %d vs later %d\n", 2737 first_value, value); 2738 return -EINVAL; 2739 } 2740 } 2741 2742 switch (value) { 2743 case 0: 2744 spi->mode |= SPI_NO_RX; 2745 break; 2746 case 1: 2747 break; 2748 case 2: 2749 spi->mode |= SPI_RX_DUAL; 2750 break; 2751 case 4: 2752 spi->mode |= SPI_RX_QUAD; 2753 break; 2754 case 8: 2755 spi->mode |= SPI_RX_OCTAL; 2756 break; 2757 default: 2758 dev_warn(&ctlr->dev, 2759 "spi-rx-bus-width %d not supported\n", 2760 value); 2761 break; 2762 } 2763 } 2764 2765 for (idx = 0; idx < spi->num_rx_lanes; idx++) { 2766 if (spi->rx_lane_map[idx] >= spi->controller->num_data_lanes) { 2767 dev_err(&ctlr->dev, 2768 "spi-rx-lane-map has invalid value %d (num_data_lanes=%d)\n", 2769 spi->rx_lane_map[idx], 2770 spi->controller->num_data_lanes); 2771 return -EINVAL; 2772 } 2773 } 2774 2775 if (spi_controller_is_target(ctlr)) { 2776 if (!of_node_name_eq(nc, "slave")) { 2777 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n", 2778 nc); 2779 return -EINVAL; 2780 } 2781 return 0; 2782 } 2783 2784 /* Device address */ 2785 rc = of_property_read_variable_u32_array(nc, "reg", &cs[0], 1, 2786 SPI_DEVICE_CS_CNT_MAX); 2787 if (rc < 0) { 2788 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n", 2789 nc, rc); 2790 return rc; 2791 } 2792 2793 if ((of_property_present(nc, "parallel-memories")) && 2794 (!(ctlr->flags & SPI_CONTROLLER_MULTI_CS))) { 2795 dev_err(&ctlr->dev, "SPI controller doesn't support multi CS\n"); 2796 return -EINVAL; 2797 } 2798 2799 spi->num_chipselect = rc; 2800 for (idx = 0; idx < rc; idx++) 2801 spi_set_chipselect(spi, idx, cs[idx]); 2802 2803 /* 2804 * By default spi->chip_select[0] will hold the physical CS number, 2805 * so set bit 0 in spi->cs_index_mask. 2806 */ 2807 spi->cs_index_mask = BIT(0); 2808 2809 /* Device speed */ 2810 if (!of_property_read_u32(nc, "spi-max-frequency", &value)) 2811 spi->max_speed_hz = value; 2812 2813 /* Device CS delays */ 2814 of_spi_parse_dt_cs_delay(nc, &spi->cs_setup, "spi-cs-setup-delay-ns"); 2815 of_spi_parse_dt_cs_delay(nc, &spi->cs_hold, "spi-cs-hold-delay-ns"); 2816 of_spi_parse_dt_cs_delay(nc, &spi->cs_inactive, "spi-cs-inactive-delay-ns"); 2817 2818 return 0; 2819 } 2820 2821 static struct spi_device * 2822 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc) 2823 { 2824 struct spi_device *spi; 2825 int rc; 2826 2827 /* Alloc an spi_device */ 2828 spi = spi_alloc_device(ctlr); 2829 if (!spi) { 2830 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc); 2831 rc = -ENOMEM; 2832 goto err_out; 2833 } 2834 2835 /* Select device driver */ 2836 rc = of_alias_from_compatible(nc, spi->modalias, 2837 sizeof(spi->modalias)); 2838 if (rc < 0) { 2839 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc); 2840 goto err_out; 2841 } 2842 2843 rc = of_spi_parse_dt(ctlr, spi, nc); 2844 if (rc) 2845 goto err_out; 2846 2847 /* Store a pointer to the node in the device structure */ 2848 of_node_get(nc); 2849 2850 device_set_node(&spi->dev, of_fwnode_handle(nc)); 2851 2852 /* Register the new device */ 2853 rc = spi_add_device(spi); 2854 if (rc) { 2855 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc); 2856 goto err_of_node_put; 2857 } 2858 2859 return spi; 2860 2861 err_of_node_put: 2862 of_node_put(nc); 2863 err_out: 2864 spi_dev_put(spi); 2865 return ERR_PTR(rc); 2866 } 2867 2868 /** 2869 * of_register_spi_devices() - Register child devices onto the SPI bus 2870 * @ctlr: Pointer to spi_controller device 2871 * 2872 * Registers an spi_device for each child node of controller node which 2873 * represents a valid SPI target device. 2874 */ 2875 static void of_register_spi_devices(struct spi_controller *ctlr) 2876 { 2877 struct spi_device *spi; 2878 struct device_node *nc; 2879 2880 for_each_available_child_of_node(ctlr->dev.of_node, nc) { 2881 if (of_node_test_and_set_flag(nc, OF_POPULATED)) 2882 continue; 2883 spi = of_register_spi_device(ctlr, nc); 2884 if (IS_ERR(spi)) { 2885 dev_warn(&ctlr->dev, 2886 "Failed to create SPI device for %pOF\n", nc); 2887 of_node_clear_flag(nc, OF_POPULATED); 2888 } 2889 } 2890 } 2891 #else 2892 static void of_register_spi_devices(struct spi_controller *ctlr) { } 2893 #endif 2894 2895 /** 2896 * spi_new_ancillary_device() - Register ancillary SPI device 2897 * @spi: Pointer to the main SPI device registering the ancillary device 2898 * @chip_select: Chip Select of the ancillary device 2899 * 2900 * Register an ancillary SPI device; for example some chips have a chip-select 2901 * for normal device usage and another one for setup/firmware upload. 2902 * 2903 * This may only be called from main SPI device's probe routine. 2904 * 2905 * Return: the new device on success; an ERR_PTR() on failure 2906 */ 2907 struct spi_device *spi_new_ancillary_device(struct spi_device *spi, 2908 u8 chip_select) 2909 { 2910 struct spi_controller *ctlr = spi->controller; 2911 struct spi_device *ancillary; 2912 int rc; 2913 2914 /* Alloc an spi_device */ 2915 ancillary = spi_alloc_device(ctlr); 2916 if (!ancillary) { 2917 rc = -ENOMEM; 2918 goto err_out; 2919 } 2920 2921 strscpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias)); 2922 2923 /* Use provided chip-select for ancillary device */ 2924 spi_set_chipselect(ancillary, 0, chip_select); 2925 2926 /* Take over SPI mode/speed from SPI main device */ 2927 ancillary->max_speed_hz = spi->max_speed_hz; 2928 ancillary->mode = spi->mode; 2929 /* 2930 * By default spi->chip_select[0] will hold the physical CS number, 2931 * so set bit 0 in spi->cs_index_mask. 2932 */ 2933 ancillary->cs_index_mask = BIT(0); 2934 2935 WARN_ON(!mutex_is_locked(&ctlr->add_lock)); 2936 2937 /* Register the new device, passing the parent to skip CS conflict check */ 2938 rc = __spi_add_device(ancillary, spi); 2939 if (rc) { 2940 dev_err(&spi->dev, "failed to register ancillary device\n"); 2941 goto err_out; 2942 } 2943 2944 return ancillary; 2945 2946 err_out: 2947 spi_dev_put(ancillary); 2948 return ERR_PTR(rc); 2949 } 2950 EXPORT_SYMBOL_GPL(spi_new_ancillary_device); 2951 2952 static void devm_spi_unregister_device(void *spi) 2953 { 2954 spi_unregister_device(spi); 2955 } 2956 2957 /** 2958 * devm_spi_new_ancillary_device() - Register managed ancillary SPI device 2959 * @spi: Pointer to the main SPI device registering the ancillary device 2960 * @chip_select: Chip Select of the ancillary device 2961 * 2962 * Register an ancillary SPI device; for example some chips have a chip-select 2963 * for normal device usage and another one for setup/firmware upload. 2964 * 2965 * This is the managed version of spi_new_ancillary_device(). The ancillary 2966 * device will be unregistered automatically when the parent SPI device is 2967 * unregistered. 2968 * 2969 * This may only be called from main SPI device's probe routine. 2970 * 2971 * Return: Pointer to new ancillary device on success; ERR_PTR on failure 2972 */ 2973 struct spi_device *devm_spi_new_ancillary_device(struct spi_device *spi, 2974 u8 chip_select) 2975 { 2976 struct spi_device *ancillary; 2977 int ret; 2978 2979 ancillary = spi_new_ancillary_device(spi, chip_select); 2980 if (IS_ERR(ancillary)) 2981 return ancillary; 2982 2983 ret = devm_add_action_or_reset(&spi->dev, devm_spi_unregister_device, 2984 ancillary); 2985 if (ret) 2986 return ERR_PTR(ret); 2987 2988 return ancillary; 2989 } 2990 EXPORT_SYMBOL_GPL(devm_spi_new_ancillary_device); 2991 2992 #ifdef CONFIG_ACPI 2993 struct acpi_spi_lookup { 2994 struct spi_controller *ctlr; 2995 acpi_handle device_handle; 2996 u32 max_speed_hz; 2997 u32 mode; 2998 int irq; 2999 u8 bits_per_word; 3000 u8 chip_select; 3001 int n; 3002 int index; 3003 }; 3004 3005 static int acpi_spi_count(struct acpi_resource *ares, void *data) 3006 { 3007 struct acpi_resource_spi_serialbus *sb; 3008 int *count = data; 3009 3010 if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) 3011 return 1; 3012 3013 sb = &ares->data.spi_serial_bus; 3014 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_SPI) 3015 return 1; 3016 3017 *count = *count + 1; 3018 3019 return 1; 3020 } 3021 3022 /** 3023 * acpi_spi_count_resources - Count the number of SpiSerialBus resources 3024 * @adev: ACPI device 3025 * 3026 * Return: the number of SpiSerialBus resources in the ACPI-device's 3027 * resource-list; or a negative error code. 3028 */ 3029 int acpi_spi_count_resources(struct acpi_device *adev) 3030 { 3031 LIST_HEAD(r); 3032 int count = 0; 3033 int ret; 3034 3035 ret = acpi_dev_get_resources(adev, &r, acpi_spi_count, &count); 3036 if (ret < 0) 3037 return ret; 3038 3039 acpi_dev_free_resource_list(&r); 3040 3041 return count; 3042 } 3043 EXPORT_SYMBOL_GPL(acpi_spi_count_resources); 3044 3045 static void acpi_spi_parse_apple_properties(struct acpi_device *dev, 3046 struct acpi_spi_lookup *lookup) 3047 { 3048 const union acpi_object *obj; 3049 3050 if (!x86_apple_machine) 3051 return; 3052 3053 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj) 3054 && obj->buffer.length >= 4) 3055 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer; 3056 3057 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj) 3058 && obj->buffer.length == 8) 3059 lookup->bits_per_word = *(u64 *)obj->buffer.pointer; 3060 3061 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj) 3062 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer) 3063 lookup->mode |= SPI_LSB_FIRST; 3064 3065 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj) 3066 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer) 3067 lookup->mode |= SPI_CPOL; 3068 3069 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj) 3070 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer) 3071 lookup->mode |= SPI_CPHA; 3072 } 3073 3074 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data) 3075 { 3076 struct acpi_spi_lookup *lookup = data; 3077 struct spi_controller *ctlr = lookup->ctlr; 3078 3079 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) { 3080 struct acpi_resource_spi_serialbus *sb; 3081 acpi_handle parent_handle; 3082 acpi_status status; 3083 3084 sb = &ares->data.spi_serial_bus; 3085 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) { 3086 3087 if (lookup->index != -1 && lookup->n++ != lookup->index) 3088 return 1; 3089 3090 status = acpi_get_handle(lookup->device_handle, 3091 sb->resource_source.string_ptr, 3092 &parent_handle); 3093 3094 if (ACPI_FAILURE(status)) 3095 return -ENODEV; 3096 3097 if (ctlr) { 3098 if (!device_match_acpi_handle(ctlr->dev.parent, parent_handle)) 3099 return -ENODEV; 3100 } else { 3101 struct acpi_device *adev; 3102 3103 adev = acpi_fetch_acpi_dev(parent_handle); 3104 if (!adev) 3105 return -ENODEV; 3106 3107 ctlr = acpi_spi_find_controller_by_adev(adev); 3108 if (!ctlr) 3109 return -EPROBE_DEFER; 3110 3111 lookup->ctlr = ctlr; 3112 } 3113 3114 /* 3115 * ACPI DeviceSelection numbering is handled by the 3116 * host controller driver in Windows and can vary 3117 * from driver to driver. In Linux we always expect 3118 * 0 .. max - 1 so we need to ask the driver to 3119 * translate between the two schemes. 3120 */ 3121 if (ctlr->fw_translate_cs) { 3122 int cs = ctlr->fw_translate_cs(ctlr, 3123 sb->device_selection); 3124 if (cs < 0) 3125 return cs; 3126 lookup->chip_select = cs; 3127 } else { 3128 lookup->chip_select = sb->device_selection; 3129 } 3130 3131 lookup->max_speed_hz = sb->connection_speed; 3132 lookup->bits_per_word = sb->data_bit_length; 3133 3134 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE) 3135 lookup->mode |= SPI_CPHA; 3136 if (sb->clock_polarity == ACPI_SPI_START_HIGH) 3137 lookup->mode |= SPI_CPOL; 3138 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH) 3139 lookup->mode |= SPI_CS_HIGH; 3140 } 3141 } else if (lookup->irq < 0) { 3142 struct resource r; 3143 3144 if (acpi_dev_resource_interrupt(ares, 0, &r)) 3145 lookup->irq = r.start; 3146 } 3147 3148 /* Always tell the ACPI core to skip this resource */ 3149 return 1; 3150 } 3151 3152 /** 3153 * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information 3154 * @ctlr: controller to which the spi device belongs 3155 * @adev: ACPI Device for the spi device 3156 * @index: Index of the spi resource inside the ACPI Node 3157 * 3158 * This should be used to allocate a new SPI device from and ACPI Device node. 3159 * The caller is responsible for calling spi_add_device to register the SPI device. 3160 * 3161 * If ctlr is set to NULL, the Controller for the SPI device will be looked up 3162 * using the resource. 3163 * If index is set to -1, index is not used. 3164 * Note: If index is -1, ctlr must be set. 3165 * 3166 * Return: a pointer to the new device, or ERR_PTR on error. 3167 */ 3168 struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr, 3169 struct acpi_device *adev, 3170 int index) 3171 { 3172 acpi_handle parent_handle = NULL; 3173 struct list_head resource_list; 3174 struct acpi_spi_lookup lookup = {}; 3175 struct spi_device *spi; 3176 int ret; 3177 3178 if (!ctlr && index == -1) 3179 return ERR_PTR(-EINVAL); 3180 3181 lookup.ctlr = ctlr; 3182 lookup.device_handle = acpi_device_handle(adev); 3183 lookup.irq = -1; 3184 lookup.index = index; 3185 lookup.n = 0; 3186 3187 INIT_LIST_HEAD(&resource_list); 3188 ret = acpi_dev_get_resources(adev, &resource_list, 3189 acpi_spi_add_resource, &lookup); 3190 if (ret < 0) 3191 /* Found SPI in _CRS but it points to another controller */ 3192 return ERR_PTR(ret); 3193 3194 acpi_dev_free_resource_list(&resource_list); 3195 3196 if (!lookup.max_speed_hz && 3197 ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) && 3198 device_match_acpi_handle(lookup.ctlr->dev.parent, parent_handle)) { 3199 /* Apple does not use _CRS but nested devices for SPI target devices */ 3200 acpi_spi_parse_apple_properties(adev, &lookup); 3201 } 3202 3203 if (!lookup.max_speed_hz) 3204 return ERR_PTR(-ENODEV); 3205 3206 spi = spi_alloc_device(lookup.ctlr); 3207 if (!spi) { 3208 dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n", 3209 dev_name(&adev->dev)); 3210 return ERR_PTR(-ENOMEM); 3211 } 3212 3213 spi_set_chipselect(spi, 0, lookup.chip_select); 3214 3215 ACPI_COMPANION_SET(&spi->dev, adev); 3216 spi->max_speed_hz = lookup.max_speed_hz; 3217 spi->mode |= lookup.mode; 3218 spi->irq = lookup.irq; 3219 spi->bits_per_word = lookup.bits_per_word; 3220 /* 3221 * By default spi->chip_select[0] will hold the physical CS number, 3222 * so set bit 0 in spi->cs_index_mask. 3223 */ 3224 spi->cs_index_mask = BIT(0); 3225 3226 return spi; 3227 } 3228 EXPORT_SYMBOL_GPL(acpi_spi_device_alloc); 3229 3230 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr, 3231 struct acpi_device *adev) 3232 { 3233 struct spi_device *spi; 3234 3235 if (acpi_bus_get_status(adev) || !adev->status.present || 3236 acpi_device_enumerated(adev)) 3237 return AE_OK; 3238 3239 spi = acpi_spi_device_alloc(ctlr, adev, -1); 3240 if (IS_ERR(spi)) { 3241 if (PTR_ERR(spi) == -ENOMEM) 3242 return AE_NO_MEMORY; 3243 else 3244 return AE_OK; 3245 } 3246 3247 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias, 3248 sizeof(spi->modalias)); 3249 3250 /* 3251 * This gets re-tried in spi_probe() for -EPROBE_DEFER handling in case 3252 * the GPIO controller does not have a driver yet. This needs to be done 3253 * here too, because this call sets the GPIO direction and/or bias. 3254 * Setting these needs to be done even if there is no driver, in which 3255 * case spi_probe() will never get called. 3256 * TODO: ideally the setup of the GPIO should be handled in a generic 3257 * manner in the ACPI/gpiolib core code. 3258 */ 3259 if (spi->irq < 0) 3260 spi->irq = acpi_dev_gpio_irq_get(adev, 0); 3261 3262 acpi_device_set_enumerated(adev); 3263 3264 adev->power.flags.ignore_parent = true; 3265 if (spi_add_device(spi)) { 3266 adev->power.flags.ignore_parent = false; 3267 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n", 3268 dev_name(&adev->dev)); 3269 spi_dev_put(spi); 3270 } 3271 3272 return AE_OK; 3273 } 3274 3275 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level, 3276 void *data, void **return_value) 3277 { 3278 struct acpi_device *adev = acpi_fetch_acpi_dev(handle); 3279 struct spi_controller *ctlr = data; 3280 3281 if (!adev) 3282 return AE_OK; 3283 3284 return acpi_register_spi_device(ctlr, adev); 3285 } 3286 3287 #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32 3288 3289 static void acpi_register_spi_devices(struct spi_controller *ctlr) 3290 { 3291 acpi_status status; 3292 acpi_handle handle; 3293 3294 handle = ACPI_HANDLE(ctlr->dev.parent); 3295 if (!handle) 3296 return; 3297 3298 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT, 3299 SPI_ACPI_ENUMERATE_MAX_DEPTH, 3300 acpi_spi_add_device, NULL, ctlr, NULL); 3301 if (ACPI_FAILURE(status)) 3302 dev_warn(&ctlr->dev, "failed to enumerate SPI target devices\n"); 3303 } 3304 #else 3305 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {} 3306 #endif /* CONFIG_ACPI */ 3307 3308 static void spi_controller_release(struct device *dev) 3309 { 3310 struct spi_controller *ctlr; 3311 3312 ctlr = container_of(dev, struct spi_controller, dev); 3313 3314 free_percpu(ctlr->pcpu_statistics); 3315 kfree(ctlr); 3316 } 3317 3318 static const struct class spi_controller_class = { 3319 .name = "spi_master", 3320 .dev_release = spi_controller_release, 3321 .dev_groups = spi_controller_groups, 3322 }; 3323 3324 #ifdef CONFIG_SPI_SLAVE 3325 /** 3326 * spi_target_abort - abort the ongoing transfer request on an SPI target controller 3327 * @spi: device used for the current transfer 3328 */ 3329 int spi_target_abort(struct spi_device *spi) 3330 { 3331 struct spi_controller *ctlr = spi->controller; 3332 3333 if (spi_controller_is_target(ctlr) && ctlr->target_abort) 3334 return ctlr->target_abort(ctlr); 3335 3336 return -ENOTSUPP; 3337 } 3338 EXPORT_SYMBOL_GPL(spi_target_abort); 3339 3340 static ssize_t slave_show(struct device *dev, struct device_attribute *attr, 3341 char *buf) 3342 { 3343 struct spi_controller *ctlr = container_of(dev, struct spi_controller, 3344 dev); 3345 struct device *child; 3346 int ret; 3347 3348 child = device_find_any_child(&ctlr->dev); 3349 ret = sysfs_emit(buf, "%s\n", child ? to_spi_device(child)->modalias : NULL); 3350 put_device(child); 3351 3352 return ret; 3353 } 3354 3355 static ssize_t slave_store(struct device *dev, struct device_attribute *attr, 3356 const char *buf, size_t count) 3357 { 3358 struct spi_controller *ctlr = container_of(dev, struct spi_controller, 3359 dev); 3360 struct spi_device *spi; 3361 struct device *child; 3362 char name[32]; 3363 int rc; 3364 3365 rc = sscanf(buf, "%31s", name); 3366 if (rc != 1 || !name[0]) 3367 return -EINVAL; 3368 3369 child = device_find_any_child(&ctlr->dev); 3370 if (child) { 3371 /* Remove registered target device */ 3372 device_unregister(child); 3373 put_device(child); 3374 } 3375 3376 if (strcmp(name, "(null)")) { 3377 /* Register new target device */ 3378 spi = spi_alloc_device(ctlr); 3379 if (!spi) 3380 return -ENOMEM; 3381 3382 strscpy(spi->modalias, name, sizeof(spi->modalias)); 3383 3384 rc = spi_add_device(spi); 3385 if (rc) { 3386 spi_dev_put(spi); 3387 return rc; 3388 } 3389 } 3390 3391 return count; 3392 } 3393 3394 static DEVICE_ATTR_RW(slave); 3395 3396 static struct attribute *spi_target_attrs[] = { 3397 &dev_attr_slave.attr, 3398 NULL, 3399 }; 3400 3401 static const struct attribute_group spi_target_group = { 3402 .attrs = spi_target_attrs, 3403 }; 3404 3405 static const struct attribute_group *spi_target_groups[] = { 3406 &spi_controller_statistics_group, 3407 &spi_target_group, 3408 NULL, 3409 }; 3410 3411 static const struct class spi_target_class = { 3412 .name = "spi_slave", 3413 .dev_release = spi_controller_release, 3414 .dev_groups = spi_target_groups, 3415 }; 3416 #else 3417 extern struct class spi_target_class; /* dummy */ 3418 #endif 3419 3420 /** 3421 * __spi_alloc_controller - allocate an SPI host or target controller 3422 * @dev: the controller, possibly using the platform_bus 3423 * @size: how much zeroed driver-private data to allocate; the pointer to this 3424 * memory is in the driver_data field of the returned device, accessible 3425 * with spi_controller_get_devdata(); the memory is cacheline aligned; 3426 * drivers granting DMA access to portions of their private data need to 3427 * round up @size using ALIGN(size, dma_get_cache_alignment()). 3428 * @target: flag indicating whether to allocate an SPI host (false) or SPI target (true) 3429 * controller 3430 * Context: can sleep 3431 * 3432 * This call is used only by SPI controller drivers, which are the 3433 * only ones directly touching chip registers. It's how they allocate 3434 * an spi_controller structure, prior to calling spi_register_controller(). 3435 * 3436 * This must be called from context that can sleep. 3437 * 3438 * The caller is responsible for assigning the bus number and initializing the 3439 * controller's methods before calling spi_register_controller(); and calling 3440 * spi_controller_put() to prevent a memory leak when done with the 3441 * controller. 3442 * 3443 * Return: the SPI controller structure on success, else NULL. 3444 */ 3445 struct spi_controller *__spi_alloc_controller(struct device *dev, 3446 unsigned int size, bool target) 3447 { 3448 struct spi_controller *ctlr; 3449 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment()); 3450 3451 if (!dev) 3452 return NULL; 3453 3454 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL); 3455 if (!ctlr) 3456 return NULL; 3457 3458 ctlr->pcpu_statistics = spi_alloc_pcpu_stats(); 3459 if (!ctlr->pcpu_statistics) { 3460 kfree(ctlr); 3461 return NULL; 3462 } 3463 3464 device_initialize(&ctlr->dev); 3465 INIT_LIST_HEAD(&ctlr->queue); 3466 spin_lock_init(&ctlr->queue_lock); 3467 spin_lock_init(&ctlr->bus_lock_spinlock); 3468 mutex_init(&ctlr->bus_lock_mutex); 3469 mutex_init(&ctlr->io_mutex); 3470 mutex_init(&ctlr->add_lock); 3471 #if IS_ENABLED(CONFIG_SPI_DYNAMIC) 3472 INIT_LIST_HEAD(&ctlr->userspace_clients); 3473 #endif 3474 ctlr->bus_num = -1; 3475 ctlr->num_chipselect = 1; 3476 ctlr->num_data_lanes = 1; 3477 ctlr->target = target; 3478 if (IS_ENABLED(CONFIG_SPI_SLAVE) && target) 3479 ctlr->dev.class = &spi_target_class; 3480 else 3481 ctlr->dev.class = &spi_controller_class; 3482 ctlr->dev.parent = dev; 3483 3484 device_set_node(&ctlr->dev, dev_fwnode(dev)); 3485 3486 pm_suspend_ignore_children(&ctlr->dev, true); 3487 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size); 3488 3489 return ctlr; 3490 } 3491 EXPORT_SYMBOL_GPL(__spi_alloc_controller); 3492 3493 static void devm_spi_release_controller(void *ctlr) 3494 { 3495 spi_controller_put(ctlr); 3496 } 3497 3498 /** 3499 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller() 3500 * @dev: physical device of SPI controller 3501 * @size: how much zeroed driver-private data to allocate 3502 * @target: whether to allocate an SPI host (false) or SPI target (true) controller 3503 * Context: can sleep 3504 * 3505 * Allocate an SPI controller and automatically release a reference on it 3506 * when @dev is unbound from its driver. Drivers are thus relieved from 3507 * having to call spi_controller_put(). 3508 * 3509 * The arguments to this function are identical to __spi_alloc_controller(). 3510 * 3511 * Return: the SPI controller structure on success, else NULL. 3512 */ 3513 struct spi_controller *__devm_spi_alloc_controller(struct device *dev, 3514 unsigned int size, 3515 bool target) 3516 { 3517 struct spi_controller *ctlr; 3518 int ret; 3519 3520 ctlr = __spi_alloc_controller(dev, size, target); 3521 if (!ctlr) 3522 return NULL; 3523 3524 ret = devm_add_action_or_reset(dev, devm_spi_release_controller, ctlr); 3525 if (ret) 3526 return NULL; 3527 3528 return ctlr; 3529 } 3530 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller); 3531 3532 /** 3533 * spi_get_gpio_descs() - grab chip select GPIOs for the controller 3534 * @ctlr: The SPI controller to grab GPIO descriptors for 3535 */ 3536 static int spi_get_gpio_descs(struct spi_controller *ctlr) 3537 { 3538 int nb, i; 3539 struct gpio_desc **cs; 3540 struct device *dev = &ctlr->dev; 3541 unsigned long native_cs_mask = 0; 3542 unsigned int num_cs_gpios = 0; 3543 3544 nb = gpiod_count(dev, "cs"); 3545 if (nb < 0) { 3546 /* No GPIOs at all is fine, else return the error */ 3547 if (nb == -ENOENT) 3548 return 0; 3549 return nb; 3550 } 3551 3552 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect); 3553 3554 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs), 3555 GFP_KERNEL); 3556 if (!cs) 3557 return -ENOMEM; 3558 ctlr->cs_gpiods = cs; 3559 3560 for (i = 0; i < nb; i++) { 3561 /* 3562 * Most chipselects are active low, the inverted 3563 * semantics are handled by special quirks in gpiolib, 3564 * so initializing them GPIOD_OUT_LOW here means 3565 * "unasserted", in most cases this will drive the physical 3566 * line high. 3567 */ 3568 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i, 3569 GPIOD_OUT_LOW); 3570 if (IS_ERR(cs[i])) 3571 return PTR_ERR(cs[i]); 3572 3573 if (cs[i]) { 3574 /* 3575 * If we find a CS GPIO, name it after the device and 3576 * chip select line. 3577 */ 3578 char *gpioname; 3579 3580 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d", 3581 dev_name(dev), i); 3582 if (!gpioname) 3583 return -ENOMEM; 3584 gpiod_set_consumer_name(cs[i], gpioname); 3585 num_cs_gpios++; 3586 continue; 3587 } 3588 3589 if (ctlr->max_native_cs && i >= ctlr->max_native_cs) { 3590 dev_err(dev, "Invalid native chip select %d\n", i); 3591 return -EINVAL; 3592 } 3593 native_cs_mask |= BIT(i); 3594 } 3595 3596 ctlr->unused_native_cs = ffs(~native_cs_mask) - 1; 3597 3598 if ((ctlr->flags & SPI_CONTROLLER_GPIO_SS) && num_cs_gpios && 3599 ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) { 3600 dev_err(dev, "No unused native chip select available\n"); 3601 return -EINVAL; 3602 } 3603 3604 return 0; 3605 } 3606 3607 static int spi_controller_check_ops(struct spi_controller *ctlr) 3608 { 3609 /* 3610 * The controller may implement only the high-level SPI-memory like 3611 * operations if it does not support regular SPI transfers, and this is 3612 * valid use case. 3613 * If ->mem_ops or ->mem_ops->exec_op is NULL, we request that at least 3614 * one of the ->transfer_xxx() method be implemented. 3615 */ 3616 if (!ctlr->mem_ops || !ctlr->mem_ops->exec_op) { 3617 if (!ctlr->transfer && !ctlr->transfer_one && 3618 !ctlr->transfer_one_message) { 3619 return -EINVAL; 3620 } 3621 } 3622 3623 return 0; 3624 } 3625 3626 /* Allocate dynamic bus number using Linux idr */ 3627 static int spi_controller_id_alloc(struct spi_controller *ctlr, int start, int end) 3628 { 3629 int id; 3630 3631 mutex_lock(&board_lock); 3632 id = idr_alloc(&spi_controller_idr, ctlr, start, end, GFP_KERNEL); 3633 mutex_unlock(&board_lock); 3634 if (WARN(id < 0, "couldn't get idr")) 3635 return id == -ENOSPC ? -EBUSY : id; 3636 ctlr->bus_num = id; 3637 return 0; 3638 } 3639 3640 /** 3641 * spi_register_controller - register SPI host or target controller 3642 * @ctlr: initialized controller, originally from spi_alloc_host() or 3643 * spi_alloc_target() 3644 * Context: can sleep 3645 * 3646 * SPI controllers connect to their drivers using some non-SPI bus, 3647 * such as the platform bus. The final stage of probe() in that code 3648 * includes calling spi_register_controller() to hook up to this SPI bus glue. 3649 * 3650 * SPI controllers use board specific (often SOC specific) bus numbers, 3651 * and board-specific addressing for SPI devices combines those numbers 3652 * with chip select numbers. Since SPI does not directly support dynamic 3653 * device identification, boards need configuration tables telling which 3654 * chip is at which address. 3655 * 3656 * This must be called from context that can sleep. 3657 * 3658 * After a successful return, the caller is responsible for calling 3659 * spi_unregister_controller(). 3660 * 3661 * Return: zero on success, else a negative error code. 3662 */ 3663 int spi_register_controller(struct spi_controller *ctlr) 3664 { 3665 struct device *dev = ctlr->dev.parent; 3666 struct boardinfo *bi; 3667 int first_dynamic; 3668 int status; 3669 int idx; 3670 3671 if (!dev) 3672 return -ENODEV; 3673 3674 /* 3675 * Make sure all necessary hooks are implemented before registering 3676 * the SPI controller. 3677 */ 3678 status = spi_controller_check_ops(ctlr); 3679 if (status) 3680 return status; 3681 3682 if (ctlr->bus_num < 0) 3683 ctlr->bus_num = of_alias_get_id(ctlr->dev.of_node, "spi"); 3684 if (ctlr->bus_num >= 0) { 3685 /* Devices with a fixed bus num must check-in with the num */ 3686 status = spi_controller_id_alloc(ctlr, ctlr->bus_num, ctlr->bus_num + 1); 3687 if (status) 3688 return status; 3689 } 3690 if (ctlr->bus_num < 0) { 3691 first_dynamic = of_alias_get_highest_id("spi"); 3692 if (first_dynamic < 0) 3693 first_dynamic = 0; 3694 else 3695 first_dynamic++; 3696 3697 status = spi_controller_id_alloc(ctlr, first_dynamic, 0); 3698 if (status) 3699 return status; 3700 } 3701 ctlr->bus_lock_flag = 0; 3702 init_completion(&ctlr->xfer_completion); 3703 init_completion(&ctlr->cur_msg_completion); 3704 if (!ctlr->max_dma_len) 3705 ctlr->max_dma_len = INT_MAX; 3706 3707 /* 3708 * Register the device, then userspace will see it. 3709 * Registration fails if the bus ID is in use. 3710 */ 3711 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num); 3712 3713 if (!spi_controller_is_target(ctlr) && ctlr->use_gpio_descriptors) { 3714 status = spi_get_gpio_descs(ctlr); 3715 if (status) 3716 goto free_bus_id; 3717 /* 3718 * A controller using GPIO descriptors always 3719 * supports SPI_CS_HIGH if need be. 3720 */ 3721 ctlr->mode_bits |= SPI_CS_HIGH; 3722 } 3723 3724 /* 3725 * Even if it's just one always-selected device, there must 3726 * be at least one chipselect. 3727 */ 3728 if (!ctlr->num_chipselect) { 3729 status = -EINVAL; 3730 goto free_bus_id; 3731 } 3732 3733 /* Setting last_cs to SPI_INVALID_CS means no chip selected */ 3734 for (idx = 0; idx < SPI_DEVICE_CS_CNT_MAX; idx++) 3735 ctlr->last_cs[idx] = SPI_INVALID_CS; 3736 3737 status = device_add(&ctlr->dev); 3738 if (status < 0) 3739 goto free_bus_id; 3740 dev_dbg(dev, "registered %s %s\n", 3741 spi_controller_is_target(ctlr) ? "target" : "host", 3742 dev_name(&ctlr->dev)); 3743 3744 /* 3745 * If we're using a queued driver, start the queue. Note that we don't 3746 * need the queueing logic if the driver is only supporting high-level 3747 * memory operations. 3748 */ 3749 if (ctlr->transfer) { 3750 dev_info(dev, "controller is unqueued, this is deprecated\n"); 3751 } else if (ctlr->transfer_one || ctlr->transfer_one_message) { 3752 status = spi_controller_initialize_queue(ctlr); 3753 if (status) 3754 goto del_ctrl; 3755 } 3756 3757 mutex_lock(&board_lock); 3758 list_add_tail(&ctlr->list, &spi_controller_list); 3759 list_for_each_entry(bi, &board_list, list) 3760 spi_match_controller_to_boardinfo(ctlr, &bi->board_info); 3761 mutex_unlock(&board_lock); 3762 3763 /* Register devices from the device tree and ACPI */ 3764 of_register_spi_devices(ctlr); 3765 acpi_register_spi_devices(ctlr); 3766 3767 #if IS_ENABLED(CONFIG_SPI_DYNAMIC) 3768 /* 3769 * Register the new_device/delete_device sysfs interface as the 3770 * final step of host controller bringup, only after the queue, 3771 * boardinfo matching and DT/ACPI enumeration have all completed. 3772 * If this fails, the controller is otherwise usable, so log and 3773 * carry on rather than tearing everything down. 3774 */ 3775 if (!spi_controller_is_target(ctlr)) { 3776 status = sysfs_create_group(&ctlr->dev.kobj, 3777 &spi_controller_userspace_group); 3778 if (status) { 3779 dev_warn(&ctlr->dev, 3780 "Failed to create userspace client interface: %d\n", 3781 status); 3782 } else { 3783 ctlr->userspace_registered = true; 3784 /* Notify userspace that the new attributes are available. */ 3785 kobject_uevent(&ctlr->dev.kobj, KOBJ_CHANGE); 3786 } 3787 } 3788 #endif 3789 3790 return 0; 3791 3792 del_ctrl: 3793 device_del(&ctlr->dev); 3794 free_bus_id: 3795 mutex_lock(&board_lock); 3796 idr_remove(&spi_controller_idr, ctlr->bus_num); 3797 mutex_unlock(&board_lock); 3798 3799 return status; 3800 } 3801 EXPORT_SYMBOL_GPL(spi_register_controller); 3802 3803 static void devm_spi_unregister_controller(void *ctlr) 3804 { 3805 spi_unregister_controller(ctlr); 3806 } 3807 3808 /** 3809 * devm_spi_register_controller - register managed SPI host or target controller 3810 * @dev: device managing SPI controller 3811 * @ctlr: initialized controller, originally from spi_alloc_host() or 3812 * spi_alloc_target() 3813 * Context: can sleep 3814 * 3815 * Register a SPI device as with spi_register_controller() which will 3816 * automatically be unregistered. 3817 * 3818 * Return: zero on success, else a negative error code. 3819 */ 3820 int devm_spi_register_controller(struct device *dev, 3821 struct spi_controller *ctlr) 3822 { 3823 int ret; 3824 3825 ret = spi_register_controller(ctlr); 3826 if (ret) 3827 return ret; 3828 3829 return devm_add_action_or_reset(dev, devm_spi_unregister_controller, ctlr); 3830 } 3831 EXPORT_SYMBOL_GPL(devm_spi_register_controller); 3832 3833 static int __unregister(struct device *dev, void *null) 3834 { 3835 spi_unregister_device(to_spi_device(dev)); 3836 return 0; 3837 } 3838 3839 /** 3840 * spi_unregister_controller - unregister SPI host or target controller 3841 * @ctlr: the controller being unregistered 3842 * Context: can sleep 3843 * 3844 * This call is used only by SPI controller drivers, which are the 3845 * only ones directly touching chip registers. 3846 * 3847 * This must be called from context that can sleep. 3848 */ 3849 void spi_unregister_controller(struct spi_controller *ctlr) 3850 { 3851 struct spi_controller *found; 3852 int id = ctlr->bus_num; 3853 3854 /* 3855 * Drain in-flight new_device/delete_device sysfs stores and 3856 * prevent new ones from starting. Must happen before we take 3857 * add_lock so kernfs_drain doesn't wait on a store that is 3858 * itself blocked on add_lock. 3859 */ 3860 #if IS_ENABLED(CONFIG_SPI_DYNAMIC) 3861 if (ctlr->userspace_registered) { 3862 sysfs_remove_group(&ctlr->dev.kobj, 3863 &spi_controller_userspace_group); 3864 ctlr->userspace_registered = false; 3865 } 3866 #endif 3867 3868 /* Prevent addition of new devices, unregister existing ones */ 3869 if (IS_ENABLED(CONFIG_SPI_DYNAMIC)) 3870 mutex_lock(&ctlr->add_lock); 3871 3872 #if IS_ENABLED(CONFIG_SPI_DYNAMIC) 3873 /* 3874 * Drain userspace_clients before __unregister since 3875 * spi_unregister_device() doesn't do list_del() itself. The 3876 * userspace sysfs group has already been removed above and 3877 * kernfs_drain() has completed, so no new entries can appear 3878 * here. 3879 */ 3880 while (!list_empty(&ctlr->userspace_clients)) { 3881 struct spi_device *spi; 3882 3883 spi = list_first_entry(&ctlr->userspace_clients, 3884 struct spi_device, 3885 userspace_node); 3886 list_del(&spi->userspace_node); 3887 spi_unregister_device(spi); 3888 } 3889 #endif 3890 3891 device_for_each_child(&ctlr->dev, NULL, __unregister); 3892 3893 /* First make sure that this controller was ever added */ 3894 mutex_lock(&board_lock); 3895 found = idr_find(&spi_controller_idr, id); 3896 mutex_unlock(&board_lock); 3897 if (ctlr->queued) { 3898 if (spi_destroy_queue(ctlr)) 3899 dev_err(&ctlr->dev, "queue remove failed\n"); 3900 } 3901 mutex_lock(&board_lock); 3902 list_del(&ctlr->list); 3903 mutex_unlock(&board_lock); 3904 3905 device_del(&ctlr->dev); 3906 3907 /* Free bus id */ 3908 mutex_lock(&board_lock); 3909 if (found == ctlr) 3910 idr_remove(&spi_controller_idr, id); 3911 mutex_unlock(&board_lock); 3912 3913 if (IS_ENABLED(CONFIG_SPI_DYNAMIC)) 3914 mutex_unlock(&ctlr->add_lock); 3915 } 3916 EXPORT_SYMBOL_GPL(spi_unregister_controller); 3917 3918 static inline int __spi_check_suspended(const struct spi_controller *ctlr) 3919 { 3920 return ctlr->flags & SPI_CONTROLLER_SUSPENDED ? -ESHUTDOWN : 0; 3921 } 3922 3923 static inline void __spi_mark_suspended(struct spi_controller *ctlr) 3924 { 3925 mutex_lock(&ctlr->bus_lock_mutex); 3926 ctlr->flags |= SPI_CONTROLLER_SUSPENDED; 3927 mutex_unlock(&ctlr->bus_lock_mutex); 3928 } 3929 3930 static inline void __spi_mark_resumed(struct spi_controller *ctlr) 3931 { 3932 mutex_lock(&ctlr->bus_lock_mutex); 3933 ctlr->flags &= ~SPI_CONTROLLER_SUSPENDED; 3934 mutex_unlock(&ctlr->bus_lock_mutex); 3935 } 3936 3937 int spi_controller_suspend(struct spi_controller *ctlr) 3938 { 3939 int ret = 0; 3940 3941 if (ctlr->cur_msg && spi_controller_is_target(ctlr) && ctlr->target_abort) 3942 ctlr->target_abort(ctlr); 3943 3944 /* Basically no-ops for non-queued controllers */ 3945 if (ctlr->queued) { 3946 ret = spi_stop_queue(ctlr); 3947 if (ret) 3948 dev_err(&ctlr->dev, "queue stop failed\n"); 3949 } 3950 3951 __spi_mark_suspended(ctlr); 3952 return ret; 3953 } 3954 EXPORT_SYMBOL_GPL(spi_controller_suspend); 3955 3956 int spi_controller_resume(struct spi_controller *ctlr) 3957 { 3958 int ret = 0; 3959 3960 __spi_mark_resumed(ctlr); 3961 3962 if (ctlr->queued) { 3963 ret = spi_start_queue(ctlr); 3964 if (ret) 3965 dev_err(&ctlr->dev, "queue restart failed\n"); 3966 } 3967 return ret; 3968 } 3969 EXPORT_SYMBOL_GPL(spi_controller_resume); 3970 3971 /*-------------------------------------------------------------------------*/ 3972 3973 /* Core methods for spi_message alterations */ 3974 3975 static void __spi_replace_transfers_release(struct spi_controller *ctlr, 3976 struct spi_message *msg, 3977 void *res) 3978 { 3979 struct spi_replaced_transfers *rxfer = res; 3980 size_t i; 3981 3982 /* Call extra callback if requested */ 3983 if (rxfer->release) 3984 rxfer->release(ctlr, msg, res); 3985 3986 /* Insert replaced transfers back into the message */ 3987 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after); 3988 3989 /* Remove the formerly inserted entries */ 3990 for (i = 0; i < rxfer->inserted; i++) 3991 list_del(&rxfer->inserted_transfers[i].transfer_list); 3992 } 3993 3994 /** 3995 * spi_replace_transfers - replace transfers with several transfers 3996 * and register change with spi_message.resources 3997 * @msg: the spi_message we work upon 3998 * @xfer_first: the first spi_transfer we want to replace 3999 * @remove: number of transfers to remove 4000 * @insert: the number of transfers we want to insert instead 4001 * @release: extra release code necessary in some circumstances 4002 * @extradatasize: extra data to allocate (with alignment guarantees 4003 * of struct @spi_transfer) 4004 * @gfp: gfp flags 4005 * 4006 * Returns: pointer to @spi_replaced_transfers, 4007 * PTR_ERR(...) in case of errors. 4008 */ 4009 static struct spi_replaced_transfers *spi_replace_transfers( 4010 struct spi_message *msg, 4011 struct spi_transfer *xfer_first, 4012 size_t remove, 4013 size_t insert, 4014 spi_replaced_release_t release, 4015 size_t extradatasize, 4016 gfp_t gfp) 4017 { 4018 struct spi_replaced_transfers *rxfer; 4019 struct spi_transfer *xfer; 4020 size_t i; 4021 4022 /* Allocate the structure using spi_res */ 4023 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release, 4024 struct_size(rxfer, inserted_transfers, insert) 4025 + extradatasize, 4026 gfp); 4027 if (!rxfer) 4028 return ERR_PTR(-ENOMEM); 4029 4030 /* The release code to invoke before running the generic release */ 4031 rxfer->release = release; 4032 4033 /* Assign extradata */ 4034 if (extradatasize) 4035 rxfer->extradata = 4036 &rxfer->inserted_transfers[insert]; 4037 4038 /* Init the replaced_transfers list */ 4039 INIT_LIST_HEAD(&rxfer->replaced_transfers); 4040 4041 /* 4042 * Assign the list_entry after which we should reinsert 4043 * the @replaced_transfers - it may be spi_message.messages! 4044 */ 4045 rxfer->replaced_after = xfer_first->transfer_list.prev; 4046 4047 /* Remove the requested number of transfers */ 4048 for (i = 0; i < remove; i++) { 4049 /* 4050 * If the entry after replaced_after it is msg->transfers 4051 * then we have been requested to remove more transfers 4052 * than are in the list. 4053 */ 4054 if (rxfer->replaced_after->next == &msg->transfers) { 4055 dev_err(&msg->spi->dev, 4056 "requested to remove more spi_transfers than are available\n"); 4057 /* Insert replaced transfers back into the message */ 4058 list_splice(&rxfer->replaced_transfers, 4059 rxfer->replaced_after); 4060 4061 /* Free the spi_replace_transfer structure... */ 4062 spi_res_free(rxfer); 4063 4064 /* ...and return with an error */ 4065 return ERR_PTR(-EINVAL); 4066 } 4067 4068 /* 4069 * Remove the entry after replaced_after from list of 4070 * transfers and add it to list of replaced_transfers. 4071 */ 4072 list_move_tail(rxfer->replaced_after->next, 4073 &rxfer->replaced_transfers); 4074 } 4075 4076 /* 4077 * Create copy of the given xfer with identical settings 4078 * based on the first transfer to get removed. 4079 */ 4080 for (i = 0; i < insert; i++) { 4081 /* We need to run in reverse order */ 4082 xfer = &rxfer->inserted_transfers[insert - 1 - i]; 4083 4084 /* Copy all spi_transfer data */ 4085 memcpy(xfer, xfer_first, sizeof(*xfer)); 4086 4087 /* Add to list */ 4088 list_add(&xfer->transfer_list, rxfer->replaced_after); 4089 4090 /* Clear cs_change and delay for all but the last */ 4091 if (i) { 4092 xfer->cs_change = false; 4093 xfer->delay.value = 0; 4094 } 4095 } 4096 4097 /* Set up inserted... */ 4098 rxfer->inserted = insert; 4099 4100 /* ...and register it with spi_res/spi_message */ 4101 spi_res_add(msg, rxfer); 4102 4103 return rxfer; 4104 } 4105 4106 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr, 4107 struct spi_message *msg, 4108 struct spi_transfer **xferp, 4109 size_t maxsize) 4110 { 4111 struct spi_transfer *xfer = *xferp, *xfers; 4112 struct spi_replaced_transfers *srt; 4113 size_t offset; 4114 size_t count, i; 4115 4116 /* Calculate how many we have to replace */ 4117 count = DIV_ROUND_UP(xfer->len, maxsize); 4118 4119 /* Create replacement */ 4120 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, GFP_KERNEL); 4121 if (IS_ERR(srt)) 4122 return PTR_ERR(srt); 4123 xfers = srt->inserted_transfers; 4124 4125 /* 4126 * Now handle each of those newly inserted spi_transfers. 4127 * Note that the replacements spi_transfers all are preset 4128 * to the same values as *xferp, so tx_buf, rx_buf and len 4129 * are all identical (as well as most others) 4130 * so we just have to fix up len and the pointers. 4131 */ 4132 4133 /* 4134 * The first transfer just needs the length modified, so we 4135 * run it outside the loop. 4136 */ 4137 xfers[0].len = min_t(size_t, maxsize, xfer[0].len); 4138 4139 /* All the others need rx_buf/tx_buf also set */ 4140 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) { 4141 /* Update rx_buf, tx_buf and DMA */ 4142 if (xfers[i].rx_buf) 4143 xfers[i].rx_buf += offset; 4144 if (xfers[i].tx_buf) 4145 xfers[i].tx_buf += offset; 4146 4147 /* Update length */ 4148 xfers[i].len = min(maxsize, xfers[i].len - offset); 4149 } 4150 4151 /* 4152 * We set up xferp to the last entry we have inserted, 4153 * so that we skip those already split transfers. 4154 */ 4155 *xferp = &xfers[count - 1]; 4156 4157 /* Increment statistics counters */ 4158 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, 4159 transfers_split_maxsize); 4160 SPI_STATISTICS_INCREMENT_FIELD(msg->spi->pcpu_statistics, 4161 transfers_split_maxsize); 4162 4163 return 0; 4164 } 4165 4166 /** 4167 * spi_split_transfers_maxsize - split spi transfers into multiple transfers 4168 * when an individual transfer exceeds a 4169 * certain size 4170 * @ctlr: the @spi_controller for this transfer 4171 * @msg: the @spi_message to transform 4172 * @maxsize: the maximum when to apply this 4173 * 4174 * This function allocates resources that are automatically freed during the 4175 * spi message unoptimize phase so this function should only be called from 4176 * optimize_message callbacks. 4177 * 4178 * Return: status of transformation 4179 */ 4180 int spi_split_transfers_maxsize(struct spi_controller *ctlr, 4181 struct spi_message *msg, 4182 size_t maxsize) 4183 { 4184 struct spi_transfer *xfer; 4185 int ret; 4186 4187 /* 4188 * Iterate over the transfer_list, 4189 * but note that xfer is advanced to the last transfer inserted 4190 * to avoid checking sizes again unnecessarily (also xfer does 4191 * potentially belong to a different list by the time the 4192 * replacement has happened). 4193 */ 4194 list_for_each_entry(xfer, &msg->transfers, transfer_list) { 4195 if (xfer->len > maxsize) { 4196 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer, 4197 maxsize); 4198 if (ret) 4199 return ret; 4200 } 4201 } 4202 4203 return 0; 4204 } 4205 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize); 4206 4207 4208 /** 4209 * spi_split_transfers_maxwords - split SPI transfers into multiple transfers 4210 * when an individual transfer exceeds a 4211 * certain number of SPI words 4212 * @ctlr: the @spi_controller for this transfer 4213 * @msg: the @spi_message to transform 4214 * @maxwords: the number of words to limit each transfer to 4215 * 4216 * This function allocates resources that are automatically freed during the 4217 * spi message unoptimize phase so this function should only be called from 4218 * optimize_message callbacks. 4219 * 4220 * Return: status of transformation 4221 */ 4222 int spi_split_transfers_maxwords(struct spi_controller *ctlr, 4223 struct spi_message *msg, 4224 size_t maxwords) 4225 { 4226 struct spi_transfer *xfer; 4227 4228 /* 4229 * Iterate over the transfer_list, 4230 * but note that xfer is advanced to the last transfer inserted 4231 * to avoid checking sizes again unnecessarily (also xfer does 4232 * potentially belong to a different list by the time the 4233 * replacement has happened). 4234 */ 4235 list_for_each_entry(xfer, &msg->transfers, transfer_list) { 4236 size_t maxsize; 4237 int ret; 4238 4239 maxsize = maxwords * spi_bpw_to_bytes(xfer->bits_per_word); 4240 if (xfer->len > maxsize) { 4241 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer, 4242 maxsize); 4243 if (ret) 4244 return ret; 4245 } 4246 } 4247 4248 return 0; 4249 } 4250 EXPORT_SYMBOL_GPL(spi_split_transfers_maxwords); 4251 4252 /*-------------------------------------------------------------------------*/ 4253 4254 /* 4255 * Core methods for SPI controller protocol drivers. Some of the 4256 * other core methods are currently defined as inline functions. 4257 */ 4258 4259 static int __spi_validate_bits_per_word(struct spi_controller *ctlr, 4260 u8 bits_per_word) 4261 { 4262 if (ctlr->bits_per_word_mask) { 4263 /* Only 32 bits fit in the mask */ 4264 if (bits_per_word > 32) 4265 return -EINVAL; 4266 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word))) 4267 return -EINVAL; 4268 } 4269 4270 return 0; 4271 } 4272 4273 /** 4274 * spi_set_cs_timing - configure CS setup, hold, and inactive delays 4275 * @spi: the device that requires specific CS timing configuration 4276 * 4277 * Return: zero on success, else a negative error code. 4278 */ 4279 static int spi_set_cs_timing(struct spi_device *spi) 4280 { 4281 struct device *parent = spi->controller->dev.parent; 4282 int status = 0; 4283 4284 if (spi->controller->set_cs_timing && !spi_get_csgpiod(spi, 0)) { 4285 if (spi->controller->auto_runtime_pm) { 4286 status = pm_runtime_get_sync(parent); 4287 if (status < 0) { 4288 pm_runtime_put_noidle(parent); 4289 dev_err(&spi->controller->dev, "Failed to power device: %d\n", 4290 status); 4291 return status; 4292 } 4293 4294 status = spi->controller->set_cs_timing(spi); 4295 pm_runtime_put_autosuspend(parent); 4296 } else { 4297 status = spi->controller->set_cs_timing(spi); 4298 } 4299 } 4300 return status; 4301 } 4302 4303 static int __spi_setup(struct spi_device *spi, bool initial_setup) 4304 { 4305 unsigned bad_bits, ugly_bits; 4306 int status; 4307 4308 /* 4309 * Check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO 4310 * are set at the same time. 4311 */ 4312 if ((hweight_long(spi->mode & 4313 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) || 4314 (hweight_long(spi->mode & 4315 (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) { 4316 dev_err(&spi->dev, 4317 "setup: can not select any two of dual, quad and no-rx/tx at the same time\n"); 4318 return -EINVAL; 4319 } 4320 /* If it is SPI_3WIRE mode, DUAL and QUAD should be forbidden */ 4321 if ((spi->mode & SPI_3WIRE) && (spi->mode & 4322 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL | 4323 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL))) 4324 return -EINVAL; 4325 /* Check against conflicting MOSI idle configuration */ 4326 if ((spi->mode & SPI_MOSI_IDLE_LOW) && (spi->mode & SPI_MOSI_IDLE_HIGH)) { 4327 dev_err(&spi->dev, 4328 "setup: MOSI configured to idle low and high at the same time.\n"); 4329 return -EINVAL; 4330 } 4331 /* 4332 * Help drivers fail *cleanly* when they need options 4333 * that aren't supported with their current controller. 4334 * SPI_CS_WORD has a fallback software implementation, 4335 * so it is ignored here. 4336 */ 4337 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD | 4338 SPI_NO_TX | SPI_NO_RX); 4339 ugly_bits = bad_bits & 4340 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL | 4341 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL); 4342 if (ugly_bits) { 4343 dev_warn(&spi->dev, 4344 "setup: ignoring unsupported mode bits %x\n", 4345 ugly_bits); 4346 spi->mode &= ~ugly_bits; 4347 bad_bits &= ~ugly_bits; 4348 } 4349 if (bad_bits) { 4350 dev_err(&spi->dev, "setup: unsupported mode bits %x\n", 4351 bad_bits); 4352 return -EINVAL; 4353 } 4354 4355 if (!spi->bits_per_word) { 4356 spi->bits_per_word = 8; 4357 } else { 4358 /* 4359 * Some controllers may not support the default 8 bits-per-word 4360 * so only perform the check when this is explicitly provided. 4361 */ 4362 status = __spi_validate_bits_per_word(spi->controller, 4363 spi->bits_per_word); 4364 if (status) 4365 return status; 4366 } 4367 4368 if (spi->controller->max_speed_hz && 4369 (!spi->max_speed_hz || 4370 spi->max_speed_hz > spi->controller->max_speed_hz)) 4371 spi->max_speed_hz = spi->controller->max_speed_hz; 4372 4373 mutex_lock(&spi->controller->io_mutex); 4374 4375 if (spi->controller->setup) { 4376 status = spi->controller->setup(spi); 4377 if (status) { 4378 mutex_unlock(&spi->controller->io_mutex); 4379 dev_err(&spi->controller->dev, "Failed to setup device: %d\n", 4380 status); 4381 return status; 4382 } 4383 } 4384 4385 status = spi_set_cs_timing(spi); 4386 if (status) { 4387 mutex_unlock(&spi->controller->io_mutex); 4388 goto err_cleanup; 4389 } 4390 4391 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) { 4392 status = pm_runtime_resume_and_get(spi->controller->dev.parent); 4393 if (status < 0) { 4394 mutex_unlock(&spi->controller->io_mutex); 4395 dev_err(&spi->controller->dev, "Failed to power device: %d\n", 4396 status); 4397 goto err_cleanup; 4398 } 4399 4400 /* 4401 * We do not want to return positive value from pm_runtime_get, 4402 * there are many instances of devices calling spi_setup() and 4403 * checking for a non-zero return value instead of a negative 4404 * return value. 4405 */ 4406 status = 0; 4407 4408 spi_set_cs(spi, false, true); 4409 pm_runtime_put_autosuspend(spi->controller->dev.parent); 4410 } else { 4411 spi_set_cs(spi, false, true); 4412 } 4413 4414 mutex_unlock(&spi->controller->io_mutex); 4415 4416 if (spi->rt && !spi->controller->rt) { 4417 spi->controller->rt = true; 4418 spi_set_thread_rt(spi->controller); 4419 } 4420 4421 trace_spi_setup(spi, status); 4422 4423 dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n", 4424 spi->mode & SPI_MODE_X_MASK, 4425 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "", 4426 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "", 4427 (spi->mode & SPI_3WIRE) ? "3wire, " : "", 4428 (spi->mode & SPI_LOOP) ? "loopback, " : "", 4429 spi->bits_per_word, spi->max_speed_hz, 4430 status); 4431 4432 return status; 4433 4434 err_cleanup: 4435 if (initial_setup) 4436 spi_cleanup(spi); 4437 4438 return status; 4439 } 4440 4441 /** 4442 * spi_setup - setup SPI mode and clock rate 4443 * @spi: the device whose settings are being modified 4444 * Context: can sleep, and no requests are queued to the device 4445 * 4446 * SPI protocol drivers may need to update the transfer mode if the 4447 * device doesn't work with its default. They may likewise need 4448 * to update clock rates or word sizes from initial values. This function 4449 * changes those settings, and must be called from a context that can sleep. 4450 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take 4451 * effect the next time the device is selected and data is transferred to 4452 * or from it. When this function returns, the SPI device is deselected. 4453 * 4454 * Note that this call will fail if the protocol driver specifies an option 4455 * that the underlying controller or its driver does not support. For 4456 * example, not all hardware supports wire transfers using nine bit words, 4457 * LSB-first wire encoding, or active-high chipselects. 4458 * 4459 * Return: zero on success, else a negative error code. 4460 */ 4461 int spi_setup(struct spi_device *spi) 4462 { 4463 return __spi_setup(spi, false); 4464 } 4465 EXPORT_SYMBOL_GPL(spi_setup); 4466 4467 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer, 4468 struct spi_device *spi) 4469 { 4470 int delay1, delay2; 4471 4472 delay1 = spi_delay_to_ns(&xfer->word_delay, xfer); 4473 if (delay1 < 0) 4474 return delay1; 4475 4476 delay2 = spi_delay_to_ns(&spi->word_delay, xfer); 4477 if (delay2 < 0) 4478 return delay2; 4479 4480 if (delay1 < delay2) 4481 memcpy(&xfer->word_delay, &spi->word_delay, 4482 sizeof(xfer->word_delay)); 4483 4484 return 0; 4485 } 4486 4487 static int __spi_validate(struct spi_device *spi, struct spi_message *message) 4488 { 4489 struct spi_controller *ctlr = spi->controller; 4490 struct spi_transfer *xfer; 4491 int w_size; 4492 4493 if (list_empty(&message->transfers)) 4494 return -EINVAL; 4495 4496 message->spi = spi; 4497 4498 /* 4499 * Half-duplex links include original MicroWire, and ones with 4500 * only one data pin like SPI_3WIRE (switches direction) or where 4501 * either MOSI or MISO is missing. They can also be caused by 4502 * software limitations. 4503 */ 4504 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) || 4505 (spi->mode & SPI_3WIRE)) { 4506 unsigned flags = ctlr->flags; 4507 4508 list_for_each_entry(xfer, &message->transfers, transfer_list) { 4509 if (xfer->rx_buf && xfer->tx_buf) 4510 return -EINVAL; 4511 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf) 4512 return -EINVAL; 4513 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf) 4514 return -EINVAL; 4515 } 4516 } 4517 4518 /* 4519 * Set transfer bits_per_word and max speed as spi device default if 4520 * it is not set for this transfer. 4521 * Set transfer tx_nbits and rx_nbits as single transfer default 4522 * (SPI_NBITS_SINGLE) if it is not set for this transfer. 4523 * Ensure transfer word_delay is at least as long as that required by 4524 * device itself. 4525 */ 4526 message->frame_length = 0; 4527 list_for_each_entry(xfer, &message->transfers, transfer_list) { 4528 xfer->effective_speed_hz = 0; 4529 message->frame_length += xfer->len; 4530 if (!xfer->bits_per_word) 4531 xfer->bits_per_word = spi->bits_per_word; 4532 4533 if (!xfer->speed_hz) 4534 xfer->speed_hz = spi->max_speed_hz; 4535 4536 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz) 4537 xfer->speed_hz = ctlr->max_speed_hz; 4538 4539 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word)) 4540 return -EINVAL; 4541 4542 /* DDR mode is supported only if controller has dtr_caps=true. 4543 * default considered as SDR mode for SPI and QSPI controller. 4544 * Note: This is applicable only to QSPI controller. 4545 */ 4546 if (xfer->dtr_mode && !ctlr->dtr_caps) 4547 return -EINVAL; 4548 4549 /* 4550 * SPI transfer length should be multiple of SPI word size 4551 * where SPI word size should be power-of-two multiple. 4552 */ 4553 w_size = spi_bpw_to_bytes(xfer->bits_per_word); 4554 4555 /* No partial transfers accepted */ 4556 if (xfer->len % w_size) 4557 return -EINVAL; 4558 4559 if (xfer->speed_hz && ctlr->min_speed_hz && 4560 xfer->speed_hz < ctlr->min_speed_hz) 4561 return -EINVAL; 4562 4563 if (xfer->tx_buf && !xfer->tx_nbits) 4564 xfer->tx_nbits = SPI_NBITS_SINGLE; 4565 if (xfer->rx_buf && !xfer->rx_nbits) 4566 xfer->rx_nbits = SPI_NBITS_SINGLE; 4567 /* 4568 * Check transfer tx/rx_nbits: 4569 * 1. check the value matches one of single, dual and quad 4570 * 2. check tx/rx_nbits match the mode in spi_device 4571 */ 4572 if (xfer->tx_buf) { 4573 if (spi->mode & SPI_NO_TX) 4574 return -EINVAL; 4575 if (xfer->tx_nbits != SPI_NBITS_SINGLE && 4576 xfer->tx_nbits != SPI_NBITS_DUAL && 4577 xfer->tx_nbits != SPI_NBITS_QUAD && 4578 xfer->tx_nbits != SPI_NBITS_OCTAL) 4579 return -EINVAL; 4580 if ((xfer->tx_nbits == SPI_NBITS_DUAL) && 4581 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL))) 4582 return -EINVAL; 4583 if ((xfer->tx_nbits == SPI_NBITS_QUAD) && 4584 !(spi->mode & (SPI_TX_QUAD | SPI_TX_OCTAL))) 4585 return -EINVAL; 4586 if ((xfer->tx_nbits == SPI_NBITS_OCTAL) && 4587 !(spi->mode & SPI_TX_OCTAL)) 4588 return -EINVAL; 4589 } 4590 /* Check transfer rx_nbits */ 4591 if (xfer->rx_buf) { 4592 if (spi->mode & SPI_NO_RX) 4593 return -EINVAL; 4594 if (xfer->rx_nbits != SPI_NBITS_SINGLE && 4595 xfer->rx_nbits != SPI_NBITS_DUAL && 4596 xfer->rx_nbits != SPI_NBITS_QUAD && 4597 xfer->rx_nbits != SPI_NBITS_OCTAL) 4598 return -EINVAL; 4599 if ((xfer->rx_nbits == SPI_NBITS_DUAL) && 4600 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL))) 4601 return -EINVAL; 4602 if ((xfer->rx_nbits == SPI_NBITS_QUAD) && 4603 !(spi->mode & (SPI_RX_QUAD | SPI_RX_OCTAL))) 4604 return -EINVAL; 4605 if ((xfer->rx_nbits == SPI_NBITS_OCTAL) && 4606 !(spi->mode & SPI_RX_OCTAL)) 4607 return -EINVAL; 4608 } 4609 4610 if (_spi_xfer_word_delay_update(xfer, spi)) 4611 return -EINVAL; 4612 4613 /* Make sure controller supports required offload features. */ 4614 if (xfer->offload_flags) { 4615 if (!message->offload) 4616 return -EINVAL; 4617 4618 if (xfer->offload_flags & ~message->offload->xfer_flags) 4619 return -EINVAL; 4620 } 4621 } 4622 4623 message->status = -EINPROGRESS; 4624 4625 return 0; 4626 } 4627 4628 /* 4629 * spi_split_transfers - generic handling of transfer splitting 4630 * @msg: the message to split 4631 * 4632 * Under certain conditions, a SPI controller may not support arbitrary 4633 * transfer sizes or other features required by a peripheral. This function 4634 * will split the transfers in the message into smaller transfers that are 4635 * supported by the controller. 4636 * 4637 * Controllers with special requirements not covered here can also split 4638 * transfers in the optimize_message() callback. 4639 * 4640 * Context: can sleep 4641 * Return: zero on success, else a negative error code 4642 */ 4643 static int spi_split_transfers(struct spi_message *msg) 4644 { 4645 struct spi_controller *ctlr = msg->spi->controller; 4646 struct spi_transfer *xfer; 4647 int ret; 4648 4649 /* 4650 * If an SPI controller does not support toggling the CS line on each 4651 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO 4652 * for the CS line, we can emulate the CS-per-word hardware function by 4653 * splitting transfers into one-word transfers and ensuring that 4654 * cs_change is set for each transfer. 4655 */ 4656 if ((msg->spi->mode & SPI_CS_WORD) && 4657 (!(ctlr->mode_bits & SPI_CS_WORD) || spi_is_csgpiod(msg->spi))) { 4658 ret = spi_split_transfers_maxwords(ctlr, msg, 1); 4659 if (ret) 4660 return ret; 4661 4662 list_for_each_entry(xfer, &msg->transfers, transfer_list) { 4663 /* Don't change cs_change on the last entry in the list */ 4664 if (list_is_last(&xfer->transfer_list, &msg->transfers)) 4665 break; 4666 4667 xfer->cs_change = 1; 4668 } 4669 } else { 4670 ret = spi_split_transfers_maxsize(ctlr, msg, 4671 spi_max_transfer_size(msg->spi)); 4672 if (ret) 4673 return ret; 4674 } 4675 4676 return 0; 4677 } 4678 4679 /* 4680 * __spi_optimize_message - shared implementation for spi_optimize_message() 4681 * and spi_maybe_optimize_message() 4682 * @spi: the device that will be used for the message 4683 * @msg: the message to optimize 4684 * 4685 * Peripheral drivers will call spi_optimize_message() and the spi core will 4686 * call spi_maybe_optimize_message() instead of calling this directly. 4687 * 4688 * It is not valid to call this on a message that has already been optimized. 4689 * 4690 * Return: zero on success, else a negative error code 4691 */ 4692 static int __spi_optimize_message(struct spi_device *spi, 4693 struct spi_message *msg) 4694 { 4695 struct spi_controller *ctlr = spi->controller; 4696 int ret; 4697 4698 ret = __spi_validate(spi, msg); 4699 if (ret) 4700 return ret; 4701 4702 ret = spi_split_transfers(msg); 4703 if (ret) 4704 return ret; 4705 4706 if (ctlr->optimize_message) { 4707 ret = ctlr->optimize_message(msg); 4708 if (ret) { 4709 spi_res_release(ctlr, msg); 4710 return ret; 4711 } 4712 } 4713 4714 msg->optimized = true; 4715 4716 return 0; 4717 } 4718 4719 /* 4720 * spi_maybe_optimize_message - optimize message if it isn't already pre-optimized 4721 * @spi: the device that will be used for the message 4722 * @msg: the message to optimize 4723 * Return: zero on success, else a negative error code 4724 */ 4725 static int spi_maybe_optimize_message(struct spi_device *spi, 4726 struct spi_message *msg) 4727 { 4728 if (spi->controller->defer_optimize_message) { 4729 msg->spi = spi; 4730 return 0; 4731 } 4732 4733 if (msg->pre_optimized) 4734 return 0; 4735 4736 return __spi_optimize_message(spi, msg); 4737 } 4738 4739 /** 4740 * spi_optimize_message - do any one-time validation and setup for a SPI message 4741 * @spi: the device that will be used for the message 4742 * @msg: the message to optimize 4743 * 4744 * Peripheral drivers that reuse the same message repeatedly may call this to 4745 * perform as much message prep as possible once, rather than repeating it each 4746 * time a message transfer is performed to improve throughput and reduce CPU 4747 * usage. 4748 * 4749 * Once a message has been optimized, it cannot be modified with the exception 4750 * of updating the contents of any xfer->tx_buf (the pointer can't be changed, 4751 * only the data in the memory it points to). 4752 * 4753 * Calls to this function must be balanced with calls to spi_unoptimize_message() 4754 * to avoid leaking resources. 4755 * 4756 * Context: can sleep 4757 * Return: zero on success, else a negative error code 4758 */ 4759 int spi_optimize_message(struct spi_device *spi, struct spi_message *msg) 4760 { 4761 int ret; 4762 4763 /* 4764 * Pre-optimization is not supported and optimization is deferred e.g. 4765 * when using spi-mux. 4766 */ 4767 if (spi->controller->defer_optimize_message) 4768 return 0; 4769 4770 ret = __spi_optimize_message(spi, msg); 4771 if (ret) 4772 return ret; 4773 4774 /* 4775 * This flag indicates that the peripheral driver called spi_optimize_message() 4776 * and therefore we shouldn't unoptimize message automatically when finalizing 4777 * the message but rather wait until spi_unoptimize_message() is called 4778 * by the peripheral driver. 4779 */ 4780 msg->pre_optimized = true; 4781 4782 return 0; 4783 } 4784 EXPORT_SYMBOL_GPL(spi_optimize_message); 4785 4786 /** 4787 * spi_unoptimize_message - releases any resources allocated by spi_optimize_message() 4788 * @msg: the message to unoptimize 4789 * 4790 * Calls to this function must be balanced with calls to spi_optimize_message(). 4791 * 4792 * Context: can sleep 4793 */ 4794 void spi_unoptimize_message(struct spi_message *msg) 4795 { 4796 if (msg->spi->controller->defer_optimize_message) 4797 return; 4798 4799 __spi_unoptimize_message(msg); 4800 msg->pre_optimized = false; 4801 } 4802 EXPORT_SYMBOL_GPL(spi_unoptimize_message); 4803 4804 static int __spi_async(struct spi_device *spi, struct spi_message *message) 4805 { 4806 struct spi_controller *ctlr = spi->controller; 4807 struct spi_transfer *xfer; 4808 4809 /* 4810 * Some controllers do not support doing regular SPI transfers. Return 4811 * ENOTSUPP when this is the case. 4812 */ 4813 if (!ctlr->transfer) 4814 return -ENOTSUPP; 4815 4816 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_async); 4817 SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_async); 4818 4819 trace_spi_message_submit(message); 4820 4821 if (!ctlr->ptp_sts_supported) { 4822 list_for_each_entry(xfer, &message->transfers, transfer_list) { 4823 xfer->ptp_sts_word_pre = 0; 4824 ptp_read_system_prets(xfer->ptp_sts); 4825 } 4826 } 4827 4828 return ctlr->transfer(spi, message); 4829 } 4830 4831 static void devm_spi_unoptimize_message(void *msg) 4832 { 4833 spi_unoptimize_message(msg); 4834 } 4835 4836 /** 4837 * devm_spi_optimize_message - managed version of spi_optimize_message() 4838 * @dev: the device that manages @msg (usually @spi->dev) 4839 * @spi: the device that will be used for the message 4840 * @msg: the message to optimize 4841 * Return: zero on success, else a negative error code 4842 * 4843 * spi_unoptimize_message() will automatically be called when the device is 4844 * removed. 4845 */ 4846 int devm_spi_optimize_message(struct device *dev, struct spi_device *spi, 4847 struct spi_message *msg) 4848 { 4849 int ret; 4850 4851 ret = spi_optimize_message(spi, msg); 4852 if (ret) 4853 return ret; 4854 4855 return devm_add_action_or_reset(dev, devm_spi_unoptimize_message, msg); 4856 } 4857 EXPORT_SYMBOL_GPL(devm_spi_optimize_message); 4858 4859 /** 4860 * spi_async - asynchronous SPI transfer 4861 * @spi: device with which data will be exchanged 4862 * @message: describes the data transfers, including completion callback 4863 * Context: any (IRQs may be blocked, etc) 4864 * 4865 * This call may be used in_irq and other contexts which can't sleep, 4866 * as well as from task contexts which can sleep. 4867 * 4868 * The completion callback is invoked in a context which can't sleep. 4869 * Before that invocation, the value of message->status is undefined. 4870 * When the callback is issued, message->status holds either zero (to 4871 * indicate complete success) or a negative error code. After that 4872 * callback returns, the driver which issued the transfer request may 4873 * deallocate the associated memory; it's no longer in use by any SPI 4874 * core or controller driver code. 4875 * 4876 * Note that although all messages to a spi_device are handled in 4877 * FIFO order, messages may go to different devices in other orders. 4878 * Some device might be higher priority, or have various "hard" access 4879 * time requirements, for example. 4880 * 4881 * On detection of any fault during the transfer, processing of 4882 * the entire message is aborted, and the device is deselected. 4883 * Until returning from the associated message completion callback, 4884 * no other spi_message queued to that device will be processed. 4885 * (This rule applies equally to all the synchronous transfer calls, 4886 * which are wrappers around this core asynchronous primitive.) 4887 * 4888 * Return: zero on success, else a negative error code. 4889 */ 4890 int spi_async(struct spi_device *spi, struct spi_message *message) 4891 { 4892 struct spi_controller *ctlr = spi->controller; 4893 int ret; 4894 unsigned long flags; 4895 4896 ret = spi_maybe_optimize_message(spi, message); 4897 if (ret) 4898 return ret; 4899 4900 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags); 4901 4902 if (ctlr->bus_lock_flag) 4903 ret = -EBUSY; 4904 else 4905 ret = __spi_async(spi, message); 4906 4907 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags); 4908 4909 return ret; 4910 } 4911 EXPORT_SYMBOL_GPL(spi_async); 4912 4913 static void __spi_transfer_message_noqueue(struct spi_controller *ctlr, struct spi_message *msg) 4914 { 4915 bool was_busy; 4916 int ret; 4917 4918 mutex_lock(&ctlr->io_mutex); 4919 4920 was_busy = ctlr->busy; 4921 4922 ctlr->cur_msg = msg; 4923 ret = __spi_pump_transfer_message(ctlr, msg, was_busy); 4924 if (ret) 4925 dev_err(&ctlr->dev, "noqueue transfer failed\n"); 4926 ctlr->cur_msg = NULL; 4927 ctlr->fallback = false; 4928 4929 if (!was_busy) { 4930 kfree(ctlr->dummy_rx); 4931 ctlr->dummy_rx = NULL; 4932 kfree(ctlr->dummy_tx); 4933 ctlr->dummy_tx = NULL; 4934 if (ctlr->unprepare_transfer_hardware && 4935 ctlr->unprepare_transfer_hardware(ctlr)) 4936 dev_err(&ctlr->dev, 4937 "failed to unprepare transfer hardware\n"); 4938 spi_idle_runtime_pm(ctlr); 4939 } 4940 4941 mutex_unlock(&ctlr->io_mutex); 4942 } 4943 4944 /*-------------------------------------------------------------------------*/ 4945 4946 /* 4947 * Utility methods for SPI protocol drivers, layered on 4948 * top of the core. Some other utility methods are defined as 4949 * inline functions. 4950 */ 4951 4952 static void spi_complete(void *arg) 4953 { 4954 complete(arg); 4955 } 4956 4957 static int __spi_sync(struct spi_device *spi, struct spi_message *message) 4958 { 4959 DECLARE_COMPLETION_ONSTACK(done); 4960 unsigned long flags; 4961 int status; 4962 struct spi_controller *ctlr = spi->controller; 4963 4964 if (__spi_check_suspended(ctlr)) { 4965 dev_warn_once(&spi->dev, "Attempted to sync while suspend\n"); 4966 return -ESHUTDOWN; 4967 } 4968 4969 status = spi_maybe_optimize_message(spi, message); 4970 if (status) 4971 return status; 4972 4973 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync); 4974 SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync); 4975 4976 /* 4977 * Checking queue_empty here only guarantees async/sync message 4978 * ordering when coming from the same context. It does not need to 4979 * guard against reentrancy from a different context. The io_mutex 4980 * will catch those cases. 4981 */ 4982 if (READ_ONCE(ctlr->queue_empty) && !ctlr->must_async) { 4983 message->actual_length = 0; 4984 message->status = -EINPROGRESS; 4985 4986 trace_spi_message_submit(message); 4987 4988 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync_immediate); 4989 SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync_immediate); 4990 4991 __spi_transfer_message_noqueue(ctlr, message); 4992 4993 return message->status; 4994 } 4995 4996 /* 4997 * There are messages in the async queue that could have originated 4998 * from the same context, so we need to preserve ordering. 4999 * Therefor we send the message to the async queue and wait until they 5000 * are completed. 5001 */ 5002 message->complete = spi_complete; 5003 message->context = &done; 5004 5005 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags); 5006 status = __spi_async(spi, message); 5007 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags); 5008 5009 if (status == 0) { 5010 wait_for_completion(&done); 5011 status = message->status; 5012 } 5013 message->complete = NULL; 5014 message->context = NULL; 5015 5016 return status; 5017 } 5018 5019 /** 5020 * spi_sync - blocking/synchronous SPI data transfers 5021 * @spi: device with which data will be exchanged 5022 * @message: describes the data transfers 5023 * Context: can sleep 5024 * 5025 * This call may only be used from a context that may sleep. The sleep 5026 * is non-interruptible, and has no timeout. Low-overhead controller 5027 * drivers may DMA directly into and out of the message buffers. 5028 * 5029 * Note that the SPI device's chip select is active during the message, 5030 * and then is normally disabled between messages. Drivers for some 5031 * frequently-used devices may want to minimize costs of selecting a chip, 5032 * by leaving it selected in anticipation that the next message will go 5033 * to the same chip. (That may increase power usage.) 5034 * 5035 * Also, the caller is guaranteeing that the memory associated with the 5036 * message will not be freed before this call returns. 5037 * 5038 * Return: zero on success, else a negative error code. 5039 */ 5040 int spi_sync(struct spi_device *spi, struct spi_message *message) 5041 { 5042 int ret; 5043 5044 mutex_lock(&spi->controller->bus_lock_mutex); 5045 ret = __spi_sync(spi, message); 5046 mutex_unlock(&spi->controller->bus_lock_mutex); 5047 5048 return ret; 5049 } 5050 EXPORT_SYMBOL_GPL(spi_sync); 5051 5052 /** 5053 * spi_sync_locked - version of spi_sync with exclusive bus usage 5054 * @spi: device with which data will be exchanged 5055 * @message: describes the data transfers 5056 * Context: can sleep 5057 * 5058 * This call may only be used from a context that may sleep. The sleep 5059 * is non-interruptible, and has no timeout. Low-overhead controller 5060 * drivers may DMA directly into and out of the message buffers. 5061 * 5062 * This call should be used by drivers that require exclusive access to the 5063 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must 5064 * be released by a spi_bus_unlock call when the exclusive access is over. 5065 * 5066 * Return: zero on success, else a negative error code. 5067 */ 5068 int spi_sync_locked(struct spi_device *spi, struct spi_message *message) 5069 { 5070 return __spi_sync(spi, message); 5071 } 5072 EXPORT_SYMBOL_GPL(spi_sync_locked); 5073 5074 /** 5075 * spi_bus_lock - obtain a lock for exclusive SPI bus usage 5076 * @ctlr: SPI bus controller that should be locked for exclusive bus access 5077 * Context: can sleep 5078 * 5079 * This call may only be used from a context that may sleep. The sleep 5080 * is non-interruptible, and has no timeout. 5081 * 5082 * This call should be used by drivers that require exclusive access to the 5083 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the 5084 * exclusive access is over. Data transfer must be done by spi_sync_locked 5085 * and spi_async_locked calls when the SPI bus lock is held. 5086 * 5087 * Return: always zero. 5088 */ 5089 int spi_bus_lock(struct spi_controller *ctlr) 5090 { 5091 unsigned long flags; 5092 5093 mutex_lock(&ctlr->bus_lock_mutex); 5094 5095 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags); 5096 ctlr->bus_lock_flag = 1; 5097 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags); 5098 5099 /* Mutex remains locked until spi_bus_unlock() is called */ 5100 5101 return 0; 5102 } 5103 EXPORT_SYMBOL_GPL(spi_bus_lock); 5104 5105 /** 5106 * spi_bus_unlock - release the lock for exclusive SPI bus usage 5107 * @ctlr: SPI bus controller that was locked for exclusive bus access 5108 * Context: can sleep 5109 * 5110 * This call may only be used from a context that may sleep. The sleep 5111 * is non-interruptible, and has no timeout. 5112 * 5113 * This call releases an SPI bus lock previously obtained by an spi_bus_lock 5114 * call. 5115 * 5116 * Return: always zero. 5117 */ 5118 int spi_bus_unlock(struct spi_controller *ctlr) 5119 { 5120 ctlr->bus_lock_flag = 0; 5121 5122 mutex_unlock(&ctlr->bus_lock_mutex); 5123 5124 return 0; 5125 } 5126 EXPORT_SYMBOL_GPL(spi_bus_unlock); 5127 5128 /* Portable code must never pass more than 32 bytes */ 5129 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES) 5130 5131 static u8 *buf; 5132 5133 /** 5134 * spi_write_then_read - SPI synchronous write followed by read 5135 * @spi: device with which data will be exchanged 5136 * @txbuf: data to be written (need not be DMA-safe) 5137 * @n_tx: size of txbuf, in bytes 5138 * @rxbuf: buffer into which data will be read (need not be DMA-safe) 5139 * @n_rx: size of rxbuf, in bytes 5140 * Context: can sleep 5141 * 5142 * This performs a half duplex MicroWire style transaction with the 5143 * device, sending txbuf and then reading rxbuf. The return value 5144 * is zero for success, else a negative errno status code. 5145 * This call may only be used from a context that may sleep. 5146 * 5147 * Parameters to this routine are always copied using a small buffer. 5148 * Performance-sensitive or bulk transfer code should instead use 5149 * spi_{async,sync}() calls with DMA-safe buffers. 5150 * 5151 * Return: zero on success, else a negative error code. 5152 */ 5153 int spi_write_then_read(struct spi_device *spi, 5154 const void *txbuf, unsigned n_tx, 5155 void *rxbuf, unsigned n_rx) 5156 { 5157 static DEFINE_MUTEX(lock); 5158 5159 int status; 5160 struct spi_message message; 5161 struct spi_transfer x[2]; 5162 u8 *local_buf; 5163 5164 /* 5165 * Use preallocated DMA-safe buffer if we can. We can't avoid 5166 * copying here, (as a pure convenience thing), but we can 5167 * keep heap costs out of the hot path unless someone else is 5168 * using the pre-allocated buffer or the transfer is too large. 5169 */ 5170 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) { 5171 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx), 5172 GFP_KERNEL | GFP_DMA); 5173 if (!local_buf) 5174 return -ENOMEM; 5175 } else { 5176 local_buf = buf; 5177 } 5178 5179 spi_message_init(&message); 5180 memset(x, 0, sizeof(x)); 5181 if (n_tx) { 5182 x[0].len = n_tx; 5183 spi_message_add_tail(&x[0], &message); 5184 } 5185 if (n_rx) { 5186 x[1].len = n_rx; 5187 spi_message_add_tail(&x[1], &message); 5188 } 5189 5190 memcpy(local_buf, txbuf, n_tx); 5191 x[0].tx_buf = local_buf; 5192 x[1].rx_buf = local_buf + n_tx; 5193 5194 /* Do the I/O */ 5195 status = spi_sync(spi, &message); 5196 if (status == 0) 5197 memcpy(rxbuf, x[1].rx_buf, n_rx); 5198 5199 if (x[0].tx_buf == buf) 5200 mutex_unlock(&lock); 5201 else 5202 kfree(local_buf); 5203 5204 return status; 5205 } 5206 EXPORT_SYMBOL_GPL(spi_write_then_read); 5207 5208 /*-------------------------------------------------------------------------*/ 5209 5210 #if IS_ENABLED(CONFIG_OF) 5211 /* The spi controllers are not using spi_bus, so we find it with another way */ 5212 struct spi_controller *of_find_spi_controller_by_node(struct device_node *node) 5213 { 5214 struct device *dev; 5215 5216 dev = class_find_device_by_of_node(&spi_controller_class, node); 5217 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE)) 5218 dev = class_find_device_by_of_node(&spi_target_class, node); 5219 if (!dev) 5220 return NULL; 5221 5222 /* Reference got in class_find_device */ 5223 return container_of(dev, struct spi_controller, dev); 5224 } 5225 EXPORT_SYMBOL_GPL(of_find_spi_controller_by_node); 5226 #endif 5227 5228 #if IS_ENABLED(CONFIG_OF_DYNAMIC) 5229 /* Must call put_device() when done with returned spi_device device */ 5230 static struct spi_device *of_find_spi_device_by_node(struct device_node *node) 5231 { 5232 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node); 5233 5234 return dev ? to_spi_device(dev) : NULL; 5235 } 5236 5237 static int of_spi_notify(struct notifier_block *nb, unsigned long action, 5238 void *arg) 5239 { 5240 struct of_reconfig_data *rd = arg; 5241 struct spi_controller *ctlr; 5242 struct spi_device *spi; 5243 5244 switch (of_reconfig_get_state_change(action, arg)) { 5245 case OF_RECONFIG_CHANGE_ADD: 5246 ctlr = of_find_spi_controller_by_node(rd->dn->parent); 5247 if (ctlr == NULL) 5248 return NOTIFY_OK; /* Not for us */ 5249 5250 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) { 5251 put_device(&ctlr->dev); 5252 return NOTIFY_OK; 5253 } 5254 5255 spi = of_register_spi_device(ctlr, rd->dn); 5256 put_device(&ctlr->dev); 5257 5258 if (IS_ERR(spi)) { 5259 pr_err("%s: failed to create for '%pOF'\n", 5260 __func__, rd->dn); 5261 of_node_clear_flag(rd->dn, OF_POPULATED); 5262 return notifier_from_errno(PTR_ERR(spi)); 5263 } 5264 break; 5265 5266 case OF_RECONFIG_CHANGE_REMOVE: 5267 /* Already depopulated? */ 5268 if (!of_node_check_flag(rd->dn, OF_POPULATED)) 5269 return NOTIFY_OK; 5270 5271 /* Find our device by node */ 5272 spi = of_find_spi_device_by_node(rd->dn); 5273 if (spi == NULL) 5274 return NOTIFY_OK; /* No? not meant for us */ 5275 5276 /* Unregister takes one ref away */ 5277 spi_unregister_device(spi); 5278 5279 /* And put the reference of the find */ 5280 put_device(&spi->dev); 5281 break; 5282 } 5283 5284 return NOTIFY_OK; 5285 } 5286 5287 static struct notifier_block spi_of_notifier = { 5288 .notifier_call = of_spi_notify, 5289 }; 5290 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */ 5291 extern struct notifier_block spi_of_notifier; 5292 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */ 5293 5294 #if IS_ENABLED(CONFIG_ACPI) 5295 static int spi_acpi_controller_match(struct device *dev, const void *data) 5296 { 5297 return device_match_acpi_dev(dev->parent, data); 5298 } 5299 5300 struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev) 5301 { 5302 struct device *dev; 5303 5304 dev = class_find_device(&spi_controller_class, NULL, adev, 5305 spi_acpi_controller_match); 5306 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE)) 5307 dev = class_find_device(&spi_target_class, NULL, adev, 5308 spi_acpi_controller_match); 5309 if (!dev) 5310 return NULL; 5311 5312 return container_of(dev, struct spi_controller, dev); 5313 } 5314 EXPORT_SYMBOL_GPL(acpi_spi_find_controller_by_adev); 5315 5316 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev) 5317 { 5318 struct device *dev; 5319 5320 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev); 5321 return to_spi_device(dev); 5322 } 5323 5324 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value, 5325 void *arg) 5326 { 5327 struct acpi_device *adev = arg; 5328 struct spi_controller *ctlr; 5329 struct spi_device *spi; 5330 5331 switch (value) { 5332 case ACPI_RECONFIG_DEVICE_ADD: 5333 ctlr = acpi_spi_find_controller_by_adev(acpi_dev_parent(adev)); 5334 if (!ctlr) 5335 break; 5336 5337 acpi_register_spi_device(ctlr, adev); 5338 put_device(&ctlr->dev); 5339 break; 5340 case ACPI_RECONFIG_DEVICE_REMOVE: 5341 if (!acpi_device_enumerated(adev)) 5342 break; 5343 5344 spi = acpi_spi_find_device_by_adev(adev); 5345 if (!spi) 5346 break; 5347 5348 spi_unregister_device(spi); 5349 put_device(&spi->dev); 5350 break; 5351 } 5352 5353 return NOTIFY_OK; 5354 } 5355 5356 static struct notifier_block spi_acpi_notifier = { 5357 .notifier_call = acpi_spi_notify, 5358 }; 5359 #else 5360 extern struct notifier_block spi_acpi_notifier; 5361 #endif 5362 5363 static int __init spi_init(void) 5364 { 5365 int status; 5366 5367 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL); 5368 if (!buf) { 5369 status = -ENOMEM; 5370 goto err0; 5371 } 5372 5373 status = bus_register(&spi_bus_type); 5374 if (status < 0) 5375 goto err1; 5376 5377 status = class_register(&spi_controller_class); 5378 if (status < 0) 5379 goto err2; 5380 5381 if (IS_ENABLED(CONFIG_SPI_SLAVE)) { 5382 status = class_register(&spi_target_class); 5383 if (status < 0) 5384 goto err3; 5385 } 5386 5387 if (IS_ENABLED(CONFIG_OF_DYNAMIC)) 5388 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier)); 5389 if (IS_ENABLED(CONFIG_ACPI)) 5390 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier)); 5391 5392 return 0; 5393 5394 err3: 5395 class_unregister(&spi_controller_class); 5396 err2: 5397 bus_unregister(&spi_bus_type); 5398 err1: 5399 kfree(buf); 5400 buf = NULL; 5401 err0: 5402 return status; 5403 } 5404 5405 /* 5406 * A board_info is normally registered in arch_initcall(), 5407 * but even essential drivers wait till later. 5408 * 5409 * REVISIT only boardinfo really needs static linking. The rest (device and 5410 * driver registration) _could_ be dynamically linked (modular) ... Costs 5411 * include needing to have boardinfo data structures be much more public. 5412 */ 5413 postcore_initcall(spi_init); 5414