1 // SPDX-License-Identifier: GPL-2.0 2 /* Copyright (c) 2021-2022, NVIDIA CORPORATION & AFFILIATES. 3 * 4 * The iopt_pages is the center of the storage and motion of PFNs. Each 5 * iopt_pages represents a logical linear array of full PFNs. The array is 0 6 * based and has npages in it. Accessors use 'index' to refer to the entry in 7 * this logical array, regardless of its storage location. 8 * 9 * PFNs are stored in a tiered scheme: 10 * 1) iopt_pages::pinned_pfns xarray 11 * 2) An iommu_domain 12 * 3) The origin of the PFNs, i.e. the userspace pointer 13 * 14 * PFN have to be copied between all combinations of tiers, depending on the 15 * configuration. 16 * 17 * When a PFN is taken out of the userspace pointer it is pinned exactly once. 18 * The storage locations of the PFN's index are tracked in the two interval 19 * trees. If no interval includes the index then it is not pinned. 20 * 21 * If access_itree includes the PFN's index then an in-kernel access has 22 * requested the page. The PFN is stored in the xarray so other requestors can 23 * continue to find it. 24 * 25 * If the domains_itree includes the PFN's index then an iommu_domain is storing 26 * the PFN and it can be read back using iommu_iova_to_phys(). To avoid 27 * duplicating storage the xarray is not used if only iommu_domains are using 28 * the PFN's index. 29 * 30 * As a general principle this is designed so that destroy never fails. This 31 * means removing an iommu_domain or releasing a in-kernel access will not fail 32 * due to insufficient memory. In practice this means some cases have to hold 33 * PFNs in the xarray even though they are also being stored in an iommu_domain. 34 * 35 * While the iopt_pages can use an iommu_domain as storage, it does not have an 36 * IOVA itself. Instead the iopt_area represents a range of IOVA and uses the 37 * iopt_pages as the PFN provider. Multiple iopt_areas can share the iopt_pages 38 * and reference their own slice of the PFN array, with sub page granularity. 39 * 40 * In this file the term 'last' indicates an inclusive and closed interval, eg 41 * [0,0] refers to a single PFN. 'end' means an open range, eg [0,0) refers to 42 * no PFNs. 43 * 44 * Be cautious of overflow. An IOVA can go all the way up to U64_MAX, so 45 * last_iova + 1 can overflow. An iopt_pages index will always be much less than 46 * ULONG_MAX so last_index + 1 cannot overflow. 47 */ 48 #include <linux/dma-buf.h> 49 #include <linux/dma-resv.h> 50 #include <linux/file.h> 51 #include <linux/highmem.h> 52 #include <linux/iommu.h> 53 #include <linux/iommufd.h> 54 #include <linux/kthread.h> 55 #include <linux/overflow.h> 56 #include <linux/slab.h> 57 #include <linux/sched/mm.h> 58 #include <linux/vfio_pci_core.h> 59 60 #include "double_span.h" 61 #include "io_pagetable.h" 62 63 #ifndef CONFIG_IOMMUFD_TEST 64 #define TEMP_MEMORY_LIMIT 65536 65 #else 66 #define TEMP_MEMORY_LIMIT iommufd_test_memory_limit 67 #endif 68 #define BATCH_BACKUP_SIZE 32 69 70 /* 71 * More memory makes pin_user_pages() and the batching more efficient, but as 72 * this is only a performance optimization don't try too hard to get it. A 64k 73 * allocation can hold about 26M of 4k pages and 13G of 2M pages in an 74 * pfn_batch. Various destroy paths cannot fail and provide a small amount of 75 * stack memory as a backup contingency. If backup_len is given this cannot 76 * fail. 77 */ 78 static void *temp_kmalloc(size_t *size, void *backup, size_t backup_len) 79 { 80 void *res; 81 82 if (WARN_ON(*size == 0)) 83 return NULL; 84 85 if (*size < backup_len) 86 return backup; 87 88 if (!backup && iommufd_should_fail()) 89 return NULL; 90 91 *size = min_t(size_t, *size, TEMP_MEMORY_LIMIT); 92 res = kmalloc(*size, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); 93 if (res) 94 return res; 95 *size = PAGE_SIZE; 96 if (backup_len) { 97 res = kmalloc(*size, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); 98 if (res) 99 return res; 100 *size = backup_len; 101 return backup; 102 } 103 return kmalloc(*size, GFP_KERNEL); 104 } 105 106 void interval_tree_double_span_iter_update( 107 struct interval_tree_double_span_iter *iter) 108 { 109 unsigned long last_hole = ULONG_MAX; 110 unsigned int i; 111 112 for (i = 0; i != ARRAY_SIZE(iter->spans); i++) { 113 if (interval_tree_span_iter_done(&iter->spans[i])) { 114 iter->is_used = -1; 115 return; 116 } 117 118 if (iter->spans[i].is_hole) { 119 last_hole = min(last_hole, iter->spans[i].last_hole); 120 continue; 121 } 122 123 iter->is_used = i + 1; 124 iter->start_used = iter->spans[i].start_used; 125 iter->last_used = min(iter->spans[i].last_used, last_hole); 126 return; 127 } 128 129 iter->is_used = 0; 130 iter->start_hole = iter->spans[0].start_hole; 131 iter->last_hole = 132 min(iter->spans[0].last_hole, iter->spans[1].last_hole); 133 } 134 135 void interval_tree_double_span_iter_first( 136 struct interval_tree_double_span_iter *iter, 137 struct rb_root_cached *itree1, struct rb_root_cached *itree2, 138 unsigned long first_index, unsigned long last_index) 139 { 140 unsigned int i; 141 142 iter->itrees[0] = itree1; 143 iter->itrees[1] = itree2; 144 for (i = 0; i != ARRAY_SIZE(iter->spans); i++) 145 interval_tree_span_iter_first(&iter->spans[i], iter->itrees[i], 146 first_index, last_index); 147 interval_tree_double_span_iter_update(iter); 148 } 149 150 void interval_tree_double_span_iter_next( 151 struct interval_tree_double_span_iter *iter) 152 { 153 unsigned int i; 154 155 if (iter->is_used == -1 || 156 iter->last_hole == iter->spans[0].last_index) { 157 iter->is_used = -1; 158 return; 159 } 160 161 for (i = 0; i != ARRAY_SIZE(iter->spans); i++) 162 interval_tree_span_iter_advance( 163 &iter->spans[i], iter->itrees[i], iter->last_hole + 1); 164 interval_tree_double_span_iter_update(iter); 165 } 166 167 static void iopt_pages_add_npinned(struct iopt_pages *pages, size_t npages) 168 { 169 int rc; 170 171 rc = check_add_overflow(pages->npinned, npages, &pages->npinned); 172 if (IS_ENABLED(CONFIG_IOMMUFD_TEST)) 173 WARN_ON(rc || pages->npinned > pages->npages); 174 } 175 176 static void iopt_pages_sub_npinned(struct iopt_pages *pages, size_t npages) 177 { 178 int rc; 179 180 rc = check_sub_overflow(pages->npinned, npages, &pages->npinned); 181 if (IS_ENABLED(CONFIG_IOMMUFD_TEST)) 182 WARN_ON(rc || pages->npinned > pages->npages); 183 } 184 185 static void iopt_pages_err_unpin(struct iopt_pages *pages, 186 unsigned long start_index, 187 unsigned long last_index, 188 struct page **page_list) 189 { 190 unsigned long npages = last_index - start_index + 1; 191 192 unpin_user_pages(page_list, npages); 193 iopt_pages_sub_npinned(pages, npages); 194 } 195 196 /* 197 * index is the number of PAGE_SIZE units from the start of the area's 198 * iopt_pages. If the iova is sub page-size then the area has an iova that 199 * covers a portion of the first and last pages in the range. 200 */ 201 static unsigned long iopt_area_index_to_iova(struct iopt_area *area, 202 unsigned long index) 203 { 204 if (IS_ENABLED(CONFIG_IOMMUFD_TEST)) 205 WARN_ON(index < iopt_area_index(area) || 206 index > iopt_area_last_index(area)); 207 index -= iopt_area_index(area); 208 if (index == 0) 209 return iopt_area_iova(area); 210 return iopt_area_iova(area) - area->page_offset + index * PAGE_SIZE; 211 } 212 213 static unsigned long iopt_area_index_to_iova_last(struct iopt_area *area, 214 unsigned long index) 215 { 216 if (IS_ENABLED(CONFIG_IOMMUFD_TEST)) 217 WARN_ON(index < iopt_area_index(area) || 218 index > iopt_area_last_index(area)); 219 if (index == iopt_area_last_index(area)) 220 return iopt_area_last_iova(area); 221 return iopt_area_iova(area) - area->page_offset + 222 (index - iopt_area_index(area) + 1) * PAGE_SIZE - 1; 223 } 224 225 static void iommu_unmap_nofail(struct iommu_domain *domain, unsigned long iova, 226 size_t size) 227 { 228 size_t ret; 229 230 ret = iommu_unmap(domain, iova, size); 231 /* 232 * It is a logic error in this code or a driver bug if the IOMMU unmaps 233 * something other than exactly as requested. This implies that the 234 * iommu driver may not fail unmap for reasons beyond bad agruments. 235 * Particularly, the iommu driver may not do a memory allocation on the 236 * unmap path. 237 */ 238 WARN_ON(ret != size); 239 } 240 241 static void iopt_area_unmap_domain_range(struct iopt_area *area, 242 struct iommu_domain *domain, 243 unsigned long start_index, 244 unsigned long last_index) 245 { 246 unsigned long start_iova = iopt_area_index_to_iova(area, start_index); 247 248 iommu_unmap_nofail(domain, start_iova, 249 iopt_area_index_to_iova_last(area, last_index) - 250 start_iova + 1); 251 } 252 253 static struct iopt_area *iopt_pages_find_domain_area(struct iopt_pages *pages, 254 unsigned long index) 255 { 256 struct interval_tree_node *node; 257 258 node = interval_tree_iter_first(&pages->domains_itree, index, index); 259 if (!node) 260 return NULL; 261 return container_of(node, struct iopt_area, pages_node); 262 } 263 264 enum batch_kind { 265 BATCH_CPU_MEMORY = 0, 266 BATCH_MMIO, 267 }; 268 269 /* 270 * A simple datastructure to hold a vector of PFNs, optimized for contiguous 271 * PFNs. This is used as a temporary holding memory for shuttling pfns from one 272 * place to another. Generally everything is made more efficient if operations 273 * work on the largest possible grouping of pfns. eg fewer lock/unlock cycles, 274 * better cache locality, etc 275 */ 276 struct pfn_batch { 277 unsigned long *pfns; 278 u32 *npfns; 279 unsigned int array_size; 280 unsigned int end; 281 unsigned int total_pfns; 282 enum batch_kind kind; 283 }; 284 enum { MAX_NPFNS = type_max(typeof(((struct pfn_batch *)0)->npfns[0])) }; 285 286 static void batch_clear(struct pfn_batch *batch) 287 { 288 batch->total_pfns = 0; 289 batch->end = 0; 290 batch->pfns[0] = 0; 291 batch->npfns[0] = 0; 292 batch->kind = 0; 293 } 294 295 /* 296 * Carry means we carry a portion of the final hugepage over to the front of the 297 * batch 298 */ 299 static void batch_clear_carry(struct pfn_batch *batch, unsigned int keep_pfns) 300 { 301 if (!keep_pfns) 302 return batch_clear(batch); 303 304 if (IS_ENABLED(CONFIG_IOMMUFD_TEST)) 305 WARN_ON(!batch->end || 306 batch->npfns[batch->end - 1] < keep_pfns); 307 308 batch->total_pfns = keep_pfns; 309 batch->pfns[0] = batch->pfns[batch->end - 1] + 310 (batch->npfns[batch->end - 1] - keep_pfns); 311 batch->npfns[0] = keep_pfns; 312 batch->end = 1; 313 } 314 315 static void batch_skip_carry(struct pfn_batch *batch, unsigned int skip_pfns) 316 { 317 if (!batch->total_pfns) 318 return; 319 if (IS_ENABLED(CONFIG_IOMMUFD_TEST)) 320 WARN_ON(batch->total_pfns != batch->npfns[0]); 321 skip_pfns = min(batch->total_pfns, skip_pfns); 322 batch->pfns[0] += skip_pfns; 323 batch->npfns[0] -= skip_pfns; 324 batch->total_pfns -= skip_pfns; 325 } 326 327 static int __batch_init(struct pfn_batch *batch, size_t max_pages, void *backup, 328 size_t backup_len) 329 { 330 const size_t elmsz = sizeof(*batch->pfns) + sizeof(*batch->npfns); 331 size_t size = max_pages * elmsz; 332 333 batch->pfns = temp_kmalloc(&size, backup, backup_len); 334 if (!batch->pfns) 335 return -ENOMEM; 336 if (IS_ENABLED(CONFIG_IOMMUFD_TEST) && WARN_ON(size < elmsz)) 337 return -EINVAL; 338 batch->array_size = size / elmsz; 339 batch->npfns = (u32 *)(batch->pfns + batch->array_size); 340 batch_clear(batch); 341 return 0; 342 } 343 344 static int batch_init(struct pfn_batch *batch, size_t max_pages) 345 { 346 return __batch_init(batch, max_pages, NULL, 0); 347 } 348 349 static void batch_init_backup(struct pfn_batch *batch, size_t max_pages, 350 void *backup, size_t backup_len) 351 { 352 __batch_init(batch, max_pages, backup, backup_len); 353 } 354 355 static void batch_destroy(struct pfn_batch *batch, void *backup) 356 { 357 if (batch->pfns != backup) 358 kfree(batch->pfns); 359 } 360 361 static bool batch_add_pfn_num(struct pfn_batch *batch, unsigned long pfn, 362 u32 nr, enum batch_kind kind) 363 { 364 unsigned int end = batch->end; 365 366 if (batch->kind != kind) { 367 /* One kind per batch */ 368 if (batch->end != 0) 369 return false; 370 batch->kind = kind; 371 } 372 373 if (end && pfn == batch->pfns[end - 1] + batch->npfns[end - 1] && 374 nr <= MAX_NPFNS - batch->npfns[end - 1]) { 375 batch->npfns[end - 1] += nr; 376 } else if (end < batch->array_size) { 377 batch->pfns[end] = pfn; 378 batch->npfns[end] = nr; 379 batch->end++; 380 } else { 381 return false; 382 } 383 384 batch->total_pfns += nr; 385 return true; 386 } 387 388 static void batch_remove_pfn_num(struct pfn_batch *batch, unsigned long nr) 389 { 390 batch->npfns[batch->end - 1] -= nr; 391 if (batch->npfns[batch->end - 1] == 0) 392 batch->end--; 393 batch->total_pfns -= nr; 394 } 395 396 /* true if the pfn was added, false otherwise */ 397 static bool batch_add_pfn(struct pfn_batch *batch, unsigned long pfn) 398 { 399 return batch_add_pfn_num(batch, pfn, 1, BATCH_CPU_MEMORY); 400 } 401 402 /* 403 * Fill the batch with pfns from the domain. When the batch is full, or it 404 * reaches last_index, the function will return. The caller should use 405 * batch->total_pfns to determine the starting point for the next iteration. 406 */ 407 static void batch_from_domain(struct pfn_batch *batch, 408 struct iommu_domain *domain, 409 struct iopt_area *area, unsigned long start_index, 410 unsigned long last_index) 411 { 412 unsigned int page_offset = 0; 413 unsigned long iova; 414 phys_addr_t phys; 415 416 iova = iopt_area_index_to_iova(area, start_index); 417 if (start_index == iopt_area_index(area)) 418 page_offset = area->page_offset; 419 while (start_index <= last_index) { 420 /* 421 * This is pretty slow, it would be nice to get the page size 422 * back from the driver, or have the driver directly fill the 423 * batch. 424 */ 425 phys = iommu_iova_to_phys(domain, iova) - page_offset; 426 if (!batch_add_pfn(batch, PHYS_PFN(phys))) 427 return; 428 iova += PAGE_SIZE - page_offset; 429 page_offset = 0; 430 start_index++; 431 } 432 } 433 434 static struct page **raw_pages_from_domain(struct iommu_domain *domain, 435 struct iopt_area *area, 436 unsigned long start_index, 437 unsigned long last_index, 438 struct page **out_pages) 439 { 440 unsigned int page_offset = 0; 441 unsigned long iova; 442 phys_addr_t phys; 443 444 iova = iopt_area_index_to_iova(area, start_index); 445 if (start_index == iopt_area_index(area)) 446 page_offset = area->page_offset; 447 while (start_index <= last_index) { 448 phys = iommu_iova_to_phys(domain, iova) - page_offset; 449 *(out_pages++) = pfn_to_page(PHYS_PFN(phys)); 450 iova += PAGE_SIZE - page_offset; 451 page_offset = 0; 452 start_index++; 453 } 454 return out_pages; 455 } 456 457 /* Continues reading a domain until we reach a discontinuity in the pfns. */ 458 static void batch_from_domain_continue(struct pfn_batch *batch, 459 struct iommu_domain *domain, 460 struct iopt_area *area, 461 unsigned long start_index, 462 unsigned long last_index) 463 { 464 unsigned int array_size = batch->array_size; 465 466 batch->array_size = batch->end; 467 batch_from_domain(batch, domain, area, start_index, last_index); 468 batch->array_size = array_size; 469 } 470 471 /* 472 * This is part of the VFIO compatibility support for VFIO_TYPE1_IOMMU. That 473 * mode permits splitting a mapped area up, and then one of the splits is 474 * unmapped. Doing this normally would cause us to violate our invariant of 475 * pairing map/unmap. Thus, to support old VFIO compatibility disable support 476 * for batching consecutive PFNs. All PFNs mapped into the iommu are done in 477 * PAGE_SIZE units, not larger or smaller. 478 */ 479 static int batch_iommu_map_small(struct iommu_domain *domain, 480 unsigned long iova, phys_addr_t paddr, 481 size_t size, int prot) 482 { 483 unsigned long start_iova = iova; 484 int rc; 485 486 if (IS_ENABLED(CONFIG_IOMMUFD_TEST)) 487 WARN_ON(paddr % PAGE_SIZE || iova % PAGE_SIZE || 488 size % PAGE_SIZE); 489 490 while (size) { 491 rc = iommu_map(domain, iova, paddr, PAGE_SIZE, prot, 492 GFP_KERNEL_ACCOUNT); 493 if (rc) 494 goto err_unmap; 495 iova += PAGE_SIZE; 496 paddr += PAGE_SIZE; 497 size -= PAGE_SIZE; 498 } 499 return 0; 500 501 err_unmap: 502 if (start_iova != iova) 503 iommu_unmap_nofail(domain, start_iova, iova - start_iova); 504 return rc; 505 } 506 507 static int batch_to_domain(struct pfn_batch *batch, struct iommu_domain *domain, 508 struct iopt_area *area, unsigned long start_index) 509 { 510 bool disable_large_pages = area->iopt->disable_large_pages; 511 unsigned long last_iova = iopt_area_last_iova(area); 512 int iommu_prot = area->iommu_prot; 513 unsigned int page_offset = 0; 514 unsigned long start_iova; 515 unsigned long next_iova; 516 unsigned int cur = 0; 517 unsigned long iova; 518 int rc; 519 520 if (batch->kind == BATCH_MMIO) { 521 iommu_prot &= ~IOMMU_CACHE; 522 iommu_prot |= IOMMU_MMIO; 523 } 524 525 /* The first index might be a partial page */ 526 if (start_index == iopt_area_index(area)) 527 page_offset = area->page_offset; 528 next_iova = iova = start_iova = 529 iopt_area_index_to_iova(area, start_index); 530 while (cur < batch->end) { 531 next_iova = min(last_iova + 1, 532 next_iova + batch->npfns[cur] * PAGE_SIZE - 533 page_offset); 534 if (disable_large_pages) 535 rc = batch_iommu_map_small( 536 domain, iova, 537 PFN_PHYS(batch->pfns[cur]) + page_offset, 538 next_iova - iova, iommu_prot); 539 else 540 rc = iommu_map(domain, iova, 541 PFN_PHYS(batch->pfns[cur]) + page_offset, 542 next_iova - iova, iommu_prot, 543 GFP_KERNEL_ACCOUNT); 544 if (rc) 545 goto err_unmap; 546 iova = next_iova; 547 page_offset = 0; 548 cur++; 549 } 550 return 0; 551 err_unmap: 552 if (start_iova != iova) 553 iommu_unmap_nofail(domain, start_iova, iova - start_iova); 554 return rc; 555 } 556 557 static void batch_from_xarray(struct pfn_batch *batch, struct xarray *xa, 558 unsigned long start_index, 559 unsigned long last_index) 560 { 561 XA_STATE(xas, xa, start_index); 562 void *entry; 563 564 rcu_read_lock(); 565 while (true) { 566 entry = xas_next(&xas); 567 if (xas_retry(&xas, entry)) 568 continue; 569 WARN_ON(!xa_is_value(entry)); 570 if (!batch_add_pfn(batch, xa_to_value(entry)) || 571 start_index == last_index) 572 break; 573 start_index++; 574 } 575 rcu_read_unlock(); 576 } 577 578 static void batch_from_xarray_clear(struct pfn_batch *batch, struct xarray *xa, 579 unsigned long start_index, 580 unsigned long last_index) 581 { 582 XA_STATE(xas, xa, start_index); 583 void *entry; 584 585 xas_lock(&xas); 586 while (true) { 587 entry = xas_next(&xas); 588 if (xas_retry(&xas, entry)) 589 continue; 590 WARN_ON(!xa_is_value(entry)); 591 if (!batch_add_pfn(batch, xa_to_value(entry))) 592 break; 593 xas_store(&xas, NULL); 594 if (start_index == last_index) 595 break; 596 start_index++; 597 } 598 xas_unlock(&xas); 599 } 600 601 static void clear_xarray(struct xarray *xa, unsigned long start_index, 602 unsigned long last_index) 603 { 604 XA_STATE(xas, xa, start_index); 605 void *entry; 606 607 xas_lock(&xas); 608 xas_for_each(&xas, entry, last_index) 609 xas_store(&xas, NULL); 610 xas_unlock(&xas); 611 } 612 613 static int pages_to_xarray(struct xarray *xa, unsigned long start_index, 614 unsigned long last_index, struct page **pages) 615 { 616 struct page **end_pages = pages + (last_index - start_index) + 1; 617 struct page **half_pages = pages + (end_pages - pages) / 2; 618 XA_STATE(xas, xa, start_index); 619 620 do { 621 void *old; 622 623 xas_lock(&xas); 624 while (pages != end_pages) { 625 /* xarray does not participate in fault injection */ 626 if (pages == half_pages && iommufd_should_fail()) { 627 xas_set_err(&xas, -EINVAL); 628 xas_unlock(&xas); 629 /* aka xas_destroy() */ 630 xas_nomem(&xas, GFP_KERNEL); 631 goto err_clear; 632 } 633 634 old = xas_store(&xas, xa_mk_value(page_to_pfn(*pages))); 635 if (xas_error(&xas)) 636 break; 637 WARN_ON(old); 638 pages++; 639 xas_next(&xas); 640 } 641 xas_unlock(&xas); 642 } while (xas_nomem(&xas, GFP_KERNEL)); 643 644 err_clear: 645 if (xas_error(&xas)) { 646 if (xas.xa_index != start_index) 647 clear_xarray(xa, start_index, xas.xa_index - 1); 648 return xas_error(&xas); 649 } 650 return 0; 651 } 652 653 static void batch_from_pages(struct pfn_batch *batch, struct page **pages, 654 size_t npages) 655 { 656 struct page **end = pages + npages; 657 658 for (; pages != end; pages++) 659 if (!batch_add_pfn(batch, page_to_pfn(*pages))) 660 break; 661 } 662 663 static int batch_from_folios(struct pfn_batch *batch, struct folio ***folios_p, 664 unsigned long *offset_p, unsigned long npages) 665 { 666 int rc = 0; 667 struct folio **folios = *folios_p; 668 unsigned long offset = *offset_p; 669 670 while (npages) { 671 struct folio *folio = *folios; 672 unsigned long nr = folio_nr_pages(folio) - offset; 673 unsigned long pfn = page_to_pfn(folio_page(folio, offset)); 674 675 nr = min(nr, npages); 676 npages -= nr; 677 678 if (!batch_add_pfn_num(batch, pfn, nr, BATCH_CPU_MEMORY)) 679 break; 680 if (nr > 1) { 681 rc = folio_add_pins(folio, nr - 1); 682 if (rc) { 683 batch_remove_pfn_num(batch, nr); 684 goto out; 685 } 686 } 687 688 folios++; 689 offset = 0; 690 } 691 692 out: 693 *folios_p = folios; 694 *offset_p = offset; 695 return rc; 696 } 697 698 static void batch_unpin(struct pfn_batch *batch, struct iopt_pages *pages, 699 unsigned int first_page_off, size_t npages) 700 { 701 unsigned int cur = 0; 702 703 while (first_page_off) { 704 if (batch->npfns[cur] > first_page_off) 705 break; 706 first_page_off -= batch->npfns[cur]; 707 cur++; 708 } 709 710 while (npages) { 711 size_t to_unpin = min_t(size_t, npages, 712 batch->npfns[cur] - first_page_off); 713 714 unpin_user_page_range_dirty_lock( 715 pfn_to_page(batch->pfns[cur] + first_page_off), 716 to_unpin, pages->writable); 717 iopt_pages_sub_npinned(pages, to_unpin); 718 cur++; 719 first_page_off = 0; 720 npages -= to_unpin; 721 } 722 } 723 724 static void copy_data_page(struct page *page, void *data, unsigned long offset, 725 size_t length, unsigned int flags) 726 { 727 void *mem; 728 729 mem = kmap_local_page(page); 730 if (flags & IOMMUFD_ACCESS_RW_WRITE) { 731 memcpy(mem + offset, data, length); 732 set_page_dirty_lock(page); 733 } else { 734 memcpy(data, mem + offset, length); 735 } 736 kunmap_local(mem); 737 } 738 739 static unsigned long batch_rw(struct pfn_batch *batch, void *data, 740 unsigned long offset, unsigned long length, 741 unsigned int flags) 742 { 743 unsigned long copied = 0; 744 unsigned int npage = 0; 745 unsigned int cur = 0; 746 747 while (cur < batch->end) { 748 unsigned long bytes = min(length, PAGE_SIZE - offset); 749 750 copy_data_page(pfn_to_page(batch->pfns[cur] + npage), data, 751 offset, bytes, flags); 752 offset = 0; 753 length -= bytes; 754 data += bytes; 755 copied += bytes; 756 npage++; 757 if (npage == batch->npfns[cur]) { 758 npage = 0; 759 cur++; 760 } 761 if (!length) 762 break; 763 } 764 return copied; 765 } 766 767 /* pfn_reader_user is just the pin_user_pages() path */ 768 struct pfn_reader_user { 769 struct page **upages; 770 size_t upages_len; 771 unsigned long upages_start; 772 unsigned long upages_end; 773 unsigned int gup_flags; 774 /* 775 * 1 means mmget() and mmap_read_lock(), 0 means only mmget(), -1 is 776 * neither 777 */ 778 int locked; 779 780 /* The following are only valid if file != NULL. */ 781 struct file *file; 782 struct folio **ufolios; 783 size_t ufolios_len; 784 unsigned long ufolios_offset; 785 struct folio **ufolios_next; 786 }; 787 788 static void pfn_reader_user_init(struct pfn_reader_user *user, 789 struct iopt_pages *pages) 790 { 791 user->upages = NULL; 792 user->upages_len = 0; 793 user->upages_start = 0; 794 user->upages_end = 0; 795 user->locked = -1; 796 user->gup_flags = FOLL_LONGTERM; 797 if (pages->writable) 798 user->gup_flags |= FOLL_WRITE; 799 800 user->file = (pages->type == IOPT_ADDRESS_FILE) ? pages->file : NULL; 801 user->ufolios = NULL; 802 user->ufolios_len = 0; 803 user->ufolios_next = NULL; 804 user->ufolios_offset = 0; 805 } 806 807 static void pfn_reader_user_destroy(struct pfn_reader_user *user, 808 struct iopt_pages *pages) 809 { 810 if (user->locked != -1) { 811 if (user->locked) 812 mmap_read_unlock(pages->source_mm); 813 if (!user->file && pages->source_mm != current->mm) 814 mmput(pages->source_mm); 815 user->locked = -1; 816 } 817 818 kfree(user->upages); 819 user->upages = NULL; 820 kfree(user->ufolios); 821 user->ufolios = NULL; 822 } 823 824 static long pin_memfd_pages(struct pfn_reader_user *user, unsigned long start, 825 unsigned long npages) 826 { 827 unsigned long i; 828 unsigned long offset; 829 unsigned long npages_out = 0; 830 struct page **upages = user->upages; 831 unsigned long end = start + (npages << PAGE_SHIFT) - 1; 832 long nfolios = user->ufolios_len / sizeof(*user->ufolios); 833 834 /* 835 * todo: memfd_pin_folios should return the last pinned offset so 836 * we can compute npages pinned, and avoid looping over folios here 837 * if upages == NULL. 838 */ 839 nfolios = memfd_pin_folios(user->file, start, end, user->ufolios, 840 nfolios, &offset); 841 if (nfolios <= 0) 842 return nfolios; 843 844 offset >>= PAGE_SHIFT; 845 user->ufolios_next = user->ufolios; 846 user->ufolios_offset = offset; 847 848 for (i = 0; i < nfolios; i++) { 849 struct folio *folio = user->ufolios[i]; 850 unsigned long nr = folio_nr_pages(folio); 851 unsigned long npin = min(nr - offset, npages); 852 853 npages -= npin; 854 npages_out += npin; 855 856 if (upages) { 857 if (npin == 1) { 858 *upages++ = folio_page(folio, offset); 859 } else { 860 int rc = folio_add_pins(folio, npin - 1); 861 862 if (rc) 863 return rc; 864 865 while (npin--) 866 *upages++ = folio_page(folio, offset++); 867 } 868 } 869 870 offset = 0; 871 } 872 873 return npages_out; 874 } 875 876 static int pfn_reader_user_pin(struct pfn_reader_user *user, 877 struct iopt_pages *pages, 878 unsigned long start_index, 879 unsigned long last_index) 880 { 881 bool remote_mm = pages->source_mm != current->mm; 882 unsigned long npages = last_index - start_index + 1; 883 unsigned long start; 884 unsigned long unum; 885 uintptr_t uptr; 886 long rc; 887 888 if (IS_ENABLED(CONFIG_IOMMUFD_TEST) && 889 WARN_ON(last_index < start_index)) 890 return -EINVAL; 891 892 if (!user->file && !user->upages) { 893 /* All undone in pfn_reader_destroy() */ 894 user->upages_len = npages * sizeof(*user->upages); 895 user->upages = temp_kmalloc(&user->upages_len, NULL, 0); 896 if (!user->upages) 897 return -ENOMEM; 898 } 899 900 if (user->file && !user->ufolios) { 901 user->ufolios_len = npages * sizeof(*user->ufolios); 902 user->ufolios = temp_kmalloc(&user->ufolios_len, NULL, 0); 903 if (!user->ufolios) 904 return -ENOMEM; 905 } 906 907 if (user->locked == -1) { 908 /* 909 * The majority of usages will run the map task within the mm 910 * providing the pages, so we can optimize into 911 * get_user_pages_fast() 912 */ 913 if (!user->file && remote_mm) { 914 if (!mmget_not_zero(pages->source_mm)) 915 return -EFAULT; 916 } 917 user->locked = 0; 918 } 919 920 unum = user->file ? user->ufolios_len / sizeof(*user->ufolios) : 921 user->upages_len / sizeof(*user->upages); 922 npages = min_t(unsigned long, npages, unum); 923 924 if (iommufd_should_fail()) 925 return -EFAULT; 926 927 if (user->file) { 928 start = pages->start + (start_index * PAGE_SIZE); 929 rc = pin_memfd_pages(user, start, npages); 930 } else if (!remote_mm) { 931 uptr = (uintptr_t)(pages->uptr + start_index * PAGE_SIZE); 932 rc = pin_user_pages_fast(uptr, npages, user->gup_flags, 933 user->upages); 934 } else { 935 uptr = (uintptr_t)(pages->uptr + start_index * PAGE_SIZE); 936 if (!user->locked) { 937 mmap_read_lock(pages->source_mm); 938 user->locked = 1; 939 } 940 rc = pin_user_pages_remote(pages->source_mm, uptr, npages, 941 user->gup_flags, user->upages, 942 &user->locked); 943 } 944 if (rc <= 0) { 945 if (WARN_ON(!rc)) 946 return -EFAULT; 947 return rc; 948 } 949 iopt_pages_add_npinned(pages, rc); 950 user->upages_start = start_index; 951 user->upages_end = start_index + rc; 952 return 0; 953 } 954 955 /* This is the "modern" and faster accounting method used by io_uring */ 956 static int incr_user_locked_vm(struct iopt_pages *pages, unsigned long npages) 957 { 958 unsigned long lock_limit; 959 unsigned long cur_pages; 960 unsigned long new_pages; 961 962 lock_limit = task_rlimit(pages->source_task, RLIMIT_MEMLOCK) >> 963 PAGE_SHIFT; 964 965 cur_pages = atomic_long_read(&pages->source_user->locked_vm); 966 do { 967 new_pages = cur_pages + npages; 968 if (new_pages > lock_limit) 969 return -ENOMEM; 970 } while (!atomic_long_try_cmpxchg(&pages->source_user->locked_vm, 971 &cur_pages, new_pages)); 972 return 0; 973 } 974 975 static void decr_user_locked_vm(struct iopt_pages *pages, unsigned long npages) 976 { 977 if (WARN_ON(atomic_long_read(&pages->source_user->locked_vm) < npages)) 978 return; 979 atomic_long_sub(npages, &pages->source_user->locked_vm); 980 } 981 982 /* This is the accounting method used for compatibility with VFIO */ 983 static int update_mm_locked_vm(struct iopt_pages *pages, unsigned long npages, 984 bool inc, struct pfn_reader_user *user) 985 { 986 bool do_put = false; 987 int rc; 988 989 if (user && user->locked) { 990 mmap_read_unlock(pages->source_mm); 991 user->locked = 0; 992 /* If we had the lock then we also have a get */ 993 994 } else if ((!user || (!user->upages && !user->ufolios)) && 995 pages->source_mm != current->mm) { 996 if (!mmget_not_zero(pages->source_mm)) 997 return -EINVAL; 998 do_put = true; 999 } 1000 1001 mmap_write_lock(pages->source_mm); 1002 rc = __account_locked_vm(pages->source_mm, npages, inc, 1003 pages->source_task, false); 1004 mmap_write_unlock(pages->source_mm); 1005 1006 if (do_put) 1007 mmput(pages->source_mm); 1008 return rc; 1009 } 1010 1011 int iopt_pages_update_pinned(struct iopt_pages *pages, unsigned long npages, 1012 bool inc, struct pfn_reader_user *user) 1013 { 1014 int rc = 0; 1015 1016 switch (pages->account_mode) { 1017 case IOPT_PAGES_ACCOUNT_NONE: 1018 break; 1019 case IOPT_PAGES_ACCOUNT_USER: 1020 if (inc) 1021 rc = incr_user_locked_vm(pages, npages); 1022 else 1023 decr_user_locked_vm(pages, npages); 1024 break; 1025 case IOPT_PAGES_ACCOUNT_MM: 1026 rc = update_mm_locked_vm(pages, npages, inc, user); 1027 break; 1028 } 1029 if (rc) 1030 return rc; 1031 1032 pages->last_npinned = pages->npinned; 1033 if (inc) 1034 atomic64_add(npages, &pages->source_mm->pinned_vm); 1035 else 1036 atomic64_sub(npages, &pages->source_mm->pinned_vm); 1037 return 0; 1038 } 1039 1040 static void update_unpinned(struct iopt_pages *pages) 1041 { 1042 if (WARN_ON(pages->npinned > pages->last_npinned)) 1043 return; 1044 if (pages->npinned == pages->last_npinned) 1045 return; 1046 iopt_pages_update_pinned(pages, pages->last_npinned - pages->npinned, 1047 false, NULL); 1048 } 1049 1050 /* 1051 * Changes in the number of pages pinned is done after the pages have been read 1052 * and processed. If the user lacked the limit then the error unwind will unpin 1053 * everything that was just pinned. This is because it is expensive to calculate 1054 * how many pages we have already pinned within a range to generate an accurate 1055 * prediction in advance of doing the work to actually pin them. 1056 */ 1057 static int pfn_reader_user_update_pinned(struct pfn_reader_user *user, 1058 struct iopt_pages *pages) 1059 { 1060 unsigned long npages; 1061 bool inc; 1062 1063 lockdep_assert_held(&pages->mutex); 1064 1065 if (pages->npinned == pages->last_npinned) 1066 return 0; 1067 1068 if (pages->npinned < pages->last_npinned) { 1069 npages = pages->last_npinned - pages->npinned; 1070 inc = false; 1071 } else { 1072 if (iommufd_should_fail()) 1073 return -ENOMEM; 1074 npages = pages->npinned - pages->last_npinned; 1075 inc = true; 1076 } 1077 return iopt_pages_update_pinned(pages, npages, inc, user); 1078 } 1079 1080 struct pfn_reader_dmabuf { 1081 struct phys_vec phys; 1082 unsigned long start_offset; 1083 }; 1084 1085 static int pfn_reader_dmabuf_init(struct pfn_reader_dmabuf *dmabuf, 1086 struct iopt_pages *pages) 1087 { 1088 /* Callers must not get here if the dmabuf was already revoked */ 1089 if (WARN_ON(iopt_dmabuf_revoked(pages))) 1090 return -EINVAL; 1091 1092 dmabuf->phys = pages->dmabuf.phys; 1093 dmabuf->start_offset = pages->dmabuf.start; 1094 return 0; 1095 } 1096 1097 static int pfn_reader_fill_dmabuf(struct pfn_reader_dmabuf *dmabuf, 1098 struct pfn_batch *batch, 1099 unsigned long start_index, 1100 unsigned long last_index) 1101 { 1102 unsigned long start = dmabuf->start_offset + start_index * PAGE_SIZE; 1103 1104 /* 1105 * start/last_index and start are all PAGE_SIZE aligned, the batch is 1106 * always filled using page size aligned PFNs just like the other types. 1107 * If the dmabuf has been sliced on a sub page offset then the common 1108 * batch to domain code will adjust it before mapping to the domain. 1109 */ 1110 batch_add_pfn_num(batch, PHYS_PFN(dmabuf->phys.paddr + start), 1111 last_index - start_index + 1, BATCH_MMIO); 1112 return 0; 1113 } 1114 1115 /* 1116 * PFNs are stored in three places, in order of preference: 1117 * - The iopt_pages xarray. This is only populated if there is a 1118 * iopt_pages_access 1119 * - The iommu_domain under an area 1120 * - The original PFN source, ie pages->source_mm 1121 * 1122 * This iterator reads the pfns optimizing to load according to the 1123 * above order. 1124 */ 1125 struct pfn_reader { 1126 struct iopt_pages *pages; 1127 struct interval_tree_double_span_iter span; 1128 struct pfn_batch batch; 1129 unsigned long batch_start_index; 1130 unsigned long batch_end_index; 1131 unsigned long last_index; 1132 1133 union { 1134 struct pfn_reader_user user; 1135 struct pfn_reader_dmabuf dmabuf; 1136 }; 1137 }; 1138 1139 static int pfn_reader_update_pinned(struct pfn_reader *pfns) 1140 { 1141 return pfn_reader_user_update_pinned(&pfns->user, pfns->pages); 1142 } 1143 1144 /* 1145 * The batch can contain a mixture of pages that are still in use and pages that 1146 * need to be unpinned. Unpin only pages that are not held anywhere else. 1147 */ 1148 static void pfn_reader_unpin(struct pfn_reader *pfns) 1149 { 1150 unsigned long last = pfns->batch_end_index - 1; 1151 unsigned long start = pfns->batch_start_index; 1152 struct interval_tree_double_span_iter span; 1153 struct iopt_pages *pages = pfns->pages; 1154 1155 lockdep_assert_held(&pages->mutex); 1156 1157 interval_tree_for_each_double_span(&span, &pages->access_itree, 1158 &pages->domains_itree, start, last) { 1159 if (span.is_used) 1160 continue; 1161 1162 batch_unpin(&pfns->batch, pages, span.start_hole - start, 1163 span.last_hole - span.start_hole + 1); 1164 } 1165 } 1166 1167 /* Process a single span to load it from the proper storage */ 1168 static int pfn_reader_fill_span(struct pfn_reader *pfns) 1169 { 1170 struct interval_tree_double_span_iter *span = &pfns->span; 1171 unsigned long start_index = pfns->batch_end_index; 1172 struct pfn_reader_user *user; 1173 unsigned long npages; 1174 struct iopt_area *area; 1175 int rc; 1176 1177 if (IS_ENABLED(CONFIG_IOMMUFD_TEST) && 1178 WARN_ON(span->last_used < start_index)) 1179 return -EINVAL; 1180 1181 /* 1182 * Always read a dmabuf from its phys, even where a domain already 1183 * maps it: a domain can only report CPU memory PFNs, losing 1184 * BATCH_MMIO. last_hole aliases last_used, so this covers any span. 1185 */ 1186 if (iopt_is_dmabuf(pfns->pages)) 1187 return pfn_reader_fill_dmabuf(&pfns->dmabuf, &pfns->batch, 1188 start_index, span->last_hole); 1189 1190 if (span->is_used == 1) { 1191 batch_from_xarray(&pfns->batch, &pfns->pages->pinned_pfns, 1192 start_index, span->last_used); 1193 return 0; 1194 } 1195 1196 if (span->is_used == 2) { 1197 /* 1198 * Pull as many pages from the first domain we find in the 1199 * target span. If it is too small then we will be called again 1200 * and we'll find another area. 1201 */ 1202 area = iopt_pages_find_domain_area(pfns->pages, start_index); 1203 if (WARN_ON(!area)) 1204 return -EINVAL; 1205 1206 /* The storage_domain cannot change without the pages mutex */ 1207 batch_from_domain( 1208 &pfns->batch, area->storage_domain, area, start_index, 1209 min(iopt_area_last_index(area), span->last_used)); 1210 return 0; 1211 } 1212 1213 user = &pfns->user; 1214 if (start_index >= user->upages_end) { 1215 rc = pfn_reader_user_pin(user, pfns->pages, start_index, 1216 span->last_hole); 1217 if (rc) 1218 return rc; 1219 } 1220 1221 npages = user->upages_end - start_index; 1222 start_index -= user->upages_start; 1223 rc = 0; 1224 1225 if (!user->file) 1226 batch_from_pages(&pfns->batch, user->upages + start_index, 1227 npages); 1228 else 1229 rc = batch_from_folios(&pfns->batch, &user->ufolios_next, 1230 &user->ufolios_offset, npages); 1231 return rc; 1232 } 1233 1234 static bool pfn_reader_done(struct pfn_reader *pfns) 1235 { 1236 return pfns->batch_start_index == pfns->last_index + 1; 1237 } 1238 1239 static int pfn_reader_next(struct pfn_reader *pfns) 1240 { 1241 int rc; 1242 1243 batch_clear(&pfns->batch); 1244 pfns->batch_start_index = pfns->batch_end_index; 1245 1246 while (pfns->batch_end_index != pfns->last_index + 1) { 1247 unsigned int npfns = pfns->batch.total_pfns; 1248 1249 if (IS_ENABLED(CONFIG_IOMMUFD_TEST) && 1250 WARN_ON(interval_tree_double_span_iter_done(&pfns->span))) 1251 return -EINVAL; 1252 1253 rc = pfn_reader_fill_span(pfns); 1254 if (rc) 1255 return rc; 1256 1257 if (WARN_ON(!pfns->batch.total_pfns)) 1258 return -EINVAL; 1259 1260 pfns->batch_end_index = 1261 pfns->batch_start_index + pfns->batch.total_pfns; 1262 if (pfns->batch_end_index == pfns->span.last_used + 1) 1263 interval_tree_double_span_iter_next(&pfns->span); 1264 1265 /* Batch is full */ 1266 if (npfns == pfns->batch.total_pfns) 1267 return 0; 1268 } 1269 return 0; 1270 } 1271 1272 static int pfn_reader_init(struct pfn_reader *pfns, struct iopt_pages *pages, 1273 unsigned long start_index, unsigned long last_index) 1274 { 1275 int rc; 1276 1277 lockdep_assert_held(&pages->mutex); 1278 1279 pfns->pages = pages; 1280 pfns->batch_start_index = start_index; 1281 pfns->batch_end_index = start_index; 1282 pfns->last_index = last_index; 1283 if (iopt_is_dmabuf(pages)) 1284 pfn_reader_dmabuf_init(&pfns->dmabuf, pages); 1285 else 1286 pfn_reader_user_init(&pfns->user, pages); 1287 rc = batch_init(&pfns->batch, last_index - start_index + 1); 1288 if (rc) 1289 return rc; 1290 interval_tree_double_span_iter_first(&pfns->span, &pages->access_itree, 1291 &pages->domains_itree, start_index, 1292 last_index); 1293 return 0; 1294 } 1295 1296 /* 1297 * There are many assertions regarding the state of pages->npinned vs 1298 * pages->last_pinned, for instance something like unmapping a domain must only 1299 * decrement the npinned, and pfn_reader_destroy() must be called only after all 1300 * the pins are updated. This is fine for success flows, but error flows 1301 * sometimes need to release the pins held inside the pfn_reader before going on 1302 * to complete unmapping and releasing pins held in domains. 1303 */ 1304 static void pfn_reader_release_pins(struct pfn_reader *pfns) 1305 { 1306 struct iopt_pages *pages = pfns->pages; 1307 struct pfn_reader_user *user; 1308 1309 if (iopt_is_dmabuf(pages)) 1310 return; 1311 1312 user = &pfns->user; 1313 if (user->upages_end > pfns->batch_end_index) { 1314 /* Any pages not transferred to the batch are just unpinned */ 1315 1316 unsigned long npages = user->upages_end - pfns->batch_end_index; 1317 unsigned long start_index = pfns->batch_end_index - 1318 user->upages_start; 1319 1320 if (!user->file) { 1321 unpin_user_pages(user->upages + start_index, npages); 1322 } else { 1323 long n = user->ufolios_len / sizeof(*user->ufolios); 1324 1325 unpin_folios(user->ufolios_next, 1326 user->ufolios + n - user->ufolios_next); 1327 } 1328 iopt_pages_sub_npinned(pages, npages); 1329 user->upages_end = pfns->batch_end_index; 1330 } 1331 if (pfns->batch_start_index != pfns->batch_end_index) { 1332 pfn_reader_unpin(pfns); 1333 pfns->batch_start_index = pfns->batch_end_index; 1334 } 1335 } 1336 1337 static void pfn_reader_destroy(struct pfn_reader *pfns) 1338 { 1339 struct iopt_pages *pages = pfns->pages; 1340 1341 pfn_reader_release_pins(pfns); 1342 if (!iopt_is_dmabuf(pfns->pages)) 1343 pfn_reader_user_destroy(&pfns->user, pfns->pages); 1344 batch_destroy(&pfns->batch, NULL); 1345 WARN_ON(pages->last_npinned != pages->npinned); 1346 } 1347 1348 static int pfn_reader_first(struct pfn_reader *pfns, struct iopt_pages *pages, 1349 unsigned long start_index, unsigned long last_index) 1350 { 1351 int rc; 1352 1353 if (IS_ENABLED(CONFIG_IOMMUFD_TEST) && 1354 WARN_ON(last_index < start_index)) 1355 return -EINVAL; 1356 1357 rc = pfn_reader_init(pfns, pages, start_index, last_index); 1358 if (rc) 1359 return rc; 1360 rc = pfn_reader_next(pfns); 1361 if (rc) { 1362 pfn_reader_destroy(pfns); 1363 return rc; 1364 } 1365 return 0; 1366 } 1367 1368 static struct iopt_pages *iopt_alloc_pages(unsigned long start_byte, 1369 unsigned long length, bool writable) 1370 { 1371 struct iopt_pages *pages; 1372 1373 /* 1374 * The iommu API uses size_t as the length, and protect the DIV_ROUND_UP 1375 * below from overflow 1376 */ 1377 if (length > SIZE_MAX - PAGE_SIZE || length == 0) 1378 return ERR_PTR(-EINVAL); 1379 1380 pages = kzalloc_obj(*pages, GFP_KERNEL_ACCOUNT); 1381 if (!pages) 1382 return ERR_PTR(-ENOMEM); 1383 1384 kref_init(&pages->kref); 1385 xa_init_flags(&pages->pinned_pfns, XA_FLAGS_ACCOUNT); 1386 mutex_init(&pages->mutex); 1387 pages->source_mm = current->mm; 1388 mmgrab(pages->source_mm); 1389 pages->npages = DIV_ROUND_UP(length + start_byte, PAGE_SIZE); 1390 pages->access_itree = RB_ROOT_CACHED; 1391 pages->domains_itree = RB_ROOT_CACHED; 1392 pages->writable = writable; 1393 if (capable(CAP_IPC_LOCK)) 1394 pages->account_mode = IOPT_PAGES_ACCOUNT_NONE; 1395 else 1396 pages->account_mode = IOPT_PAGES_ACCOUNT_USER; 1397 pages->source_task = current->group_leader; 1398 get_task_struct(current->group_leader); 1399 pages->source_user = get_uid(current_user()); 1400 return pages; 1401 } 1402 1403 struct iopt_pages *iopt_alloc_user_pages(void __user *uptr, 1404 unsigned long length, bool writable) 1405 { 1406 struct iopt_pages *pages; 1407 unsigned long end; 1408 void __user *uptr_down = 1409 (void __user *)ALIGN_DOWN((uintptr_t)uptr, PAGE_SIZE); 1410 1411 if (check_add_overflow((unsigned long)uptr, length, &end)) 1412 return ERR_PTR(-EOVERFLOW); 1413 1414 pages = iopt_alloc_pages(uptr - uptr_down, length, writable); 1415 if (IS_ERR(pages)) 1416 return pages; 1417 pages->uptr = uptr_down; 1418 pages->type = IOPT_ADDRESS_USER; 1419 return pages; 1420 } 1421 1422 struct iopt_pages *iopt_alloc_file_pages(struct file *file, 1423 unsigned long start_byte, 1424 unsigned long start, 1425 unsigned long length, bool writable) 1426 1427 { 1428 struct iopt_pages *pages; 1429 1430 pages = iopt_alloc_pages(start_byte, length, writable); 1431 if (IS_ERR(pages)) 1432 return pages; 1433 pages->file = get_file(file); 1434 pages->start = start - start_byte; 1435 pages->type = IOPT_ADDRESS_FILE; 1436 return pages; 1437 } 1438 1439 static void iopt_revoke_notify(struct dma_buf_attachment *attach) 1440 { 1441 struct iopt_pages *pages = attach->importer_priv; 1442 struct iopt_pages_dmabuf_track *track; 1443 1444 guard(mutex)(&pages->mutex); 1445 if (iopt_dmabuf_revoked(pages)) 1446 return; 1447 1448 list_for_each_entry(track, &pages->dmabuf.tracker, elm) { 1449 struct iopt_area *area = track->area; 1450 1451 iopt_area_unmap_domain_range(area, track->domain, 1452 iopt_area_index(area), 1453 iopt_area_last_index(area)); 1454 } 1455 pages->dmabuf.phys.len = 0; 1456 } 1457 1458 static const struct dma_buf_attach_ops iopt_dmabuf_attach_revoke_ops = { 1459 .allow_peer2peer = true, 1460 .invalidate_mappings = iopt_revoke_notify, 1461 }; 1462 1463 /* 1464 * iommufd and vfio have a circular dependency. Future work for a phys 1465 * based private interconnect will remove this. 1466 */ 1467 static int 1468 sym_vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment, 1469 struct phys_vec *phys) 1470 { 1471 typeof(&vfio_pci_dma_buf_iommufd_map) fn; 1472 int rc; 1473 1474 rc = iommufd_test_dma_buf_iommufd_map(attachment, phys); 1475 if (rc != -EOPNOTSUPP) 1476 return rc; 1477 1478 if (!IS_ENABLED(CONFIG_VFIO_PCI_DMABUF)) 1479 return -EOPNOTSUPP; 1480 1481 fn = symbol_get(vfio_pci_dma_buf_iommufd_map); 1482 if (!fn) 1483 return -EOPNOTSUPP; 1484 rc = fn(attachment, phys); 1485 symbol_put(vfio_pci_dma_buf_iommufd_map); 1486 return rc; 1487 } 1488 1489 static int iopt_map_dmabuf(struct iommufd_ctx *ictx, struct iopt_pages *pages, 1490 struct dma_buf *dmabuf) 1491 { 1492 struct dma_buf_attachment *attach; 1493 int rc; 1494 1495 attach = dma_buf_dynamic_attach(dmabuf, iommufd_global_device(), 1496 &iopt_dmabuf_attach_revoke_ops, pages); 1497 if (IS_ERR(attach)) 1498 return PTR_ERR(attach); 1499 1500 dma_resv_lock(dmabuf->resv, NULL); 1501 /* 1502 * Lock ordering requires the mutex to be taken inside the reservation, 1503 * make sure lockdep sees this. 1504 */ 1505 if (IS_ENABLED(CONFIG_LOCKDEP)) { 1506 mutex_lock(&pages->mutex); 1507 mutex_unlock(&pages->mutex); 1508 } 1509 1510 rc = dma_buf_pin(attach); 1511 if (rc) 1512 goto err_detach; 1513 1514 rc = sym_vfio_pci_dma_buf_iommufd_map(attach, &pages->dmabuf.phys); 1515 if (rc) 1516 goto err_unpin; 1517 1518 dma_resv_unlock(dmabuf->resv); 1519 1520 /* On success iopt_release_pages() will detach and put the dmabuf. */ 1521 pages->dmabuf.attach = attach; 1522 return 0; 1523 1524 err_unpin: 1525 dma_buf_unpin(attach); 1526 err_detach: 1527 dma_resv_unlock(dmabuf->resv); 1528 dma_buf_detach(dmabuf, attach); 1529 return rc; 1530 } 1531 1532 struct iopt_pages *iopt_alloc_dmabuf_pages(struct iommufd_ctx *ictx, 1533 struct dma_buf *dmabuf, 1534 unsigned long start_byte, 1535 unsigned long start, 1536 unsigned long length, bool writable) 1537 { 1538 static struct lock_class_key pages_dmabuf_mutex_key; 1539 struct iopt_pages *pages; 1540 int rc; 1541 1542 if (!IS_ENABLED(CONFIG_DMA_SHARED_BUFFER)) 1543 return ERR_PTR(-EOPNOTSUPP); 1544 1545 if (dmabuf->size <= (start + length - 1) || 1546 length / PAGE_SIZE >= MAX_NPFNS) 1547 return ERR_PTR(-EINVAL); 1548 1549 pages = iopt_alloc_pages(start_byte, length, writable); 1550 if (IS_ERR(pages)) 1551 return pages; 1552 1553 /* 1554 * The mmap_lock can be held when obtaining the dmabuf reservation lock 1555 * which creates a locking cycle with the pages mutex which is held 1556 * while obtaining the mmap_lock. This locking path is not present for 1557 * IOPT_ADDRESS_DMABUF so split the lock class. 1558 */ 1559 lockdep_set_class(&pages->mutex, &pages_dmabuf_mutex_key); 1560 1561 /* dmabuf does not use pinned page accounting. */ 1562 pages->account_mode = IOPT_PAGES_ACCOUNT_NONE; 1563 pages->type = IOPT_ADDRESS_DMABUF; 1564 pages->dmabuf.start = start - start_byte; 1565 INIT_LIST_HEAD(&pages->dmabuf.tracker); 1566 1567 rc = iopt_map_dmabuf(ictx, pages, dmabuf); 1568 if (rc) { 1569 iopt_put_pages(pages); 1570 return ERR_PTR(rc); 1571 } 1572 1573 return pages; 1574 } 1575 1576 int iopt_dmabuf_track_domain(struct iopt_pages *pages, struct iopt_area *area, 1577 struct iommu_domain *domain) 1578 { 1579 struct iopt_pages_dmabuf_track *track; 1580 1581 lockdep_assert_held(&pages->mutex); 1582 if (WARN_ON(!iopt_is_dmabuf(pages))) 1583 return -EINVAL; 1584 1585 list_for_each_entry(track, &pages->dmabuf.tracker, elm) 1586 if (WARN_ON(track->domain == domain && track->area == area)) 1587 return -EINVAL; 1588 1589 track = kzalloc_obj(*track); 1590 if (!track) 1591 return -ENOMEM; 1592 track->domain = domain; 1593 track->area = area; 1594 list_add_tail(&track->elm, &pages->dmabuf.tracker); 1595 1596 return 0; 1597 } 1598 1599 void iopt_dmabuf_untrack_domain(struct iopt_pages *pages, 1600 struct iopt_area *area, 1601 struct iommu_domain *domain) 1602 { 1603 struct iopt_pages_dmabuf_track *track; 1604 1605 lockdep_assert_held(&pages->mutex); 1606 WARN_ON(!iopt_is_dmabuf(pages)); 1607 1608 list_for_each_entry(track, &pages->dmabuf.tracker, elm) { 1609 if (track->domain == domain && track->area == area) { 1610 list_del(&track->elm); 1611 kfree(track); 1612 return; 1613 } 1614 } 1615 WARN_ON(true); 1616 } 1617 1618 int iopt_dmabuf_track_all_domains(struct iopt_area *area, 1619 struct iopt_pages *pages) 1620 { 1621 struct iopt_pages_dmabuf_track *track; 1622 struct iommu_domain *domain; 1623 unsigned long index; 1624 int rc; 1625 1626 list_for_each_entry(track, &pages->dmabuf.tracker, elm) 1627 if (WARN_ON(track->area == area)) 1628 return -EINVAL; 1629 1630 xa_for_each(&area->iopt->domains, index, domain) { 1631 rc = iopt_dmabuf_track_domain(pages, area, domain); 1632 if (rc) 1633 goto err_untrack; 1634 } 1635 return 0; 1636 err_untrack: 1637 iopt_dmabuf_untrack_all_domains(area, pages); 1638 return rc; 1639 } 1640 1641 void iopt_dmabuf_untrack_all_domains(struct iopt_area *area, 1642 struct iopt_pages *pages) 1643 { 1644 struct iopt_pages_dmabuf_track *track; 1645 struct iopt_pages_dmabuf_track *tmp; 1646 1647 list_for_each_entry_safe(track, tmp, &pages->dmabuf.tracker, 1648 elm) { 1649 if (track->area == area) { 1650 list_del(&track->elm); 1651 kfree(track); 1652 } 1653 } 1654 } 1655 1656 void iopt_release_pages(struct kref *kref) 1657 { 1658 struct iopt_pages *pages = container_of(kref, struct iopt_pages, kref); 1659 1660 WARN_ON(!RB_EMPTY_ROOT(&pages->access_itree.rb_root)); 1661 WARN_ON(!RB_EMPTY_ROOT(&pages->domains_itree.rb_root)); 1662 WARN_ON(pages->npinned); 1663 WARN_ON(!xa_empty(&pages->pinned_pfns)); 1664 if (iopt_is_dmabuf(pages) && pages->dmabuf.attach) { 1665 struct dma_buf *dmabuf = pages->dmabuf.attach->dmabuf; 1666 1667 dma_resv_lock(dmabuf->resv, NULL); 1668 dma_buf_unpin(pages->dmabuf.attach); 1669 dma_resv_unlock(dmabuf->resv); 1670 dma_buf_detach(dmabuf, pages->dmabuf.attach); 1671 dma_buf_put(dmabuf); 1672 WARN_ON(!list_empty(&pages->dmabuf.tracker)); 1673 } else if (pages->type == IOPT_ADDRESS_FILE) { 1674 fput(pages->file); 1675 } 1676 mmdrop(pages->source_mm); 1677 mutex_destroy(&pages->mutex); 1678 put_task_struct(pages->source_task); 1679 free_uid(pages->source_user); 1680 kfree(pages); 1681 } 1682 1683 static void 1684 iopt_area_unpin_domain(struct pfn_batch *batch, struct iopt_area *area, 1685 struct iopt_pages *pages, struct iommu_domain *domain, 1686 unsigned long start_index, unsigned long last_index, 1687 unsigned long *unmapped_end_index, 1688 unsigned long real_last_index) 1689 { 1690 while (start_index <= last_index) { 1691 unsigned long batch_last_index; 1692 1693 if (*unmapped_end_index <= last_index) { 1694 unsigned long start = 1695 max(start_index, *unmapped_end_index); 1696 1697 if (IS_ENABLED(CONFIG_IOMMUFD_TEST) && 1698 batch->total_pfns) 1699 WARN_ON(*unmapped_end_index - 1700 batch->total_pfns != 1701 start_index); 1702 batch_from_domain(batch, domain, area, start, 1703 last_index); 1704 batch_last_index = start_index + batch->total_pfns - 1; 1705 } else { 1706 batch_last_index = last_index; 1707 } 1708 1709 if (IS_ENABLED(CONFIG_IOMMUFD_TEST)) 1710 WARN_ON(batch_last_index > real_last_index); 1711 1712 /* 1713 * unmaps must always 'cut' at a place where the pfns are not 1714 * contiguous to pair with the maps that always install 1715 * contiguous pages. Thus, if we have to stop unpinning in the 1716 * middle of the domains we need to keep reading pfns until we 1717 * find a cut point to do the unmap. The pfns we read are 1718 * carried over and either skipped or integrated into the next 1719 * batch. 1720 */ 1721 if (batch_last_index == last_index && 1722 last_index != real_last_index) 1723 batch_from_domain_continue(batch, domain, area, 1724 last_index + 1, 1725 real_last_index); 1726 1727 if (*unmapped_end_index <= batch_last_index) { 1728 iopt_area_unmap_domain_range( 1729 area, domain, *unmapped_end_index, 1730 start_index + batch->total_pfns - 1); 1731 *unmapped_end_index = start_index + batch->total_pfns; 1732 } 1733 1734 /* unpin must follow unmap */ 1735 batch_unpin(batch, pages, 0, 1736 batch_last_index - start_index + 1); 1737 start_index = batch_last_index + 1; 1738 1739 batch_clear_carry(batch, 1740 *unmapped_end_index - batch_last_index - 1); 1741 } 1742 } 1743 1744 static void __iopt_area_unfill_domain(struct iopt_area *area, 1745 struct iopt_pages *pages, 1746 struct iommu_domain *domain, 1747 unsigned long last_index) 1748 { 1749 struct interval_tree_double_span_iter span; 1750 unsigned long start_index = iopt_area_index(area); 1751 unsigned long unmapped_end_index = start_index; 1752 u64 backup[BATCH_BACKUP_SIZE]; 1753 struct pfn_batch batch; 1754 1755 lockdep_assert_held(&pages->mutex); 1756 1757 if (iopt_is_dmabuf(pages)) { 1758 if (WARN_ON(iopt_dmabuf_revoked(pages))) 1759 return; 1760 iopt_area_unmap_domain_range(area, domain, start_index, 1761 last_index); 1762 return; 1763 } 1764 1765 /* 1766 * For security we must not unpin something that is still DMA mapped, 1767 * so this must unmap any IOVA before we go ahead and unpin the pages. 1768 * This creates a complexity where we need to skip over unpinning pages 1769 * held in the xarray, but continue to unmap from the domain. 1770 * 1771 * The domain unmap cannot stop in the middle of a contiguous range of 1772 * PFNs. To solve this problem the unpinning step will read ahead to the 1773 * end of any contiguous span, unmap that whole span, and then only 1774 * unpin the leading part that does not have any accesses. The residual 1775 * PFNs that were unmapped but not unpinned are called a "carry" in the 1776 * batch as they are moved to the front of the PFN list and continue on 1777 * to the next iteration(s). 1778 */ 1779 batch_init_backup(&batch, last_index + 1, backup, sizeof(backup)); 1780 interval_tree_for_each_double_span(&span, &pages->domains_itree, 1781 &pages->access_itree, start_index, 1782 last_index) { 1783 if (span.is_used) { 1784 batch_skip_carry(&batch, 1785 span.last_used - span.start_used + 1); 1786 continue; 1787 } 1788 iopt_area_unpin_domain(&batch, area, pages, domain, 1789 span.start_hole, span.last_hole, 1790 &unmapped_end_index, last_index); 1791 } 1792 /* 1793 * If the range ends in a access then we do the residual unmap without 1794 * any unpins. 1795 */ 1796 if (unmapped_end_index != last_index + 1) 1797 iopt_area_unmap_domain_range(area, domain, unmapped_end_index, 1798 last_index); 1799 WARN_ON(batch.total_pfns); 1800 batch_destroy(&batch, backup); 1801 update_unpinned(pages); 1802 } 1803 1804 static void iopt_area_unfill_partial_domain(struct iopt_area *area, 1805 struct iopt_pages *pages, 1806 struct iommu_domain *domain, 1807 unsigned long end_index) 1808 { 1809 if (end_index != iopt_area_index(area)) 1810 __iopt_area_unfill_domain(area, pages, domain, end_index - 1); 1811 } 1812 1813 /** 1814 * iopt_area_unmap_domain() - Unmap without unpinning PFNs in a domain 1815 * @area: The IOVA range to unmap 1816 * @domain: The domain to unmap 1817 * 1818 * The caller must know that unpinning is not required, usually because there 1819 * are other domains in the iopt. 1820 */ 1821 void iopt_area_unmap_domain(struct iopt_area *area, struct iommu_domain *domain) 1822 { 1823 iommu_unmap_nofail(domain, iopt_area_iova(area), 1824 iopt_area_length(area)); 1825 } 1826 1827 /** 1828 * iopt_area_unfill_domain() - Unmap and unpin PFNs in a domain 1829 * @area: IOVA area to use 1830 * @pages: page supplier for the area (area->pages is NULL) 1831 * @domain: Domain to unmap from 1832 * 1833 * The domain should be removed from the domains_itree before calling. The 1834 * domain will always be unmapped, but the PFNs may not be unpinned if there are 1835 * still accesses. 1836 */ 1837 void iopt_area_unfill_domain(struct iopt_area *area, struct iopt_pages *pages, 1838 struct iommu_domain *domain) 1839 { 1840 if (iopt_dmabuf_revoked(pages)) 1841 return; 1842 1843 __iopt_area_unfill_domain(area, pages, domain, 1844 iopt_area_last_index(area)); 1845 } 1846 1847 /** 1848 * iopt_area_fill_domain() - Map PFNs from the area into a domain 1849 * @area: IOVA area to use 1850 * @domain: Domain to load PFNs into 1851 * 1852 * Read the pfns from the area's underlying iopt_pages and map them into the 1853 * given domain. Called when attaching a new domain to an io_pagetable. 1854 */ 1855 int iopt_area_fill_domain(struct iopt_area *area, struct iommu_domain *domain) 1856 { 1857 unsigned long done_end_index; 1858 struct pfn_reader pfns; 1859 int rc; 1860 1861 lockdep_assert_held(&area->pages->mutex); 1862 1863 if (iopt_dmabuf_revoked(area->pages)) 1864 return 0; 1865 1866 rc = pfn_reader_first(&pfns, area->pages, iopt_area_index(area), 1867 iopt_area_last_index(area)); 1868 if (rc) 1869 return rc; 1870 1871 while (!pfn_reader_done(&pfns)) { 1872 done_end_index = pfns.batch_start_index; 1873 rc = batch_to_domain(&pfns.batch, domain, area, 1874 pfns.batch_start_index); 1875 if (rc) 1876 goto out_unmap; 1877 done_end_index = pfns.batch_end_index; 1878 1879 rc = pfn_reader_next(&pfns); 1880 if (rc) 1881 goto out_unmap; 1882 } 1883 1884 rc = pfn_reader_update_pinned(&pfns); 1885 if (rc) 1886 goto out_unmap; 1887 goto out_destroy; 1888 1889 out_unmap: 1890 pfn_reader_release_pins(&pfns); 1891 iopt_area_unfill_partial_domain(area, area->pages, domain, 1892 done_end_index); 1893 out_destroy: 1894 pfn_reader_destroy(&pfns); 1895 return rc; 1896 } 1897 1898 /** 1899 * iopt_area_fill_domains() - Install PFNs into the area's domains 1900 * @area: The area to act on 1901 * @pages: The pages associated with the area (area->pages is NULL) 1902 * 1903 * Called during area creation. The area is freshly created and not inserted in 1904 * the domains_itree yet. PFNs are read and loaded into every domain held in the 1905 * area's io_pagetable and the area is installed in the domains_itree. 1906 * 1907 * On failure all domains are left unchanged. 1908 */ 1909 int iopt_area_fill_domains(struct iopt_area *area, struct iopt_pages *pages) 1910 { 1911 unsigned long done_first_end_index; 1912 unsigned long done_all_end_index; 1913 struct iommu_domain *domain; 1914 unsigned long unmap_index; 1915 struct pfn_reader pfns; 1916 unsigned long index; 1917 int rc; 1918 1919 lockdep_assert_held(&area->iopt->domains_rwsem); 1920 1921 if (xa_empty(&area->iopt->domains)) 1922 return 0; 1923 1924 mutex_lock(&pages->mutex); 1925 if (iopt_is_dmabuf(pages)) { 1926 rc = iopt_dmabuf_track_all_domains(area, pages); 1927 if (rc) 1928 goto out_unlock; 1929 } 1930 1931 if (!iopt_dmabuf_revoked(pages)) { 1932 rc = pfn_reader_first(&pfns, pages, iopt_area_index(area), 1933 iopt_area_last_index(area)); 1934 if (rc) 1935 goto out_untrack; 1936 1937 while (!pfn_reader_done(&pfns)) { 1938 done_first_end_index = pfns.batch_end_index; 1939 done_all_end_index = pfns.batch_start_index; 1940 xa_for_each(&area->iopt->domains, index, domain) { 1941 rc = batch_to_domain(&pfns.batch, domain, area, 1942 pfns.batch_start_index); 1943 if (rc) 1944 goto out_unmap; 1945 } 1946 done_all_end_index = done_first_end_index; 1947 1948 rc = pfn_reader_next(&pfns); 1949 if (rc) 1950 goto out_unmap; 1951 } 1952 rc = pfn_reader_update_pinned(&pfns); 1953 if (rc) 1954 goto out_unmap; 1955 1956 pfn_reader_destroy(&pfns); 1957 } 1958 1959 area->storage_domain = xa_load(&area->iopt->domains, 0); 1960 interval_tree_insert(&area->pages_node, &pages->domains_itree); 1961 mutex_unlock(&pages->mutex); 1962 return 0; 1963 1964 out_unmap: 1965 pfn_reader_release_pins(&pfns); 1966 xa_for_each(&area->iopt->domains, unmap_index, domain) { 1967 unsigned long end_index; 1968 1969 if (unmap_index < index) 1970 end_index = done_first_end_index; 1971 else 1972 end_index = done_all_end_index; 1973 1974 /* 1975 * The area is not yet part of the domains_itree so we have to 1976 * manage the unpinning specially. The last domain does the 1977 * unpin, every other domain is just unmapped. 1978 */ 1979 if (unmap_index != area->iopt->next_domain_id - 1) { 1980 if (end_index != iopt_area_index(area)) 1981 iopt_area_unmap_domain_range( 1982 area, domain, iopt_area_index(area), 1983 end_index - 1); 1984 } else { 1985 iopt_area_unfill_partial_domain(area, pages, domain, 1986 end_index); 1987 } 1988 } 1989 pfn_reader_destroy(&pfns); 1990 out_untrack: 1991 if (iopt_is_dmabuf(pages)) 1992 iopt_dmabuf_untrack_all_domains(area, pages); 1993 out_unlock: 1994 mutex_unlock(&pages->mutex); 1995 return rc; 1996 } 1997 1998 /** 1999 * iopt_area_unfill_domains() - unmap PFNs from the area's domains 2000 * @area: The area to act on 2001 * @pages: The pages associated with the area (area->pages is NULL) 2002 * 2003 * Called during area destruction. This unmaps the iova's covered by all the 2004 * area's domains and releases the PFNs. 2005 */ 2006 void iopt_area_unfill_domains(struct iopt_area *area, struct iopt_pages *pages) 2007 { 2008 struct io_pagetable *iopt = area->iopt; 2009 struct iommu_domain *domain; 2010 unsigned long index; 2011 2012 lockdep_assert_held(&iopt->domains_rwsem); 2013 2014 mutex_lock(&pages->mutex); 2015 if (!area->storage_domain) 2016 goto out_unlock; 2017 2018 xa_for_each(&iopt->domains, index, domain) { 2019 if (domain == area->storage_domain) 2020 continue; 2021 2022 if (!iopt_dmabuf_revoked(pages)) 2023 iopt_area_unmap_domain_range( 2024 area, domain, iopt_area_index(area), 2025 iopt_area_last_index(area)); 2026 } 2027 2028 if (IS_ENABLED(CONFIG_IOMMUFD_TEST)) 2029 WARN_ON(RB_EMPTY_NODE(&area->pages_node.rb)); 2030 interval_tree_remove(&area->pages_node, &pages->domains_itree); 2031 iopt_area_unfill_domain(area, pages, area->storage_domain); 2032 if (iopt_is_dmabuf(pages)) 2033 iopt_dmabuf_untrack_all_domains(area, pages); 2034 area->storage_domain = NULL; 2035 out_unlock: 2036 mutex_unlock(&pages->mutex); 2037 } 2038 2039 static void iopt_pages_unpin_xarray(struct pfn_batch *batch, 2040 struct iopt_pages *pages, 2041 unsigned long start_index, 2042 unsigned long end_index) 2043 { 2044 while (start_index <= end_index) { 2045 batch_from_xarray_clear(batch, &pages->pinned_pfns, start_index, 2046 end_index); 2047 batch_unpin(batch, pages, 0, batch->total_pfns); 2048 start_index += batch->total_pfns; 2049 batch_clear(batch); 2050 } 2051 } 2052 2053 /** 2054 * iopt_pages_unfill_xarray() - Update the xarry after removing an access 2055 * @pages: The pages to act on 2056 * @start_index: Starting PFN index 2057 * @last_index: Last PFN index 2058 * 2059 * Called when an iopt_pages_access is removed, removes pages from the itree. 2060 * The access should already be removed from the access_itree. 2061 */ 2062 void iopt_pages_unfill_xarray(struct iopt_pages *pages, 2063 unsigned long start_index, 2064 unsigned long last_index) 2065 { 2066 struct interval_tree_double_span_iter span; 2067 u64 backup[BATCH_BACKUP_SIZE]; 2068 struct pfn_batch batch; 2069 bool batch_inited = false; 2070 2071 lockdep_assert_held(&pages->mutex); 2072 2073 interval_tree_for_each_double_span(&span, &pages->access_itree, 2074 &pages->domains_itree, start_index, 2075 last_index) { 2076 if (!span.is_used) { 2077 if (!batch_inited) { 2078 batch_init_backup(&batch, 2079 last_index - start_index + 1, 2080 backup, sizeof(backup)); 2081 batch_inited = true; 2082 } 2083 iopt_pages_unpin_xarray(&batch, pages, span.start_hole, 2084 span.last_hole); 2085 } else if (span.is_used == 2) { 2086 /* Covered by a domain */ 2087 clear_xarray(&pages->pinned_pfns, span.start_used, 2088 span.last_used); 2089 } 2090 /* Otherwise covered by an existing access */ 2091 } 2092 if (batch_inited) 2093 batch_destroy(&batch, backup); 2094 update_unpinned(pages); 2095 } 2096 2097 /** 2098 * iopt_pages_fill_from_xarray() - Fast path for reading PFNs 2099 * @pages: The pages to act on 2100 * @start_index: The first page index in the range 2101 * @last_index: The last page index in the range 2102 * @out_pages: The output array to return the pages 2103 * 2104 * This can be called if the caller is holding a refcount on an 2105 * iopt_pages_access that is known to have already been filled. It quickly reads 2106 * the pages directly from the xarray. 2107 * 2108 * This is part of the SW iommu interface to read pages for in-kernel use. 2109 */ 2110 void iopt_pages_fill_from_xarray(struct iopt_pages *pages, 2111 unsigned long start_index, 2112 unsigned long last_index, 2113 struct page **out_pages) 2114 { 2115 XA_STATE(xas, &pages->pinned_pfns, start_index); 2116 void *entry; 2117 2118 rcu_read_lock(); 2119 while (start_index <= last_index) { 2120 entry = xas_next(&xas); 2121 if (xas_retry(&xas, entry)) 2122 continue; 2123 WARN_ON(!xa_is_value(entry)); 2124 *(out_pages++) = pfn_to_page(xa_to_value(entry)); 2125 start_index++; 2126 } 2127 rcu_read_unlock(); 2128 } 2129 2130 static int iopt_pages_fill_from_domain(struct iopt_pages *pages, 2131 unsigned long start_index, 2132 unsigned long last_index, 2133 struct page **out_pages) 2134 { 2135 while (start_index != last_index + 1) { 2136 unsigned long domain_last; 2137 struct iopt_area *area; 2138 2139 area = iopt_pages_find_domain_area(pages, start_index); 2140 if (WARN_ON(!area)) 2141 return -EINVAL; 2142 2143 domain_last = min(iopt_area_last_index(area), last_index); 2144 out_pages = raw_pages_from_domain(area->storage_domain, area, 2145 start_index, domain_last, 2146 out_pages); 2147 start_index = domain_last + 1; 2148 } 2149 return 0; 2150 } 2151 2152 static int iopt_pages_fill(struct iopt_pages *pages, 2153 struct pfn_reader_user *user, 2154 unsigned long start_index, 2155 unsigned long last_index, 2156 struct page **out_pages) 2157 { 2158 unsigned long cur_index = start_index; 2159 int rc; 2160 2161 while (cur_index != last_index + 1) { 2162 user->upages = out_pages + (cur_index - start_index); 2163 rc = pfn_reader_user_pin(user, pages, cur_index, last_index); 2164 if (rc) 2165 goto out_unpin; 2166 cur_index = user->upages_end; 2167 } 2168 return 0; 2169 2170 out_unpin: 2171 if (start_index != cur_index) 2172 iopt_pages_err_unpin(pages, start_index, cur_index - 1, 2173 out_pages); 2174 return rc; 2175 } 2176 2177 /** 2178 * iopt_pages_fill_xarray() - Read PFNs 2179 * @pages: The pages to act on 2180 * @start_index: The first page index in the range 2181 * @last_index: The last page index in the range 2182 * @out_pages: The output array to return the pages, may be NULL 2183 * 2184 * This populates the xarray and returns the pages in out_pages. As the slow 2185 * path this is able to copy pages from other storage tiers into the xarray. 2186 * 2187 * On failure the xarray is left unchanged. 2188 * 2189 * This is part of the SW iommu interface to read pages for in-kernel use. 2190 */ 2191 int iopt_pages_fill_xarray(struct iopt_pages *pages, unsigned long start_index, 2192 unsigned long last_index, struct page **out_pages) 2193 { 2194 struct interval_tree_double_span_iter span; 2195 unsigned long xa_end = start_index; 2196 struct pfn_reader_user user; 2197 int rc; 2198 2199 lockdep_assert_held(&pages->mutex); 2200 2201 pfn_reader_user_init(&user, pages); 2202 user.upages_len = (last_index - start_index + 1) * sizeof(*out_pages); 2203 interval_tree_for_each_double_span(&span, &pages->access_itree, 2204 &pages->domains_itree, start_index, 2205 last_index) { 2206 struct page **cur_pages; 2207 2208 if (span.is_used == 1) { 2209 cur_pages = out_pages + (span.start_used - start_index); 2210 iopt_pages_fill_from_xarray(pages, span.start_used, 2211 span.last_used, cur_pages); 2212 continue; 2213 } 2214 2215 if (span.is_used == 2) { 2216 cur_pages = out_pages + (span.start_used - start_index); 2217 iopt_pages_fill_from_domain(pages, span.start_used, 2218 span.last_used, cur_pages); 2219 rc = pages_to_xarray(&pages->pinned_pfns, 2220 span.start_used, span.last_used, 2221 cur_pages); 2222 if (rc) 2223 goto out_clean_xa; 2224 xa_end = span.last_used + 1; 2225 continue; 2226 } 2227 2228 /* hole */ 2229 cur_pages = out_pages + (span.start_hole - start_index); 2230 rc = iopt_pages_fill(pages, &user, span.start_hole, 2231 span.last_hole, cur_pages); 2232 if (rc) 2233 goto out_clean_xa; 2234 rc = pages_to_xarray(&pages->pinned_pfns, span.start_hole, 2235 span.last_hole, cur_pages); 2236 if (rc) { 2237 iopt_pages_err_unpin(pages, span.start_hole, 2238 span.last_hole, cur_pages); 2239 goto out_clean_xa; 2240 } 2241 xa_end = span.last_hole + 1; 2242 } 2243 rc = pfn_reader_user_update_pinned(&user, pages); 2244 if (rc) 2245 goto out_clean_xa; 2246 user.upages = NULL; 2247 pfn_reader_user_destroy(&user, pages); 2248 return 0; 2249 2250 out_clean_xa: 2251 if (start_index != xa_end) 2252 iopt_pages_unfill_xarray(pages, start_index, xa_end - 1); 2253 user.upages = NULL; 2254 pfn_reader_user_destroy(&user, pages); 2255 return rc; 2256 } 2257 2258 /* 2259 * This uses the pfn_reader instead of taking a shortcut by using the mm. It can 2260 * do every scenario and is fully consistent with what an iommu_domain would 2261 * see. 2262 */ 2263 static int iopt_pages_rw_slow(struct iopt_pages *pages, 2264 unsigned long start_index, 2265 unsigned long last_index, unsigned long offset, 2266 void *data, unsigned long length, 2267 unsigned int flags) 2268 { 2269 struct pfn_reader pfns; 2270 int rc; 2271 2272 mutex_lock(&pages->mutex); 2273 2274 rc = pfn_reader_first(&pfns, pages, start_index, last_index); 2275 if (rc) 2276 goto out_unlock; 2277 2278 while (!pfn_reader_done(&pfns)) { 2279 unsigned long done; 2280 2281 done = batch_rw(&pfns.batch, data, offset, length, flags); 2282 data += done; 2283 length -= done; 2284 offset = 0; 2285 pfn_reader_unpin(&pfns); 2286 2287 rc = pfn_reader_next(&pfns); 2288 if (rc) 2289 goto out_destroy; 2290 } 2291 if (WARN_ON(length != 0)) 2292 rc = -EINVAL; 2293 out_destroy: 2294 pfn_reader_destroy(&pfns); 2295 out_unlock: 2296 mutex_unlock(&pages->mutex); 2297 return rc; 2298 } 2299 2300 /* 2301 * A medium speed path that still allows DMA inconsistencies, but doesn't do any 2302 * memory allocations or interval tree searches. 2303 */ 2304 static int iopt_pages_rw_page(struct iopt_pages *pages, unsigned long index, 2305 unsigned long offset, void *data, 2306 unsigned long length, unsigned int flags) 2307 { 2308 struct page *page = NULL; 2309 int rc; 2310 2311 if (IS_ENABLED(CONFIG_IOMMUFD_TEST) && 2312 WARN_ON(pages->type != IOPT_ADDRESS_USER)) 2313 return -EINVAL; 2314 2315 if (!mmget_not_zero(pages->source_mm)) 2316 return iopt_pages_rw_slow(pages, index, index, offset, data, 2317 length, flags); 2318 2319 if (iommufd_should_fail()) { 2320 rc = -EINVAL; 2321 goto out_mmput; 2322 } 2323 2324 mmap_read_lock(pages->source_mm); 2325 rc = pin_user_pages_remote( 2326 pages->source_mm, (uintptr_t)(pages->uptr + index * PAGE_SIZE), 2327 1, (flags & IOMMUFD_ACCESS_RW_WRITE) ? FOLL_WRITE : 0, &page, 2328 NULL); 2329 mmap_read_unlock(pages->source_mm); 2330 if (rc != 1) { 2331 if (WARN_ON(rc >= 0)) 2332 rc = -EINVAL; 2333 goto out_mmput; 2334 } 2335 copy_data_page(page, data, offset, length, flags); 2336 unpin_user_page(page); 2337 rc = 0; 2338 2339 out_mmput: 2340 mmput(pages->source_mm); 2341 return rc; 2342 } 2343 2344 /** 2345 * iopt_pages_rw_access - Copy to/from a linear slice of the pages 2346 * @pages: pages to act on 2347 * @start_byte: First byte of pages to copy to/from 2348 * @data: Kernel buffer to get/put the data 2349 * @length: Number of bytes to copy 2350 * @flags: IOMMUFD_ACCESS_RW_* flags 2351 * 2352 * This will find each page in the range, kmap it and then memcpy to/from 2353 * the given kernel buffer. 2354 */ 2355 int iopt_pages_rw_access(struct iopt_pages *pages, unsigned long start_byte, 2356 void *data, unsigned long length, unsigned int flags) 2357 { 2358 unsigned long start_index = start_byte / PAGE_SIZE; 2359 unsigned long last_index = (start_byte + length - 1) / PAGE_SIZE; 2360 bool change_mm = current->mm != pages->source_mm; 2361 int rc = 0; 2362 2363 if (IS_ENABLED(CONFIG_IOMMUFD_TEST) && 2364 (flags & __IOMMUFD_ACCESS_RW_SLOW_PATH)) 2365 change_mm = true; 2366 2367 if ((flags & IOMMUFD_ACCESS_RW_WRITE) && !pages->writable) 2368 return -EPERM; 2369 2370 if (iopt_is_dmabuf(pages)) 2371 return -EINVAL; 2372 2373 if (pages->type != IOPT_ADDRESS_USER) 2374 return iopt_pages_rw_slow(pages, start_index, last_index, 2375 start_byte % PAGE_SIZE, data, length, 2376 flags); 2377 2378 if (!(flags & IOMMUFD_ACCESS_RW_KTHREAD) && change_mm) { 2379 if (start_index == last_index) 2380 return iopt_pages_rw_page(pages, start_index, 2381 start_byte % PAGE_SIZE, data, 2382 length, flags); 2383 return iopt_pages_rw_slow(pages, start_index, last_index, 2384 start_byte % PAGE_SIZE, data, length, 2385 flags); 2386 } 2387 2388 /* 2389 * Try to copy using copy_to_user(). We do this as a fast path and 2390 * ignore any pinning inconsistencies, unlike a real DMA path. 2391 */ 2392 if (change_mm) { 2393 if (!mmget_not_zero(pages->source_mm)) 2394 return iopt_pages_rw_slow(pages, start_index, 2395 last_index, 2396 start_byte % PAGE_SIZE, data, 2397 length, flags); 2398 kthread_use_mm(pages->source_mm); 2399 } 2400 2401 if (flags & IOMMUFD_ACCESS_RW_WRITE) { 2402 if (copy_to_user(pages->uptr + start_byte, data, length)) 2403 rc = -EFAULT; 2404 } else { 2405 if (copy_from_user(data, pages->uptr + start_byte, length)) 2406 rc = -EFAULT; 2407 } 2408 2409 if (change_mm) { 2410 kthread_unuse_mm(pages->source_mm); 2411 mmput(pages->source_mm); 2412 } 2413 2414 return rc; 2415 } 2416 2417 static struct iopt_pages_access * 2418 iopt_pages_get_exact_access(struct iopt_pages *pages, unsigned long index, 2419 unsigned long last) 2420 { 2421 struct interval_tree_node *node; 2422 2423 lockdep_assert_held(&pages->mutex); 2424 2425 /* There can be overlapping ranges in this interval tree */ 2426 for (node = interval_tree_iter_first(&pages->access_itree, index, last); 2427 node; node = interval_tree_iter_next(node, index, last)) 2428 if (node->start == index && node->last == last) 2429 return container_of(node, struct iopt_pages_access, 2430 node); 2431 return NULL; 2432 } 2433 2434 /** 2435 * iopt_area_add_access() - Record an in-knerel access for PFNs 2436 * @area: The source of PFNs 2437 * @start_index: First page index 2438 * @last_index: Inclusive last page index 2439 * @out_pages: Output list of struct page's representing the PFNs 2440 * @flags: IOMMUFD_ACCESS_RW_* flags 2441 * @lock_area: Fail userspace munmap on this area 2442 * 2443 * Record that an in-kernel access will be accessing the pages, ensure they are 2444 * pinned, and return the PFNs as a simple list of 'struct page *'. 2445 * 2446 * This should be undone through a matching call to iopt_area_remove_access() 2447 */ 2448 int iopt_area_add_access(struct iopt_area *area, unsigned long start_index, 2449 unsigned long last_index, struct page **out_pages, 2450 unsigned int flags, bool lock_area) 2451 { 2452 struct iopt_pages *pages = area->pages; 2453 struct iopt_pages_access *access; 2454 int rc; 2455 2456 if ((flags & IOMMUFD_ACCESS_RW_WRITE) && !pages->writable) 2457 return -EPERM; 2458 2459 if (iopt_is_dmabuf(pages)) 2460 return -EINVAL; 2461 2462 mutex_lock(&pages->mutex); 2463 access = iopt_pages_get_exact_access(pages, start_index, last_index); 2464 if (access) { 2465 area->num_accesses++; 2466 if (lock_area) 2467 area->num_locks++; 2468 access->users++; 2469 iopt_pages_fill_from_xarray(pages, start_index, last_index, 2470 out_pages); 2471 mutex_unlock(&pages->mutex); 2472 return 0; 2473 } 2474 2475 access = kzalloc_obj(*access, GFP_KERNEL_ACCOUNT); 2476 if (!access) { 2477 rc = -ENOMEM; 2478 goto err_unlock; 2479 } 2480 2481 rc = iopt_pages_fill_xarray(pages, start_index, last_index, out_pages); 2482 if (rc) 2483 goto err_free; 2484 2485 access->node.start = start_index; 2486 access->node.last = last_index; 2487 access->users = 1; 2488 area->num_accesses++; 2489 if (lock_area) 2490 area->num_locks++; 2491 interval_tree_insert(&access->node, &pages->access_itree); 2492 mutex_unlock(&pages->mutex); 2493 return 0; 2494 2495 err_free: 2496 kfree(access); 2497 err_unlock: 2498 mutex_unlock(&pages->mutex); 2499 return rc; 2500 } 2501 2502 /** 2503 * iopt_area_remove_access() - Release an in-kernel access for PFNs 2504 * @area: The source of PFNs 2505 * @start_index: First page index 2506 * @last_index: Inclusive last page index 2507 * @unlock_area: Must match the matching iopt_area_add_access()'s lock_area 2508 * 2509 * Undo iopt_area_add_access() and unpin the pages if necessary. The caller 2510 * must stop using the PFNs before calling this. 2511 */ 2512 void iopt_area_remove_access(struct iopt_area *area, unsigned long start_index, 2513 unsigned long last_index, bool unlock_area) 2514 { 2515 struct iopt_pages *pages = area->pages; 2516 struct iopt_pages_access *access; 2517 2518 mutex_lock(&pages->mutex); 2519 access = iopt_pages_get_exact_access(pages, start_index, last_index); 2520 if (WARN_ON(!access)) 2521 goto out_unlock; 2522 2523 WARN_ON(area->num_accesses == 0 || access->users == 0); 2524 if (unlock_area) { 2525 WARN_ON(area->num_locks == 0); 2526 area->num_locks--; 2527 } 2528 area->num_accesses--; 2529 access->users--; 2530 if (access->users) 2531 goto out_unlock; 2532 2533 interval_tree_remove(&access->node, &pages->access_itree); 2534 iopt_pages_unfill_xarray(pages, start_index, last_index); 2535 kfree(access); 2536 out_unlock: 2537 mutex_unlock(&pages->mutex); 2538 } 2539