File Index
Files and directories
Sign in
FILE

dma-iommu.c

File preview with syntax highlighting.

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