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