1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * A fairly generic DMA-API to IOMMU-API glue layer. 4 * 5 * Copyright (C) 2014-2015 ARM Ltd. 6 * 7 * based in part on arch/arm/mm/dma-mapping.c: 8 * Copyright (C) 2000-2004 Russell King 9 */ 10 11 #include <linux/acpi_iort.h> 12 #include <linux/atomic.h> 13 #include <linux/crash_dump.h> 14 #include <linux/device.h> 15 #include <linux/dma-direct.h> 16 #include <linux/dma-map-ops.h> 17 #include <linux/gfp.h> 18 #include <linux/huge_mm.h> 19 #include <linux/iommu.h> 20 #include <linux/iova.h> 21 #include <linux/irq.h> 22 #include <linux/list_sort.h> 23 #include <linux/memremap.h> 24 #include <linux/mm.h> 25 #include <linux/mutex.h> 26 #include <linux/of_iommu.h> 27 #include <linux/pci.h> 28 #include <linux/scatterlist.h> 29 #include <linux/spinlock.h> 30 #include <linux/swiotlb.h> 31 #include <linux/vmalloc.h> 32 #include <trace/events/swiotlb.h> 33 34 #include "dma-iommu.h" 35 #include "iommu-pages.h" 36 37 struct iommu_dma_msi_page { 38 struct list_head list; 39 dma_addr_t iova; 40 phys_addr_t phys; 41 }; 42 43 enum iommu_dma_cookie_type { 44 IOMMU_DMA_IOVA_COOKIE, 45 IOMMU_DMA_MSI_COOKIE, 46 }; 47 48 enum iommu_dma_queue_type { 49 IOMMU_DMA_OPTS_PER_CPU_QUEUE, 50 IOMMU_DMA_OPTS_SINGLE_QUEUE, 51 }; 52 53 struct iommu_dma_options { 54 enum iommu_dma_queue_type qt; 55 size_t fq_size; 56 unsigned int fq_timeout; 57 }; 58 59 struct iommu_dma_cookie { 60 enum iommu_dma_cookie_type type; 61 union { 62 /* Full allocator for IOMMU_DMA_IOVA_COOKIE */ 63 struct { 64 struct iova_domain iovad; 65 /* Flush queue */ 66 union { 67 struct iova_fq *single_fq; 68 struct iova_fq __percpu *percpu_fq; 69 }; 70 /* Number of TLB flushes that have been started */ 71 atomic64_t fq_flush_start_cnt; 72 /* Number of TLB flushes that have been finished */ 73 atomic64_t fq_flush_finish_cnt; 74 /* Timer to regularily empty the flush queues */ 75 struct timer_list fq_timer; 76 /* 1 when timer is active, 0 when not */ 77 atomic_t fq_timer_on; 78 }; 79 /* Trivial linear page allocator for IOMMU_DMA_MSI_COOKIE */ 80 dma_addr_t msi_iova; 81 }; 82 struct list_head msi_page_list; 83 84 /* Domain for flush queue callback; NULL if flush queue not in use */ 85 struct iommu_domain *fq_domain; 86 /* Options for dma-iommu use */ 87 struct iommu_dma_options options; 88 struct mutex mutex; 89 }; 90 91 static DEFINE_STATIC_KEY_FALSE(iommu_deferred_attach_enabled); 92 bool iommu_dma_forcedac __read_mostly; 93 94 static int __init iommu_dma_forcedac_setup(char *str) 95 { 96 int ret = kstrtobool(str, &iommu_dma_forcedac); 97 98 if (!ret && iommu_dma_forcedac) 99 pr_info("Forcing DAC for PCI devices\n"); 100 return ret; 101 } 102 early_param("iommu.forcedac", iommu_dma_forcedac_setup); 103 104 /* Number of entries per flush queue */ 105 #define IOVA_DEFAULT_FQ_SIZE 256 106 #define IOVA_SINGLE_FQ_SIZE 32768 107 108 /* Timeout (in ms) after which entries are flushed from the queue */ 109 #define IOVA_DEFAULT_FQ_TIMEOUT 10 110 #define IOVA_SINGLE_FQ_TIMEOUT 1000 111 112 /* Flush queue entry for deferred flushing */ 113 struct iova_fq_entry { 114 unsigned long iova_pfn; 115 unsigned long pages; 116 struct list_head freelist; 117 u64 counter; /* Flush counter when this entry was added */ 118 }; 119 120 /* Per-CPU flush queue structure */ 121 struct iova_fq { 122 spinlock_t lock; 123 unsigned int head, tail; 124 unsigned int mod_mask; 125 struct iova_fq_entry entries[]; 126 }; 127 128 #define fq_ring_for_each(i, fq) \ 129 for ((i) = (fq)->head; (i) != (fq)->tail; (i) = ((i) + 1) & (fq)->mod_mask) 130 131 static inline bool fq_full(struct iova_fq *fq) 132 { 133 assert_spin_locked(&fq->lock); 134 return (((fq->tail + 1) & fq->mod_mask) == fq->head); 135 } 136 137 static inline unsigned int fq_ring_add(struct iova_fq *fq) 138 { 139 unsigned int idx = fq->tail; 140 141 assert_spin_locked(&fq->lock); 142 143 fq->tail = (idx + 1) & fq->mod_mask; 144 145 return idx; 146 } 147 148 static void fq_ring_free_locked(struct iommu_dma_cookie *cookie, struct iova_fq *fq) 149 { 150 u64 counter = atomic64_read(&cookie->fq_flush_finish_cnt); 151 unsigned int idx; 152 153 assert_spin_locked(&fq->lock); 154 155 fq_ring_for_each(idx, fq) { 156 157 if (fq->entries[idx].counter >= counter) 158 break; 159 160 iommu_put_pages_list(&fq->entries[idx].freelist); 161 free_iova_fast(&cookie->iovad, 162 fq->entries[idx].iova_pfn, 163 fq->entries[idx].pages); 164 165 fq->head = (fq->head + 1) & fq->mod_mask; 166 } 167 } 168 169 static void fq_ring_free(struct iommu_dma_cookie *cookie, struct iova_fq *fq) 170 { 171 unsigned long flags; 172 173 spin_lock_irqsave(&fq->lock, flags); 174 fq_ring_free_locked(cookie, fq); 175 spin_unlock_irqrestore(&fq->lock, flags); 176 } 177 178 static void fq_flush_iotlb(struct iommu_dma_cookie *cookie) 179 { 180 atomic64_inc(&cookie->fq_flush_start_cnt); 181 cookie->fq_domain->ops->flush_iotlb_all(cookie->fq_domain); 182 atomic64_inc(&cookie->fq_flush_finish_cnt); 183 } 184 185 static void fq_flush_timeout(struct timer_list *t) 186 { 187 struct iommu_dma_cookie *cookie = from_timer(cookie, t, fq_timer); 188 int cpu; 189 190 atomic_set(&cookie->fq_timer_on, 0); 191 fq_flush_iotlb(cookie); 192 193 if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE) { 194 fq_ring_free(cookie, cookie->single_fq); 195 } else { 196 for_each_possible_cpu(cpu) 197 fq_ring_free(cookie, per_cpu_ptr(cookie->percpu_fq, cpu)); 198 } 199 } 200 201 static void queue_iova(struct iommu_dma_cookie *cookie, 202 unsigned long pfn, unsigned long pages, 203 struct list_head *freelist) 204 { 205 struct iova_fq *fq; 206 unsigned long flags; 207 unsigned int idx; 208 209 /* 210 * Order against the IOMMU driver's pagetable update from unmapping 211 * @pte, to guarantee that fq_flush_iotlb() observes that if called 212 * from a different CPU before we release the lock below. Full barrier 213 * so it also pairs with iommu_dma_init_fq() to avoid seeing partially 214 * written fq state here. 215 */ 216 smp_mb(); 217 218 if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE) 219 fq = cookie->single_fq; 220 else 221 fq = raw_cpu_ptr(cookie->percpu_fq); 222 223 spin_lock_irqsave(&fq->lock, flags); 224 225 /* 226 * First remove all entries from the flush queue that have already been 227 * flushed out on another CPU. This makes the fq_full() check below less 228 * likely to be true. 229 */ 230 fq_ring_free_locked(cookie, fq); 231 232 if (fq_full(fq)) { 233 fq_flush_iotlb(cookie); 234 fq_ring_free_locked(cookie, fq); 235 } 236 237 idx = fq_ring_add(fq); 238 239 fq->entries[idx].iova_pfn = pfn; 240 fq->entries[idx].pages = pages; 241 fq->entries[idx].counter = atomic64_read(&cookie->fq_flush_start_cnt); 242 list_splice(freelist, &fq->entries[idx].freelist); 243 244 spin_unlock_irqrestore(&fq->lock, flags); 245 246 /* Avoid false sharing as much as possible. */ 247 if (!atomic_read(&cookie->fq_timer_on) && 248 !atomic_xchg(&cookie->fq_timer_on, 1)) 249 mod_timer(&cookie->fq_timer, 250 jiffies + msecs_to_jiffies(cookie->options.fq_timeout)); 251 } 252 253 static void iommu_dma_free_fq_single(struct iova_fq *fq) 254 { 255 int idx; 256 257 fq_ring_for_each(idx, fq) 258 iommu_put_pages_list(&fq->entries[idx].freelist); 259 vfree(fq); 260 } 261 262 static void iommu_dma_free_fq_percpu(struct iova_fq __percpu *percpu_fq) 263 { 264 int cpu, idx; 265 266 /* The IOVAs will be torn down separately, so just free our queued pages */ 267 for_each_possible_cpu(cpu) { 268 struct iova_fq *fq = per_cpu_ptr(percpu_fq, cpu); 269 270 fq_ring_for_each(idx, fq) 271 iommu_put_pages_list(&fq->entries[idx].freelist); 272 } 273 274 free_percpu(percpu_fq); 275 } 276 277 static void iommu_dma_free_fq(struct iommu_dma_cookie *cookie) 278 { 279 if (!cookie->fq_domain) 280 return; 281 282 del_timer_sync(&cookie->fq_timer); 283 if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE) 284 iommu_dma_free_fq_single(cookie->single_fq); 285 else 286 iommu_dma_free_fq_percpu(cookie->percpu_fq); 287 } 288 289 static void iommu_dma_init_one_fq(struct iova_fq *fq, size_t fq_size) 290 { 291 int i; 292 293 fq->head = 0; 294 fq->tail = 0; 295 fq->mod_mask = fq_size - 1; 296 297 spin_lock_init(&fq->lock); 298 299 for (i = 0; i < fq_size; i++) 300 INIT_LIST_HEAD(&fq->entries[i].freelist); 301 } 302 303 static int iommu_dma_init_fq_single(struct iommu_dma_cookie *cookie) 304 { 305 size_t fq_size = cookie->options.fq_size; 306 struct iova_fq *queue; 307 308 queue = vmalloc(struct_size(queue, entries, fq_size)); 309 if (!queue) 310 return -ENOMEM; 311 iommu_dma_init_one_fq(queue, fq_size); 312 cookie->single_fq = queue; 313 314 return 0; 315 } 316 317 static int iommu_dma_init_fq_percpu(struct iommu_dma_cookie *cookie) 318 { 319 size_t fq_size = cookie->options.fq_size; 320 struct iova_fq __percpu *queue; 321 int cpu; 322 323 queue = __alloc_percpu(struct_size(queue, entries, fq_size), 324 __alignof__(*queue)); 325 if (!queue) 326 return -ENOMEM; 327 328 for_each_possible_cpu(cpu) 329 iommu_dma_init_one_fq(per_cpu_ptr(queue, cpu), fq_size); 330 cookie->percpu_fq = queue; 331 return 0; 332 } 333 334 /* sysfs updates are serialised by the mutex of the group owning @domain */ 335 int iommu_dma_init_fq(struct iommu_domain *domain) 336 { 337 struct iommu_dma_cookie *cookie = domain->iova_cookie; 338 int rc; 339 340 if (cookie->fq_domain) 341 return 0; 342 343 atomic64_set(&cookie->fq_flush_start_cnt, 0); 344 atomic64_set(&cookie->fq_flush_finish_cnt, 0); 345 346 if (cookie->options.qt == IOMMU_DMA_OPTS_SINGLE_QUEUE) 347 rc = iommu_dma_init_fq_single(cookie); 348 else 349 rc = iommu_dma_init_fq_percpu(cookie); 350 351 if (rc) { 352 pr_warn("iova flush queue initialization failed\n"); 353 return -ENOMEM; 354 } 355 356 timer_setup(&cookie->fq_timer, fq_flush_timeout, 0); 357 atomic_set(&cookie->fq_timer_on, 0); 358 /* 359 * Prevent incomplete fq state being observable. Pairs with path from 360 * __iommu_dma_unmap() through iommu_dma_free_iova() to queue_iova() 361 */ 362 smp_wmb(); 363 WRITE_ONCE(cookie->fq_domain, domain); 364 return 0; 365 } 366 367 static inline size_t cookie_msi_granule(struct iommu_dma_cookie *cookie) 368 { 369 if (cookie->type == IOMMU_DMA_IOVA_COOKIE) 370 return cookie->iovad.granule; 371 return PAGE_SIZE; 372 } 373 374 static struct iommu_dma_cookie *cookie_alloc(enum iommu_dma_cookie_type type) 375 { 376 struct iommu_dma_cookie *cookie; 377 378 cookie = kzalloc(sizeof(*cookie), GFP_KERNEL); 379 if (cookie) { 380 INIT_LIST_HEAD(&cookie->msi_page_list); 381 cookie->type = type; 382 } 383 return cookie; 384 } 385 386 /** 387 * iommu_get_dma_cookie - Acquire DMA-API resources for a domain 388 * @domain: IOMMU domain to prepare for DMA-API usage 389 */ 390 int iommu_get_dma_cookie(struct iommu_domain *domain) 391 { 392 if (domain->iova_cookie) 393 return -EEXIST; 394 395 domain->iova_cookie = cookie_alloc(IOMMU_DMA_IOVA_COOKIE); 396 if (!domain->iova_cookie) 397 return -ENOMEM; 398 399 mutex_init(&domain->iova_cookie->mutex); 400 return 0; 401 } 402 403 /** 404 * iommu_get_msi_cookie - Acquire just MSI remapping resources 405 * @domain: IOMMU domain to prepare 406 * @base: Start address of IOVA region for MSI mappings 407 * 408 * Users who manage their own IOVA allocation and do not want DMA API support, 409 * but would still like to take advantage of automatic MSI remapping, can use 410 * this to initialise their own domain appropriately. Users should reserve a 411 * contiguous IOVA region, starting at @base, large enough to accommodate the 412 * number of PAGE_SIZE mappings necessary to cover every MSI doorbell address 413 * used by the devices attached to @domain. 414 */ 415 int iommu_get_msi_cookie(struct iommu_domain *domain, dma_addr_t base) 416 { 417 struct iommu_dma_cookie *cookie; 418 419 if (domain->type != IOMMU_DOMAIN_UNMANAGED) 420 return -EINVAL; 421 422 if (domain->iova_cookie) 423 return -EEXIST; 424 425 cookie = cookie_alloc(IOMMU_DMA_MSI_COOKIE); 426 if (!cookie) 427 return -ENOMEM; 428 429 cookie->msi_iova = base; 430 domain->iova_cookie = cookie; 431 return 0; 432 } 433 EXPORT_SYMBOL(iommu_get_msi_cookie); 434 435 /** 436 * iommu_put_dma_cookie - Release a domain's DMA mapping resources 437 * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie() or 438 * iommu_get_msi_cookie() 439 */ 440 void iommu_put_dma_cookie(struct iommu_domain *domain) 441 { 442 struct iommu_dma_cookie *cookie = domain->iova_cookie; 443 struct iommu_dma_msi_page *msi, *tmp; 444 445 if (!cookie) 446 return; 447 448 if (cookie->type == IOMMU_DMA_IOVA_COOKIE && cookie->iovad.granule) { 449 iommu_dma_free_fq(cookie); 450 put_iova_domain(&cookie->iovad); 451 } 452 453 list_for_each_entry_safe(msi, tmp, &cookie->msi_page_list, list) { 454 list_del(&msi->list); 455 kfree(msi); 456 } 457 kfree(cookie); 458 domain->iova_cookie = NULL; 459 } 460 461 /** 462 * iommu_dma_get_resv_regions - Reserved region driver helper 463 * @dev: Device from iommu_get_resv_regions() 464 * @list: Reserved region list from iommu_get_resv_regions() 465 * 466 * IOMMU drivers can use this to implement their .get_resv_regions callback 467 * for general non-IOMMU-specific reservations. Currently, this covers GICv3 468 * ITS region reservation on ACPI based ARM platforms that may require HW MSI 469 * reservation. 470 */ 471 void iommu_dma_get_resv_regions(struct device *dev, struct list_head *list) 472 { 473 474 if (!is_of_node(dev_iommu_fwspec_get(dev)->iommu_fwnode)) 475 iort_iommu_get_resv_regions(dev, list); 476 477 if (dev->of_node) 478 of_iommu_get_resv_regions(dev, list); 479 } 480 EXPORT_SYMBOL(iommu_dma_get_resv_regions); 481 482 static int cookie_init_hw_msi_region(struct iommu_dma_cookie *cookie, 483 phys_addr_t start, phys_addr_t end) 484 { 485 struct iova_domain *iovad = &cookie->iovad; 486 struct iommu_dma_msi_page *msi_page; 487 int i, num_pages; 488 489 start -= iova_offset(iovad, start); 490 num_pages = iova_align(iovad, end - start) >> iova_shift(iovad); 491 492 for (i = 0; i < num_pages; i++) { 493 msi_page = kmalloc(sizeof(*msi_page), GFP_KERNEL); 494 if (!msi_page) 495 return -ENOMEM; 496 497 msi_page->phys = start; 498 msi_page->iova = start; 499 INIT_LIST_HEAD(&msi_page->list); 500 list_add(&msi_page->list, &cookie->msi_page_list); 501 start += iovad->granule; 502 } 503 504 return 0; 505 } 506 507 static int iommu_dma_ranges_sort(void *priv, const struct list_head *a, 508 const struct list_head *b) 509 { 510 struct resource_entry *res_a = list_entry(a, typeof(*res_a), node); 511 struct resource_entry *res_b = list_entry(b, typeof(*res_b), node); 512 513 return res_a->res->start > res_b->res->start; 514 } 515 516 static int iova_reserve_pci_windows(struct pci_dev *dev, 517 struct iova_domain *iovad) 518 { 519 struct pci_host_bridge *bridge = pci_find_host_bridge(dev->bus); 520 struct resource_entry *window; 521 unsigned long lo, hi; 522 phys_addr_t start = 0, end; 523 524 resource_list_for_each_entry(window, &bridge->windows) { 525 if (resource_type(window->res) != IORESOURCE_MEM) 526 continue; 527 528 lo = iova_pfn(iovad, window->res->start - window->offset); 529 hi = iova_pfn(iovad, window->res->end - window->offset); 530 reserve_iova(iovad, lo, hi); 531 } 532 533 /* Get reserved DMA windows from host bridge */ 534 list_sort(NULL, &bridge->dma_ranges, iommu_dma_ranges_sort); 535 resource_list_for_each_entry(window, &bridge->dma_ranges) { 536 end = window->res->start - window->offset; 537 resv_iova: 538 if (end > start) { 539 lo = iova_pfn(iovad, start); 540 hi = iova_pfn(iovad, end); 541 reserve_iova(iovad, lo, hi); 542 } else if (end < start) { 543 /* DMA ranges should be non-overlapping */ 544 dev_err(&dev->dev, 545 "Failed to reserve IOVA [%pa-%pa]\n", 546 &start, &end); 547 return -EINVAL; 548 } 549 550 start = window->res->end - window->offset + 1; 551 /* If window is last entry */ 552 if (window->node.next == &bridge->dma_ranges && 553 end != ~(phys_addr_t)0) { 554 end = ~(phys_addr_t)0; 555 goto resv_iova; 556 } 557 } 558 559 return 0; 560 } 561 562 static int iova_reserve_iommu_regions(struct device *dev, 563 struct iommu_domain *domain) 564 { 565 struct iommu_dma_cookie *cookie = domain->iova_cookie; 566 struct iova_domain *iovad = &cookie->iovad; 567 struct iommu_resv_region *region; 568 LIST_HEAD(resv_regions); 569 int ret = 0; 570 571 if (dev_is_pci(dev)) { 572 ret = iova_reserve_pci_windows(to_pci_dev(dev), iovad); 573 if (ret) 574 return ret; 575 } 576 577 iommu_get_resv_regions(dev, &resv_regions); 578 list_for_each_entry(region, &resv_regions, list) { 579 unsigned long lo, hi; 580 581 /* We ARE the software that manages these! */ 582 if (region->type == IOMMU_RESV_SW_MSI) 583 continue; 584 585 lo = iova_pfn(iovad, region->start); 586 hi = iova_pfn(iovad, region->start + region->length - 1); 587 reserve_iova(iovad, lo, hi); 588 589 if (region->type == IOMMU_RESV_MSI) 590 ret = cookie_init_hw_msi_region(cookie, region->start, 591 region->start + region->length); 592 if (ret) 593 break; 594 } 595 iommu_put_resv_regions(dev, &resv_regions); 596 597 return ret; 598 } 599 600 static bool dev_is_untrusted(struct device *dev) 601 { 602 return dev_is_pci(dev) && to_pci_dev(dev)->untrusted; 603 } 604 605 static bool dev_use_swiotlb(struct device *dev, size_t size, 606 enum dma_data_direction dir) 607 { 608 return IS_ENABLED(CONFIG_SWIOTLB) && 609 (dev_is_untrusted(dev) || 610 dma_kmalloc_needs_bounce(dev, size, dir)); 611 } 612 613 static bool dev_use_sg_swiotlb(struct device *dev, struct scatterlist *sg, 614 int nents, enum dma_data_direction dir) 615 { 616 struct scatterlist *s; 617 int i; 618 619 if (!IS_ENABLED(CONFIG_SWIOTLB)) 620 return false; 621 622 if (dev_is_untrusted(dev)) 623 return true; 624 625 /* 626 * If kmalloc() buffers are not DMA-safe for this device and 627 * direction, check the individual lengths in the sg list. If any 628 * element is deemed unsafe, use the swiotlb for bouncing. 629 */ 630 if (!dma_kmalloc_safe(dev, dir)) { 631 for_each_sg(sg, s, nents, i) 632 if (!dma_kmalloc_size_aligned(s->length)) 633 return true; 634 } 635 636 return false; 637 } 638 639 /** 640 * iommu_dma_init_options - Initialize dma-iommu options 641 * @options: The options to be initialized 642 * @dev: Device the options are set for 643 * 644 * This allows tuning dma-iommu specific to device properties 645 */ 646 static void iommu_dma_init_options(struct iommu_dma_options *options, 647 struct device *dev) 648 { 649 /* Shadowing IOTLB flushes do better with a single large queue */ 650 if (dev->iommu->shadow_on_flush) { 651 options->qt = IOMMU_DMA_OPTS_SINGLE_QUEUE; 652 options->fq_timeout = IOVA_SINGLE_FQ_TIMEOUT; 653 options->fq_size = IOVA_SINGLE_FQ_SIZE; 654 } else { 655 options->qt = IOMMU_DMA_OPTS_PER_CPU_QUEUE; 656 options->fq_size = IOVA_DEFAULT_FQ_SIZE; 657 options->fq_timeout = IOVA_DEFAULT_FQ_TIMEOUT; 658 } 659 } 660 661 /** 662 * iommu_dma_init_domain - Initialise a DMA mapping domain 663 * @domain: IOMMU domain previously prepared by iommu_get_dma_cookie() 664 * @dev: Device the domain is being initialised for 665 * 666 * If the geometry and dma_range_map include address 0, we reserve that page 667 * to ensure it is an invalid IOVA. It is safe to reinitialise a domain, but 668 * any change which could make prior IOVAs invalid will fail. 669 */ 670 static int iommu_dma_init_domain(struct iommu_domain *domain, struct device *dev) 671 { 672 struct iommu_dma_cookie *cookie = domain->iova_cookie; 673 const struct bus_dma_region *map = dev->dma_range_map; 674 unsigned long order, base_pfn; 675 struct iova_domain *iovad; 676 int ret; 677 678 if (!cookie || cookie->type != IOMMU_DMA_IOVA_COOKIE) 679 return -EINVAL; 680 681 iovad = &cookie->iovad; 682 683 /* Use the smallest supported page size for IOVA granularity */ 684 order = __ffs(domain->pgsize_bitmap); 685 base_pfn = 1; 686 687 /* Check the domain allows at least some access to the device... */ 688 if (map) { 689 if (dma_range_map_min(map) > domain->geometry.aperture_end || 690 dma_range_map_max(map) < domain->geometry.aperture_start) { 691 pr_warn("specified DMA range outside IOMMU capability\n"); 692 return -EFAULT; 693 } 694 } 695 /* ...then finally give it a kicking to make sure it fits */ 696 base_pfn = max_t(unsigned long, base_pfn, 697 domain->geometry.aperture_start >> order); 698 699 /* start_pfn is always nonzero for an already-initialised domain */ 700 mutex_lock(&cookie->mutex); 701 if (iovad->start_pfn) { 702 if (1UL << order != iovad->granule || 703 base_pfn != iovad->start_pfn) { 704 pr_warn("Incompatible range for DMA domain\n"); 705 ret = -EFAULT; 706 goto done_unlock; 707 } 708 709 ret = 0; 710 goto done_unlock; 711 } 712 713 init_iova_domain(iovad, 1UL << order, base_pfn); 714 ret = iova_domain_init_rcaches(iovad); 715 if (ret) 716 goto done_unlock; 717 718 iommu_dma_init_options(&cookie->options, dev); 719 720 /* If the FQ fails we can simply fall back to strict mode */ 721 if (domain->type == IOMMU_DOMAIN_DMA_FQ && 722 (!device_iommu_capable(dev, IOMMU_CAP_DEFERRED_FLUSH) || iommu_dma_init_fq(domain))) 723 domain->type = IOMMU_DOMAIN_DMA; 724 725 ret = iova_reserve_iommu_regions(dev, domain); 726 727 done_unlock: 728 mutex_unlock(&cookie->mutex); 729 return ret; 730 } 731 732 /** 733 * dma_info_to_prot - Translate DMA API directions and attributes to IOMMU API 734 * page flags. 735 * @dir: Direction of DMA transfer 736 * @coherent: Is the DMA master cache-coherent? 737 * @attrs: DMA attributes for the mapping 738 * 739 * Return: corresponding IOMMU API page protection flags 740 */ 741 static int dma_info_to_prot(enum dma_data_direction dir, bool coherent, 742 unsigned long attrs) 743 { 744 int prot = coherent ? IOMMU_CACHE : 0; 745 746 if (attrs & DMA_ATTR_PRIVILEGED) 747 prot |= IOMMU_PRIV; 748 749 switch (dir) { 750 case DMA_BIDIRECTIONAL: 751 return prot | IOMMU_READ | IOMMU_WRITE; 752 case DMA_TO_DEVICE: 753 return prot | IOMMU_READ; 754 case DMA_FROM_DEVICE: 755 return prot | IOMMU_WRITE; 756 default: 757 return 0; 758 } 759 } 760 761 static dma_addr_t iommu_dma_alloc_iova(struct iommu_domain *domain, 762 size_t size, u64 dma_limit, struct device *dev) 763 { 764 struct iommu_dma_cookie *cookie = domain->iova_cookie; 765 struct iova_domain *iovad = &cookie->iovad; 766 unsigned long shift, iova_len, iova; 767 768 if (cookie->type == IOMMU_DMA_MSI_COOKIE) { 769 cookie->msi_iova += size; 770 return cookie->msi_iova - size; 771 } 772 773 shift = iova_shift(iovad); 774 iova_len = size >> shift; 775 776 dma_limit = min_not_zero(dma_limit, dev->bus_dma_limit); 777 778 if (domain->geometry.force_aperture) 779 dma_limit = min(dma_limit, (u64)domain->geometry.aperture_end); 780 781 /* 782 * Try to use all the 32-bit PCI addresses first. The original SAC vs. 783 * DAC reasoning loses relevance with PCIe, but enough hardware and 784 * firmware bugs are still lurking out there that it's safest not to 785 * venture into the 64-bit space until necessary. 786 * 787 * If your device goes wrong after seeing the notice then likely either 788 * its driver is not setting DMA masks accurately, the hardware has 789 * some inherent bug in handling >32-bit addresses, or not all the 790 * expected address bits are wired up between the device and the IOMMU. 791 */ 792 if (dma_limit > DMA_BIT_MASK(32) && dev->iommu->pci_32bit_workaround) { 793 iova = alloc_iova_fast(iovad, iova_len, 794 DMA_BIT_MASK(32) >> shift, false); 795 if (iova) 796 goto done; 797 798 dev->iommu->pci_32bit_workaround = false; 799 dev_notice(dev, "Using %d-bit DMA addresses\n", bits_per(dma_limit)); 800 } 801 802 iova = alloc_iova_fast(iovad, iova_len, dma_limit >> shift, true); 803 done: 804 return (dma_addr_t)iova << shift; 805 } 806 807 static void iommu_dma_free_iova(struct iommu_dma_cookie *cookie, 808 dma_addr_t iova, size_t size, struct iommu_iotlb_gather *gather) 809 { 810 struct iova_domain *iovad = &cookie->iovad; 811 812 /* The MSI case is only ever cleaning up its most recent allocation */ 813 if (cookie->type == IOMMU_DMA_MSI_COOKIE) 814 cookie->msi_iova -= size; 815 else if (gather && gather->queued) 816 queue_iova(cookie, iova_pfn(iovad, iova), 817 size >> iova_shift(iovad), 818 &gather->freelist); 819 else 820 free_iova_fast(iovad, iova_pfn(iovad, iova), 821 size >> iova_shift(iovad)); 822 } 823 824 static void __iommu_dma_unmap(struct device *dev, dma_addr_t dma_addr, 825 size_t size) 826 { 827 struct iommu_domain *domain = iommu_get_dma_domain(dev); 828 struct iommu_dma_cookie *cookie = domain->iova_cookie; 829 struct iova_domain *iovad = &cookie->iovad; 830 size_t iova_off = iova_offset(iovad, dma_addr); 831 struct iommu_iotlb_gather iotlb_gather; 832 size_t unmapped; 833 834 dma_addr -= iova_off; 835 size = iova_align(iovad, size + iova_off); 836 iommu_iotlb_gather_init(&iotlb_gather); 837 iotlb_gather.queued = READ_ONCE(cookie->fq_domain); 838 839 unmapped = iommu_unmap_fast(domain, dma_addr, size, &iotlb_gather); 840 WARN_ON(unmapped != size); 841 842 if (!iotlb_gather.queued) 843 iommu_iotlb_sync(domain, &iotlb_gather); 844 iommu_dma_free_iova(cookie, dma_addr, size, &iotlb_gather); 845 } 846 847 static dma_addr_t __iommu_dma_map(struct device *dev, phys_addr_t phys, 848 size_t size, int prot, u64 dma_mask) 849 { 850 struct iommu_domain *domain = iommu_get_dma_domain(dev); 851 struct iommu_dma_cookie *cookie = domain->iova_cookie; 852 struct iova_domain *iovad = &cookie->iovad; 853 size_t iova_off = iova_offset(iovad, phys); 854 dma_addr_t iova; 855 856 if (static_branch_unlikely(&iommu_deferred_attach_enabled) && 857 iommu_deferred_attach(dev, domain)) 858 return DMA_MAPPING_ERROR; 859 860 /* If anyone ever wants this we'd need support in the IOVA allocator */ 861 if (dev_WARN_ONCE(dev, dma_get_min_align_mask(dev) > iova_mask(iovad), 862 "Unsupported alignment constraint\n")) 863 return DMA_MAPPING_ERROR; 864 865 size = iova_align(iovad, size + iova_off); 866 867 iova = iommu_dma_alloc_iova(domain, size, dma_mask, dev); 868 if (!iova) 869 return DMA_MAPPING_ERROR; 870 871 if (iommu_map(domain, iova, phys - iova_off, size, prot, GFP_ATOMIC)) { 872 iommu_dma_free_iova(cookie, iova, size, NULL); 873 return DMA_MAPPING_ERROR; 874 } 875 return iova + iova_off; 876 } 877 878 static void __iommu_dma_free_pages(struct page **pages, int count) 879 { 880 while (count--) 881 __free_page(pages[count]); 882 kvfree(pages); 883 } 884 885 static struct page **__iommu_dma_alloc_pages(struct device *dev, 886 unsigned int count, unsigned long order_mask, gfp_t gfp) 887 { 888 struct page **pages; 889 unsigned int i = 0, nid = dev_to_node(dev); 890 891 order_mask &= GENMASK(MAX_PAGE_ORDER, 0); 892 if (!order_mask) 893 return NULL; 894 895 pages = kvcalloc(count, sizeof(*pages), GFP_KERNEL); 896 if (!pages) 897 return NULL; 898 899 /* IOMMU can map any pages, so himem can also be used here */ 900 gfp |= __GFP_NOWARN | __GFP_HIGHMEM; 901 902 while (count) { 903 struct page *page = NULL; 904 unsigned int order_size; 905 906 /* 907 * Higher-order allocations are a convenience rather 908 * than a necessity, hence using __GFP_NORETRY until 909 * falling back to minimum-order allocations. 910 */ 911 for (order_mask &= GENMASK(__fls(count), 0); 912 order_mask; order_mask &= ~order_size) { 913 unsigned int order = __fls(order_mask); 914 gfp_t alloc_flags = gfp; 915 916 order_size = 1U << order; 917 if (order_mask > order_size) 918 alloc_flags |= __GFP_NORETRY; 919 page = alloc_pages_node(nid, alloc_flags, order); 920 if (!page) 921 continue; 922 if (order) 923 split_page(page, order); 924 break; 925 } 926 if (!page) { 927 __iommu_dma_free_pages(pages, i); 928 return NULL; 929 } 930 count -= order_size; 931 while (order_size--) 932 pages[i++] = page++; 933 } 934 return pages; 935 } 936 937 /* 938 * If size is less than PAGE_SIZE, then a full CPU page will be allocated, 939 * but an IOMMU which supports smaller pages might not map the whole thing. 940 */ 941 static struct page **__iommu_dma_alloc_noncontiguous(struct device *dev, 942 size_t size, struct sg_table *sgt, gfp_t gfp, unsigned long attrs) 943 { 944 struct iommu_domain *domain = iommu_get_dma_domain(dev); 945 struct iommu_dma_cookie *cookie = domain->iova_cookie; 946 struct iova_domain *iovad = &cookie->iovad; 947 bool coherent = dev_is_dma_coherent(dev); 948 int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs); 949 unsigned int count, min_size, alloc_sizes = domain->pgsize_bitmap; 950 struct page **pages; 951 dma_addr_t iova; 952 ssize_t ret; 953 954 if (static_branch_unlikely(&iommu_deferred_attach_enabled) && 955 iommu_deferred_attach(dev, domain)) 956 return NULL; 957 958 min_size = alloc_sizes & -alloc_sizes; 959 if (min_size < PAGE_SIZE) { 960 min_size = PAGE_SIZE; 961 alloc_sizes |= PAGE_SIZE; 962 } else { 963 size = ALIGN(size, min_size); 964 } 965 if (attrs & DMA_ATTR_ALLOC_SINGLE_PAGES) 966 alloc_sizes = min_size; 967 968 count = PAGE_ALIGN(size) >> PAGE_SHIFT; 969 pages = __iommu_dma_alloc_pages(dev, count, alloc_sizes >> PAGE_SHIFT, 970 gfp); 971 if (!pages) 972 return NULL; 973 974 size = iova_align(iovad, size); 975 iova = iommu_dma_alloc_iova(domain, size, dev->coherent_dma_mask, dev); 976 if (!iova) 977 goto out_free_pages; 978 979 /* 980 * Remove the zone/policy flags from the GFP - these are applied to the 981 * __iommu_dma_alloc_pages() but are not used for the supporting 982 * internal allocations that follow. 983 */ 984 gfp &= ~(__GFP_DMA | __GFP_DMA32 | __GFP_HIGHMEM | __GFP_COMP); 985 986 if (sg_alloc_table_from_pages(sgt, pages, count, 0, size, gfp)) 987 goto out_free_iova; 988 989 if (!(ioprot & IOMMU_CACHE)) { 990 struct scatterlist *sg; 991 int i; 992 993 for_each_sg(sgt->sgl, sg, sgt->orig_nents, i) 994 arch_dma_prep_coherent(sg_page(sg), sg->length); 995 } 996 997 ret = iommu_map_sg(domain, iova, sgt->sgl, sgt->orig_nents, ioprot, 998 gfp); 999 if (ret < 0 || ret < size) 1000 goto out_free_sg; 1001 1002 sgt->sgl->dma_address = iova; 1003 sgt->sgl->dma_length = size; 1004 return pages; 1005 1006 out_free_sg: 1007 sg_free_table(sgt); 1008 out_free_iova: 1009 iommu_dma_free_iova(cookie, iova, size, NULL); 1010 out_free_pages: 1011 __iommu_dma_free_pages(pages, count); 1012 return NULL; 1013 } 1014 1015 static void *iommu_dma_alloc_remap(struct device *dev, size_t size, 1016 dma_addr_t *dma_handle, gfp_t gfp, unsigned long attrs) 1017 { 1018 struct page **pages; 1019 struct sg_table sgt; 1020 void *vaddr; 1021 pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs); 1022 1023 pages = __iommu_dma_alloc_noncontiguous(dev, size, &sgt, gfp, attrs); 1024 if (!pages) 1025 return NULL; 1026 *dma_handle = sgt.sgl->dma_address; 1027 sg_free_table(&sgt); 1028 vaddr = dma_common_pages_remap(pages, size, prot, 1029 __builtin_return_address(0)); 1030 if (!vaddr) 1031 goto out_unmap; 1032 return vaddr; 1033 1034 out_unmap: 1035 __iommu_dma_unmap(dev, *dma_handle, size); 1036 __iommu_dma_free_pages(pages, PAGE_ALIGN(size) >> PAGE_SHIFT); 1037 return NULL; 1038 } 1039 1040 static struct sg_table *iommu_dma_alloc_noncontiguous(struct device *dev, 1041 size_t size, enum dma_data_direction dir, gfp_t gfp, 1042 unsigned long attrs) 1043 { 1044 struct dma_sgt_handle *sh; 1045 1046 sh = kmalloc(sizeof(*sh), gfp); 1047 if (!sh) 1048 return NULL; 1049 1050 sh->pages = __iommu_dma_alloc_noncontiguous(dev, size, &sh->sgt, gfp, attrs); 1051 if (!sh->pages) { 1052 kfree(sh); 1053 return NULL; 1054 } 1055 return &sh->sgt; 1056 } 1057 1058 static void iommu_dma_free_noncontiguous(struct device *dev, size_t size, 1059 struct sg_table *sgt, enum dma_data_direction dir) 1060 { 1061 struct dma_sgt_handle *sh = sgt_handle(sgt); 1062 1063 __iommu_dma_unmap(dev, sgt->sgl->dma_address, size); 1064 __iommu_dma_free_pages(sh->pages, PAGE_ALIGN(size) >> PAGE_SHIFT); 1065 sg_free_table(&sh->sgt); 1066 kfree(sh); 1067 } 1068 1069 static void iommu_dma_sync_single_for_cpu(struct device *dev, 1070 dma_addr_t dma_handle, size_t size, enum dma_data_direction dir) 1071 { 1072 phys_addr_t phys; 1073 1074 if (dev_is_dma_coherent(dev) && !dev_use_swiotlb(dev, size, dir)) 1075 return; 1076 1077 phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle); 1078 if (!dev_is_dma_coherent(dev)) 1079 arch_sync_dma_for_cpu(phys, size, dir); 1080 1081 swiotlb_sync_single_for_cpu(dev, phys, size, dir); 1082 } 1083 1084 static void iommu_dma_sync_single_for_device(struct device *dev, 1085 dma_addr_t dma_handle, size_t size, enum dma_data_direction dir) 1086 { 1087 phys_addr_t phys; 1088 1089 if (dev_is_dma_coherent(dev) && !dev_use_swiotlb(dev, size, dir)) 1090 return; 1091 1092 phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle); 1093 swiotlb_sync_single_for_device(dev, phys, size, dir); 1094 1095 if (!dev_is_dma_coherent(dev)) 1096 arch_sync_dma_for_device(phys, size, dir); 1097 } 1098 1099 static void iommu_dma_sync_sg_for_cpu(struct device *dev, 1100 struct scatterlist *sgl, int nelems, 1101 enum dma_data_direction dir) 1102 { 1103 struct scatterlist *sg; 1104 int i; 1105 1106 if (sg_dma_is_swiotlb(sgl)) 1107 for_each_sg(sgl, sg, nelems, i) 1108 iommu_dma_sync_single_for_cpu(dev, sg_dma_address(sg), 1109 sg->length, dir); 1110 else if (!dev_is_dma_coherent(dev)) 1111 for_each_sg(sgl, sg, nelems, i) 1112 arch_sync_dma_for_cpu(sg_phys(sg), sg->length, dir); 1113 } 1114 1115 static void iommu_dma_sync_sg_for_device(struct device *dev, 1116 struct scatterlist *sgl, int nelems, 1117 enum dma_data_direction dir) 1118 { 1119 struct scatterlist *sg; 1120 int i; 1121 1122 if (sg_dma_is_swiotlb(sgl)) 1123 for_each_sg(sgl, sg, nelems, i) 1124 iommu_dma_sync_single_for_device(dev, 1125 sg_dma_address(sg), 1126 sg->length, dir); 1127 else if (!dev_is_dma_coherent(dev)) 1128 for_each_sg(sgl, sg, nelems, i) 1129 arch_sync_dma_for_device(sg_phys(sg), sg->length, dir); 1130 } 1131 1132 static dma_addr_t iommu_dma_map_page(struct device *dev, struct page *page, 1133 unsigned long offset, size_t size, enum dma_data_direction dir, 1134 unsigned long attrs) 1135 { 1136 phys_addr_t phys = page_to_phys(page) + offset; 1137 bool coherent = dev_is_dma_coherent(dev); 1138 int prot = dma_info_to_prot(dir, coherent, attrs); 1139 struct iommu_domain *domain = iommu_get_dma_domain(dev); 1140 struct iommu_dma_cookie *cookie = domain->iova_cookie; 1141 struct iova_domain *iovad = &cookie->iovad; 1142 dma_addr_t iova, dma_mask = dma_get_mask(dev); 1143 1144 /* 1145 * If both the physical buffer start address and size are 1146 * page aligned, we don't need to use a bounce page. 1147 */ 1148 if (dev_use_swiotlb(dev, size, dir) && 1149 iova_offset(iovad, phys | size)) { 1150 if (!is_swiotlb_active(dev)) { 1151 dev_warn_once(dev, "DMA bounce buffers are inactive, unable to map unaligned transaction.\n"); 1152 return DMA_MAPPING_ERROR; 1153 } 1154 1155 trace_swiotlb_bounced(dev, phys, size); 1156 1157 phys = swiotlb_tbl_map_single(dev, phys, size, 1158 iova_mask(iovad), dir, attrs); 1159 1160 if (phys == DMA_MAPPING_ERROR) 1161 return DMA_MAPPING_ERROR; 1162 1163 /* 1164 * Untrusted devices should not see padding areas with random 1165 * leftover kernel data, so zero the pre- and post-padding. 1166 * swiotlb_tbl_map_single() has initialized the bounce buffer 1167 * proper to the contents of the original memory buffer. 1168 */ 1169 if (dev_is_untrusted(dev)) { 1170 size_t start, virt = (size_t)phys_to_virt(phys); 1171 1172 /* Pre-padding */ 1173 start = iova_align_down(iovad, virt); 1174 memset((void *)start, 0, virt - start); 1175 1176 /* Post-padding */ 1177 start = virt + size; 1178 memset((void *)start, 0, 1179 iova_align(iovad, start) - start); 1180 } 1181 } 1182 1183 if (!coherent && !(attrs & DMA_ATTR_SKIP_CPU_SYNC)) 1184 arch_sync_dma_for_device(phys, size, dir); 1185 1186 iova = __iommu_dma_map(dev, phys, size, prot, dma_mask); 1187 if (iova == DMA_MAPPING_ERROR) 1188 swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs); 1189 return iova; 1190 } 1191 1192 static void iommu_dma_unmap_page(struct device *dev, dma_addr_t dma_handle, 1193 size_t size, enum dma_data_direction dir, unsigned long attrs) 1194 { 1195 struct iommu_domain *domain = iommu_get_dma_domain(dev); 1196 phys_addr_t phys; 1197 1198 phys = iommu_iova_to_phys(domain, dma_handle); 1199 if (WARN_ON(!phys)) 1200 return; 1201 1202 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) && !dev_is_dma_coherent(dev)) 1203 arch_sync_dma_for_cpu(phys, size, dir); 1204 1205 __iommu_dma_unmap(dev, dma_handle, size); 1206 1207 swiotlb_tbl_unmap_single(dev, phys, size, dir, attrs); 1208 } 1209 1210 /* 1211 * Prepare a successfully-mapped scatterlist to give back to the caller. 1212 * 1213 * At this point the segments are already laid out by iommu_dma_map_sg() to 1214 * avoid individually crossing any boundaries, so we merely need to check a 1215 * segment's start address to avoid concatenating across one. 1216 */ 1217 static int __finalise_sg(struct device *dev, struct scatterlist *sg, int nents, 1218 dma_addr_t dma_addr) 1219 { 1220 struct scatterlist *s, *cur = sg; 1221 unsigned long seg_mask = dma_get_seg_boundary(dev); 1222 unsigned int cur_len = 0, max_len = dma_get_max_seg_size(dev); 1223 int i, count = 0; 1224 1225 for_each_sg(sg, s, nents, i) { 1226 /* Restore this segment's original unaligned fields first */ 1227 dma_addr_t s_dma_addr = sg_dma_address(s); 1228 unsigned int s_iova_off = sg_dma_address(s); 1229 unsigned int s_length = sg_dma_len(s); 1230 unsigned int s_iova_len = s->length; 1231 1232 sg_dma_address(s) = DMA_MAPPING_ERROR; 1233 sg_dma_len(s) = 0; 1234 1235 if (sg_dma_is_bus_address(s)) { 1236 if (i > 0) 1237 cur = sg_next(cur); 1238 1239 sg_dma_unmark_bus_address(s); 1240 sg_dma_address(cur) = s_dma_addr; 1241 sg_dma_len(cur) = s_length; 1242 sg_dma_mark_bus_address(cur); 1243 count++; 1244 cur_len = 0; 1245 continue; 1246 } 1247 1248 s->offset += s_iova_off; 1249 s->length = s_length; 1250 1251 /* 1252 * Now fill in the real DMA data. If... 1253 * - there is a valid output segment to append to 1254 * - and this segment starts on an IOVA page boundary 1255 * - but doesn't fall at a segment boundary 1256 * - and wouldn't make the resulting output segment too long 1257 */ 1258 if (cur_len && !s_iova_off && (dma_addr & seg_mask) && 1259 (max_len - cur_len >= s_length)) { 1260 /* ...then concatenate it with the previous one */ 1261 cur_len += s_length; 1262 } else { 1263 /* Otherwise start the next output segment */ 1264 if (i > 0) 1265 cur = sg_next(cur); 1266 cur_len = s_length; 1267 count++; 1268 1269 sg_dma_address(cur) = dma_addr + s_iova_off; 1270 } 1271 1272 sg_dma_len(cur) = cur_len; 1273 dma_addr += s_iova_len; 1274 1275 if (s_length + s_iova_off < s_iova_len) 1276 cur_len = 0; 1277 } 1278 return count; 1279 } 1280 1281 /* 1282 * If mapping failed, then just restore the original list, 1283 * but making sure the DMA fields are invalidated. 1284 */ 1285 static void __invalidate_sg(struct scatterlist *sg, int nents) 1286 { 1287 struct scatterlist *s; 1288 int i; 1289 1290 for_each_sg(sg, s, nents, i) { 1291 if (sg_dma_is_bus_address(s)) { 1292 sg_dma_unmark_bus_address(s); 1293 } else { 1294 if (sg_dma_address(s) != DMA_MAPPING_ERROR) 1295 s->offset += sg_dma_address(s); 1296 if (sg_dma_len(s)) 1297 s->length = sg_dma_len(s); 1298 } 1299 sg_dma_address(s) = DMA_MAPPING_ERROR; 1300 sg_dma_len(s) = 0; 1301 } 1302 } 1303 1304 static void iommu_dma_unmap_sg_swiotlb(struct device *dev, struct scatterlist *sg, 1305 int nents, enum dma_data_direction dir, unsigned long attrs) 1306 { 1307 struct scatterlist *s; 1308 int i; 1309 1310 for_each_sg(sg, s, nents, i) 1311 iommu_dma_unmap_page(dev, sg_dma_address(s), 1312 sg_dma_len(s), dir, attrs); 1313 } 1314 1315 static int iommu_dma_map_sg_swiotlb(struct device *dev, struct scatterlist *sg, 1316 int nents, enum dma_data_direction dir, unsigned long attrs) 1317 { 1318 struct scatterlist *s; 1319 int i; 1320 1321 sg_dma_mark_swiotlb(sg); 1322 1323 for_each_sg(sg, s, nents, i) { 1324 sg_dma_address(s) = iommu_dma_map_page(dev, sg_page(s), 1325 s->offset, s->length, dir, attrs); 1326 if (sg_dma_address(s) == DMA_MAPPING_ERROR) 1327 goto out_unmap; 1328 sg_dma_len(s) = s->length; 1329 } 1330 1331 return nents; 1332 1333 out_unmap: 1334 iommu_dma_unmap_sg_swiotlb(dev, sg, i, dir, attrs | DMA_ATTR_SKIP_CPU_SYNC); 1335 return -EIO; 1336 } 1337 1338 /* 1339 * The DMA API client is passing in a scatterlist which could describe 1340 * any old buffer layout, but the IOMMU API requires everything to be 1341 * aligned to IOMMU pages. Hence the need for this complicated bit of 1342 * impedance-matching, to be able to hand off a suitably-aligned list, 1343 * but still preserve the original offsets and sizes for the caller. 1344 */ 1345 static int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, 1346 int nents, enum dma_data_direction dir, unsigned long attrs) 1347 { 1348 struct iommu_domain *domain = iommu_get_dma_domain(dev); 1349 struct iommu_dma_cookie *cookie = domain->iova_cookie; 1350 struct iova_domain *iovad = &cookie->iovad; 1351 struct scatterlist *s, *prev = NULL; 1352 int prot = dma_info_to_prot(dir, dev_is_dma_coherent(dev), attrs); 1353 struct pci_p2pdma_map_state p2pdma_state = {}; 1354 enum pci_p2pdma_map_type map; 1355 dma_addr_t iova; 1356 size_t iova_len = 0; 1357 unsigned long mask = dma_get_seg_boundary(dev); 1358 ssize_t ret; 1359 int i; 1360 1361 if (static_branch_unlikely(&iommu_deferred_attach_enabled)) { 1362 ret = iommu_deferred_attach(dev, domain); 1363 if (ret) 1364 goto out; 1365 } 1366 1367 if (dev_use_sg_swiotlb(dev, sg, nents, dir)) 1368 return iommu_dma_map_sg_swiotlb(dev, sg, nents, dir, attrs); 1369 1370 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC)) 1371 iommu_dma_sync_sg_for_device(dev, sg, nents, dir); 1372 1373 /* 1374 * Work out how much IOVA space we need, and align the segments to 1375 * IOVA granules for the IOMMU driver to handle. With some clever 1376 * trickery we can modify the list in-place, but reversibly, by 1377 * stashing the unaligned parts in the as-yet-unused DMA fields. 1378 */ 1379 for_each_sg(sg, s, nents, i) { 1380 size_t s_iova_off = iova_offset(iovad, s->offset); 1381 size_t s_length = s->length; 1382 size_t pad_len = (mask - iova_len + 1) & mask; 1383 1384 if (is_pci_p2pdma_page(sg_page(s))) { 1385 map = pci_p2pdma_map_segment(&p2pdma_state, dev, s); 1386 switch (map) { 1387 case PCI_P2PDMA_MAP_BUS_ADDR: 1388 /* 1389 * iommu_map_sg() will skip this segment as 1390 * it is marked as a bus address, 1391 * __finalise_sg() will copy the dma address 1392 * into the output segment. 1393 */ 1394 continue; 1395 case PCI_P2PDMA_MAP_THRU_HOST_BRIDGE: 1396 /* 1397 * Mapping through host bridge should be 1398 * mapped with regular IOVAs, thus we 1399 * do nothing here and continue below. 1400 */ 1401 break; 1402 default: 1403 ret = -EREMOTEIO; 1404 goto out_restore_sg; 1405 } 1406 } 1407 1408 sg_dma_address(s) = s_iova_off; 1409 sg_dma_len(s) = s_length; 1410 s->offset -= s_iova_off; 1411 s_length = iova_align(iovad, s_length + s_iova_off); 1412 s->length = s_length; 1413 1414 /* 1415 * Due to the alignment of our single IOVA allocation, we can 1416 * depend on these assumptions about the segment boundary mask: 1417 * - If mask size >= IOVA size, then the IOVA range cannot 1418 * possibly fall across a boundary, so we don't care. 1419 * - If mask size < IOVA size, then the IOVA range must start 1420 * exactly on a boundary, therefore we can lay things out 1421 * based purely on segment lengths without needing to know 1422 * the actual addresses beforehand. 1423 * - The mask must be a power of 2, so pad_len == 0 if 1424 * iova_len == 0, thus we cannot dereference prev the first 1425 * time through here (i.e. before it has a meaningful value). 1426 */ 1427 if (pad_len && pad_len < s_length - 1) { 1428 prev->length += pad_len; 1429 iova_len += pad_len; 1430 } 1431 1432 iova_len += s_length; 1433 prev = s; 1434 } 1435 1436 if (!iova_len) 1437 return __finalise_sg(dev, sg, nents, 0); 1438 1439 iova = iommu_dma_alloc_iova(domain, iova_len, dma_get_mask(dev), dev); 1440 if (!iova) { 1441 ret = -ENOMEM; 1442 goto out_restore_sg; 1443 } 1444 1445 /* 1446 * We'll leave any physical concatenation to the IOMMU driver's 1447 * implementation - it knows better than we do. 1448 */ 1449 ret = iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC); 1450 if (ret < 0 || ret < iova_len) 1451 goto out_free_iova; 1452 1453 return __finalise_sg(dev, sg, nents, iova); 1454 1455 out_free_iova: 1456 iommu_dma_free_iova(cookie, iova, iova_len, NULL); 1457 out_restore_sg: 1458 __invalidate_sg(sg, nents); 1459 out: 1460 if (ret != -ENOMEM && ret != -EREMOTEIO) 1461 return -EINVAL; 1462 return ret; 1463 } 1464 1465 static void iommu_dma_unmap_sg(struct device *dev, struct scatterlist *sg, 1466 int nents, enum dma_data_direction dir, unsigned long attrs) 1467 { 1468 dma_addr_t end = 0, start; 1469 struct scatterlist *tmp; 1470 int i; 1471 1472 if (sg_dma_is_swiotlb(sg)) { 1473 iommu_dma_unmap_sg_swiotlb(dev, sg, nents, dir, attrs); 1474 return; 1475 } 1476 1477 if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC)) 1478 iommu_dma_sync_sg_for_cpu(dev, sg, nents, dir); 1479 1480 /* 1481 * The scatterlist segments are mapped into a single 1482 * contiguous IOVA allocation, the start and end points 1483 * just have to be determined. 1484 */ 1485 for_each_sg(sg, tmp, nents, i) { 1486 if (sg_dma_is_bus_address(tmp)) { 1487 sg_dma_unmark_bus_address(tmp); 1488 continue; 1489 } 1490 1491 if (sg_dma_len(tmp) == 0) 1492 break; 1493 1494 start = sg_dma_address(tmp); 1495 break; 1496 } 1497 1498 nents -= i; 1499 for_each_sg(tmp, tmp, nents, i) { 1500 if (sg_dma_is_bus_address(tmp)) { 1501 sg_dma_unmark_bus_address(tmp); 1502 continue; 1503 } 1504 1505 if (sg_dma_len(tmp) == 0) 1506 break; 1507 1508 end = sg_dma_address(tmp) + sg_dma_len(tmp); 1509 } 1510 1511 if (end) 1512 __iommu_dma_unmap(dev, start, end - start); 1513 } 1514 1515 static dma_addr_t iommu_dma_map_resource(struct device *dev, phys_addr_t phys, 1516 size_t size, enum dma_data_direction dir, unsigned long attrs) 1517 { 1518 return __iommu_dma_map(dev, phys, size, 1519 dma_info_to_prot(dir, false, attrs) | IOMMU_MMIO, 1520 dma_get_mask(dev)); 1521 } 1522 1523 static void iommu_dma_unmap_resource(struct device *dev, dma_addr_t handle, 1524 size_t size, enum dma_data_direction dir, unsigned long attrs) 1525 { 1526 __iommu_dma_unmap(dev, handle, size); 1527 } 1528 1529 static void __iommu_dma_free(struct device *dev, size_t size, void *cpu_addr) 1530 { 1531 size_t alloc_size = PAGE_ALIGN(size); 1532 int count = alloc_size >> PAGE_SHIFT; 1533 struct page *page = NULL, **pages = NULL; 1534 1535 /* Non-coherent atomic allocation? Easy */ 1536 if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) && 1537 dma_free_from_pool(dev, cpu_addr, alloc_size)) 1538 return; 1539 1540 if (is_vmalloc_addr(cpu_addr)) { 1541 /* 1542 * If it the address is remapped, then it's either non-coherent 1543 * or highmem CMA, or an iommu_dma_alloc_remap() construction. 1544 */ 1545 pages = dma_common_find_pages(cpu_addr); 1546 if (!pages) 1547 page = vmalloc_to_page(cpu_addr); 1548 dma_common_free_remap(cpu_addr, alloc_size); 1549 } else { 1550 /* Lowmem means a coherent atomic or CMA allocation */ 1551 page = virt_to_page(cpu_addr); 1552 } 1553 1554 if (pages) 1555 __iommu_dma_free_pages(pages, count); 1556 if (page) 1557 dma_free_contiguous(dev, page, alloc_size); 1558 } 1559 1560 static void iommu_dma_free(struct device *dev, size_t size, void *cpu_addr, 1561 dma_addr_t handle, unsigned long attrs) 1562 { 1563 __iommu_dma_unmap(dev, handle, size); 1564 __iommu_dma_free(dev, size, cpu_addr); 1565 } 1566 1567 static void *iommu_dma_alloc_pages(struct device *dev, size_t size, 1568 struct page **pagep, gfp_t gfp, unsigned long attrs) 1569 { 1570 bool coherent = dev_is_dma_coherent(dev); 1571 size_t alloc_size = PAGE_ALIGN(size); 1572 int node = dev_to_node(dev); 1573 struct page *page = NULL; 1574 void *cpu_addr; 1575 1576 page = dma_alloc_contiguous(dev, alloc_size, gfp); 1577 if (!page) 1578 page = alloc_pages_node(node, gfp, get_order(alloc_size)); 1579 if (!page) 1580 return NULL; 1581 1582 if (!coherent || PageHighMem(page)) { 1583 pgprot_t prot = dma_pgprot(dev, PAGE_KERNEL, attrs); 1584 1585 cpu_addr = dma_common_contiguous_remap(page, alloc_size, 1586 prot, __builtin_return_address(0)); 1587 if (!cpu_addr) 1588 goto out_free_pages; 1589 1590 if (!coherent) 1591 arch_dma_prep_coherent(page, size); 1592 } else { 1593 cpu_addr = page_address(page); 1594 } 1595 1596 *pagep = page; 1597 memset(cpu_addr, 0, alloc_size); 1598 return cpu_addr; 1599 out_free_pages: 1600 dma_free_contiguous(dev, page, alloc_size); 1601 return NULL; 1602 } 1603 1604 static void *iommu_dma_alloc(struct device *dev, size_t size, 1605 dma_addr_t *handle, gfp_t gfp, unsigned long attrs) 1606 { 1607 bool coherent = dev_is_dma_coherent(dev); 1608 int ioprot = dma_info_to_prot(DMA_BIDIRECTIONAL, coherent, attrs); 1609 struct page *page = NULL; 1610 void *cpu_addr; 1611 1612 gfp |= __GFP_ZERO; 1613 1614 if (gfpflags_allow_blocking(gfp) && 1615 !(attrs & DMA_ATTR_FORCE_CONTIGUOUS)) { 1616 return iommu_dma_alloc_remap(dev, size, handle, gfp, attrs); 1617 } 1618 1619 if (IS_ENABLED(CONFIG_DMA_DIRECT_REMAP) && 1620 !gfpflags_allow_blocking(gfp) && !coherent) 1621 page = dma_alloc_from_pool(dev, PAGE_ALIGN(size), &cpu_addr, 1622 gfp, NULL); 1623 else 1624 cpu_addr = iommu_dma_alloc_pages(dev, size, &page, gfp, attrs); 1625 if (!cpu_addr) 1626 return NULL; 1627 1628 *handle = __iommu_dma_map(dev, page_to_phys(page), size, ioprot, 1629 dev->coherent_dma_mask); 1630 if (*handle == DMA_MAPPING_ERROR) { 1631 __iommu_dma_free(dev, size, cpu_addr); 1632 return NULL; 1633 } 1634 1635 return cpu_addr; 1636 } 1637 1638 static int iommu_dma_mmap(struct device *dev, struct vm_area_struct *vma, 1639 void *cpu_addr, dma_addr_t dma_addr, size_t size, 1640 unsigned long attrs) 1641 { 1642 unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT; 1643 unsigned long pfn, off = vma->vm_pgoff; 1644 int ret; 1645 1646 vma->vm_page_prot = dma_pgprot(dev, vma->vm_page_prot, attrs); 1647 1648 if (dma_mmap_from_dev_coherent(dev, vma, cpu_addr, size, &ret)) 1649 return ret; 1650 1651 if (off >= nr_pages || vma_pages(vma) > nr_pages - off) 1652 return -ENXIO; 1653 1654 if (is_vmalloc_addr(cpu_addr)) { 1655 struct page **pages = dma_common_find_pages(cpu_addr); 1656 1657 if (pages) 1658 return vm_map_pages(vma, pages, nr_pages); 1659 pfn = vmalloc_to_pfn(cpu_addr); 1660 } else { 1661 pfn = page_to_pfn(virt_to_page(cpu_addr)); 1662 } 1663 1664 return remap_pfn_range(vma, vma->vm_start, pfn + off, 1665 vma->vm_end - vma->vm_start, 1666 vma->vm_page_prot); 1667 } 1668 1669 static int iommu_dma_get_sgtable(struct device *dev, struct sg_table *sgt, 1670 void *cpu_addr, dma_addr_t dma_addr, size_t size, 1671 unsigned long attrs) 1672 { 1673 struct page *page; 1674 int ret; 1675 1676 if (is_vmalloc_addr(cpu_addr)) { 1677 struct page **pages = dma_common_find_pages(cpu_addr); 1678 1679 if (pages) { 1680 return sg_alloc_table_from_pages(sgt, pages, 1681 PAGE_ALIGN(size) >> PAGE_SHIFT, 1682 0, size, GFP_KERNEL); 1683 } 1684 1685 page = vmalloc_to_page(cpu_addr); 1686 } else { 1687 page = virt_to_page(cpu_addr); 1688 } 1689 1690 ret = sg_alloc_table(sgt, 1, GFP_KERNEL); 1691 if (!ret) 1692 sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0); 1693 return ret; 1694 } 1695 1696 static unsigned long iommu_dma_get_merge_boundary(struct device *dev) 1697 { 1698 struct iommu_domain *domain = iommu_get_dma_domain(dev); 1699 1700 return (1UL << __ffs(domain->pgsize_bitmap)) - 1; 1701 } 1702 1703 static size_t iommu_dma_opt_mapping_size(void) 1704 { 1705 return iova_rcache_range(); 1706 } 1707 1708 static size_t iommu_dma_max_mapping_size(struct device *dev) 1709 { 1710 if (dev_is_untrusted(dev)) 1711 return swiotlb_max_mapping_size(dev); 1712 1713 return SIZE_MAX; 1714 } 1715 1716 static const struct dma_map_ops iommu_dma_ops = { 1717 .flags = DMA_F_PCI_P2PDMA_SUPPORTED | 1718 DMA_F_CAN_SKIP_SYNC, 1719 .alloc = iommu_dma_alloc, 1720 .free = iommu_dma_free, 1721 .alloc_pages_op = dma_common_alloc_pages, 1722 .free_pages = dma_common_free_pages, 1723 .alloc_noncontiguous = iommu_dma_alloc_noncontiguous, 1724 .free_noncontiguous = iommu_dma_free_noncontiguous, 1725 .mmap = iommu_dma_mmap, 1726 .get_sgtable = iommu_dma_get_sgtable, 1727 .map_page = iommu_dma_map_page, 1728 .unmap_page = iommu_dma_unmap_page, 1729 .map_sg = iommu_dma_map_sg, 1730 .unmap_sg = iommu_dma_unmap_sg, 1731 .sync_single_for_cpu = iommu_dma_sync_single_for_cpu, 1732 .sync_single_for_device = iommu_dma_sync_single_for_device, 1733 .sync_sg_for_cpu = iommu_dma_sync_sg_for_cpu, 1734 .sync_sg_for_device = iommu_dma_sync_sg_for_device, 1735 .map_resource = iommu_dma_map_resource, 1736 .unmap_resource = iommu_dma_unmap_resource, 1737 .get_merge_boundary = iommu_dma_get_merge_boundary, 1738 .opt_mapping_size = iommu_dma_opt_mapping_size, 1739 .max_mapping_size = iommu_dma_max_mapping_size, 1740 }; 1741 1742 void iommu_setup_dma_ops(struct device *dev) 1743 { 1744 struct iommu_domain *domain = iommu_get_domain_for_dev(dev); 1745 1746 if (dev_is_pci(dev)) 1747 dev->iommu->pci_32bit_workaround = !iommu_dma_forcedac; 1748 1749 if (iommu_is_dma_domain(domain)) { 1750 if (iommu_dma_init_domain(domain, dev)) 1751 goto out_err; 1752 dev->dma_ops = &iommu_dma_ops; 1753 } else if (dev->dma_ops == &iommu_dma_ops) { 1754 /* Clean up if we've switched *from* a DMA domain */ 1755 dev->dma_ops = NULL; 1756 } 1757 1758 return; 1759 out_err: 1760 pr_warn("Failed to set up IOMMU for device %s; retaining platform DMA ops\n", 1761 dev_name(dev)); 1762 } 1763 1764 static struct iommu_dma_msi_page *iommu_dma_get_msi_page(struct device *dev, 1765 phys_addr_t msi_addr, struct iommu_domain *domain) 1766 { 1767 struct iommu_dma_cookie *cookie = domain->iova_cookie; 1768 struct iommu_dma_msi_page *msi_page; 1769 dma_addr_t iova; 1770 int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO; 1771 size_t size = cookie_msi_granule(cookie); 1772 1773 msi_addr &= ~(phys_addr_t)(size - 1); 1774 list_for_each_entry(msi_page, &cookie->msi_page_list, list) 1775 if (msi_page->phys == msi_addr) 1776 return msi_page; 1777 1778 msi_page = kzalloc(sizeof(*msi_page), GFP_KERNEL); 1779 if (!msi_page) 1780 return NULL; 1781 1782 iova = iommu_dma_alloc_iova(domain, size, dma_get_mask(dev), dev); 1783 if (!iova) 1784 goto out_free_page; 1785 1786 if (iommu_map(domain, iova, msi_addr, size, prot, GFP_KERNEL)) 1787 goto out_free_iova; 1788 1789 INIT_LIST_HEAD(&msi_page->list); 1790 msi_page->phys = msi_addr; 1791 msi_page->iova = iova; 1792 list_add(&msi_page->list, &cookie->msi_page_list); 1793 return msi_page; 1794 1795 out_free_iova: 1796 iommu_dma_free_iova(cookie, iova, size, NULL); 1797 out_free_page: 1798 kfree(msi_page); 1799 return NULL; 1800 } 1801 1802 /** 1803 * iommu_dma_prepare_msi() - Map the MSI page in the IOMMU domain 1804 * @desc: MSI descriptor, will store the MSI page 1805 * @msi_addr: MSI target address to be mapped 1806 * 1807 * Return: 0 on success or negative error code if the mapping failed. 1808 */ 1809 int iommu_dma_prepare_msi(struct msi_desc *desc, phys_addr_t msi_addr) 1810 { 1811 struct device *dev = msi_desc_to_dev(desc); 1812 struct iommu_domain *domain = iommu_get_domain_for_dev(dev); 1813 struct iommu_dma_msi_page *msi_page; 1814 static DEFINE_MUTEX(msi_prepare_lock); /* see below */ 1815 1816 if (!domain || !domain->iova_cookie) { 1817 desc->iommu_cookie = NULL; 1818 return 0; 1819 } 1820 1821 /* 1822 * In fact the whole prepare operation should already be serialised by 1823 * irq_domain_mutex further up the callchain, but that's pretty subtle 1824 * on its own, so consider this locking as failsafe documentation... 1825 */ 1826 mutex_lock(&msi_prepare_lock); 1827 msi_page = iommu_dma_get_msi_page(dev, msi_addr, domain); 1828 mutex_unlock(&msi_prepare_lock); 1829 1830 msi_desc_set_iommu_cookie(desc, msi_page); 1831 1832 if (!msi_page) 1833 return -ENOMEM; 1834 return 0; 1835 } 1836 1837 /** 1838 * iommu_dma_compose_msi_msg() - Apply translation to an MSI message 1839 * @desc: MSI descriptor prepared by iommu_dma_prepare_msi() 1840 * @msg: MSI message containing target physical address 1841 */ 1842 void iommu_dma_compose_msi_msg(struct msi_desc *desc, struct msi_msg *msg) 1843 { 1844 struct device *dev = msi_desc_to_dev(desc); 1845 const struct iommu_domain *domain = iommu_get_domain_for_dev(dev); 1846 const struct iommu_dma_msi_page *msi_page; 1847 1848 msi_page = msi_desc_get_iommu_cookie(desc); 1849 1850 if (!domain || !domain->iova_cookie || WARN_ON(!msi_page)) 1851 return; 1852 1853 msg->address_hi = upper_32_bits(msi_page->iova); 1854 msg->address_lo &= cookie_msi_granule(domain->iova_cookie) - 1; 1855 msg->address_lo += lower_32_bits(msi_page->iova); 1856 } 1857 1858 static int iommu_dma_init(void) 1859 { 1860 if (is_kdump_kernel()) 1861 static_branch_enable(&iommu_deferred_attach_enabled); 1862 1863 return iova_cache_get(); 1864 } 1865 arch_initcall(iommu_dma_init); 1866