xref: /linux/drivers/iommu/intel/iommu.c (revision 9cebfe6504488198b012e746bc6b313f88b95439)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright © 2006-2014 Intel Corporation.
4  *
5  * Authors: David Woodhouse <dwmw2@infradead.org>,
6  *          Ashok Raj <ashok.raj@intel.com>,
7  *          Shaohua Li <shaohua.li@intel.com>,
8  *          Anil S Keshavamurthy <anil.s.keshavamurthy@intel.com>,
9  *          Fenghua Yu <fenghua.yu@intel.com>
10  *          Joerg Roedel <jroedel@suse.de>
11  */
12 
13 #define pr_fmt(fmt)     "DMAR: " fmt
14 #define dev_fmt(fmt)    pr_fmt(fmt)
15 
16 #include <linux/crash_dump.h>
17 #include <linux/dma-direct.h>
18 #include <linux/dmi.h>
19 #include <linux/memory.h>
20 #include <linux/pci.h>
21 #include <linux/pci-ats.h>
22 #include <linux/spinlock.h>
23 #include <linux/syscore_ops.h>
24 #include <linux/tboot.h>
25 #include <uapi/linux/iommufd.h>
26 
27 #include "iommu.h"
28 #include "../dma-iommu.h"
29 #include "../irq_remapping.h"
30 #include "../iommu-pages.h"
31 #include "pasid.h"
32 #include "perfmon.h"
33 
34 #define ROOT_SIZE		VTD_PAGE_SIZE
35 #define CONTEXT_SIZE		VTD_PAGE_SIZE
36 
37 #define IS_GFX_DEVICE(pdev) pci_is_display(pdev)
38 #define IS_USB_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_SERIAL_USB)
39 #define IS_ISA_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_BRIDGE_ISA)
40 #define IS_AZALIA(pdev) ((pdev)->vendor == 0x8086 && (pdev)->device == 0x3a3e)
41 
42 #define IOAPIC_RANGE_START	(0xfee00000)
43 #define IOAPIC_RANGE_END	(0xfeefffff)
44 #define IOVA_START_ADDR		(0x1000)
45 
46 #define DEFAULT_DOMAIN_ADDRESS_WIDTH 57
47 
48 static void __init check_tylersburg_isoch(void);
49 static int intel_iommu_set_dirty_tracking(struct iommu_domain *domain,
50 					  bool enable);
51 static int rwbf_quirk;
52 
53 #define rwbf_required(iommu)	(rwbf_quirk || cap_rwbf((iommu)->cap))
54 
55 /*
56  * Skip forcing iommu on and avoid tboot-related kernel panics during
57  * initialization when set to 1 (via intel_iommu=tboot_noforce).
58  */
59 int intel_iommu_tboot_noforce;
60 
61 #define ROOT_ENTRY_NR (VTD_PAGE_SIZE/sizeof(struct root_entry))
62 
63 /*
64  * Take a root_entry and return the Lower Context Table Pointer (LCTP)
65  * if marked present.
66  */
67 static phys_addr_t root_entry_lctp(struct root_entry *re)
68 {
69 	if (!(re->lo & 1))
70 		return 0;
71 
72 	return re->lo & VTD_PAGE_MASK;
73 }
74 
75 /*
76  * Take a root_entry and return the Upper Context Table Pointer (UCTP)
77  * if marked present.
78  */
79 static phys_addr_t root_entry_uctp(struct root_entry *re)
80 {
81 	if (!(re->hi & 1))
82 		return 0;
83 
84 	return re->hi & VTD_PAGE_MASK;
85 }
86 
87 static int device_rid_cmp_key(const void *key, const struct rb_node *node)
88 {
89 	struct device_domain_info *info =
90 		rb_entry(node, struct device_domain_info, node);
91 	const u16 *rid_lhs = key;
92 
93 	if (*rid_lhs < PCI_DEVID(info->bus, info->devfn))
94 		return -1;
95 
96 	if (*rid_lhs > PCI_DEVID(info->bus, info->devfn))
97 		return 1;
98 
99 	return 0;
100 }
101 
102 static int device_rid_cmp(struct rb_node *lhs, const struct rb_node *rhs)
103 {
104 	struct device_domain_info *info =
105 		rb_entry(lhs, struct device_domain_info, node);
106 	u16 key = PCI_DEVID(info->bus, info->devfn);
107 
108 	return device_rid_cmp_key(&key, rhs);
109 }
110 
111 /*
112  * Looks up an IOMMU-probed device using its source ID.
113  *
114  * Returns the pointer to the device if there is a match. Otherwise,
115  * returns NULL.
116  *
117  * Note that this helper doesn't guarantee that the device won't be
118  * released by the iommu subsystem after being returned. The caller
119  * should use its own synchronization mechanism to avoid the device
120  * being released during its use if its possibly the case.
121  */
122 struct device *device_rbtree_find(struct intel_iommu *iommu, u16 rid)
123 {
124 	struct device_domain_info *info = NULL;
125 	struct rb_node *node;
126 	unsigned long flags;
127 
128 	spin_lock_irqsave(&iommu->device_rbtree_lock, flags);
129 	node = rb_find(&rid, &iommu->device_rbtree, device_rid_cmp_key);
130 	if (node)
131 		info = rb_entry(node, struct device_domain_info, node);
132 	spin_unlock_irqrestore(&iommu->device_rbtree_lock, flags);
133 
134 	return info ? info->dev : NULL;
135 }
136 
137 static int device_rbtree_insert(struct intel_iommu *iommu,
138 				struct device_domain_info *info)
139 {
140 	struct rb_node *curr;
141 	unsigned long flags;
142 
143 	spin_lock_irqsave(&iommu->device_rbtree_lock, flags);
144 	curr = rb_find_add(&info->node, &iommu->device_rbtree, device_rid_cmp);
145 	spin_unlock_irqrestore(&iommu->device_rbtree_lock, flags);
146 	if (WARN_ON(curr))
147 		return -EEXIST;
148 
149 	return 0;
150 }
151 
152 static void device_rbtree_remove(struct device_domain_info *info)
153 {
154 	struct intel_iommu *iommu = info->iommu;
155 	unsigned long flags;
156 
157 	spin_lock_irqsave(&iommu->device_rbtree_lock, flags);
158 	if (!RB_EMPTY_NODE(&info->node)) {
159 		rb_erase(&info->node, &iommu->device_rbtree);
160 		RB_CLEAR_NODE(&info->node);
161 	}
162 	spin_unlock_irqrestore(&iommu->device_rbtree_lock, flags);
163 }
164 
165 struct dmar_rmrr_unit {
166 	struct list_head list;		/* list of rmrr units	*/
167 	struct acpi_dmar_header *hdr;	/* ACPI header		*/
168 	u64	base_address;		/* reserved base address*/
169 	u64	end_address;		/* reserved end address */
170 	struct dmar_dev_scope *devices;	/* target devices */
171 	int	devices_cnt;		/* target device count */
172 };
173 
174 struct dmar_atsr_unit {
175 	struct list_head list;		/* list of ATSR units */
176 	struct acpi_dmar_header *hdr;	/* ACPI header */
177 	struct dmar_dev_scope *devices;	/* target devices */
178 	int devices_cnt;		/* target device count */
179 	u8 include_all:1;		/* include all ports */
180 };
181 
182 struct dmar_satc_unit {
183 	struct list_head list;		/* list of SATC units */
184 	struct acpi_dmar_header *hdr;	/* ACPI header */
185 	struct dmar_dev_scope *devices;	/* target devices */
186 	struct intel_iommu *iommu;	/* the corresponding iommu */
187 	int devices_cnt;		/* target device count */
188 	u8 atc_required:1;		/* ATS is required */
189 };
190 
191 static LIST_HEAD(dmar_atsr_units);
192 static LIST_HEAD(dmar_rmrr_units);
193 static LIST_HEAD(dmar_satc_units);
194 
195 #define for_each_rmrr_units(rmrr) \
196 	list_for_each_entry(rmrr, &dmar_rmrr_units, list)
197 
198 static void intel_iommu_domain_free(struct iommu_domain *domain);
199 
200 #ifdef CONFIG_INTEL_IOMMU_DEFAULT_ON
201 int dmar_policy = DMAR_ON;
202 #else
203 int dmar_policy = DMAR_DEFAULT_OFF;
204 #endif
205 int intel_iommu_sm = IS_ENABLED(CONFIG_INTEL_IOMMU_SCALABLE_MODE_DEFAULT_ON);
206 
207 int intel_iommu_enabled = 0;
208 EXPORT_SYMBOL_GPL(intel_iommu_enabled);
209 
210 static int intel_iommu_superpage = 1;
211 static int iommu_identity_mapping;
212 static int iommu_skip_te_disable;
213 static int disable_igfx_iommu;
214 
215 #define IDENTMAP_AZALIA		4
216 
217 const struct iommu_ops intel_iommu_ops;
218 
219 static bool translation_pre_enabled(struct intel_iommu *iommu)
220 {
221 	return (iommu->flags & VTD_FLAG_TRANS_PRE_ENABLED);
222 }
223 
224 static void clear_translation_pre_enabled(struct intel_iommu *iommu)
225 {
226 	iommu->flags &= ~VTD_FLAG_TRANS_PRE_ENABLED;
227 }
228 
229 static void init_translation_status(struct intel_iommu *iommu)
230 {
231 	u32 gsts;
232 
233 	gsts = readl(iommu->reg + DMAR_GSTS_REG);
234 	if (gsts & DMA_GSTS_TES)
235 		iommu->flags |= VTD_FLAG_TRANS_PRE_ENABLED;
236 }
237 
238 static int __init intel_iommu_setup(char *str)
239 {
240 	if (!str)
241 		return -EINVAL;
242 
243 	while (*str) {
244 		if (!strncmp(str, "on", 2)) {
245 			dmar_policy = DMAR_ON;
246 			pr_info("IOMMU enabled\n");
247 		} else if (!strncmp(str, "off", 3)) {
248 			dmar_policy = DMAR_USER_OFF;
249 			pr_info("IOMMU disabled\n");
250 		} else if (!strncmp(str, "igfx_off", 8)) {
251 			disable_igfx_iommu = 1;
252 			pr_info("Disable GFX device mapping\n");
253 		} else if (!strncmp(str, "forcedac", 8)) {
254 			pr_warn("intel_iommu=forcedac deprecated; use iommu.forcedac instead\n");
255 			iommu_dma_forcedac = true;
256 		} else if (!strncmp(str, "strict", 6)) {
257 			pr_warn("intel_iommu=strict deprecated; use iommu.strict=1 instead\n");
258 			iommu_set_dma_strict();
259 		} else if (!strncmp(str, "sp_off", 6)) {
260 			pr_info("Disable supported super page\n");
261 			intel_iommu_superpage = 0;
262 		} else if (!strncmp(str, "sm_on", 5)) {
263 			pr_info("Enable scalable mode if hardware supports\n");
264 			intel_iommu_sm = 1;
265 		} else if (!strncmp(str, "sm_off", 6)) {
266 			pr_info("Scalable mode is disallowed\n");
267 			intel_iommu_sm = 0;
268 		} else if (!strncmp(str, "tboot_noforce", 13)) {
269 			pr_info("Intel-IOMMU: not forcing on after tboot. This could expose security risk for tboot\n");
270 			intel_iommu_tboot_noforce = 1;
271 		} else {
272 			pr_notice("Unknown option - '%s'\n", str);
273 		}
274 
275 		str += strcspn(str, ",");
276 		while (*str == ',')
277 			str++;
278 	}
279 
280 	return 1;
281 }
282 __setup("intel_iommu=", intel_iommu_setup);
283 
284 /*
285  * Calculate the Supported Adjusted Guest Address Widths of an IOMMU.
286  * Refer to 11.4.2 of the VT-d spec for the encoding of each bit of
287  * the returned SAGAW.
288  */
289 static unsigned long __iommu_calculate_sagaw(struct intel_iommu *iommu)
290 {
291 	unsigned long fl_sagaw, sl_sagaw;
292 
293 	fl_sagaw = BIT(2) | (cap_fl5lp_support(iommu->cap) ? BIT(3) : 0);
294 	sl_sagaw = cap_sagaw(iommu->cap);
295 
296 	/* Second level only. */
297 	if (!sm_supported(iommu) || !ecap_flts(iommu->ecap))
298 		return sl_sagaw;
299 
300 	/* First level only. */
301 	if (!ecap_slts(iommu->ecap))
302 		return fl_sagaw;
303 
304 	return fl_sagaw & sl_sagaw;
305 }
306 
307 static int __iommu_calculate_agaw(struct intel_iommu *iommu, int max_gaw)
308 {
309 	unsigned long sagaw;
310 	int agaw;
311 
312 	sagaw = __iommu_calculate_sagaw(iommu);
313 	for (agaw = width_to_agaw(max_gaw); agaw >= 0; agaw--) {
314 		if (test_bit(agaw, &sagaw))
315 			break;
316 	}
317 
318 	return agaw;
319 }
320 
321 /*
322  * Calculate max SAGAW for each iommu.
323  */
324 int iommu_calculate_max_sagaw(struct intel_iommu *iommu)
325 {
326 	return __iommu_calculate_agaw(iommu, MAX_AGAW_WIDTH);
327 }
328 
329 /*
330  * calculate agaw for each iommu.
331  * "SAGAW" may be different across iommus, use a default agaw, and
332  * get a supported less agaw for iommus that don't support the default agaw.
333  */
334 int iommu_calculate_agaw(struct intel_iommu *iommu)
335 {
336 	return __iommu_calculate_agaw(iommu, DEFAULT_DOMAIN_ADDRESS_WIDTH);
337 }
338 
339 static bool iommu_paging_structure_coherency(struct intel_iommu *iommu)
340 {
341 	return sm_supported(iommu) ?
342 			ecap_smpwc(iommu->ecap) : ecap_coherent(iommu->ecap);
343 }
344 
345 struct context_entry *iommu_context_addr(struct intel_iommu *iommu, u8 bus,
346 					 u8 devfn, int alloc)
347 {
348 	struct root_entry *root = &iommu->root_entry[bus];
349 	struct context_entry *context;
350 	u64 *entry;
351 
352 	/*
353 	 * Except that the caller requested to allocate a new entry,
354 	 * returning a copied context entry makes no sense.
355 	 */
356 	if (!alloc && context_copied(iommu, bus, devfn))
357 		return NULL;
358 
359 	entry = &root->lo;
360 	if (sm_supported(iommu)) {
361 		if (devfn >= 0x80) {
362 			devfn -= 0x80;
363 			entry = &root->hi;
364 		}
365 		devfn *= 2;
366 	}
367 	if (*entry & 1)
368 		context = phys_to_virt(*entry & VTD_PAGE_MASK);
369 	else {
370 		unsigned long phy_addr;
371 		if (!alloc)
372 			return NULL;
373 
374 		context = iommu_alloc_pages_node_sz(iommu->node, GFP_ATOMIC,
375 						    SZ_4K);
376 		if (!context)
377 			return NULL;
378 
379 		__iommu_flush_cache(iommu, (void *)context, CONTEXT_SIZE);
380 		phy_addr = virt_to_phys((void *)context);
381 		*entry = phy_addr | 1;
382 		__iommu_flush_cache(iommu, entry, sizeof(*entry));
383 	}
384 	return &context[devfn];
385 }
386 
387 /**
388  * is_downstream_to_pci_bridge - test if a device belongs to the PCI
389  *				 sub-hierarchy of a candidate PCI-PCI bridge
390  * @dev: candidate PCI device belonging to @bridge PCI sub-hierarchy
391  * @bridge: the candidate PCI-PCI bridge
392  *
393  * Return: true if @dev belongs to @bridge PCI sub-hierarchy, else false.
394  */
395 static bool
396 is_downstream_to_pci_bridge(struct device *dev, struct device *bridge)
397 {
398 	struct pci_dev *pdev, *pbridge;
399 
400 	if (!dev_is_pci(dev) || !dev_is_pci(bridge))
401 		return false;
402 
403 	pdev = to_pci_dev(dev);
404 	pbridge = to_pci_dev(bridge);
405 
406 	if (pbridge->subordinate &&
407 	    pbridge->subordinate->number <= pdev->bus->number &&
408 	    pbridge->subordinate->busn_res.end >= pdev->bus->number)
409 		return true;
410 
411 	return false;
412 }
413 
414 static bool quirk_ioat_snb_local_iommu(struct pci_dev *pdev)
415 {
416 	struct dmar_drhd_unit *drhd;
417 	u32 vtbar;
418 	int rc;
419 
420 	/* We know that this device on this chipset has its own IOMMU.
421 	 * If we find it under a different IOMMU, then the BIOS is lying
422 	 * to us. Hope that the IOMMU for this device is actually
423 	 * disabled, and it needs no translation...
424 	 */
425 	rc = pci_bus_read_config_dword(pdev->bus, PCI_DEVFN(0, 0), 0xb0, &vtbar);
426 	if (rc) {
427 		/* "can't" happen */
428 		dev_info(&pdev->dev, "failed to run vt-d quirk\n");
429 		return false;
430 	}
431 	vtbar &= 0xffff0000;
432 
433 	/* we know that the this iommu should be at offset 0xa000 from vtbar */
434 	drhd = dmar_find_matched_drhd_unit(pdev);
435 	if (!drhd || drhd->reg_base_addr - vtbar != 0xa000) {
436 		pr_warn_once(FW_BUG "BIOS assigned incorrect VT-d unit for Intel(R) QuickData Technology device\n");
437 		add_taint(TAINT_FIRMWARE_WORKAROUND, LOCKDEP_STILL_OK);
438 		return true;
439 	}
440 
441 	return false;
442 }
443 
444 static bool iommu_is_dummy(struct intel_iommu *iommu, struct device *dev)
445 {
446 	if (!iommu || iommu->drhd->ignored)
447 		return true;
448 
449 	if (dev_is_pci(dev)) {
450 		struct pci_dev *pdev = to_pci_dev(dev);
451 
452 		if (pdev->vendor == PCI_VENDOR_ID_INTEL &&
453 		    pdev->device == PCI_DEVICE_ID_INTEL_IOAT_SNB &&
454 		    quirk_ioat_snb_local_iommu(pdev))
455 			return true;
456 	}
457 
458 	return false;
459 }
460 
461 static struct intel_iommu *device_lookup_iommu(struct device *dev, u8 *bus, u8 *devfn)
462 {
463 	struct dmar_drhd_unit *drhd = NULL;
464 	struct pci_dev *pdev = NULL;
465 	struct intel_iommu *iommu;
466 	struct device *tmp;
467 	u16 segment = 0;
468 	int i;
469 
470 	if (!dev)
471 		return NULL;
472 
473 	if (dev_is_pci(dev)) {
474 		struct pci_dev *pf_pdev;
475 
476 		pdev = pci_real_dma_dev(to_pci_dev(dev));
477 
478 		/* VFs aren't listed in scope tables; we need to look up
479 		 * the PF instead to find the IOMMU. */
480 		pf_pdev = pci_physfn(pdev);
481 		dev = &pf_pdev->dev;
482 		segment = pci_domain_nr(pdev->bus);
483 	} else if (has_acpi_companion(dev))
484 		dev = &ACPI_COMPANION(dev)->dev;
485 
486 	rcu_read_lock();
487 	for_each_iommu(iommu, drhd) {
488 		if (pdev && segment != drhd->segment)
489 			continue;
490 
491 		for_each_active_dev_scope(drhd->devices,
492 					  drhd->devices_cnt, i, tmp) {
493 			if (tmp == dev) {
494 				/* For a VF use its original BDF# not that of the PF
495 				 * which we used for the IOMMU lookup. Strictly speaking
496 				 * we could do this for all PCI devices; we only need to
497 				 * get the BDF# from the scope table for ACPI matches. */
498 				if (pdev && pdev->is_virtfn)
499 					goto got_pdev;
500 
501 				if (bus && devfn) {
502 					*bus = drhd->devices[i].bus;
503 					*devfn = drhd->devices[i].devfn;
504 				}
505 				goto out;
506 			}
507 
508 			if (is_downstream_to_pci_bridge(dev, tmp))
509 				goto got_pdev;
510 		}
511 
512 		if (pdev && drhd->include_all) {
513 got_pdev:
514 			if (bus && devfn) {
515 				*bus = pdev->bus->number;
516 				*devfn = pdev->devfn;
517 			}
518 			goto out;
519 		}
520 	}
521 	iommu = NULL;
522 out:
523 	if (iommu_is_dummy(iommu, dev))
524 		iommu = NULL;
525 
526 	rcu_read_unlock();
527 
528 	return iommu;
529 }
530 
531 static void free_context_table(struct intel_iommu *iommu)
532 {
533 	struct context_entry *context;
534 	int i;
535 
536 	if (!iommu->root_entry)
537 		return;
538 
539 	for (i = 0; i < ROOT_ENTRY_NR; i++) {
540 		context = iommu_context_addr(iommu, i, 0, 0);
541 		if (context)
542 			iommu_free_pages(context);
543 
544 		if (!sm_supported(iommu))
545 			continue;
546 
547 		context = iommu_context_addr(iommu, i, 0x80, 0);
548 		if (context)
549 			iommu_free_pages(context);
550 	}
551 
552 	iommu_free_pages(iommu->root_entry);
553 	iommu->root_entry = NULL;
554 }
555 
556 #ifdef CONFIG_DMAR_DEBUG
557 static void pgtable_walk(struct intel_iommu *iommu, unsigned long pfn,
558 			 u8 bus, u8 devfn, struct dma_pte *parent, int level)
559 {
560 	struct dma_pte *pte;
561 	int offset;
562 
563 	while (1) {
564 		offset = pfn_level_offset(pfn, level);
565 		pte = &parent[offset];
566 
567 		pr_info("pte level: %d, pte value: 0x%016llx\n", level, pte->val);
568 
569 		if (!dma_pte_present(pte)) {
570 			pr_info("page table not present at level %d\n", level - 1);
571 			break;
572 		}
573 
574 		if (level == 1 || dma_pte_superpage(pte))
575 			break;
576 
577 		parent = phys_to_virt(dma_pte_addr(pte));
578 		level--;
579 	}
580 }
581 
582 void dmar_fault_dump_ptes(struct intel_iommu *iommu, u16 source_id,
583 			  unsigned long long addr, u32 pasid)
584 {
585 	struct pasid_dir_entry *dir, *pde;
586 	struct pasid_entry *entries, *pte;
587 	struct context_entry *ctx_entry;
588 	struct root_entry *rt_entry;
589 	int i, dir_index, index, level;
590 	u8 devfn = source_id & 0xff;
591 	u8 bus = source_id >> 8;
592 	struct dma_pte *pgtable;
593 
594 	pr_info("Dump %s table entries for IOVA 0x%llx\n", iommu->name, addr);
595 
596 	/* root entry dump */
597 	if (!iommu->root_entry) {
598 		pr_info("root table is not present\n");
599 		return;
600 	}
601 	rt_entry = &iommu->root_entry[bus];
602 
603 	if (sm_supported(iommu))
604 		pr_info("scalable mode root entry: hi 0x%016llx, low 0x%016llx\n",
605 			rt_entry->hi, rt_entry->lo);
606 	else
607 		pr_info("root entry: 0x%016llx", rt_entry->lo);
608 
609 	/* context entry dump */
610 	ctx_entry = iommu_context_addr(iommu, bus, devfn, 0);
611 	if (!ctx_entry) {
612 		pr_info("context table is not present\n");
613 		return;
614 	}
615 
616 	pr_info("context entry: hi 0x%016llx, low 0x%016llx\n",
617 		ctx_entry->hi, ctx_entry->lo);
618 
619 	/* legacy mode does not require PASID entries */
620 	if (!sm_supported(iommu)) {
621 		if (!context_present(ctx_entry)) {
622 			pr_info("legacy mode page table is not present\n");
623 			return;
624 		}
625 		level = agaw_to_level(ctx_entry->hi & 7);
626 		pgtable = phys_to_virt(ctx_entry->lo & VTD_PAGE_MASK);
627 		goto pgtable_walk;
628 	}
629 
630 	if (!context_present(ctx_entry)) {
631 		pr_info("pasid directory table is not present\n");
632 		return;
633 	}
634 
635 	/* get the pointer to pasid directory entry */
636 	dir = phys_to_virt(ctx_entry->lo & VTD_PAGE_MASK);
637 
638 	/* For request-without-pasid, get the pasid from context entry */
639 	if (intel_iommu_sm && pasid == IOMMU_PASID_INVALID)
640 		pasid = IOMMU_NO_PASID;
641 
642 	dir_index = pasid >> PASID_PDE_SHIFT;
643 	pde = &dir[dir_index];
644 	pr_info("pasid dir entry: 0x%016llx\n", pde->val);
645 
646 	/* get the pointer to the pasid table entry */
647 	entries = get_pasid_table_from_pde(pde);
648 	if (!entries) {
649 		pr_info("pasid table is not present\n");
650 		return;
651 	}
652 	index = pasid & PASID_PTE_MASK;
653 	pte = &entries[index];
654 	for (i = 0; i < ARRAY_SIZE(pte->val); i++)
655 		pr_info("pasid table entry[%d]: 0x%016llx\n", i, pte->val[i]);
656 
657 	if (!pasid_pte_is_present(pte)) {
658 		pr_info("scalable mode page table is not present\n");
659 		return;
660 	}
661 
662 	if (pasid_pte_get_pgtt(pte) == PASID_ENTRY_PGTT_FL_ONLY) {
663 		level = pte->val[2] & BIT_ULL(2) ? 5 : 4;
664 		pgtable = phys_to_virt(pte->val[2] & VTD_PAGE_MASK);
665 	} else {
666 		level = agaw_to_level((pte->val[0] >> 2) & 0x7);
667 		pgtable = phys_to_virt(pte->val[0] & VTD_PAGE_MASK);
668 	}
669 
670 pgtable_walk:
671 	pgtable_walk(iommu, addr >> VTD_PAGE_SHIFT, bus, devfn, pgtable, level);
672 }
673 #endif
674 
675 /* iommu handling */
676 static int iommu_alloc_root_entry(struct intel_iommu *iommu)
677 {
678 	struct root_entry *root;
679 
680 	root = iommu_alloc_pages_node_sz(iommu->node, GFP_ATOMIC, SZ_4K);
681 	if (!root) {
682 		pr_err("Allocating root entry for %s failed\n",
683 			iommu->name);
684 		return -ENOMEM;
685 	}
686 
687 	__iommu_flush_cache(iommu, root, ROOT_SIZE);
688 	iommu->root_entry = root;
689 
690 	return 0;
691 }
692 
693 static void iommu_set_root_entry(struct intel_iommu *iommu)
694 {
695 	u64 addr;
696 	u32 sts;
697 	unsigned long flag;
698 
699 	addr = virt_to_phys(iommu->root_entry);
700 	if (sm_supported(iommu))
701 		addr |= DMA_RTADDR_SMT;
702 
703 	raw_spin_lock_irqsave(&iommu->register_lock, flag);
704 	writeq(addr, iommu->reg + DMAR_RTADDR_REG);
705 
706 	writel(iommu->gcmd | DMA_GCMD_SRTP, iommu->reg + DMAR_GCMD_REG);
707 
708 	/* Make sure hardware complete it */
709 	IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
710 		      readl, (sts & DMA_GSTS_RTPS), sts);
711 
712 	raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
713 
714 	/*
715 	 * Hardware invalidates all DMA remapping hardware translation
716 	 * caches as part of SRTP flow.
717 	 */
718 	if (cap_esrtps(iommu->cap))
719 		return;
720 
721 	iommu->flush.flush_context(iommu, 0, 0, 0, DMA_CCMD_GLOBAL_INVL);
722 	if (sm_supported(iommu))
723 		qi_flush_pasid_cache(iommu, 0, QI_PC_GLOBAL, 0);
724 	iommu->flush.flush_iotlb(iommu, 0, 0, 0, DMA_TLB_GLOBAL_FLUSH);
725 }
726 
727 void iommu_flush_write_buffer(struct intel_iommu *iommu)
728 {
729 	u32 val;
730 	unsigned long flag;
731 
732 	if (!rwbf_quirk && !cap_rwbf(iommu->cap))
733 		return;
734 
735 	raw_spin_lock_irqsave(&iommu->register_lock, flag);
736 	writel(iommu->gcmd | DMA_GCMD_WBF, iommu->reg + DMAR_GCMD_REG);
737 
738 	/* Make sure hardware complete it */
739 	IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
740 		      readl, (!(val & DMA_GSTS_WBFS)), val);
741 
742 	raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
743 }
744 
745 /* return value determine if we need a write buffer flush */
746 static void __iommu_flush_context(struct intel_iommu *iommu,
747 				  u16 did, u16 source_id, u8 function_mask,
748 				  u64 type)
749 {
750 	u64 val = 0;
751 	unsigned long flag;
752 
753 	switch (type) {
754 	case DMA_CCMD_GLOBAL_INVL:
755 		val = DMA_CCMD_GLOBAL_INVL;
756 		break;
757 	case DMA_CCMD_DOMAIN_INVL:
758 		val = DMA_CCMD_DOMAIN_INVL|DMA_CCMD_DID(did);
759 		break;
760 	case DMA_CCMD_DEVICE_INVL:
761 		val = DMA_CCMD_DEVICE_INVL|DMA_CCMD_DID(did)
762 			| DMA_CCMD_SID(source_id) | DMA_CCMD_FM(function_mask);
763 		break;
764 	default:
765 		pr_warn("%s: Unexpected context-cache invalidation type 0x%llx\n",
766 			iommu->name, type);
767 		return;
768 	}
769 	val |= DMA_CCMD_ICC;
770 
771 	raw_spin_lock_irqsave(&iommu->register_lock, flag);
772 	writeq(val, iommu->reg + DMAR_CCMD_REG);
773 
774 	/* Make sure hardware complete it */
775 	IOMMU_WAIT_OP(iommu, DMAR_CCMD_REG,
776 		readq, (!(val & DMA_CCMD_ICC)), val);
777 
778 	raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
779 }
780 
781 void __iommu_flush_iotlb(struct intel_iommu *iommu, u16 did, u64 addr,
782 			 unsigned int size_order, u64 type)
783 {
784 	int tlb_offset = ecap_iotlb_offset(iommu->ecap);
785 	u64 val = 0, val_iva = 0;
786 	unsigned long flag;
787 
788 	switch (type) {
789 	case DMA_TLB_GLOBAL_FLUSH:
790 		/* global flush doesn't need set IVA_REG */
791 		val = DMA_TLB_GLOBAL_FLUSH|DMA_TLB_IVT;
792 		break;
793 	case DMA_TLB_DSI_FLUSH:
794 		val = DMA_TLB_DSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
795 		break;
796 	case DMA_TLB_PSI_FLUSH:
797 		val = DMA_TLB_PSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
798 		/* IH bit is passed in as part of address */
799 		val_iva = size_order | addr;
800 		break;
801 	default:
802 		pr_warn("%s: Unexpected iotlb invalidation type 0x%llx\n",
803 			iommu->name, type);
804 		return;
805 	}
806 
807 	if (cap_write_drain(iommu->cap))
808 		val |= DMA_TLB_WRITE_DRAIN;
809 
810 	raw_spin_lock_irqsave(&iommu->register_lock, flag);
811 	/* Note: Only uses first TLB reg currently */
812 	if (val_iva)
813 		writeq(val_iva, iommu->reg + tlb_offset);
814 	writeq(val, iommu->reg + tlb_offset + 8);
815 
816 	/* Make sure hardware complete it */
817 	IOMMU_WAIT_OP(iommu, tlb_offset + 8,
818 		readq, (!(val & DMA_TLB_IVT)), val);
819 
820 	raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
821 
822 	/* check IOTLB invalidation granularity */
823 	if (DMA_TLB_IAIG(val) == 0)
824 		pr_err("Flush IOTLB failed\n");
825 	if (DMA_TLB_IAIG(val) != DMA_TLB_IIRG(type))
826 		pr_debug("TLB flush request %Lx, actual %Lx\n",
827 			(unsigned long long)DMA_TLB_IIRG(type),
828 			(unsigned long long)DMA_TLB_IAIG(val));
829 }
830 
831 static struct device_domain_info *
832 domain_lookup_dev_info(struct dmar_domain *domain,
833 		       struct intel_iommu *iommu, u8 bus, u8 devfn)
834 {
835 	struct device_domain_info *info;
836 	unsigned long flags;
837 
838 	spin_lock_irqsave(&domain->lock, flags);
839 	list_for_each_entry(info, &domain->devices, link) {
840 		if (info->iommu == iommu && info->bus == bus &&
841 		    info->devfn == devfn) {
842 			spin_unlock_irqrestore(&domain->lock, flags);
843 			return info;
844 		}
845 	}
846 	spin_unlock_irqrestore(&domain->lock, flags);
847 
848 	return NULL;
849 }
850 
851 /*
852  * The extra devTLB flush quirk impacts those QAT devices with PCI device
853  * IDs ranging from 0x4940 to 0x4943. It is exempted from risky_device()
854  * check because it applies only to the built-in QAT devices and it doesn't
855  * grant additional privileges.
856  */
857 #define BUGGY_QAT_DEVID_MASK 0x4940
858 static bool dev_needs_extra_dtlb_flush(struct pci_dev *pdev)
859 {
860 	if (pdev->vendor != PCI_VENDOR_ID_INTEL)
861 		return false;
862 
863 	if ((pdev->device & 0xfffc) != BUGGY_QAT_DEVID_MASK)
864 		return false;
865 
866 	return true;
867 }
868 
869 static void iommu_enable_pci_ats(struct device_domain_info *info)
870 {
871 	struct pci_dev *pdev;
872 
873 	if (!info->ats_supported)
874 		return;
875 
876 	pdev = to_pci_dev(info->dev);
877 	if (!pci_ats_page_aligned(pdev))
878 		return;
879 
880 	/*
881 	 * pci_enable_ats() should not fail here because earlier checks
882 	 * have already verified support and configuration.
883 	 */
884 	if (WARN_ON(pci_enable_ats(pdev, VTD_PAGE_SHIFT)))
885 		return;
886 
887 	info->ats_enabled = 1;
888 }
889 
890 static void iommu_disable_pci_ats(struct device_domain_info *info)
891 {
892 	if (!info->ats_enabled)
893 		return;
894 
895 	pci_disable_ats(to_pci_dev(info->dev));
896 	info->ats_enabled = 0;
897 }
898 
899 static void iommu_enable_pci_pri(struct device_domain_info *info)
900 {
901 	struct pci_dev *pdev;
902 
903 	if (!info->ats_enabled || !info->pri_supported)
904 		return;
905 
906 	pdev = to_pci_dev(info->dev);
907 	/* PASID is required in PRG Response Message. */
908 	if (info->pasid_enabled && !pci_prg_resp_pasid_required(pdev))
909 		return;
910 
911 	if (pci_reset_pri(pdev))
912 		return;
913 
914 	if (!pci_enable_pri(pdev, PRQ_DEPTH))
915 		info->pri_enabled = 1;
916 }
917 
918 static void iommu_disable_pci_pri(struct device_domain_info *info)
919 {
920 	if (!info->pri_enabled)
921 		return;
922 
923 	if (WARN_ON(info->iopf_refcount))
924 		iopf_queue_remove_device(info->iommu->iopf_queue, info->dev);
925 
926 	pci_disable_pri(to_pci_dev(info->dev));
927 	info->pri_enabled = 0;
928 }
929 
930 static void intel_flush_iotlb_all(struct iommu_domain *domain)
931 {
932 	cache_tag_flush_all(to_dmar_domain(domain));
933 }
934 
935 static void iommu_disable_protect_mem_regions(struct intel_iommu *iommu)
936 {
937 	u32 pmen;
938 	unsigned long flags;
939 
940 	if (!cap_plmr(iommu->cap) && !cap_phmr(iommu->cap))
941 		return;
942 
943 	raw_spin_lock_irqsave(&iommu->register_lock, flags);
944 	pmen = readl(iommu->reg + DMAR_PMEN_REG);
945 	pmen &= ~DMA_PMEN_EPM;
946 	writel(pmen, iommu->reg + DMAR_PMEN_REG);
947 
948 	/* wait for the protected region status bit to clear */
949 	IOMMU_WAIT_OP(iommu, DMAR_PMEN_REG,
950 		readl, !(pmen & DMA_PMEN_PRS), pmen);
951 
952 	raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
953 }
954 
955 static void iommu_enable_translation(struct intel_iommu *iommu)
956 {
957 	u32 sts;
958 	unsigned long flags;
959 
960 	raw_spin_lock_irqsave(&iommu->register_lock, flags);
961 	iommu->gcmd |= DMA_GCMD_TE;
962 	writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
963 
964 	/* Make sure hardware complete it */
965 	IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
966 		      readl, (sts & DMA_GSTS_TES), sts);
967 
968 	raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
969 }
970 
971 static void iommu_disable_translation(struct intel_iommu *iommu)
972 {
973 	u32 sts;
974 	unsigned long flag;
975 
976 	if (iommu_skip_te_disable && iommu->drhd->gfx_dedicated &&
977 	    (cap_read_drain(iommu->cap) || cap_write_drain(iommu->cap)))
978 		return;
979 
980 	raw_spin_lock_irqsave(&iommu->register_lock, flag);
981 	iommu->gcmd &= ~DMA_GCMD_TE;
982 	writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
983 
984 	/* Make sure hardware complete it */
985 	IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
986 		      readl, (!(sts & DMA_GSTS_TES)), sts);
987 
988 	raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
989 }
990 
991 static void disable_dmar_iommu(struct intel_iommu *iommu)
992 {
993 	/*
994 	 * All iommu domains must have been detached from the devices,
995 	 * hence there should be no domain IDs in use.
996 	 */
997 	if (WARN_ON(!ida_is_empty(&iommu->domain_ida)))
998 		return;
999 
1000 	if (iommu->gcmd & DMA_GCMD_TE)
1001 		iommu_disable_translation(iommu);
1002 }
1003 
1004 static void free_dmar_iommu(struct intel_iommu *iommu)
1005 {
1006 	if (iommu->copied_tables) {
1007 		bitmap_free(iommu->copied_tables);
1008 		iommu->copied_tables = NULL;
1009 	}
1010 
1011 	/* free context mapping */
1012 	free_context_table(iommu);
1013 
1014 	if (ecap_prs(iommu->ecap))
1015 		intel_iommu_finish_prq(iommu);
1016 }
1017 
1018 /*
1019  * Check and return whether first level is used by default for
1020  * DMA translation.
1021  */
1022 static bool first_level_by_default(struct intel_iommu *iommu)
1023 {
1024 	/* Only SL is available in legacy mode */
1025 	if (!sm_supported(iommu))
1026 		return false;
1027 
1028 	/* Only level (either FL or SL) is available, just use it */
1029 	if (ecap_flts(iommu->ecap) ^ ecap_slts(iommu->ecap))
1030 		return ecap_flts(iommu->ecap);
1031 
1032 	return true;
1033 }
1034 
1035 int domain_attach_iommu(struct dmar_domain *domain, struct intel_iommu *iommu)
1036 {
1037 	struct iommu_domain_info *info, *curr;
1038 	int num, ret = -ENOSPC;
1039 
1040 	if (domain->domain.type == IOMMU_DOMAIN_SVA)
1041 		return 0;
1042 
1043 	info = kzalloc_obj(*info);
1044 	if (!info)
1045 		return -ENOMEM;
1046 
1047 	guard(mutex)(&iommu->did_lock);
1048 	curr = xa_load(&domain->iommu_array, iommu->seq_id);
1049 	if (curr) {
1050 		curr->refcnt++;
1051 		kfree(info);
1052 		return 0;
1053 	}
1054 
1055 	num = ida_alloc_range(&iommu->domain_ida, IDA_START_DID,
1056 			      iommu->max_domain_id - 1, GFP_KERNEL);
1057 	if (num < 0) {
1058 		pr_err("%s: No free domain ids\n", iommu->name);
1059 		goto err_unlock;
1060 	}
1061 
1062 	info->refcnt	= 1;
1063 	info->did	= num;
1064 	info->iommu	= iommu;
1065 	curr = xa_cmpxchg(&domain->iommu_array, iommu->seq_id,
1066 			  NULL, info, GFP_KERNEL);
1067 	if (curr) {
1068 		ret = xa_err(curr) ? : -EBUSY;
1069 		goto err_clear;
1070 	}
1071 
1072 	return 0;
1073 
1074 err_clear:
1075 	ida_free(&iommu->domain_ida, info->did);
1076 err_unlock:
1077 	kfree(info);
1078 	return ret;
1079 }
1080 
1081 void domain_detach_iommu(struct dmar_domain *domain, struct intel_iommu *iommu)
1082 {
1083 	struct iommu_domain_info *info;
1084 
1085 	if (domain->domain.type == IOMMU_DOMAIN_SVA)
1086 		return;
1087 
1088 	guard(mutex)(&iommu->did_lock);
1089 	info = xa_load(&domain->iommu_array, iommu->seq_id);
1090 	if (--info->refcnt == 0) {
1091 		ida_free(&iommu->domain_ida, info->did);
1092 		xa_erase(&domain->iommu_array, iommu->seq_id);
1093 		kfree(info);
1094 	}
1095 }
1096 
1097 /*
1098  * For kdump cases, old valid entries may be cached due to the
1099  * in-flight DMA and copied pgtable, but there is no unmapping
1100  * behaviour for them, thus we need an explicit cache flush for
1101  * the newly-mapped device. For kdump, at this point, the device
1102  * is supposed to finish reset at its driver probe stage, so no
1103  * in-flight DMA will exist, and we don't need to worry anymore
1104  * hereafter.
1105  */
1106 static void copied_context_tear_down(struct intel_iommu *iommu,
1107 				     struct context_entry *context,
1108 				     u8 bus, u8 devfn)
1109 {
1110 	u16 did_old;
1111 
1112 	if (!context_copied(iommu, bus, devfn))
1113 		return;
1114 
1115 	assert_spin_locked(&iommu->lock);
1116 
1117 	did_old = context_domain_id(context);
1118 	context_clear_present(context);
1119 	__iommu_flush_cache(iommu, context, sizeof(*context));
1120 
1121 	if (did_old < iommu->max_domain_id) {
1122 		iommu->flush.flush_context(iommu, did_old,
1123 					   PCI_DEVID(bus, devfn),
1124 					   DMA_CCMD_MASK_NOBIT,
1125 					   DMA_CCMD_DEVICE_INVL);
1126 		iommu->flush.flush_iotlb(iommu, did_old, 0, 0,
1127 					 DMA_TLB_DSI_FLUSH);
1128 	}
1129 
1130 	context_clear_entry(context);
1131 	__iommu_flush_cache(iommu, context, sizeof(*context));
1132 
1133 	clear_context_copied(iommu, bus, devfn);
1134 }
1135 
1136 /*
1137  * It's a non-present to present mapping. If hardware doesn't cache
1138  * non-present entry we only need to flush the write-buffer. If the
1139  * _does_ cache non-present entries, then it does so in the special
1140  * domain #0, which we have to flush:
1141  */
1142 static void context_present_cache_flush(struct intel_iommu *iommu, u16 did,
1143 					u8 bus, u8 devfn)
1144 {
1145 	if (cap_caching_mode(iommu->cap)) {
1146 		iommu->flush.flush_context(iommu, 0,
1147 					   PCI_DEVID(bus, devfn),
1148 					   DMA_CCMD_MASK_NOBIT,
1149 					   DMA_CCMD_DEVICE_INVL);
1150 		iommu->flush.flush_iotlb(iommu, did, 0, 0, DMA_TLB_DSI_FLUSH);
1151 	} else {
1152 		iommu_flush_write_buffer(iommu);
1153 	}
1154 }
1155 
1156 static int domain_context_mapping_one(struct dmar_domain *domain,
1157 				      struct intel_iommu *iommu,
1158 				      u8 bus, u8 devfn)
1159 {
1160 	struct device_domain_info *info =
1161 			domain_lookup_dev_info(domain, iommu, bus, devfn);
1162 	u16 did = domain_id_iommu(domain, iommu);
1163 	int translation = CONTEXT_TT_MULTI_LEVEL;
1164 	struct pt_iommu_vtdss_hw_info pt_info;
1165 	struct context_entry *context;
1166 	int ret;
1167 
1168 	if (WARN_ON(!intel_domain_is_ss_paging(domain)))
1169 		return -EINVAL;
1170 
1171 	pt_iommu_vtdss_hw_info(&domain->sspt, &pt_info);
1172 
1173 	pr_debug("Set context mapping for %02x:%02x.%d\n",
1174 		bus, PCI_SLOT(devfn), PCI_FUNC(devfn));
1175 
1176 	spin_lock(&iommu->lock);
1177 	ret = -ENOMEM;
1178 	context = iommu_context_addr(iommu, bus, devfn, 1);
1179 	if (!context)
1180 		goto out_unlock;
1181 
1182 	ret = 0;
1183 	if (context_present(context) && !context_copied(iommu, bus, devfn))
1184 		goto out_unlock;
1185 
1186 	copied_context_tear_down(iommu, context, bus, devfn);
1187 	context_clear_entry(context);
1188 	context_set_domain_id(context, did);
1189 
1190 	if (info && info->ats_supported)
1191 		translation = CONTEXT_TT_DEV_IOTLB;
1192 	else
1193 		translation = CONTEXT_TT_MULTI_LEVEL;
1194 
1195 	context_set_address_root(context, pt_info.ssptptr);
1196 	context_set_address_width(context, pt_info.aw);
1197 	context_set_translation_type(context, translation);
1198 	context_set_fault_enable(context);
1199 	context_set_present(context);
1200 	if (!ecap_coherent(iommu->ecap))
1201 		clflush_cache_range(context, sizeof(*context));
1202 	context_present_cache_flush(iommu, did, bus, devfn);
1203 	ret = 0;
1204 
1205 out_unlock:
1206 	spin_unlock(&iommu->lock);
1207 
1208 	return ret;
1209 }
1210 
1211 static int domain_context_mapping_cb(struct pci_dev *pdev,
1212 				     u16 alias, void *opaque)
1213 {
1214 	struct device_domain_info *info = dev_iommu_priv_get(&pdev->dev);
1215 	struct intel_iommu *iommu = info->iommu;
1216 	struct dmar_domain *domain = opaque;
1217 
1218 	return domain_context_mapping_one(domain, iommu,
1219 					  PCI_BUS_NUM(alias), alias & 0xff);
1220 }
1221 
1222 static int
1223 domain_context_mapping(struct dmar_domain *domain, struct device *dev)
1224 {
1225 	struct device_domain_info *info = dev_iommu_priv_get(dev);
1226 	struct intel_iommu *iommu = info->iommu;
1227 	u8 bus = info->bus, devfn = info->devfn;
1228 	int ret;
1229 
1230 	if (!dev_is_pci(dev))
1231 		return domain_context_mapping_one(domain, iommu, bus, devfn);
1232 
1233 	ret = pci_for_each_dma_alias(to_pci_dev(dev),
1234 				     domain_context_mapping_cb, domain);
1235 	if (ret)
1236 		return ret;
1237 
1238 	iommu_enable_pci_ats(info);
1239 
1240 	return 0;
1241 }
1242 
1243 static void domain_context_clear_one(struct device_domain_info *info, u8 bus, u8 devfn)
1244 {
1245 	struct intel_iommu *iommu = info->iommu;
1246 	struct context_entry *context;
1247 	u16 did;
1248 
1249 	spin_lock(&iommu->lock);
1250 	context = iommu_context_addr(iommu, bus, devfn, 0);
1251 	if (!context) {
1252 		spin_unlock(&iommu->lock);
1253 		return;
1254 	}
1255 
1256 	did = context_domain_id(context);
1257 	context_clear_present(context);
1258 	__iommu_flush_cache(iommu, context, sizeof(*context));
1259 	spin_unlock(&iommu->lock);
1260 	intel_context_flush_no_pasid(info, context, did, PCI_DEVID(bus, devfn));
1261 	context_clear_entry(context);
1262 	__iommu_flush_cache(iommu, context, sizeof(*context));
1263 }
1264 
1265 int __domain_setup_first_level(struct intel_iommu *iommu, struct device *dev,
1266 			       ioasid_t pasid, u16 did, phys_addr_t fsptptr,
1267 			       int flags, struct iommu_domain *old)
1268 {
1269 	if (old)
1270 		intel_pasid_tear_down_entry(iommu, dev, pasid, false);
1271 
1272 	return intel_pasid_setup_first_level(iommu, dev, fsptptr, pasid, did, flags);
1273 }
1274 
1275 static int domain_setup_second_level(struct intel_iommu *iommu,
1276 				     struct dmar_domain *domain,
1277 				     struct device *dev, ioasid_t pasid,
1278 				     struct iommu_domain *old)
1279 {
1280 	if (old)
1281 		intel_pasid_tear_down_entry(iommu, dev, pasid, false);
1282 
1283 	return intel_pasid_setup_second_level(iommu, domain, dev, pasid);
1284 }
1285 
1286 static int domain_setup_passthrough(struct intel_iommu *iommu,
1287 				    struct device *dev, ioasid_t pasid,
1288 				    struct iommu_domain *old)
1289 {
1290 	if (old)
1291 		intel_pasid_tear_down_entry(iommu, dev, pasid, false);
1292 
1293 	return intel_pasid_setup_pass_through(iommu, dev, pasid);
1294 }
1295 
1296 static int domain_setup_first_level(struct intel_iommu *iommu,
1297 				    struct dmar_domain *domain,
1298 				    struct device *dev,
1299 				    u32 pasid, struct iommu_domain *old)
1300 {
1301 	struct pt_iommu_x86_64_hw_info pt_info;
1302 	unsigned int flags = 0;
1303 
1304 	pt_iommu_x86_64_hw_info(&domain->fspt, &pt_info);
1305 	if (WARN_ON(pt_info.levels != 4 && pt_info.levels != 5))
1306 		return -EINVAL;
1307 
1308 	if (pt_info.levels == 5)
1309 		flags |= PASID_FLAG_FL5LP;
1310 
1311 	if (domain->force_snooping)
1312 		flags |= PASID_FLAG_PAGE_SNOOP;
1313 
1314 	if (!(domain->fspt.x86_64_pt.common.features &
1315 	      BIT(PT_FEAT_DMA_INCOHERENT)))
1316 		flags |= PASID_FLAG_PWSNP;
1317 
1318 	return __domain_setup_first_level(iommu, dev, pasid,
1319 					  domain_id_iommu(domain, iommu),
1320 					  pt_info.gcr3_pt, flags, old);
1321 }
1322 
1323 static int dmar_domain_attach_device(struct dmar_domain *domain,
1324 				     struct device *dev)
1325 {
1326 	struct device_domain_info *info = dev_iommu_priv_get(dev);
1327 	struct intel_iommu *iommu = info->iommu;
1328 	unsigned long flags;
1329 	int ret;
1330 
1331 	ret = domain_attach_iommu(domain, iommu);
1332 	if (ret)
1333 		return ret;
1334 
1335 	info->domain = domain;
1336 	info->domain_attached = true;
1337 	spin_lock_irqsave(&domain->lock, flags);
1338 	list_add(&info->link, &domain->devices);
1339 	spin_unlock_irqrestore(&domain->lock, flags);
1340 
1341 	if (dev_is_real_dma_subdevice(dev))
1342 		return 0;
1343 
1344 	if (!sm_supported(iommu))
1345 		ret = domain_context_mapping(domain, dev);
1346 	else if (intel_domain_is_fs_paging(domain))
1347 		ret = domain_setup_first_level(iommu, domain, dev,
1348 					       IOMMU_NO_PASID, NULL);
1349 	else if (intel_domain_is_ss_paging(domain))
1350 		ret = domain_setup_second_level(iommu, domain, dev,
1351 						IOMMU_NO_PASID, NULL);
1352 	else if (WARN_ON(true))
1353 		ret = -EINVAL;
1354 
1355 	if (ret)
1356 		goto out_block_translation;
1357 
1358 	ret = cache_tag_assign_domain(domain, dev, IOMMU_NO_PASID);
1359 	if (ret)
1360 		goto out_block_translation;
1361 
1362 	return 0;
1363 
1364 out_block_translation:
1365 	device_block_translation(dev);
1366 	return ret;
1367 }
1368 
1369 /**
1370  * device_rmrr_is_relaxable - Test whether the RMRR of this device
1371  * is relaxable (ie. is allowed to be not enforced under some conditions)
1372  * @dev: device handle
1373  *
1374  * We assume that PCI USB devices with RMRRs have them largely
1375  * for historical reasons and that the RMRR space is not actively used post
1376  * boot.  This exclusion may change if vendors begin to abuse it.
1377  *
1378  * The same exception is made for graphics devices, with the requirement that
1379  * any use of the RMRR regions will be torn down before assigning the device
1380  * to a guest.
1381  *
1382  * Return: true if the RMRR is relaxable, false otherwise
1383  */
1384 static bool device_rmrr_is_relaxable(struct device *dev)
1385 {
1386 	struct pci_dev *pdev;
1387 
1388 	if (!dev_is_pci(dev))
1389 		return false;
1390 
1391 	pdev = to_pci_dev(dev);
1392 	if (IS_USB_DEVICE(pdev) || IS_GFX_DEVICE(pdev))
1393 		return true;
1394 	else
1395 		return false;
1396 }
1397 
1398 static int device_def_domain_type(struct device *dev)
1399 {
1400 	struct device_domain_info *info = dev_iommu_priv_get(dev);
1401 	struct intel_iommu *iommu = info->iommu;
1402 
1403 	/*
1404 	 * Hardware does not support the passthrough translation mode.
1405 	 * Always use a dynamaic mapping domain.
1406 	 */
1407 	if (!ecap_pass_through(iommu->ecap))
1408 		return IOMMU_DOMAIN_DMA;
1409 
1410 	if (dev_is_pci(dev)) {
1411 		struct pci_dev *pdev = to_pci_dev(dev);
1412 
1413 		if ((iommu_identity_mapping & IDENTMAP_AZALIA) && IS_AZALIA(pdev))
1414 			return IOMMU_DOMAIN_IDENTITY;
1415 	}
1416 
1417 	return 0;
1418 }
1419 
1420 static void intel_iommu_init_qi(struct intel_iommu *iommu)
1421 {
1422 	/*
1423 	 * Start from the sane iommu hardware state.
1424 	 * If the queued invalidation is already initialized by us
1425 	 * (for example, while enabling interrupt-remapping) then
1426 	 * we got the things already rolling from a sane state.
1427 	 */
1428 	if (!iommu->qi) {
1429 		/*
1430 		 * Clear any previous faults.
1431 		 */
1432 		dmar_fault(-1, iommu);
1433 		/*
1434 		 * Disable queued invalidation if supported and already enabled
1435 		 * before OS handover.
1436 		 */
1437 		dmar_disable_qi(iommu);
1438 	}
1439 
1440 	if (dmar_enable_qi(iommu)) {
1441 		/*
1442 		 * Queued Invalidate not enabled, use Register Based Invalidate
1443 		 */
1444 		iommu->flush.flush_context = __iommu_flush_context;
1445 		iommu->flush.flush_iotlb = __iommu_flush_iotlb;
1446 		pr_info("%s: Using Register based invalidation\n",
1447 			iommu->name);
1448 	} else {
1449 		iommu->flush.flush_context = qi_flush_context;
1450 		iommu->flush.flush_iotlb = qi_flush_iotlb;
1451 		pr_info("%s: Using Queued invalidation\n", iommu->name);
1452 	}
1453 }
1454 
1455 static int copy_context_table(struct intel_iommu *iommu,
1456 			      struct root_entry *old_re,
1457 			      struct context_entry **tbl,
1458 			      int bus, bool ext)
1459 {
1460 	int tbl_idx, tbl_slot = 0, idx, devfn, ret = 0, did;
1461 	struct context_entry *new_ce = NULL, ce;
1462 	struct context_entry *old_ce = NULL;
1463 	struct root_entry re;
1464 	phys_addr_t old_ce_phys;
1465 
1466 	tbl_idx = ext ? bus * 2 : bus;
1467 	memcpy(&re, old_re, sizeof(re));
1468 
1469 	for (devfn = 0; devfn < 256; devfn++) {
1470 		/* First calculate the correct index */
1471 		idx = (ext ? devfn * 2 : devfn) % 256;
1472 
1473 		if (idx == 0) {
1474 			/* First save what we may have and clean up */
1475 			if (new_ce) {
1476 				tbl[tbl_idx + tbl_slot] = new_ce;
1477 				__iommu_flush_cache(iommu, new_ce,
1478 						    VTD_PAGE_SIZE);
1479 			}
1480 
1481 			if (old_ce)
1482 				memunmap(old_ce);
1483 
1484 			ret = 0;
1485 			if (devfn < 0x80)
1486 				old_ce_phys = root_entry_lctp(&re);
1487 			else
1488 				old_ce_phys = root_entry_uctp(&re);
1489 
1490 			if (!old_ce_phys) {
1491 				if (ext && devfn == 0) {
1492 					/* No LCTP, try UCTP */
1493 					devfn = 0x7f;
1494 					continue;
1495 				} else {
1496 					goto out;
1497 				}
1498 			}
1499 
1500 			/* Track if saving UCTP or LCTP entries in scalable mode */
1501 			tbl_slot = ext && devfn >= 0x80 ? 1 : 0;
1502 
1503 			ret = -ENOMEM;
1504 			old_ce = memremap(old_ce_phys, PAGE_SIZE,
1505 					MEMREMAP_WB);
1506 			if (!old_ce)
1507 				goto out;
1508 
1509 			new_ce = iommu_alloc_pages_node_sz(iommu->node,
1510 							   GFP_KERNEL, SZ_4K);
1511 			if (!new_ce)
1512 				goto out_unmap;
1513 
1514 			ret = 0;
1515 		}
1516 
1517 		/* Now copy the context entry */
1518 		memcpy(&ce, old_ce + idx, sizeof(ce));
1519 
1520 		if (!context_present(&ce))
1521 			continue;
1522 
1523 		did = context_domain_id(&ce);
1524 		if (did >= 0 && did < iommu->max_domain_id)
1525 			ida_alloc_range(&iommu->domain_ida, did, did, GFP_KERNEL);
1526 
1527 		set_context_copied(iommu, bus, devfn);
1528 		new_ce[idx] = ce;
1529 	}
1530 
1531 	tbl[tbl_idx + tbl_slot] = new_ce;
1532 
1533 	__iommu_flush_cache(iommu, new_ce, VTD_PAGE_SIZE);
1534 
1535 out_unmap:
1536 	memunmap(old_ce);
1537 
1538 out:
1539 	return ret;
1540 }
1541 
1542 static int copy_translation_tables(struct intel_iommu *iommu)
1543 {
1544 	struct context_entry **ctxt_tbls;
1545 	struct root_entry *old_rt;
1546 	phys_addr_t old_rt_phys;
1547 	int ctxt_table_entries;
1548 	u64 rtaddr_reg;
1549 	int bus, ret;
1550 	bool new_ext, ext;
1551 
1552 	rtaddr_reg = readq(iommu->reg + DMAR_RTADDR_REG);
1553 	ext        = !!(rtaddr_reg & DMA_RTADDR_SMT);
1554 	new_ext    = !!sm_supported(iommu);
1555 
1556 	/*
1557 	 * The RTT bit can only be changed when translation is disabled,
1558 	 * but disabling translation means to open a window for data
1559 	 * corruption. So bail out and don't copy anything if we would
1560 	 * have to change the bit.
1561 	 */
1562 	if (new_ext != ext)
1563 		return -EINVAL;
1564 
1565 	iommu->copied_tables = bitmap_zalloc(BIT_ULL(16), GFP_KERNEL);
1566 	if (!iommu->copied_tables)
1567 		return -ENOMEM;
1568 
1569 	old_rt_phys = rtaddr_reg & VTD_PAGE_MASK;
1570 	if (!old_rt_phys) {
1571 		ret = -EINVAL;
1572 		goto err_free_bitmap;
1573 	}
1574 
1575 	old_rt = memremap(old_rt_phys, PAGE_SIZE, MEMREMAP_WB);
1576 	if (!old_rt) {
1577 		ret = -ENOMEM;
1578 		goto err_free_bitmap;
1579 	}
1580 
1581 	/* This is too big for the stack - allocate it from slab */
1582 	ctxt_table_entries = ext ? 512 : 256;
1583 	ret = -ENOMEM;
1584 	ctxt_tbls = kcalloc(ctxt_table_entries, sizeof(void *), GFP_KERNEL);
1585 	if (!ctxt_tbls)
1586 		goto out_unmap;
1587 
1588 	for (bus = 0; bus < 256; bus++) {
1589 		ret = copy_context_table(iommu, &old_rt[bus],
1590 					 ctxt_tbls, bus, ext);
1591 		if (ret) {
1592 			pr_err("%s: Failed to copy context table for bus %d\n",
1593 				iommu->name, bus);
1594 			continue;
1595 		}
1596 	}
1597 
1598 	spin_lock(&iommu->lock);
1599 
1600 	/* Context tables are copied, now write them to the root_entry table */
1601 	for (bus = 0; bus < 256; bus++) {
1602 		int idx = ext ? bus * 2 : bus;
1603 		u64 val;
1604 
1605 		if (ctxt_tbls[idx]) {
1606 			val = virt_to_phys(ctxt_tbls[idx]) | 1;
1607 			iommu->root_entry[bus].lo = val;
1608 		}
1609 
1610 		if (!ext || !ctxt_tbls[idx + 1])
1611 			continue;
1612 
1613 		val = virt_to_phys(ctxt_tbls[idx + 1]) | 1;
1614 		iommu->root_entry[bus].hi = val;
1615 	}
1616 
1617 	spin_unlock(&iommu->lock);
1618 
1619 	kfree(ctxt_tbls);
1620 
1621 	__iommu_flush_cache(iommu, iommu->root_entry, PAGE_SIZE);
1622 
1623 	memunmap(old_rt);
1624 	return 0;
1625 
1626 out_unmap:
1627 	memunmap(old_rt);
1628 err_free_bitmap:
1629 	bitmap_free(iommu->copied_tables);
1630 	iommu->copied_tables = NULL;
1631 	return ret;
1632 }
1633 
1634 static int __init init_dmars(void)
1635 {
1636 	struct dmar_drhd_unit *drhd;
1637 	struct intel_iommu *iommu;
1638 	int ret;
1639 
1640 	for_each_iommu(iommu, drhd) {
1641 		if (drhd->ignored) {
1642 			iommu_disable_translation(iommu);
1643 			continue;
1644 		}
1645 
1646 		/*
1647 		 * Find the max pasid size of all IOMMU's in the system.
1648 		 * We need to ensure the system pasid table is no bigger
1649 		 * than the smallest supported.
1650 		 */
1651 		if (pasid_supported(iommu)) {
1652 			u32 temp = 2 << ecap_pss(iommu->ecap);
1653 
1654 			intel_pasid_max_id = min_t(u32, temp,
1655 						   intel_pasid_max_id);
1656 		}
1657 
1658 		intel_iommu_init_qi(iommu);
1659 		init_translation_status(iommu);
1660 
1661 		if (translation_pre_enabled(iommu) && !is_kdump_kernel()) {
1662 			iommu_disable_translation(iommu);
1663 			clear_translation_pre_enabled(iommu);
1664 			pr_warn("Translation was enabled for %s but we are not in kdump mode\n",
1665 				iommu->name);
1666 		}
1667 
1668 		/*
1669 		 * TBD:
1670 		 * we could share the same root & context tables
1671 		 * among all IOMMU's. Need to Split it later.
1672 		 */
1673 		ret = iommu_alloc_root_entry(iommu);
1674 		if (ret)
1675 			goto free_iommu;
1676 
1677 		if (translation_pre_enabled(iommu)) {
1678 			pr_info("Translation already enabled - trying to copy translation structures\n");
1679 
1680 			ret = copy_translation_tables(iommu);
1681 			if (ret) {
1682 				/*
1683 				 * We found the IOMMU with translation
1684 				 * enabled - but failed to copy over the
1685 				 * old root-entry table. Try to proceed
1686 				 * by disabling translation now and
1687 				 * allocating a clean root-entry table.
1688 				 * This might cause DMAR faults, but
1689 				 * probably the dump will still succeed.
1690 				 */
1691 				pr_err("Failed to copy translation tables from previous kernel for %s\n",
1692 				       iommu->name);
1693 				iommu_disable_translation(iommu);
1694 				clear_translation_pre_enabled(iommu);
1695 			} else {
1696 				pr_info("Copied translation tables from previous kernel for %s\n",
1697 					iommu->name);
1698 			}
1699 		}
1700 
1701 		intel_svm_check(iommu);
1702 	}
1703 
1704 	/*
1705 	 * Now that qi is enabled on all iommus, set the root entry and flush
1706 	 * caches. This is required on some Intel X58 chipsets, otherwise the
1707 	 * flush_context function will loop forever and the boot hangs.
1708 	 */
1709 	for_each_active_iommu(iommu, drhd) {
1710 		iommu_flush_write_buffer(iommu);
1711 		iommu_set_root_entry(iommu);
1712 	}
1713 
1714 	check_tylersburg_isoch();
1715 
1716 	/*
1717 	 * for each drhd
1718 	 *   enable fault log
1719 	 *   global invalidate context cache
1720 	 *   global invalidate iotlb
1721 	 *   enable translation
1722 	 */
1723 	for_each_iommu(iommu, drhd) {
1724 		if (drhd->ignored) {
1725 			/*
1726 			 * we always have to disable PMRs or DMA may fail on
1727 			 * this device
1728 			 */
1729 			if (dmar_policy_force_on())
1730 				iommu_disable_protect_mem_regions(iommu);
1731 			continue;
1732 		}
1733 
1734 		iommu_flush_write_buffer(iommu);
1735 
1736 		if (ecap_prs(iommu->ecap)) {
1737 			/*
1738 			 * Call dmar_alloc_hwirq() with dmar_global_lock held,
1739 			 * could cause possible lock race condition.
1740 			 */
1741 			up_write(&dmar_global_lock);
1742 			ret = intel_iommu_enable_prq(iommu);
1743 			down_write(&dmar_global_lock);
1744 			if (ret)
1745 				goto free_iommu;
1746 		}
1747 
1748 		ret = dmar_set_interrupt(iommu);
1749 		if (ret)
1750 			goto free_iommu;
1751 	}
1752 
1753 	return 0;
1754 
1755 free_iommu:
1756 	for_each_active_iommu(iommu, drhd) {
1757 		disable_dmar_iommu(iommu);
1758 		free_dmar_iommu(iommu);
1759 	}
1760 
1761 	return ret;
1762 }
1763 
1764 static void __init init_no_remapping_devices(void)
1765 {
1766 	struct dmar_drhd_unit *drhd;
1767 	struct device *dev;
1768 	int i;
1769 
1770 	for_each_drhd_unit(drhd) {
1771 		if (!drhd->include_all) {
1772 			for_each_active_dev_scope(drhd->devices,
1773 						  drhd->devices_cnt, i, dev)
1774 				break;
1775 			/* ignore DMAR unit if no devices exist */
1776 			if (i == drhd->devices_cnt)
1777 				drhd->ignored = 1;
1778 		}
1779 	}
1780 
1781 	for_each_active_drhd_unit(drhd) {
1782 		if (drhd->include_all)
1783 			continue;
1784 
1785 		for_each_active_dev_scope(drhd->devices,
1786 					  drhd->devices_cnt, i, dev)
1787 			if (!dev_is_pci(dev) || !IS_GFX_DEVICE(to_pci_dev(dev)))
1788 				break;
1789 		if (i < drhd->devices_cnt)
1790 			continue;
1791 
1792 		/* This IOMMU has *only* gfx devices. Either bypass it or
1793 		   set the gfx_mapped flag, as appropriate */
1794 		drhd->gfx_dedicated = 1;
1795 		if (disable_igfx_iommu)
1796 			drhd->ignored = 1;
1797 	}
1798 }
1799 
1800 #ifdef CONFIG_SUSPEND
1801 static int init_iommu_hw(void)
1802 {
1803 	struct dmar_drhd_unit *drhd;
1804 	struct intel_iommu *iommu = NULL;
1805 	int ret;
1806 
1807 	for_each_active_iommu(iommu, drhd) {
1808 		if (iommu->qi) {
1809 			ret = dmar_reenable_qi(iommu);
1810 			if (ret)
1811 				return ret;
1812 		}
1813 	}
1814 
1815 	for_each_iommu(iommu, drhd) {
1816 		if (drhd->ignored) {
1817 			/*
1818 			 * we always have to disable PMRs or DMA may fail on
1819 			 * this device
1820 			 */
1821 			if (dmar_policy_force_on())
1822 				iommu_disable_protect_mem_regions(iommu);
1823 			continue;
1824 		}
1825 
1826 		iommu_flush_write_buffer(iommu);
1827 		iommu_set_root_entry(iommu);
1828 		iommu_enable_translation(iommu);
1829 		iommu_disable_protect_mem_regions(iommu);
1830 	}
1831 
1832 	return 0;
1833 }
1834 
1835 static void iommu_flush_all(void)
1836 {
1837 	struct dmar_drhd_unit *drhd;
1838 	struct intel_iommu *iommu;
1839 
1840 	for_each_active_iommu(iommu, drhd) {
1841 		iommu->flush.flush_context(iommu, 0, 0, 0,
1842 					   DMA_CCMD_GLOBAL_INVL);
1843 		iommu->flush.flush_iotlb(iommu, 0, 0, 0,
1844 					 DMA_TLB_GLOBAL_FLUSH);
1845 	}
1846 }
1847 
1848 static int iommu_suspend(void *data)
1849 {
1850 	struct dmar_drhd_unit *drhd;
1851 	struct intel_iommu *iommu = NULL;
1852 	unsigned long flag;
1853 
1854 	iommu_flush_all();
1855 
1856 	for_each_active_iommu(iommu, drhd) {
1857 		iommu_disable_translation(iommu);
1858 
1859 		raw_spin_lock_irqsave(&iommu->register_lock, flag);
1860 
1861 		iommu->iommu_state[SR_DMAR_FECTL_REG] =
1862 			readl(iommu->reg + DMAR_FECTL_REG);
1863 		iommu->iommu_state[SR_DMAR_FEDATA_REG] =
1864 			readl(iommu->reg + DMAR_FEDATA_REG);
1865 		iommu->iommu_state[SR_DMAR_FEADDR_REG] =
1866 			readl(iommu->reg + DMAR_FEADDR_REG);
1867 		iommu->iommu_state[SR_DMAR_FEUADDR_REG] =
1868 			readl(iommu->reg + DMAR_FEUADDR_REG);
1869 
1870 		raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1871 	}
1872 	return 0;
1873 }
1874 
1875 static void iommu_resume(void *data)
1876 {
1877 	struct dmar_drhd_unit *drhd;
1878 	struct intel_iommu *iommu = NULL;
1879 	unsigned long flag;
1880 
1881 	if (init_iommu_hw()) {
1882 		if (dmar_policy_force_on())
1883 			panic("tboot: IOMMU setup failed, DMAR can not resume!\n");
1884 		else
1885 			WARN(1, "IOMMU setup failed, DMAR can not resume!\n");
1886 		return;
1887 	}
1888 
1889 	for_each_active_iommu(iommu, drhd) {
1890 
1891 		raw_spin_lock_irqsave(&iommu->register_lock, flag);
1892 
1893 		writel(iommu->iommu_state[SR_DMAR_FECTL_REG],
1894 			iommu->reg + DMAR_FECTL_REG);
1895 		writel(iommu->iommu_state[SR_DMAR_FEDATA_REG],
1896 			iommu->reg + DMAR_FEDATA_REG);
1897 		writel(iommu->iommu_state[SR_DMAR_FEADDR_REG],
1898 			iommu->reg + DMAR_FEADDR_REG);
1899 		writel(iommu->iommu_state[SR_DMAR_FEUADDR_REG],
1900 			iommu->reg + DMAR_FEUADDR_REG);
1901 
1902 		raw_spin_unlock_irqrestore(&iommu->register_lock, flag);
1903 	}
1904 }
1905 
1906 static const struct syscore_ops iommu_syscore_ops = {
1907 	.resume		= iommu_resume,
1908 	.suspend	= iommu_suspend,
1909 };
1910 
1911 static struct syscore iommu_syscore = {
1912 	.ops = &iommu_syscore_ops,
1913 };
1914 
1915 static void __init init_iommu_pm_ops(void)
1916 {
1917 	register_syscore(&iommu_syscore);
1918 }
1919 
1920 #else
1921 static inline void init_iommu_pm_ops(void) {}
1922 #endif	/* CONFIG_PM */
1923 
1924 static int __init rmrr_sanity_check(struct acpi_dmar_reserved_memory *rmrr)
1925 {
1926 	if (!IS_ALIGNED(rmrr->base_address, PAGE_SIZE) ||
1927 	    !IS_ALIGNED(rmrr->end_address + 1, PAGE_SIZE) ||
1928 	    rmrr->end_address <= rmrr->base_address ||
1929 	    arch_rmrr_sanity_check(rmrr))
1930 		return -EINVAL;
1931 
1932 	return 0;
1933 }
1934 
1935 int __init dmar_parse_one_rmrr(struct acpi_dmar_header *header, void *arg)
1936 {
1937 	struct acpi_dmar_reserved_memory *rmrr;
1938 	struct dmar_rmrr_unit *rmrru;
1939 
1940 	rmrr = (struct acpi_dmar_reserved_memory *)header;
1941 	if (rmrr_sanity_check(rmrr)) {
1942 		pr_warn(FW_BUG
1943 			   "Your BIOS is broken; bad RMRR [%#018Lx-%#018Lx]\n"
1944 			   "BIOS vendor: %s; Ver: %s; Product Version: %s\n",
1945 			   rmrr->base_address, rmrr->end_address,
1946 			   dmi_get_system_info(DMI_BIOS_VENDOR),
1947 			   dmi_get_system_info(DMI_BIOS_VERSION),
1948 			   dmi_get_system_info(DMI_PRODUCT_VERSION));
1949 		add_taint(TAINT_FIRMWARE_WORKAROUND, LOCKDEP_STILL_OK);
1950 	}
1951 
1952 	rmrru = kzalloc_obj(*rmrru);
1953 	if (!rmrru)
1954 		goto out;
1955 
1956 	rmrru->hdr = header;
1957 
1958 	rmrru->base_address = rmrr->base_address;
1959 	rmrru->end_address = rmrr->end_address;
1960 
1961 	rmrru->devices = dmar_alloc_dev_scope((void *)(rmrr + 1),
1962 				((void *)rmrr) + rmrr->header.length,
1963 				&rmrru->devices_cnt);
1964 	if (rmrru->devices_cnt && rmrru->devices == NULL)
1965 		goto free_rmrru;
1966 
1967 	list_add(&rmrru->list, &dmar_rmrr_units);
1968 
1969 	return 0;
1970 free_rmrru:
1971 	kfree(rmrru);
1972 out:
1973 	return -ENOMEM;
1974 }
1975 
1976 static struct dmar_atsr_unit *dmar_find_atsr(struct acpi_dmar_atsr *atsr)
1977 {
1978 	struct dmar_atsr_unit *atsru;
1979 	struct acpi_dmar_atsr *tmp;
1980 
1981 	list_for_each_entry_rcu(atsru, &dmar_atsr_units, list,
1982 				dmar_rcu_check()) {
1983 		tmp = (struct acpi_dmar_atsr *)atsru->hdr;
1984 		if (atsr->segment != tmp->segment)
1985 			continue;
1986 		if (atsr->header.length != tmp->header.length)
1987 			continue;
1988 		if (memcmp(atsr, tmp, atsr->header.length) == 0)
1989 			return atsru;
1990 	}
1991 
1992 	return NULL;
1993 }
1994 
1995 int dmar_parse_one_atsr(struct acpi_dmar_header *hdr, void *arg)
1996 {
1997 	struct acpi_dmar_atsr *atsr;
1998 	struct dmar_atsr_unit *atsru;
1999 
2000 	if (system_state >= SYSTEM_RUNNING && !intel_iommu_enabled)
2001 		return 0;
2002 
2003 	atsr = container_of(hdr, struct acpi_dmar_atsr, header);
2004 	atsru = dmar_find_atsr(atsr);
2005 	if (atsru)
2006 		return 0;
2007 
2008 	atsru = kzalloc(sizeof(*atsru) + hdr->length, GFP_KERNEL);
2009 	if (!atsru)
2010 		return -ENOMEM;
2011 
2012 	/*
2013 	 * If memory is allocated from slab by ACPI _DSM method, we need to
2014 	 * copy the memory content because the memory buffer will be freed
2015 	 * on return.
2016 	 */
2017 	atsru->hdr = (void *)(atsru + 1);
2018 	memcpy(atsru->hdr, hdr, hdr->length);
2019 	atsru->include_all = atsr->flags & 0x1;
2020 	if (!atsru->include_all) {
2021 		atsru->devices = dmar_alloc_dev_scope((void *)(atsr + 1),
2022 				(void *)atsr + atsr->header.length,
2023 				&atsru->devices_cnt);
2024 		if (atsru->devices_cnt && atsru->devices == NULL) {
2025 			kfree(atsru);
2026 			return -ENOMEM;
2027 		}
2028 	}
2029 
2030 	list_add_rcu(&atsru->list, &dmar_atsr_units);
2031 
2032 	return 0;
2033 }
2034 
2035 static void intel_iommu_free_atsr(struct dmar_atsr_unit *atsru)
2036 {
2037 	dmar_free_dev_scope(&atsru->devices, &atsru->devices_cnt);
2038 	kfree(atsru);
2039 }
2040 
2041 int dmar_release_one_atsr(struct acpi_dmar_header *hdr, void *arg)
2042 {
2043 	struct acpi_dmar_atsr *atsr;
2044 	struct dmar_atsr_unit *atsru;
2045 
2046 	atsr = container_of(hdr, struct acpi_dmar_atsr, header);
2047 	atsru = dmar_find_atsr(atsr);
2048 	if (atsru) {
2049 		list_del_rcu(&atsru->list);
2050 		synchronize_rcu();
2051 		intel_iommu_free_atsr(atsru);
2052 	}
2053 
2054 	return 0;
2055 }
2056 
2057 int dmar_check_one_atsr(struct acpi_dmar_header *hdr, void *arg)
2058 {
2059 	int i;
2060 	struct device *dev;
2061 	struct acpi_dmar_atsr *atsr;
2062 	struct dmar_atsr_unit *atsru;
2063 
2064 	atsr = container_of(hdr, struct acpi_dmar_atsr, header);
2065 	atsru = dmar_find_atsr(atsr);
2066 	if (!atsru)
2067 		return 0;
2068 
2069 	if (!atsru->include_all && atsru->devices && atsru->devices_cnt) {
2070 		for_each_active_dev_scope(atsru->devices, atsru->devices_cnt,
2071 					  i, dev)
2072 			return -EBUSY;
2073 	}
2074 
2075 	return 0;
2076 }
2077 
2078 static struct dmar_satc_unit *dmar_find_satc(struct acpi_dmar_satc *satc)
2079 {
2080 	struct dmar_satc_unit *satcu;
2081 	struct acpi_dmar_satc *tmp;
2082 
2083 	list_for_each_entry_rcu(satcu, &dmar_satc_units, list,
2084 				dmar_rcu_check()) {
2085 		tmp = (struct acpi_dmar_satc *)satcu->hdr;
2086 		if (satc->segment != tmp->segment)
2087 			continue;
2088 		if (satc->header.length != tmp->header.length)
2089 			continue;
2090 		if (memcmp(satc, tmp, satc->header.length) == 0)
2091 			return satcu;
2092 	}
2093 
2094 	return NULL;
2095 }
2096 
2097 int dmar_parse_one_satc(struct acpi_dmar_header *hdr, void *arg)
2098 {
2099 	struct acpi_dmar_satc *satc;
2100 	struct dmar_satc_unit *satcu;
2101 
2102 	if (system_state >= SYSTEM_RUNNING && !intel_iommu_enabled)
2103 		return 0;
2104 
2105 	satc = container_of(hdr, struct acpi_dmar_satc, header);
2106 	satcu = dmar_find_satc(satc);
2107 	if (satcu)
2108 		return 0;
2109 
2110 	satcu = kzalloc(sizeof(*satcu) + hdr->length, GFP_KERNEL);
2111 	if (!satcu)
2112 		return -ENOMEM;
2113 
2114 	satcu->hdr = (void *)(satcu + 1);
2115 	memcpy(satcu->hdr, hdr, hdr->length);
2116 	satcu->atc_required = satc->flags & 0x1;
2117 	satcu->devices = dmar_alloc_dev_scope((void *)(satc + 1),
2118 					      (void *)satc + satc->header.length,
2119 					      &satcu->devices_cnt);
2120 	if (satcu->devices_cnt && !satcu->devices) {
2121 		kfree(satcu);
2122 		return -ENOMEM;
2123 	}
2124 	list_add_rcu(&satcu->list, &dmar_satc_units);
2125 
2126 	return 0;
2127 }
2128 
2129 static int intel_iommu_add(struct dmar_drhd_unit *dmaru)
2130 {
2131 	struct intel_iommu *iommu = dmaru->iommu;
2132 	int ret;
2133 
2134 	/*
2135 	 * Disable translation if already enabled prior to OS handover.
2136 	 */
2137 	if (iommu->gcmd & DMA_GCMD_TE)
2138 		iommu_disable_translation(iommu);
2139 
2140 	ret = iommu_alloc_root_entry(iommu);
2141 	if (ret)
2142 		goto out;
2143 
2144 	intel_svm_check(iommu);
2145 
2146 	if (dmaru->ignored) {
2147 		/*
2148 		 * we always have to disable PMRs or DMA may fail on this device
2149 		 */
2150 		if (dmar_policy_force_on())
2151 			iommu_disable_protect_mem_regions(iommu);
2152 		return 0;
2153 	}
2154 
2155 	intel_iommu_init_qi(iommu);
2156 	iommu_flush_write_buffer(iommu);
2157 
2158 	if (ecap_prs(iommu->ecap)) {
2159 		ret = intel_iommu_enable_prq(iommu);
2160 		if (ret)
2161 			goto disable_iommu;
2162 	}
2163 
2164 	ret = dmar_set_interrupt(iommu);
2165 	if (ret)
2166 		goto disable_iommu;
2167 
2168 	iommu_set_root_entry(iommu);
2169 	iommu_enable_translation(iommu);
2170 
2171 	iommu_disable_protect_mem_regions(iommu);
2172 	return 0;
2173 
2174 disable_iommu:
2175 	disable_dmar_iommu(iommu);
2176 out:
2177 	free_dmar_iommu(iommu);
2178 	return ret;
2179 }
2180 
2181 int dmar_iommu_hotplug(struct dmar_drhd_unit *dmaru, bool insert)
2182 {
2183 	int ret = 0;
2184 	struct intel_iommu *iommu = dmaru->iommu;
2185 
2186 	if (!intel_iommu_enabled)
2187 		return 0;
2188 	if (iommu == NULL)
2189 		return -EINVAL;
2190 
2191 	if (insert) {
2192 		ret = intel_iommu_add(dmaru);
2193 	} else {
2194 		disable_dmar_iommu(iommu);
2195 		free_dmar_iommu(iommu);
2196 	}
2197 
2198 	return ret;
2199 }
2200 
2201 static void intel_iommu_free_dmars(void)
2202 {
2203 	struct dmar_rmrr_unit *rmrru, *rmrr_n;
2204 	struct dmar_atsr_unit *atsru, *atsr_n;
2205 	struct dmar_satc_unit *satcu, *satc_n;
2206 
2207 	list_for_each_entry_safe(rmrru, rmrr_n, &dmar_rmrr_units, list) {
2208 		list_del(&rmrru->list);
2209 		dmar_free_dev_scope(&rmrru->devices, &rmrru->devices_cnt);
2210 		kfree(rmrru);
2211 	}
2212 
2213 	list_for_each_entry_safe(atsru, atsr_n, &dmar_atsr_units, list) {
2214 		list_del(&atsru->list);
2215 		intel_iommu_free_atsr(atsru);
2216 	}
2217 	list_for_each_entry_safe(satcu, satc_n, &dmar_satc_units, list) {
2218 		list_del(&satcu->list);
2219 		dmar_free_dev_scope(&satcu->devices, &satcu->devices_cnt);
2220 		kfree(satcu);
2221 	}
2222 }
2223 
2224 static struct dmar_satc_unit *dmar_find_matched_satc_unit(struct pci_dev *dev)
2225 {
2226 	struct dmar_satc_unit *satcu;
2227 	struct acpi_dmar_satc *satc;
2228 	struct device *tmp;
2229 	int i;
2230 
2231 	rcu_read_lock();
2232 
2233 	list_for_each_entry_rcu(satcu, &dmar_satc_units, list) {
2234 		satc = container_of(satcu->hdr, struct acpi_dmar_satc, header);
2235 		if (satc->segment != pci_domain_nr(dev->bus))
2236 			continue;
2237 		for_each_dev_scope(satcu->devices, satcu->devices_cnt, i, tmp)
2238 			if (to_pci_dev(tmp) == dev)
2239 				goto out;
2240 	}
2241 	satcu = NULL;
2242 out:
2243 	rcu_read_unlock();
2244 	return satcu;
2245 }
2246 
2247 static bool dmar_ats_supported(struct pci_dev *dev, struct intel_iommu *iommu)
2248 {
2249 	struct pci_dev *bridge = NULL;
2250 	struct dmar_atsr_unit *atsru;
2251 	struct dmar_satc_unit *satcu;
2252 	struct acpi_dmar_atsr *atsr;
2253 	bool supported = true;
2254 	struct pci_bus *bus;
2255 	struct device *tmp;
2256 	int i;
2257 
2258 	dev = pci_physfn(dev);
2259 	satcu = dmar_find_matched_satc_unit(dev);
2260 	if (satcu)
2261 		/*
2262 		 * This device supports ATS as it is in SATC table.
2263 		 * When IOMMU is in legacy mode, enabling ATS is done
2264 		 * automatically by HW for the device that requires
2265 		 * ATS, hence OS should not enable this device ATS
2266 		 * to avoid duplicated TLB invalidation.
2267 		 */
2268 		return !(satcu->atc_required && !sm_supported(iommu));
2269 
2270 	for (bus = dev->bus; bus; bus = bus->parent) {
2271 		bridge = bus->self;
2272 		/* If it's an integrated device, allow ATS */
2273 		if (!bridge)
2274 			return true;
2275 		/* Connected via non-PCIe: no ATS */
2276 		if (!pci_is_pcie(bridge) ||
2277 		    pci_pcie_type(bridge) == PCI_EXP_TYPE_PCI_BRIDGE)
2278 			return false;
2279 		/* If we found the root port, look it up in the ATSR */
2280 		if (pci_pcie_type(bridge) == PCI_EXP_TYPE_ROOT_PORT)
2281 			break;
2282 	}
2283 
2284 	rcu_read_lock();
2285 	list_for_each_entry_rcu(atsru, &dmar_atsr_units, list) {
2286 		atsr = container_of(atsru->hdr, struct acpi_dmar_atsr, header);
2287 		if (atsr->segment != pci_domain_nr(dev->bus))
2288 			continue;
2289 
2290 		for_each_dev_scope(atsru->devices, atsru->devices_cnt, i, tmp)
2291 			if (tmp == &bridge->dev)
2292 				goto out;
2293 
2294 		if (atsru->include_all)
2295 			goto out;
2296 	}
2297 	supported = false;
2298 out:
2299 	rcu_read_unlock();
2300 
2301 	return supported;
2302 }
2303 
2304 int dmar_iommu_notify_scope_dev(struct dmar_pci_notify_info *info)
2305 {
2306 	int ret;
2307 	struct dmar_rmrr_unit *rmrru;
2308 	struct dmar_atsr_unit *atsru;
2309 	struct dmar_satc_unit *satcu;
2310 	struct acpi_dmar_atsr *atsr;
2311 	struct acpi_dmar_reserved_memory *rmrr;
2312 	struct acpi_dmar_satc *satc;
2313 
2314 	if (!intel_iommu_enabled && system_state >= SYSTEM_RUNNING)
2315 		return 0;
2316 
2317 	list_for_each_entry(rmrru, &dmar_rmrr_units, list) {
2318 		rmrr = container_of(rmrru->hdr,
2319 				    struct acpi_dmar_reserved_memory, header);
2320 		if (info->event == BUS_NOTIFY_ADD_DEVICE) {
2321 			ret = dmar_insert_dev_scope(info, (void *)(rmrr + 1),
2322 				((void *)rmrr) + rmrr->header.length,
2323 				rmrr->segment, rmrru->devices,
2324 				rmrru->devices_cnt);
2325 			if (ret < 0)
2326 				return ret;
2327 		} else if (info->event == BUS_NOTIFY_REMOVED_DEVICE) {
2328 			dmar_remove_dev_scope(info, rmrr->segment,
2329 				rmrru->devices, rmrru->devices_cnt);
2330 		}
2331 	}
2332 
2333 	list_for_each_entry(atsru, &dmar_atsr_units, list) {
2334 		if (atsru->include_all)
2335 			continue;
2336 
2337 		atsr = container_of(atsru->hdr, struct acpi_dmar_atsr, header);
2338 		if (info->event == BUS_NOTIFY_ADD_DEVICE) {
2339 			ret = dmar_insert_dev_scope(info, (void *)(atsr + 1),
2340 					(void *)atsr + atsr->header.length,
2341 					atsr->segment, atsru->devices,
2342 					atsru->devices_cnt);
2343 			if (ret > 0)
2344 				break;
2345 			else if (ret < 0)
2346 				return ret;
2347 		} else if (info->event == BUS_NOTIFY_REMOVED_DEVICE) {
2348 			if (dmar_remove_dev_scope(info, atsr->segment,
2349 					atsru->devices, atsru->devices_cnt))
2350 				break;
2351 		}
2352 	}
2353 	list_for_each_entry(satcu, &dmar_satc_units, list) {
2354 		satc = container_of(satcu->hdr, struct acpi_dmar_satc, header);
2355 		if (info->event == BUS_NOTIFY_ADD_DEVICE) {
2356 			ret = dmar_insert_dev_scope(info, (void *)(satc + 1),
2357 					(void *)satc + satc->header.length,
2358 					satc->segment, satcu->devices,
2359 					satcu->devices_cnt);
2360 			if (ret > 0)
2361 				break;
2362 			else if (ret < 0)
2363 				return ret;
2364 		} else if (info->event == BUS_NOTIFY_REMOVED_DEVICE) {
2365 			if (dmar_remove_dev_scope(info, satc->segment,
2366 					satcu->devices, satcu->devices_cnt))
2367 				break;
2368 		}
2369 	}
2370 
2371 	return 0;
2372 }
2373 
2374 static void intel_disable_iommus(void)
2375 {
2376 	struct intel_iommu *iommu = NULL;
2377 	struct dmar_drhd_unit *drhd;
2378 
2379 	for_each_iommu(iommu, drhd)
2380 		iommu_disable_translation(iommu);
2381 }
2382 
2383 void intel_iommu_shutdown(void)
2384 {
2385 	struct dmar_drhd_unit *drhd;
2386 	struct intel_iommu *iommu = NULL;
2387 
2388 	if (dmar_policy_off())
2389 		return;
2390 
2391 	/*
2392 	 * All other CPUs were brought down, hotplug interrupts were disabled,
2393 	 * no lock and RCU checking needed anymore
2394 	 */
2395 	list_for_each_entry(drhd, &dmar_drhd_units, list) {
2396 		iommu = drhd->iommu;
2397 
2398 		/* Disable PMRs explicitly here. */
2399 		iommu_disable_protect_mem_regions(iommu);
2400 
2401 		/* Make sure the IOMMUs are switched off */
2402 		iommu_disable_translation(iommu);
2403 	}
2404 }
2405 
2406 static struct intel_iommu *dev_to_intel_iommu(struct device *dev)
2407 {
2408 	struct iommu_device *iommu_dev = dev_to_iommu_device(dev);
2409 
2410 	return container_of(iommu_dev, struct intel_iommu, iommu);
2411 }
2412 
2413 static ssize_t version_show(struct device *dev,
2414 			    struct device_attribute *attr, char *buf)
2415 {
2416 	struct intel_iommu *iommu = dev_to_intel_iommu(dev);
2417 	u32 ver = readl(iommu->reg + DMAR_VER_REG);
2418 	return sysfs_emit(buf, "%d:%d\n",
2419 			  DMAR_VER_MAJOR(ver), DMAR_VER_MINOR(ver));
2420 }
2421 static DEVICE_ATTR_RO(version);
2422 
2423 static ssize_t address_show(struct device *dev,
2424 			    struct device_attribute *attr, char *buf)
2425 {
2426 	struct intel_iommu *iommu = dev_to_intel_iommu(dev);
2427 	return sysfs_emit(buf, "%llx\n", iommu->reg_phys);
2428 }
2429 static DEVICE_ATTR_RO(address);
2430 
2431 static ssize_t cap_show(struct device *dev,
2432 			struct device_attribute *attr, char *buf)
2433 {
2434 	struct intel_iommu *iommu = dev_to_intel_iommu(dev);
2435 	return sysfs_emit(buf, "%llx\n", iommu->cap);
2436 }
2437 static DEVICE_ATTR_RO(cap);
2438 
2439 static ssize_t ecap_show(struct device *dev,
2440 			 struct device_attribute *attr, char *buf)
2441 {
2442 	struct intel_iommu *iommu = dev_to_intel_iommu(dev);
2443 	return sysfs_emit(buf, "%llx\n", iommu->ecap);
2444 }
2445 static DEVICE_ATTR_RO(ecap);
2446 
2447 static ssize_t domains_supported_show(struct device *dev,
2448 				      struct device_attribute *attr, char *buf)
2449 {
2450 	struct intel_iommu *iommu = dev_to_intel_iommu(dev);
2451 	return sysfs_emit(buf, "%ld\n", iommu->max_domain_id);
2452 }
2453 static DEVICE_ATTR_RO(domains_supported);
2454 
2455 static ssize_t domains_used_show(struct device *dev,
2456 				 struct device_attribute *attr, char *buf)
2457 {
2458 	struct intel_iommu *iommu = dev_to_intel_iommu(dev);
2459 	unsigned int count = 0;
2460 	int id;
2461 
2462 	for (id = 0; id < iommu->max_domain_id; id++)
2463 		if (ida_exists(&iommu->domain_ida, id))
2464 			count++;
2465 
2466 	return sysfs_emit(buf, "%d\n", count);
2467 }
2468 static DEVICE_ATTR_RO(domains_used);
2469 
2470 static struct attribute *intel_iommu_attrs[] = {
2471 	&dev_attr_version.attr,
2472 	&dev_attr_address.attr,
2473 	&dev_attr_cap.attr,
2474 	&dev_attr_ecap.attr,
2475 	&dev_attr_domains_supported.attr,
2476 	&dev_attr_domains_used.attr,
2477 	NULL,
2478 };
2479 
2480 static struct attribute_group intel_iommu_group = {
2481 	.name = "intel-iommu",
2482 	.attrs = intel_iommu_attrs,
2483 };
2484 
2485 const struct attribute_group *intel_iommu_groups[] = {
2486 	&intel_iommu_group,
2487 	NULL,
2488 };
2489 
2490 static bool has_external_pci(void)
2491 {
2492 	struct pci_dev *pdev = NULL;
2493 
2494 	for_each_pci_dev(pdev)
2495 		if (pdev->external_facing) {
2496 			pci_dev_put(pdev);
2497 			return true;
2498 		}
2499 
2500 	return false;
2501 }
2502 
2503 static void __init platform_optin_force_iommu(void)
2504 {
2505 	if (!dmar_platform_optin() || !dmar_can_force_on(DMAR_FORCEON_PLATFORM))
2506 		return;
2507 
2508 	if (!has_external_pci())
2509 		return;
2510 
2511 	/*
2512 	 * If Intel-IOMMU is disabled by default, we will apply identity
2513 	 * map for all devices except those marked as being untrusted.
2514 	 */
2515 	if (dmar_policy_off()) {
2516 		pr_info("Intel-IOMMU force enabled due to platform opt in\n");
2517 		iommu_set_default_passthrough(false);
2518 	}
2519 
2520 	/* No concurrent access to dmar_policy at this point. */
2521 	dmar_policy = DMAR_FORCE_ON;
2522 }
2523 
2524 static int __init probe_acpi_namespace_devices(void)
2525 {
2526 	struct dmar_drhd_unit *drhd;
2527 	/* To avoid a -Wunused-but-set-variable warning. */
2528 	struct intel_iommu *iommu __maybe_unused;
2529 	struct device *dev;
2530 	int i, ret = 0;
2531 
2532 	for_each_active_iommu(iommu, drhd) {
2533 		for_each_active_dev_scope(drhd->devices,
2534 					  drhd->devices_cnt, i, dev) {
2535 			struct acpi_device_physical_node *pn;
2536 			struct acpi_device *adev;
2537 
2538 			if (dev->bus != &acpi_bus_type)
2539 				continue;
2540 
2541 			up_read(&dmar_global_lock);
2542 			adev = to_acpi_device(dev);
2543 			mutex_lock(&adev->physical_node_lock);
2544 			list_for_each_entry(pn,
2545 					    &adev->physical_node_list, node) {
2546 				ret = iommu_probe_device(pn->dev);
2547 				if (ret)
2548 					break;
2549 			}
2550 			mutex_unlock(&adev->physical_node_lock);
2551 			down_read(&dmar_global_lock);
2552 
2553 			if (ret)
2554 				return ret;
2555 		}
2556 	}
2557 
2558 	return 0;
2559 }
2560 
2561 static __init void tboot_force_iommu(void)
2562 {
2563 	if (!tboot_enabled() || intel_iommu_tboot_noforce)
2564 		return;
2565 
2566 	if (!dmar_can_force_on(DMAR_FORCEON_TBOOT))
2567 		panic("tboot: Failed to force IOMMU on\n");
2568 
2569 	if (dmar_policy_off())
2570 		pr_warn("Forcing Intel-IOMMU to enabled\n");
2571 
2572 	/* No concurrent access to dmar_policy at this point. */
2573 	dmar_policy = DMAR_FORCE_ON;
2574 	no_iommu = 0;
2575 }
2576 
2577 int __init intel_iommu_init(void)
2578 {
2579 	int ret = -ENODEV;
2580 	struct dmar_drhd_unit *drhd;
2581 	struct intel_iommu *iommu;
2582 
2583 	/*
2584 	 * Intel IOMMU is required for a TXT/tboot launch or platform
2585 	 * opt in, so enforce that.
2586 	 */
2587 	tboot_force_iommu();
2588 	if (!dmar_policy_force_on())
2589 		platform_optin_force_iommu();
2590 
2591 	down_write(&dmar_global_lock);
2592 	if (dmar_table_init()) {
2593 		if (dmar_policy_force_on())
2594 			panic("tboot: Failed to initialize DMAR table\n");
2595 		goto out_free_dmar;
2596 	}
2597 
2598 	if (dmar_dev_scope_init() < 0) {
2599 		if (dmar_policy_force_on())
2600 			panic("tboot: Failed to initialize DMAR device scope\n");
2601 		goto out_free_dmar;
2602 	}
2603 
2604 	up_write(&dmar_global_lock);
2605 
2606 	/*
2607 	 * The bus notifier takes the dmar_global_lock, so lockdep will
2608 	 * complain later when we register it under the lock.
2609 	 */
2610 	dmar_register_bus_notifier();
2611 
2612 	down_write(&dmar_global_lock);
2613 
2614 	if (!no_iommu)
2615 		intel_iommu_debugfs_init();
2616 
2617 	if (dmar_policy_off()) {
2618 		/*
2619 		 * We exit the function here to ensure IOMMU's remapping and
2620 		 * mempool aren't setup, which means that the IOMMU's PMRs
2621 		 * won't be disabled via the call to init_dmars(). So disable
2622 		 * it explicitly here. The PMRs were setup by tboot prior to
2623 		 * calling SENTER, but the kernel is expected to reset/tear
2624 		 * down the PMRs.
2625 		 */
2626 		if (intel_iommu_tboot_noforce) {
2627 			for_each_iommu(iommu, drhd)
2628 				iommu_disable_protect_mem_regions(iommu);
2629 		}
2630 
2631 		/*
2632 		 * Make sure the IOMMUs are switched off, even when we
2633 		 * boot into a kexec kernel and the previous kernel left
2634 		 * them enabled
2635 		 */
2636 		intel_disable_iommus();
2637 		goto out_free_dmar;
2638 	}
2639 
2640 	if (list_empty(&dmar_rmrr_units))
2641 		pr_info("No RMRR found\n");
2642 
2643 	if (list_empty(&dmar_atsr_units))
2644 		pr_info("No ATSR found\n");
2645 
2646 	if (list_empty(&dmar_satc_units))
2647 		pr_info("No SATC found\n");
2648 
2649 	init_no_remapping_devices();
2650 
2651 	ret = init_dmars();
2652 	if (ret) {
2653 		if (dmar_policy_force_on())
2654 			panic("tboot: Failed to initialize DMARs\n");
2655 		pr_err("Initialization failed\n");
2656 		goto out_free_dmar;
2657 	}
2658 	up_write(&dmar_global_lock);
2659 
2660 	init_iommu_pm_ops();
2661 
2662 	down_read(&dmar_global_lock);
2663 	for_each_active_iommu(iommu, drhd) {
2664 		/*
2665 		 * The flush queue implementation does not perform
2666 		 * page-selective invalidations that are required for efficient
2667 		 * TLB flushes in virtual environments.  The benefit of batching
2668 		 * is likely to be much lower than the overhead of synchronizing
2669 		 * the virtual and physical IOMMU page-tables.
2670 		 */
2671 		if (cap_caching_mode(iommu->cap) &&
2672 		    !first_level_by_default(iommu)) {
2673 			pr_info_once("IOMMU batching disallowed due to virtualization\n");
2674 			iommu_set_dma_strict();
2675 		}
2676 		iommu_device_sysfs_add(&iommu->iommu, NULL,
2677 				       intel_iommu_groups,
2678 				       "%s", iommu->name);
2679 		/*
2680 		 * The iommu device probe is protected by the iommu_probe_device_lock.
2681 		 * Release the dmar_global_lock before entering the device probe path
2682 		 * to avoid unnecessary lock order splat.
2683 		 */
2684 		up_read(&dmar_global_lock);
2685 		iommu_device_register(&iommu->iommu, &intel_iommu_ops, NULL);
2686 		down_read(&dmar_global_lock);
2687 
2688 		iommu_pmu_register(iommu);
2689 	}
2690 
2691 	if (probe_acpi_namespace_devices())
2692 		pr_warn("ACPI name space devices didn't probe correctly\n");
2693 
2694 	/* Finally, we enable the DMA remapping hardware. */
2695 	for_each_iommu(iommu, drhd) {
2696 		if (!drhd->ignored && !translation_pre_enabled(iommu))
2697 			iommu_enable_translation(iommu);
2698 
2699 		iommu_disable_protect_mem_regions(iommu);
2700 	}
2701 	up_read(&dmar_global_lock);
2702 
2703 	pr_info("Intel(R) Virtualization Technology for Directed I/O\n");
2704 
2705 	intel_iommu_enabled = 1;
2706 
2707 	return 0;
2708 
2709 out_free_dmar:
2710 	intel_iommu_free_dmars();
2711 	up_write(&dmar_global_lock);
2712 	return ret;
2713 }
2714 
2715 static int domain_context_clear_one_cb(struct pci_dev *pdev, u16 alias, void *opaque)
2716 {
2717 	struct device_domain_info *info = opaque;
2718 
2719 	domain_context_clear_one(info, PCI_BUS_NUM(alias), alias & 0xff);
2720 	return 0;
2721 }
2722 
2723 /*
2724  * NB - intel-iommu lacks any sort of reference counting for the users of
2725  * dependent devices.  If multiple endpoints have intersecting dependent
2726  * devices, unbinding the driver from any one of them will possibly leave
2727  * the others unable to operate.
2728  */
2729 static void domain_context_clear(struct device_domain_info *info)
2730 {
2731 	if (!dev_is_pci(info->dev)) {
2732 		domain_context_clear_one(info, info->bus, info->devfn);
2733 		return;
2734 	}
2735 
2736 	pci_for_each_dma_alias(to_pci_dev(info->dev),
2737 			       &domain_context_clear_one_cb, info);
2738 	iommu_disable_pci_ats(info);
2739 }
2740 
2741 /*
2742  * Clear the page table pointer in context or pasid table entries so that
2743  * all DMA requests without PASID from the device are blocked. If the page
2744  * table has been set, clean up the data structures.
2745  */
2746 void device_block_translation(struct device *dev)
2747 {
2748 	struct device_domain_info *info = dev_iommu_priv_get(dev);
2749 	struct intel_iommu *iommu = info->iommu;
2750 	unsigned long flags;
2751 
2752 	/* Device in DMA blocking state. Noting to do. */
2753 	if (!info->domain_attached)
2754 		return;
2755 
2756 	if (info->domain)
2757 		cache_tag_unassign_domain(info->domain, dev, IOMMU_NO_PASID);
2758 
2759 	if (!dev_is_real_dma_subdevice(dev)) {
2760 		if (sm_supported(iommu))
2761 			intel_pasid_tear_down_entry(iommu, dev,
2762 						    IOMMU_NO_PASID, false);
2763 		else
2764 			domain_context_clear(info);
2765 	}
2766 
2767 	/* Device now in DMA blocking state. */
2768 	info->domain_attached = false;
2769 
2770 	if (!info->domain)
2771 		return;
2772 
2773 	spin_lock_irqsave(&info->domain->lock, flags);
2774 	list_del(&info->link);
2775 	spin_unlock_irqrestore(&info->domain->lock, flags);
2776 
2777 	domain_detach_iommu(info->domain, iommu);
2778 	info->domain = NULL;
2779 }
2780 
2781 static int blocking_domain_attach_dev(struct iommu_domain *domain,
2782 				      struct device *dev,
2783 				      struct iommu_domain *old)
2784 {
2785 	struct device_domain_info *info = dev_iommu_priv_get(dev);
2786 
2787 	iopf_for_domain_remove(info->domain ? &info->domain->domain : NULL, dev);
2788 	device_block_translation(dev);
2789 	return 0;
2790 }
2791 
2792 static int blocking_domain_set_dev_pasid(struct iommu_domain *domain,
2793 					 struct device *dev, ioasid_t pasid,
2794 					 struct iommu_domain *old);
2795 
2796 static struct iommu_domain blocking_domain = {
2797 	.type = IOMMU_DOMAIN_BLOCKED,
2798 	.ops = &(const struct iommu_domain_ops) {
2799 		.attach_dev	= blocking_domain_attach_dev,
2800 		.set_dev_pasid	= blocking_domain_set_dev_pasid,
2801 	}
2802 };
2803 
2804 static struct dmar_domain *paging_domain_alloc(void)
2805 {
2806 	struct dmar_domain *domain;
2807 
2808 	domain = kzalloc_obj(*domain);
2809 	if (!domain)
2810 		return ERR_PTR(-ENOMEM);
2811 
2812 	INIT_LIST_HEAD(&domain->devices);
2813 	INIT_LIST_HEAD(&domain->dev_pasids);
2814 	INIT_LIST_HEAD(&domain->cache_tags);
2815 	spin_lock_init(&domain->lock);
2816 	spin_lock_init(&domain->cache_lock);
2817 	xa_init(&domain->iommu_array);
2818 	INIT_LIST_HEAD(&domain->s1_domains);
2819 	spin_lock_init(&domain->s1_lock);
2820 
2821 	return domain;
2822 }
2823 
2824 static unsigned int compute_vasz_lg2_fs(struct intel_iommu *iommu,
2825 					unsigned int *top_level)
2826 {
2827 	unsigned int mgaw = cap_mgaw(iommu->cap);
2828 
2829 	/*
2830 	 * Spec 3.6 First-Stage Translation:
2831 	 *
2832 	 * Software must limit addresses to less than the minimum of MGAW
2833 	 * and the lower canonical address width implied by FSPM (i.e.,
2834 	 * 47-bit when FSPM is 4-level and 56-bit when FSPM is 5-level).
2835 	 */
2836 	if (mgaw > 48 && cap_fl5lp_support(iommu->cap)) {
2837 		*top_level = 4;
2838 		return min(57, mgaw);
2839 	}
2840 
2841 	/* Four level is always supported */
2842 	*top_level = 3;
2843 	return min(48, mgaw);
2844 }
2845 
2846 static struct iommu_domain *
2847 intel_iommu_domain_alloc_first_stage(struct device *dev,
2848 				     struct intel_iommu *iommu, u32 flags)
2849 {
2850 	struct pt_iommu_x86_64_cfg cfg = {};
2851 	struct dmar_domain *dmar_domain;
2852 	int ret;
2853 
2854 	if (flags & ~IOMMU_HWPT_ALLOC_PASID)
2855 		return ERR_PTR(-EOPNOTSUPP);
2856 
2857 	/* Only SL is available in legacy mode */
2858 	if (!sm_supported(iommu) || !ecap_flts(iommu->ecap))
2859 		return ERR_PTR(-EOPNOTSUPP);
2860 
2861 	dmar_domain = paging_domain_alloc();
2862 	if (IS_ERR(dmar_domain))
2863 		return ERR_CAST(dmar_domain);
2864 
2865 	cfg.common.hw_max_vasz_lg2 =
2866 		compute_vasz_lg2_fs(iommu, &cfg.top_level);
2867 	cfg.common.hw_max_oasz_lg2 = 52;
2868 	cfg.common.features = BIT(PT_FEAT_SIGN_EXTEND) |
2869 			      BIT(PT_FEAT_FLUSH_RANGE);
2870 	/* First stage always uses scalable mode */
2871 	if (!ecap_smpwc(iommu->ecap))
2872 		cfg.common.features |= BIT(PT_FEAT_DMA_INCOHERENT);
2873 	dmar_domain->iommu.iommu_device = dev;
2874 	dmar_domain->iommu.nid = dev_to_node(dev);
2875 	dmar_domain->domain.ops = &intel_fs_paging_domain_ops;
2876 	/*
2877 	 * iotlb sync for map is only needed for legacy implementations that
2878 	 * explicitly require flushing internal write buffers to ensure memory
2879 	 * coherence.
2880 	 */
2881 	if (rwbf_required(iommu))
2882 		dmar_domain->iotlb_sync_map = true;
2883 
2884 	ret = pt_iommu_x86_64_init(&dmar_domain->fspt, &cfg, GFP_KERNEL);
2885 	if (ret) {
2886 		kfree(dmar_domain);
2887 		return ERR_PTR(ret);
2888 	}
2889 
2890 	if (!cap_fl1gp_support(iommu->cap))
2891 		dmar_domain->domain.pgsize_bitmap &= ~(u64)SZ_1G;
2892 	if (!intel_iommu_superpage)
2893 		dmar_domain->domain.pgsize_bitmap = SZ_4K;
2894 
2895 	return &dmar_domain->domain;
2896 }
2897 
2898 static unsigned int compute_vasz_lg2_ss(struct intel_iommu *iommu,
2899 					unsigned int *top_level)
2900 {
2901 	unsigned int sagaw = cap_sagaw(iommu->cap);
2902 	unsigned int mgaw = cap_mgaw(iommu->cap);
2903 
2904 	/*
2905 	 * Find the largest table size that both the mgaw and sagaw support.
2906 	 * This sets the valid range of IOVA and the top starting level.
2907 	 * Some HW may only support a 4 or 5 level walk but must limit IOVA to
2908 	 * 3 levels.
2909 	 */
2910 	if (mgaw > 48 && sagaw >= BIT(3)) {
2911 		*top_level = 4;
2912 		return min(57, mgaw);
2913 	} else if (mgaw > 39 && sagaw >= BIT(2)) {
2914 		*top_level = 3 + ffs(sagaw >> 3);
2915 		return min(48, mgaw);
2916 	} else if (mgaw > 30 && sagaw >= BIT(1)) {
2917 		*top_level = 2 + ffs(sagaw >> 2);
2918 		return min(39, mgaw);
2919 	}
2920 	return 0;
2921 }
2922 
2923 static const struct iommu_dirty_ops intel_second_stage_dirty_ops = {
2924 	IOMMU_PT_DIRTY_OPS(vtdss),
2925 	.set_dirty_tracking = intel_iommu_set_dirty_tracking,
2926 };
2927 
2928 static struct iommu_domain *
2929 intel_iommu_domain_alloc_second_stage(struct device *dev,
2930 				      struct intel_iommu *iommu, u32 flags)
2931 {
2932 	struct pt_iommu_vtdss_cfg cfg = {};
2933 	struct dmar_domain *dmar_domain;
2934 	unsigned int sslps;
2935 	int ret;
2936 
2937 	if (flags &
2938 	    (~(IOMMU_HWPT_ALLOC_NEST_PARENT | IOMMU_HWPT_ALLOC_DIRTY_TRACKING |
2939 	       IOMMU_HWPT_ALLOC_PASID)))
2940 		return ERR_PTR(-EOPNOTSUPP);
2941 
2942 	if (((flags & IOMMU_HWPT_ALLOC_NEST_PARENT) &&
2943 	     !nested_supported(iommu)) ||
2944 	    ((flags & IOMMU_HWPT_ALLOC_DIRTY_TRACKING) &&
2945 	     !ssads_supported(iommu)))
2946 		return ERR_PTR(-EOPNOTSUPP);
2947 
2948 	/* Legacy mode always supports second stage */
2949 	if (sm_supported(iommu) && !ecap_slts(iommu->ecap))
2950 		return ERR_PTR(-EOPNOTSUPP);
2951 
2952 	dmar_domain = paging_domain_alloc();
2953 	if (IS_ERR(dmar_domain))
2954 		return ERR_CAST(dmar_domain);
2955 
2956 	cfg.common.hw_max_vasz_lg2 = compute_vasz_lg2_ss(iommu, &cfg.top_level);
2957 	cfg.common.hw_max_oasz_lg2 = 52;
2958 	cfg.common.features = BIT(PT_FEAT_FLUSH_RANGE);
2959 
2960 	/*
2961 	 * Read-only mapping is disallowed on the domain which serves as the
2962 	 * parent in a nested configuration, due to HW errata
2963 	 * (ERRATA_772415_SPR17)
2964 	 */
2965 	if (flags & IOMMU_HWPT_ALLOC_NEST_PARENT)
2966 		cfg.common.features |= BIT(PT_FEAT_VTDSS_FORCE_WRITEABLE);
2967 
2968 	if (!iommu_paging_structure_coherency(iommu))
2969 		cfg.common.features |= BIT(PT_FEAT_DMA_INCOHERENT);
2970 	dmar_domain->iommu.iommu_device = dev;
2971 	dmar_domain->iommu.nid = dev_to_node(dev);
2972 	dmar_domain->domain.ops = &intel_ss_paging_domain_ops;
2973 	dmar_domain->nested_parent = flags & IOMMU_HWPT_ALLOC_NEST_PARENT;
2974 
2975 	if (flags & IOMMU_HWPT_ALLOC_DIRTY_TRACKING)
2976 		dmar_domain->domain.dirty_ops = &intel_second_stage_dirty_ops;
2977 
2978 	ret = pt_iommu_vtdss_init(&dmar_domain->sspt, &cfg, GFP_KERNEL);
2979 	if (ret) {
2980 		kfree(dmar_domain);
2981 		return ERR_PTR(ret);
2982 	}
2983 
2984 	/* Adjust the supported page sizes to HW capability */
2985 	sslps = cap_super_page_val(iommu->cap);
2986 	if (!(sslps & BIT(0)))
2987 		dmar_domain->domain.pgsize_bitmap &= ~(u64)SZ_2M;
2988 	if (!(sslps & BIT(1)))
2989 		dmar_domain->domain.pgsize_bitmap &= ~(u64)SZ_1G;
2990 	if (!intel_iommu_superpage)
2991 		dmar_domain->domain.pgsize_bitmap = SZ_4K;
2992 
2993 	/*
2994 	 * Besides the internal write buffer flush, the caching mode used for
2995 	 * legacy nested translation (which utilizes shadowing page tables)
2996 	 * also requires iotlb sync on map.
2997 	 */
2998 	if (rwbf_required(iommu) || cap_caching_mode(iommu->cap))
2999 		dmar_domain->iotlb_sync_map = true;
3000 
3001 	return &dmar_domain->domain;
3002 }
3003 
3004 static struct iommu_domain *
3005 intel_iommu_domain_alloc_paging_flags(struct device *dev, u32 flags,
3006 				      const struct iommu_user_data *user_data)
3007 {
3008 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3009 	struct intel_iommu *iommu = info->iommu;
3010 	struct iommu_domain *domain;
3011 
3012 	if (user_data)
3013 		return ERR_PTR(-EOPNOTSUPP);
3014 
3015 	/* Prefer first stage if possible by default. */
3016 	domain = intel_iommu_domain_alloc_first_stage(dev, iommu, flags);
3017 	if (domain != ERR_PTR(-EOPNOTSUPP))
3018 		return domain;
3019 	return intel_iommu_domain_alloc_second_stage(dev, iommu, flags);
3020 }
3021 
3022 static void intel_iommu_domain_free(struct iommu_domain *domain)
3023 {
3024 	struct dmar_domain *dmar_domain = to_dmar_domain(domain);
3025 
3026 	if (WARN_ON(dmar_domain->nested_parent &&
3027 		    !list_empty(&dmar_domain->s1_domains)))
3028 		return;
3029 
3030 	if (WARN_ON(!list_empty(&dmar_domain->devices)))
3031 		return;
3032 
3033 	pt_iommu_deinit(&dmar_domain->iommu);
3034 
3035 	kfree(dmar_domain->qi_batch);
3036 	kfree(dmar_domain);
3037 }
3038 
3039 static int paging_domain_compatible_first_stage(struct dmar_domain *dmar_domain,
3040 						struct intel_iommu *iommu)
3041 {
3042 	if (WARN_ON(dmar_domain->domain.dirty_ops ||
3043 		    dmar_domain->nested_parent))
3044 		return -EINVAL;
3045 
3046 	/* Only SL is available in legacy mode */
3047 	if (!sm_supported(iommu) || !ecap_flts(iommu->ecap))
3048 		return -EINVAL;
3049 
3050 	if (!ecap_smpwc(iommu->ecap) &&
3051 	    !(dmar_domain->fspt.x86_64_pt.common.features &
3052 	      BIT(PT_FEAT_DMA_INCOHERENT)))
3053 		return -EINVAL;
3054 
3055 	/* Supports the number of table levels */
3056 	if (!cap_fl5lp_support(iommu->cap) &&
3057 	    dmar_domain->fspt.x86_64_pt.common.max_vasz_lg2 > 48)
3058 		return -EINVAL;
3059 
3060 	/* Same page size support */
3061 	if (!cap_fl1gp_support(iommu->cap) &&
3062 	    (dmar_domain->domain.pgsize_bitmap & SZ_1G))
3063 		return -EINVAL;
3064 
3065 	/* iotlb sync on map requirement */
3066 	if ((rwbf_required(iommu)) && !dmar_domain->iotlb_sync_map)
3067 		return -EINVAL;
3068 
3069 	return 0;
3070 }
3071 
3072 static int
3073 paging_domain_compatible_second_stage(struct dmar_domain *dmar_domain,
3074 				      struct intel_iommu *iommu)
3075 {
3076 	unsigned int vasz_lg2 = dmar_domain->sspt.vtdss_pt.common.max_vasz_lg2;
3077 	unsigned int sslps = cap_super_page_val(iommu->cap);
3078 	struct pt_iommu_vtdss_hw_info pt_info;
3079 
3080 	pt_iommu_vtdss_hw_info(&dmar_domain->sspt, &pt_info);
3081 
3082 	if (dmar_domain->domain.dirty_ops && !ssads_supported(iommu))
3083 		return -EINVAL;
3084 	if (dmar_domain->nested_parent && !nested_supported(iommu))
3085 		return -EINVAL;
3086 
3087 	/* Legacy mode always supports second stage */
3088 	if (sm_supported(iommu) && !ecap_slts(iommu->ecap))
3089 		return -EINVAL;
3090 
3091 	if (!iommu_paging_structure_coherency(iommu) &&
3092 	    !(dmar_domain->sspt.vtdss_pt.common.features &
3093 	      BIT(PT_FEAT_DMA_INCOHERENT)))
3094 		return -EINVAL;
3095 
3096 	/* Address width falls within the capability */
3097 	if (cap_mgaw(iommu->cap) < vasz_lg2)
3098 		return -EINVAL;
3099 
3100 	/* Page table level is supported. */
3101 	if (!(cap_sagaw(iommu->cap) & BIT(pt_info.aw)))
3102 		return -EINVAL;
3103 
3104 	/* Same page size support */
3105 	if (!(sslps & BIT(0)) && (dmar_domain->domain.pgsize_bitmap & SZ_2M))
3106 		return -EINVAL;
3107 	if (!(sslps & BIT(1)) && (dmar_domain->domain.pgsize_bitmap & SZ_1G))
3108 		return -EINVAL;
3109 
3110 	/* iotlb sync on map requirement */
3111 	if ((rwbf_required(iommu) || cap_caching_mode(iommu->cap)) &&
3112 	    !dmar_domain->iotlb_sync_map)
3113 		return -EINVAL;
3114 
3115 	/*
3116 	 * FIXME this is locked wrong, it needs to be under the
3117 	 * dmar_domain->lock
3118 	 */
3119 	if ((dmar_domain->sspt.vtdss_pt.common.features &
3120 	     BIT(PT_FEAT_VTDSS_FORCE_COHERENCE)) &&
3121 	    !ecap_sc_support(iommu->ecap))
3122 		return -EINVAL;
3123 	return 0;
3124 }
3125 
3126 int paging_domain_compatible(struct iommu_domain *domain, struct device *dev)
3127 {
3128 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3129 	struct dmar_domain *dmar_domain = to_dmar_domain(domain);
3130 	struct intel_iommu *iommu = info->iommu;
3131 	int ret = -EINVAL;
3132 
3133 	if (intel_domain_is_fs_paging(dmar_domain))
3134 		ret = paging_domain_compatible_first_stage(dmar_domain, iommu);
3135 	else if (intel_domain_is_ss_paging(dmar_domain))
3136 		ret = paging_domain_compatible_second_stage(dmar_domain, iommu);
3137 	else if (WARN_ON(true))
3138 		ret = -EINVAL;
3139 	if (ret)
3140 		return ret;
3141 
3142 	if (sm_supported(iommu) && !dev_is_real_dma_subdevice(dev) &&
3143 	    context_copied(iommu, info->bus, info->devfn))
3144 		return intel_pasid_setup_sm_context(dev);
3145 
3146 	return 0;
3147 }
3148 
3149 static int intel_iommu_attach_device(struct iommu_domain *domain,
3150 				     struct device *dev,
3151 				     struct iommu_domain *old)
3152 {
3153 	int ret;
3154 
3155 	device_block_translation(dev);
3156 
3157 	ret = paging_domain_compatible(domain, dev);
3158 	if (ret)
3159 		return ret;
3160 
3161 	ret = iopf_for_domain_replace(domain, old, dev);
3162 	if (ret)
3163 		return ret;
3164 
3165 	ret = dmar_domain_attach_device(to_dmar_domain(domain), dev);
3166 	if (ret)
3167 		iopf_for_domain_replace(old, domain, dev);
3168 
3169 	return ret;
3170 }
3171 
3172 static void intel_iommu_tlb_sync(struct iommu_domain *domain,
3173 				 struct iommu_iotlb_gather *gather)
3174 {
3175 	cache_tag_flush_range(to_dmar_domain(domain), gather->start,
3176 			      gather->end,
3177 			      iommu_pages_list_empty(&gather->freelist));
3178 	iommu_put_pages_list(&gather->freelist);
3179 }
3180 
3181 static bool domain_support_force_snooping(struct dmar_domain *domain)
3182 {
3183 	struct device_domain_info *info;
3184 	bool support = true;
3185 
3186 	assert_spin_locked(&domain->lock);
3187 	list_for_each_entry(info, &domain->devices, link) {
3188 		if (!ecap_sc_support(info->iommu->ecap)) {
3189 			support = false;
3190 			break;
3191 		}
3192 	}
3193 
3194 	return support;
3195 }
3196 
3197 static bool intel_iommu_enforce_cache_coherency_fs(struct iommu_domain *domain)
3198 {
3199 	struct dmar_domain *dmar_domain = to_dmar_domain(domain);
3200 	struct device_domain_info *info;
3201 
3202 	guard(spinlock_irqsave)(&dmar_domain->lock);
3203 
3204 	if (dmar_domain->force_snooping)
3205 		return true;
3206 
3207 	if (!domain_support_force_snooping(dmar_domain))
3208 		return false;
3209 
3210 	dmar_domain->force_snooping = true;
3211 	list_for_each_entry(info, &dmar_domain->devices, link)
3212 		intel_pasid_setup_page_snoop_control(info->iommu, info->dev,
3213 						     IOMMU_NO_PASID);
3214 	return true;
3215 }
3216 
3217 static bool intel_iommu_enforce_cache_coherency_ss(struct iommu_domain *domain)
3218 {
3219 	struct dmar_domain *dmar_domain = to_dmar_domain(domain);
3220 
3221 	guard(spinlock_irqsave)(&dmar_domain->lock);
3222 	if (!domain_support_force_snooping(dmar_domain))
3223 		return false;
3224 
3225 	/*
3226 	 * Second level page table supports per-PTE snoop control. The
3227 	 * iommu_map() interface will handle this by setting SNP bit.
3228 	 */
3229 	dmar_domain->sspt.vtdss_pt.common.features |=
3230 		BIT(PT_FEAT_VTDSS_FORCE_COHERENCE);
3231 	dmar_domain->force_snooping = true;
3232 	return true;
3233 }
3234 
3235 static bool intel_iommu_capable(struct device *dev, enum iommu_cap cap)
3236 {
3237 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3238 
3239 	switch (cap) {
3240 	case IOMMU_CAP_CACHE_COHERENCY:
3241 		return true;
3242 	case IOMMU_CAP_PRE_BOOT_PROTECTION:
3243 		return dmar_platform_optin();
3244 	case IOMMU_CAP_ENFORCE_CACHE_COHERENCY:
3245 		return ecap_sc_support(info->iommu->ecap);
3246 	case IOMMU_CAP_DIRTY_TRACKING:
3247 		return ssads_supported(info->iommu);
3248 	case IOMMU_CAP_PCI_ATS_SUPPORTED:
3249 		return info->ats_supported;
3250 	default:
3251 		return false;
3252 	}
3253 }
3254 
3255 static struct iommu_device *intel_iommu_probe_device(struct device *dev)
3256 {
3257 	struct pci_dev *pdev = dev_is_pci(dev) ? to_pci_dev(dev) : NULL;
3258 	struct device_domain_info *info;
3259 	struct intel_iommu *iommu;
3260 	u8 bus, devfn;
3261 	int ret;
3262 
3263 	iommu = device_lookup_iommu(dev, &bus, &devfn);
3264 	if (!iommu || !iommu->iommu.ops)
3265 		return ERR_PTR(-ENODEV);
3266 
3267 	info = kzalloc_obj(*info);
3268 	if (!info)
3269 		return ERR_PTR(-ENOMEM);
3270 
3271 	if (dev_is_real_dma_subdevice(dev)) {
3272 		info->bus = pdev->bus->number;
3273 		info->devfn = pdev->devfn;
3274 		info->segment = pci_domain_nr(pdev->bus);
3275 	} else {
3276 		info->bus = bus;
3277 		info->devfn = devfn;
3278 		info->segment = iommu->segment;
3279 	}
3280 
3281 	info->dev = dev;
3282 	info->iommu = iommu;
3283 	RB_CLEAR_NODE(&info->node);
3284 	if (dev_is_pci(dev)) {
3285 		if (ecap_dev_iotlb_support(iommu->ecap) &&
3286 		    pci_ats_supported(pdev) &&
3287 		    dmar_ats_supported(pdev, iommu)) {
3288 			info->ats_supported = 1;
3289 			info->dtlb_extra_inval = dev_needs_extra_dtlb_flush(pdev);
3290 
3291 			/*
3292 			 * For IOMMU that supports device IOTLB throttling
3293 			 * (DIT), we assign PFSID to the invalidation desc
3294 			 * of a VF such that IOMMU HW can gauge queue depth
3295 			 * at PF level. If DIT is not set, PFSID will be
3296 			 * treated as reserved, which should be set to 0.
3297 			 */
3298 			if (ecap_dit(iommu->ecap))
3299 				info->pfsid = pci_dev_id(pci_physfn(pdev));
3300 			info->ats_qdep = pci_ats_queue_depth(pdev);
3301 		}
3302 		if (sm_supported(iommu)) {
3303 			if (pasid_supported(iommu)) {
3304 				int features = pci_pasid_features(pdev);
3305 
3306 				if (features >= 0)
3307 					info->pasid_supported = features | 1;
3308 			}
3309 
3310 			if (info->ats_supported && ecap_prs(iommu->ecap) &&
3311 			    ecap_pds(iommu->ecap) && pci_pri_supported(pdev))
3312 				info->pri_supported = 1;
3313 		}
3314 	}
3315 
3316 	dev_iommu_priv_set(dev, info);
3317 	if (pdev && pci_ats_supported(pdev)) {
3318 		ret = pci_prepare_ats(pdev, VTD_PAGE_SHIFT);
3319 		if (ret)
3320 			goto free;
3321 
3322 		ret = device_rbtree_insert(iommu, info);
3323 		if (ret)
3324 			goto free;
3325 	}
3326 
3327 	if (sm_supported(iommu) && !dev_is_real_dma_subdevice(dev)) {
3328 		ret = intel_pasid_alloc_table(dev);
3329 		if (ret) {
3330 			dev_err(dev, "PASID table allocation failed\n");
3331 			goto clear_rbtree;
3332 		}
3333 
3334 		if (!context_copied(iommu, info->bus, info->devfn)) {
3335 			ret = intel_pasid_setup_sm_context(dev);
3336 			if (ret)
3337 				goto free_table;
3338 		}
3339 	}
3340 
3341 	intel_iommu_debugfs_create_dev(info);
3342 
3343 	return &iommu->iommu;
3344 free_table:
3345 	intel_pasid_teardown_sm_context(dev);
3346 	intel_pasid_free_table(dev);
3347 clear_rbtree:
3348 	device_rbtree_remove(info);
3349 free:
3350 	kfree(info);
3351 
3352 	return ERR_PTR(ret);
3353 }
3354 
3355 static void intel_iommu_probe_finalize(struct device *dev)
3356 {
3357 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3358 	struct intel_iommu *iommu = info->iommu;
3359 
3360 	/*
3361 	 * The PCIe spec, in its wisdom, declares that the behaviour of the
3362 	 * device is undefined if you enable PASID support after ATS support.
3363 	 * So always enable PASID support on devices which have it, even if
3364 	 * we can't yet know if we're ever going to use it.
3365 	 */
3366 	if (info->pasid_supported &&
3367 	    !pci_enable_pasid(to_pci_dev(dev), info->pasid_supported & ~1))
3368 		info->pasid_enabled = 1;
3369 
3370 	if (sm_supported(iommu) && !dev_is_real_dma_subdevice(dev)) {
3371 		iommu_enable_pci_ats(info);
3372 		/* Assign a DEVTLB cache tag to the default domain. */
3373 		if (info->ats_enabled && info->domain) {
3374 			u16 did = domain_id_iommu(info->domain, iommu);
3375 
3376 			if (cache_tag_assign(info->domain, did, dev,
3377 					     IOMMU_NO_PASID, CACHE_TAG_DEVTLB))
3378 				iommu_disable_pci_ats(info);
3379 		}
3380 	}
3381 	iommu_enable_pci_pri(info);
3382 }
3383 
3384 static void intel_iommu_release_device(struct device *dev)
3385 {
3386 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3387 	struct intel_iommu *iommu = info->iommu;
3388 
3389 	iommu_disable_pci_pri(info);
3390 	iommu_disable_pci_ats(info);
3391 
3392 	if (info->pasid_enabled) {
3393 		pci_disable_pasid(to_pci_dev(dev));
3394 		info->pasid_enabled = 0;
3395 	}
3396 
3397 	mutex_lock(&iommu->iopf_lock);
3398 	if (dev_is_pci(dev) && pci_ats_supported(to_pci_dev(dev)))
3399 		device_rbtree_remove(info);
3400 	mutex_unlock(&iommu->iopf_lock);
3401 
3402 	if (sm_supported(iommu) && !dev_is_real_dma_subdevice(dev) &&
3403 	    !context_copied(iommu, info->bus, info->devfn))
3404 		intel_pasid_teardown_sm_context(dev);
3405 
3406 	intel_pasid_free_table(dev);
3407 	intel_iommu_debugfs_remove_dev(info);
3408 	kfree(info);
3409 }
3410 
3411 static void intel_iommu_get_resv_regions(struct device *device,
3412 					 struct list_head *head)
3413 {
3414 	int prot = DMA_PTE_READ | DMA_PTE_WRITE;
3415 	struct iommu_resv_region *reg;
3416 	struct dmar_rmrr_unit *rmrr;
3417 	struct device *i_dev;
3418 	int i;
3419 
3420 	rcu_read_lock();
3421 	for_each_rmrr_units(rmrr) {
3422 		for_each_active_dev_scope(rmrr->devices, rmrr->devices_cnt,
3423 					  i, i_dev) {
3424 			struct iommu_resv_region *resv;
3425 			enum iommu_resv_type type;
3426 			size_t length;
3427 
3428 			if (i_dev != device &&
3429 			    !is_downstream_to_pci_bridge(device, i_dev))
3430 				continue;
3431 
3432 			length = rmrr->end_address - rmrr->base_address + 1;
3433 
3434 			type = device_rmrr_is_relaxable(device) ?
3435 				IOMMU_RESV_DIRECT_RELAXABLE : IOMMU_RESV_DIRECT;
3436 
3437 			resv = iommu_alloc_resv_region(rmrr->base_address,
3438 						       length, prot, type,
3439 						       GFP_ATOMIC);
3440 			if (!resv)
3441 				break;
3442 
3443 			list_add_tail(&resv->list, head);
3444 		}
3445 	}
3446 	rcu_read_unlock();
3447 
3448 #ifdef CONFIG_INTEL_IOMMU_FLOPPY_WA
3449 	if (dev_is_pci(device)) {
3450 		struct pci_dev *pdev = to_pci_dev(device);
3451 
3452 		if ((pdev->class >> 8) == PCI_CLASS_BRIDGE_ISA) {
3453 			reg = iommu_alloc_resv_region(0, 1UL << 24, prot,
3454 					IOMMU_RESV_DIRECT_RELAXABLE,
3455 					GFP_KERNEL);
3456 			if (reg)
3457 				list_add_tail(&reg->list, head);
3458 		}
3459 	}
3460 #endif /* CONFIG_INTEL_IOMMU_FLOPPY_WA */
3461 
3462 	reg = iommu_alloc_resv_region(IOAPIC_RANGE_START,
3463 				      IOAPIC_RANGE_END - IOAPIC_RANGE_START + 1,
3464 				      0, IOMMU_RESV_MSI, GFP_KERNEL);
3465 	if (!reg)
3466 		return;
3467 	list_add_tail(&reg->list, head);
3468 }
3469 
3470 static struct iommu_group *intel_iommu_device_group(struct device *dev)
3471 {
3472 	if (dev_is_pci(dev))
3473 		return pci_device_group(dev);
3474 	return generic_device_group(dev);
3475 }
3476 
3477 int intel_iommu_enable_iopf(struct device *dev)
3478 {
3479 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3480 	struct intel_iommu *iommu = info->iommu;
3481 	int ret;
3482 
3483 	if (!info->pri_enabled)
3484 		return -ENODEV;
3485 
3486 	/* pri_enabled is protected by the group mutex. */
3487 	iommu_group_mutex_assert(dev);
3488 	if (info->iopf_refcount) {
3489 		info->iopf_refcount++;
3490 		return 0;
3491 	}
3492 
3493 	ret = iopf_queue_add_device(iommu->iopf_queue, dev);
3494 	if (ret)
3495 		return ret;
3496 
3497 	info->iopf_refcount = 1;
3498 
3499 	return 0;
3500 }
3501 
3502 void intel_iommu_disable_iopf(struct device *dev)
3503 {
3504 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3505 	struct intel_iommu *iommu = info->iommu;
3506 
3507 	if (WARN_ON(!info->pri_enabled || !info->iopf_refcount))
3508 		return;
3509 
3510 	iommu_group_mutex_assert(dev);
3511 	if (--info->iopf_refcount)
3512 		return;
3513 
3514 	iopf_queue_remove_device(iommu->iopf_queue, dev);
3515 }
3516 
3517 static bool intel_iommu_is_attach_deferred(struct device *dev)
3518 {
3519 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3520 
3521 	return translation_pre_enabled(info->iommu) && !info->domain;
3522 }
3523 
3524 /*
3525  * Check that the device does not live on an external facing PCI port that is
3526  * marked as untrusted. Such devices should not be able to apply quirks and
3527  * thus not be able to bypass the IOMMU restrictions.
3528  */
3529 static bool risky_device(struct pci_dev *pdev)
3530 {
3531 	if (pdev->untrusted) {
3532 		pci_info(pdev,
3533 			 "Skipping IOMMU quirk for dev [%04X:%04X] on untrusted PCI link\n",
3534 			 pdev->vendor, pdev->device);
3535 		pci_info(pdev, "Please check with your BIOS/Platform vendor about this\n");
3536 		return true;
3537 	}
3538 	return false;
3539 }
3540 
3541 static int intel_iommu_iotlb_sync_map(struct iommu_domain *domain,
3542 				      unsigned long iova, size_t size)
3543 {
3544 	struct dmar_domain *dmar_domain = to_dmar_domain(domain);
3545 
3546 	if (dmar_domain->iotlb_sync_map)
3547 		cache_tag_flush_range_np(dmar_domain, iova, iova + size - 1);
3548 
3549 	return 0;
3550 }
3551 
3552 void domain_remove_dev_pasid(struct iommu_domain *domain,
3553 			     struct device *dev, ioasid_t pasid)
3554 {
3555 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3556 	struct dev_pasid_info *curr, *dev_pasid = NULL;
3557 	struct intel_iommu *iommu = info->iommu;
3558 	struct dmar_domain *dmar_domain;
3559 	unsigned long flags;
3560 
3561 	if (!domain)
3562 		return;
3563 
3564 	/* Identity domain and blocked domain have no meta data for pasid. */
3565 	if (domain->type == IOMMU_DOMAIN_IDENTITY || domain->type == IOMMU_DOMAIN_BLOCKED)
3566 		return;
3567 
3568 	dmar_domain = to_dmar_domain(domain);
3569 	spin_lock_irqsave(&dmar_domain->lock, flags);
3570 	list_for_each_entry(curr, &dmar_domain->dev_pasids, link_domain) {
3571 		if (curr->dev == dev && curr->pasid == pasid) {
3572 			list_del(&curr->link_domain);
3573 			dev_pasid = curr;
3574 			break;
3575 		}
3576 	}
3577 	spin_unlock_irqrestore(&dmar_domain->lock, flags);
3578 
3579 	if (WARN_ON_ONCE(!dev_pasid))
3580 		return;
3581 
3582 	cache_tag_unassign_domain(dmar_domain, dev, pasid);
3583 	domain_detach_iommu(dmar_domain, iommu);
3584 	intel_iommu_debugfs_remove_dev_pasid(dev_pasid);
3585 	kfree(dev_pasid);
3586 }
3587 
3588 static int blocking_domain_set_dev_pasid(struct iommu_domain *domain,
3589 					 struct device *dev, ioasid_t pasid,
3590 					 struct iommu_domain *old)
3591 {
3592 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3593 
3594 	intel_pasid_tear_down_entry(info->iommu, dev, pasid, false);
3595 	iopf_for_domain_remove(old, dev);
3596 	domain_remove_dev_pasid(old, dev, pasid);
3597 
3598 	return 0;
3599 }
3600 
3601 struct dev_pasid_info *
3602 domain_add_dev_pasid(struct iommu_domain *domain,
3603 		     struct device *dev, ioasid_t pasid)
3604 {
3605 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3606 	struct dmar_domain *dmar_domain = to_dmar_domain(domain);
3607 	struct intel_iommu *iommu = info->iommu;
3608 	struct dev_pasid_info *dev_pasid;
3609 	unsigned long flags;
3610 	int ret;
3611 
3612 	dev_pasid = kzalloc_obj(*dev_pasid);
3613 	if (!dev_pasid)
3614 		return ERR_PTR(-ENOMEM);
3615 
3616 	ret = domain_attach_iommu(dmar_domain, iommu);
3617 	if (ret)
3618 		goto out_free;
3619 
3620 	ret = cache_tag_assign_domain(dmar_domain, dev, pasid);
3621 	if (ret)
3622 		goto out_detach_iommu;
3623 
3624 	dev_pasid->dev = dev;
3625 	dev_pasid->pasid = pasid;
3626 	spin_lock_irqsave(&dmar_domain->lock, flags);
3627 	list_add(&dev_pasid->link_domain, &dmar_domain->dev_pasids);
3628 	spin_unlock_irqrestore(&dmar_domain->lock, flags);
3629 
3630 	return dev_pasid;
3631 out_detach_iommu:
3632 	domain_detach_iommu(dmar_domain, iommu);
3633 out_free:
3634 	kfree(dev_pasid);
3635 	return ERR_PTR(ret);
3636 }
3637 
3638 static int intel_iommu_set_dev_pasid(struct iommu_domain *domain,
3639 				     struct device *dev, ioasid_t pasid,
3640 				     struct iommu_domain *old)
3641 {
3642 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3643 	struct dmar_domain *dmar_domain = to_dmar_domain(domain);
3644 	struct intel_iommu *iommu = info->iommu;
3645 	struct dev_pasid_info *dev_pasid;
3646 	int ret;
3647 
3648 	if (WARN_ON_ONCE(!(domain->type & __IOMMU_DOMAIN_PAGING)))
3649 		return -EINVAL;
3650 
3651 	if (!pasid_supported(iommu) || dev_is_real_dma_subdevice(dev))
3652 		return -EOPNOTSUPP;
3653 
3654 	if (context_copied(iommu, info->bus, info->devfn))
3655 		return -EBUSY;
3656 
3657 	ret = paging_domain_compatible(domain, dev);
3658 	if (ret)
3659 		return ret;
3660 
3661 	dev_pasid = domain_add_dev_pasid(domain, dev, pasid);
3662 	if (IS_ERR(dev_pasid))
3663 		return PTR_ERR(dev_pasid);
3664 
3665 	ret = iopf_for_domain_replace(domain, old, dev);
3666 	if (ret)
3667 		goto out_remove_dev_pasid;
3668 
3669 	if (intel_domain_is_fs_paging(dmar_domain))
3670 		ret = domain_setup_first_level(iommu, dmar_domain,
3671 					       dev, pasid, old);
3672 	else if (intel_domain_is_ss_paging(dmar_domain))
3673 		ret = domain_setup_second_level(iommu, dmar_domain,
3674 						dev, pasid, old);
3675 	else if (WARN_ON(true))
3676 		ret = -EINVAL;
3677 
3678 	if (ret)
3679 		goto out_unwind_iopf;
3680 
3681 	domain_remove_dev_pasid(old, dev, pasid);
3682 
3683 	intel_iommu_debugfs_create_dev_pasid(dev_pasid);
3684 
3685 	return 0;
3686 
3687 out_unwind_iopf:
3688 	iopf_for_domain_replace(old, domain, dev);
3689 out_remove_dev_pasid:
3690 	domain_remove_dev_pasid(domain, dev, pasid);
3691 	return ret;
3692 }
3693 
3694 static void *intel_iommu_hw_info(struct device *dev, u32 *length,
3695 				 enum iommu_hw_info_type *type)
3696 {
3697 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3698 	struct intel_iommu *iommu = info->iommu;
3699 	struct iommu_hw_info_vtd *vtd;
3700 
3701 	if (*type != IOMMU_HW_INFO_TYPE_DEFAULT &&
3702 	    *type != IOMMU_HW_INFO_TYPE_INTEL_VTD)
3703 		return ERR_PTR(-EOPNOTSUPP);
3704 
3705 	vtd = kzalloc_obj(*vtd);
3706 	if (!vtd)
3707 		return ERR_PTR(-ENOMEM);
3708 
3709 	vtd->flags = IOMMU_HW_INFO_VTD_ERRATA_772415_SPR17;
3710 	vtd->cap_reg = iommu->cap;
3711 	vtd->ecap_reg = iommu->ecap;
3712 	*length = sizeof(*vtd);
3713 	*type = IOMMU_HW_INFO_TYPE_INTEL_VTD;
3714 	return vtd;
3715 }
3716 
3717 /* Set dirty tracking for the devices that the domain has been attached. */
3718 static int domain_set_dirty_tracking(struct dmar_domain *domain, bool enable)
3719 {
3720 	struct device_domain_info *info;
3721 	struct dev_pasid_info *dev_pasid;
3722 	int ret = 0;
3723 
3724 	lockdep_assert_held(&domain->lock);
3725 
3726 	list_for_each_entry(info, &domain->devices, link) {
3727 		ret = intel_pasid_setup_dirty_tracking(info->iommu, info->dev,
3728 						       IOMMU_NO_PASID, enable);
3729 		if (ret)
3730 			return ret;
3731 	}
3732 
3733 	list_for_each_entry(dev_pasid, &domain->dev_pasids, link_domain) {
3734 		info = dev_iommu_priv_get(dev_pasid->dev);
3735 		ret = intel_pasid_setup_dirty_tracking(info->iommu, info->dev,
3736 						       dev_pasid->pasid, enable);
3737 		if (ret)
3738 			break;
3739 	}
3740 
3741 	return ret;
3742 }
3743 
3744 static int parent_domain_set_dirty_tracking(struct dmar_domain *domain,
3745 					    bool enable)
3746 {
3747 	struct dmar_domain *s1_domain;
3748 	unsigned long flags;
3749 	int ret;
3750 
3751 	spin_lock(&domain->s1_lock);
3752 	list_for_each_entry(s1_domain, &domain->s1_domains, s2_link) {
3753 		spin_lock_irqsave(&s1_domain->lock, flags);
3754 		ret = domain_set_dirty_tracking(s1_domain, enable);
3755 		spin_unlock_irqrestore(&s1_domain->lock, flags);
3756 		if (ret)
3757 			goto err_unwind;
3758 	}
3759 	spin_unlock(&domain->s1_lock);
3760 	return 0;
3761 
3762 err_unwind:
3763 	list_for_each_entry(s1_domain, &domain->s1_domains, s2_link) {
3764 		spin_lock_irqsave(&s1_domain->lock, flags);
3765 		domain_set_dirty_tracking(s1_domain, domain->dirty_tracking);
3766 		spin_unlock_irqrestore(&s1_domain->lock, flags);
3767 	}
3768 	spin_unlock(&domain->s1_lock);
3769 	return ret;
3770 }
3771 
3772 static int intel_iommu_set_dirty_tracking(struct iommu_domain *domain,
3773 					  bool enable)
3774 {
3775 	struct dmar_domain *dmar_domain = to_dmar_domain(domain);
3776 	int ret;
3777 
3778 	spin_lock(&dmar_domain->lock);
3779 	if (dmar_domain->dirty_tracking == enable)
3780 		goto out_unlock;
3781 
3782 	ret = domain_set_dirty_tracking(dmar_domain, enable);
3783 	if (ret)
3784 		goto err_unwind;
3785 
3786 	if (dmar_domain->nested_parent) {
3787 		ret = parent_domain_set_dirty_tracking(dmar_domain, enable);
3788 		if (ret)
3789 			goto err_unwind;
3790 	}
3791 
3792 	dmar_domain->dirty_tracking = enable;
3793 out_unlock:
3794 	spin_unlock(&dmar_domain->lock);
3795 
3796 	return 0;
3797 
3798 err_unwind:
3799 	domain_set_dirty_tracking(dmar_domain, dmar_domain->dirty_tracking);
3800 	spin_unlock(&dmar_domain->lock);
3801 	return ret;
3802 }
3803 
3804 static int context_setup_pass_through(struct device *dev, u8 bus, u8 devfn)
3805 {
3806 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3807 	struct intel_iommu *iommu = info->iommu;
3808 	struct context_entry *context;
3809 
3810 	spin_lock(&iommu->lock);
3811 	context = iommu_context_addr(iommu, bus, devfn, 1);
3812 	if (!context) {
3813 		spin_unlock(&iommu->lock);
3814 		return -ENOMEM;
3815 	}
3816 
3817 	if (context_present(context) && !context_copied(iommu, bus, devfn)) {
3818 		spin_unlock(&iommu->lock);
3819 		return 0;
3820 	}
3821 
3822 	copied_context_tear_down(iommu, context, bus, devfn);
3823 	context_clear_entry(context);
3824 	context_set_domain_id(context, FLPT_DEFAULT_DID);
3825 
3826 	/*
3827 	 * In pass through mode, AW must be programmed to indicate the largest
3828 	 * AGAW value supported by hardware. And ASR is ignored by hardware.
3829 	 */
3830 	context_set_address_width(context, iommu->msagaw);
3831 	context_set_translation_type(context, CONTEXT_TT_PASS_THROUGH);
3832 	context_set_fault_enable(context);
3833 	context_set_present(context);
3834 	if (!ecap_coherent(iommu->ecap))
3835 		clflush_cache_range(context, sizeof(*context));
3836 	context_present_cache_flush(iommu, FLPT_DEFAULT_DID, bus, devfn);
3837 	spin_unlock(&iommu->lock);
3838 
3839 	return 0;
3840 }
3841 
3842 static int context_setup_pass_through_cb(struct pci_dev *pdev, u16 alias, void *data)
3843 {
3844 	struct device *dev = data;
3845 
3846 	return context_setup_pass_through(dev, PCI_BUS_NUM(alias), alias & 0xff);
3847 }
3848 
3849 static int device_setup_pass_through(struct device *dev)
3850 {
3851 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3852 
3853 	if (!dev_is_pci(dev))
3854 		return context_setup_pass_through(dev, info->bus, info->devfn);
3855 
3856 	return pci_for_each_dma_alias(to_pci_dev(dev),
3857 				      context_setup_pass_through_cb, dev);
3858 }
3859 
3860 static int identity_domain_attach_dev(struct iommu_domain *domain,
3861 				      struct device *dev,
3862 				      struct iommu_domain *old)
3863 {
3864 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3865 	struct intel_iommu *iommu = info->iommu;
3866 	int ret;
3867 
3868 	device_block_translation(dev);
3869 
3870 	if (dev_is_real_dma_subdevice(dev))
3871 		return 0;
3872 
3873 	/*
3874 	 * The identity domain has no iopf_handler, so no IOPF reference is
3875 	 * taken for it.  The reference held by the old domain must still be
3876 	 * released here; putting the device in the blocking state above does
3877 	 * not affect the IOPF reference count.
3878 	 */
3879 	iopf_for_domain_remove(old, dev);
3880 
3881 	if (sm_supported(iommu))
3882 		ret = intel_pasid_setup_pass_through(iommu, dev, IOMMU_NO_PASID);
3883 	else
3884 		ret = device_setup_pass_through(dev);
3885 
3886 	if (!ret)
3887 		info->domain_attached = true;
3888 
3889 	return ret;
3890 }
3891 
3892 static int identity_domain_set_dev_pasid(struct iommu_domain *domain,
3893 					 struct device *dev, ioasid_t pasid,
3894 					 struct iommu_domain *old)
3895 {
3896 	struct device_domain_info *info = dev_iommu_priv_get(dev);
3897 	struct intel_iommu *iommu = info->iommu;
3898 	int ret;
3899 
3900 	if (!pasid_supported(iommu) || dev_is_real_dma_subdevice(dev))
3901 		return -EOPNOTSUPP;
3902 
3903 	ret = iopf_for_domain_replace(domain, old, dev);
3904 	if (ret)
3905 		return ret;
3906 
3907 	ret = domain_setup_passthrough(iommu, dev, pasid, old);
3908 	if (ret) {
3909 		iopf_for_domain_replace(old, domain, dev);
3910 		return ret;
3911 	}
3912 
3913 	domain_remove_dev_pasid(old, dev, pasid);
3914 	return 0;
3915 }
3916 
3917 static struct iommu_domain identity_domain = {
3918 	.type = IOMMU_DOMAIN_IDENTITY,
3919 	.ops = &(const struct iommu_domain_ops) {
3920 		.attach_dev	= identity_domain_attach_dev,
3921 		.set_dev_pasid	= identity_domain_set_dev_pasid,
3922 	},
3923 };
3924 
3925 const struct iommu_domain_ops intel_fs_paging_domain_ops = {
3926 	IOMMU_PT_DOMAIN_OPS(x86_64),
3927 	.attach_dev = intel_iommu_attach_device,
3928 	.set_dev_pasid = intel_iommu_set_dev_pasid,
3929 	.iotlb_sync_map = intel_iommu_iotlb_sync_map,
3930 	.flush_iotlb_all = intel_flush_iotlb_all,
3931 	.iotlb_sync = intel_iommu_tlb_sync,
3932 	.free = intel_iommu_domain_free,
3933 	.enforce_cache_coherency = intel_iommu_enforce_cache_coherency_fs,
3934 };
3935 
3936 const struct iommu_domain_ops intel_ss_paging_domain_ops = {
3937 	IOMMU_PT_DOMAIN_OPS(vtdss),
3938 	.attach_dev = intel_iommu_attach_device,
3939 	.set_dev_pasid = intel_iommu_set_dev_pasid,
3940 	.iotlb_sync_map = intel_iommu_iotlb_sync_map,
3941 	.flush_iotlb_all = intel_flush_iotlb_all,
3942 	.iotlb_sync = intel_iommu_tlb_sync,
3943 	.free = intel_iommu_domain_free,
3944 	.enforce_cache_coherency = intel_iommu_enforce_cache_coherency_ss,
3945 };
3946 
3947 const struct iommu_ops intel_iommu_ops = {
3948 	.blocked_domain		= &blocking_domain,
3949 	.release_domain		= &blocking_domain,
3950 	.identity_domain	= &identity_domain,
3951 	.capable		= intel_iommu_capable,
3952 	.hw_info		= intel_iommu_hw_info,
3953 	.domain_alloc_paging_flags = intel_iommu_domain_alloc_paging_flags,
3954 	.domain_alloc_sva	= intel_svm_domain_alloc,
3955 	.domain_alloc_nested	= intel_iommu_domain_alloc_nested,
3956 	.probe_device		= intel_iommu_probe_device,
3957 	.probe_finalize		= intel_iommu_probe_finalize,
3958 	.release_device		= intel_iommu_release_device,
3959 	.get_resv_regions	= intel_iommu_get_resv_regions,
3960 	.device_group		= intel_iommu_device_group,
3961 	.is_attach_deferred	= intel_iommu_is_attach_deferred,
3962 	.def_domain_type	= device_def_domain_type,
3963 	.page_response		= intel_iommu_page_response,
3964 };
3965 
3966 static void quirk_iommu_igfx(struct pci_dev *dev)
3967 {
3968 	if (risky_device(dev))
3969 		return;
3970 
3971 	pci_info(dev, "Disabling IOMMU for graphics on this chipset\n");
3972 	disable_igfx_iommu = 1;
3973 }
3974 
3975 /* Q35 integrated gfx dmar support is totally busted. */
3976 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x29b2, quirk_iommu_igfx);
3977 
3978 /* G4x/GM45 integrated gfx dmar support is totally busted. */
3979 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_igfx);
3980 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e00, quirk_iommu_igfx);
3981 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e10, quirk_iommu_igfx);
3982 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e20, quirk_iommu_igfx);
3983 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e30, quirk_iommu_igfx);
3984 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e40, quirk_iommu_igfx);
3985 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e90, quirk_iommu_igfx);
3986 
3987 /* QM57/QS57 integrated gfx malfunctions with dmar */
3988 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x0044, quirk_iommu_igfx);
3989 
3990 /* Broadwell igfx malfunctions with dmar */
3991 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1606, quirk_iommu_igfx);
3992 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x160B, quirk_iommu_igfx);
3993 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x160E, quirk_iommu_igfx);
3994 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1602, quirk_iommu_igfx);
3995 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x160A, quirk_iommu_igfx);
3996 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x160D, quirk_iommu_igfx);
3997 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1616, quirk_iommu_igfx);
3998 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x161B, quirk_iommu_igfx);
3999 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x161E, quirk_iommu_igfx);
4000 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1612, quirk_iommu_igfx);
4001 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x161A, quirk_iommu_igfx);
4002 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x161D, quirk_iommu_igfx);
4003 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1626, quirk_iommu_igfx);
4004 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x162B, quirk_iommu_igfx);
4005 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x162E, quirk_iommu_igfx);
4006 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1622, quirk_iommu_igfx);
4007 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x162A, quirk_iommu_igfx);
4008 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x162D, quirk_iommu_igfx);
4009 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1636, quirk_iommu_igfx);
4010 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x163B, quirk_iommu_igfx);
4011 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x163E, quirk_iommu_igfx);
4012 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1632, quirk_iommu_igfx);
4013 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x163A, quirk_iommu_igfx);
4014 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x163D, quirk_iommu_igfx);
4015 
4016 static void quirk_iommu_rwbf(struct pci_dev *dev)
4017 {
4018 	if (risky_device(dev))
4019 		return;
4020 
4021 	/*
4022 	 * Mobile 4 Series Chipset neglects to set RWBF capability,
4023 	 * but needs it. Same seems to hold for the desktop versions.
4024 	 */
4025 	pci_info(dev, "Forcing write-buffer flush capability\n");
4026 	rwbf_quirk = 1;
4027 }
4028 
4029 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_rwbf);
4030 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e00, quirk_iommu_rwbf);
4031 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e10, quirk_iommu_rwbf);
4032 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e20, quirk_iommu_rwbf);
4033 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e30, quirk_iommu_rwbf);
4034 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e40, quirk_iommu_rwbf);
4035 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2e90, quirk_iommu_rwbf);
4036 
4037 #define GGC 0x52
4038 #define GGC_MEMORY_SIZE_MASK	(0xf << 8)
4039 #define GGC_MEMORY_SIZE_NONE	(0x0 << 8)
4040 #define GGC_MEMORY_SIZE_1M	(0x1 << 8)
4041 #define GGC_MEMORY_SIZE_2M	(0x3 << 8)
4042 #define GGC_MEMORY_VT_ENABLED	(0x8 << 8)
4043 #define GGC_MEMORY_SIZE_2M_VT	(0x9 << 8)
4044 #define GGC_MEMORY_SIZE_3M_VT	(0xa << 8)
4045 #define GGC_MEMORY_SIZE_4M_VT	(0xb << 8)
4046 
4047 static void quirk_calpella_no_shadow_gtt(struct pci_dev *dev)
4048 {
4049 	unsigned short ggc;
4050 
4051 	if (risky_device(dev))
4052 		return;
4053 
4054 	if (pci_read_config_word(dev, GGC, &ggc))
4055 		return;
4056 
4057 	if (!(ggc & GGC_MEMORY_VT_ENABLED)) {
4058 		pci_info(dev, "BIOS has allocated no shadow GTT; disabling IOMMU for graphics\n");
4059 		disable_igfx_iommu = 1;
4060 	} else if (!disable_igfx_iommu) {
4061 		/* we have to ensure the gfx device is idle before we flush */
4062 		pci_info(dev, "Disabling batched IOTLB flush on Ironlake\n");
4063 		iommu_set_dma_strict();
4064 	}
4065 }
4066 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x0040, quirk_calpella_no_shadow_gtt);
4067 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x0062, quirk_calpella_no_shadow_gtt);
4068 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x006a, quirk_calpella_no_shadow_gtt);
4069 
4070 static void quirk_igfx_skip_te_disable(struct pci_dev *dev)
4071 {
4072 	unsigned short ver;
4073 
4074 	if (!IS_GFX_DEVICE(dev))
4075 		return;
4076 
4077 	ver = (dev->device >> 8) & 0xff;
4078 	if (ver != 0x45 && ver != 0x46 && ver != 0x4c &&
4079 	    ver != 0x4e && ver != 0x8a && ver != 0x98 &&
4080 	    ver != 0x9a && ver != 0xa7 && ver != 0x7d)
4081 		return;
4082 
4083 	if (risky_device(dev))
4084 		return;
4085 
4086 	pci_info(dev, "Skip IOMMU disabling for graphics\n");
4087 	iommu_skip_te_disable = 1;
4088 }
4089 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_ANY_ID, quirk_igfx_skip_te_disable);
4090 
4091 /* On Tylersburg chipsets, some BIOSes have been known to enable the
4092    ISOCH DMAR unit for the Azalia sound device, but not give it any
4093    TLB entries, which causes it to deadlock. Check for that.  We do
4094    this in a function called from init_dmars(), instead of in a PCI
4095    quirk, because we don't want to print the obnoxious "BIOS broken"
4096    message if VT-d is actually disabled.
4097 */
4098 static void __init check_tylersburg_isoch(void)
4099 {
4100 	struct pci_dev *pdev;
4101 	uint32_t vtisochctrl;
4102 
4103 	/* If there's no Azalia in the system anyway, forget it. */
4104 	pdev = pci_get_device(PCI_VENDOR_ID_INTEL, 0x3a3e, NULL);
4105 	if (!pdev)
4106 		return;
4107 
4108 	if (risky_device(pdev)) {
4109 		pci_dev_put(pdev);
4110 		return;
4111 	}
4112 
4113 	pci_dev_put(pdev);
4114 
4115 	/* System Management Registers. Might be hidden, in which case
4116 	   we can't do the sanity check. But that's OK, because the
4117 	   known-broken BIOSes _don't_ actually hide it, so far. */
4118 	pdev = pci_get_device(PCI_VENDOR_ID_INTEL, 0x342e, NULL);
4119 	if (!pdev)
4120 		return;
4121 
4122 	if (risky_device(pdev)) {
4123 		pci_dev_put(pdev);
4124 		return;
4125 	}
4126 
4127 	if (pci_read_config_dword(pdev, 0x188, &vtisochctrl)) {
4128 		pci_dev_put(pdev);
4129 		return;
4130 	}
4131 
4132 	pci_dev_put(pdev);
4133 
4134 	/* If Azalia DMA is routed to the non-isoch DMAR unit, fine. */
4135 	if (vtisochctrl & 1)
4136 		return;
4137 
4138 	/* Drop all bits other than the number of TLB entries */
4139 	vtisochctrl &= 0x1c;
4140 
4141 	/* If we have the recommended number of TLB entries (16), fine. */
4142 	if (vtisochctrl == 0x10)
4143 		return;
4144 
4145 	/* Zero TLB entries? You get to ride the short bus to school. */
4146 	if (!vtisochctrl) {
4147 		WARN(1, "Your BIOS is broken; DMA routed to ISOCH DMAR unit but no TLB space.\n"
4148 		     "BIOS vendor: %s; Ver: %s; Product Version: %s\n",
4149 		     dmi_get_system_info(DMI_BIOS_VENDOR),
4150 		     dmi_get_system_info(DMI_BIOS_VERSION),
4151 		     dmi_get_system_info(DMI_PRODUCT_VERSION));
4152 		iommu_identity_mapping |= IDENTMAP_AZALIA;
4153 		return;
4154 	}
4155 
4156 	pr_warn("Recommended TLB entries for ISOCH unit is 16; your BIOS set %d\n",
4157 	       vtisochctrl);
4158 }
4159 
4160 /*
4161  * Here we deal with a device TLB defect where device may inadvertently issue ATS
4162  * invalidation completion before posted writes initiated with translated address
4163  * that utilized translations matching the invalidation address range, violating
4164  * the invalidation completion ordering.
4165  * Therefore, any use cases that cannot guarantee DMA is stopped before unmap is
4166  * vulnerable to this defect. In other words, any dTLB invalidation initiated not
4167  * under the control of the trusted/privileged host device driver must use this
4168  * quirk.
4169  * Device TLBs are invalidated under the following six conditions:
4170  * 1. Device driver does DMA API unmap IOVA
4171  * 2. Device driver unbind a PASID from a process, sva_unbind_device()
4172  * 3. PASID is torn down, after PASID cache is flushed. e.g. process
4173  *    exit_mmap() due to crash
4174  * 4. Under SVA usage, called by mmu_notifier.invalidate_range() where
4175  *    VM has to free pages that were unmapped
4176  * 5. Userspace driver unmaps a DMA buffer
4177  * 6. Cache invalidation in vSVA usage (upcoming)
4178  *
4179  * For #1 and #2, device drivers are responsible for stopping DMA traffic
4180  * before unmap/unbind. For #3, iommu driver gets mmu_notifier to
4181  * invalidate TLB the same way as normal user unmap which will use this quirk.
4182  * The dTLB invalidation after PASID cache flush does not need this quirk.
4183  *
4184  * As a reminder, #6 will *NEED* this quirk as we enable nested translation.
4185  */
4186 void quirk_extra_dev_tlb_flush(struct device_domain_info *info,
4187 			       unsigned long address, unsigned long mask,
4188 			       u32 pasid, u16 qdep)
4189 {
4190 	u16 sid;
4191 
4192 	if (likely(!info->dtlb_extra_inval))
4193 		return;
4194 
4195 	sid = PCI_DEVID(info->bus, info->devfn);
4196 	if (pasid == IOMMU_NO_PASID) {
4197 		qi_flush_dev_iotlb(info->iommu, sid, info->pfsid,
4198 				   qdep, address, mask);
4199 	} else {
4200 		qi_flush_dev_iotlb_pasid(info->iommu, sid, info->pfsid,
4201 					 pasid, qdep, address, mask);
4202 	}
4203 }
4204 
4205 #define ecmd_get_status_code(res)	(((res) & 0xff) >> 1)
4206 
4207 /*
4208  * Function to submit a command to the enhanced command interface. The
4209  * valid enhanced command descriptions are defined in Table 47 of the
4210  * VT-d spec. The VT-d hardware implementation may support some but not
4211  * all commands, which can be determined by checking the Enhanced
4212  * Command Capability Register.
4213  *
4214  * Return values:
4215  *  - 0: Command successful without any error;
4216  *  - Negative: software error value;
4217  *  - Nonzero positive: failure status code defined in Table 48.
4218  */
4219 int ecmd_submit_sync(struct intel_iommu *iommu, u8 ecmd, u64 oa, u64 ob)
4220 {
4221 	unsigned long flags;
4222 	u64 res;
4223 	int ret;
4224 
4225 	if (!cap_ecmds(iommu->cap))
4226 		return -ENODEV;
4227 
4228 	raw_spin_lock_irqsave(&iommu->register_lock, flags);
4229 
4230 	res = readq(iommu->reg + DMAR_ECRSP_REG);
4231 	if (res & DMA_ECMD_ECRSP_IP) {
4232 		ret = -EBUSY;
4233 		goto err;
4234 	}
4235 
4236 	/*
4237 	 * Unconditionally write the operand B, because
4238 	 * - There is no side effect if an ecmd doesn't require an
4239 	 *   operand B, but we set the register to some value.
4240 	 * - It's not invoked in any critical path. The extra MMIO
4241 	 *   write doesn't bring any performance concerns.
4242 	 */
4243 	writeq(ob, iommu->reg + DMAR_ECEO_REG);
4244 	writeq(ecmd | (oa << DMA_ECMD_OA_SHIFT), iommu->reg + DMAR_ECMD_REG);
4245 
4246 	IOMMU_WAIT_OP(iommu, DMAR_ECRSP_REG, readq,
4247 		      !(res & DMA_ECMD_ECRSP_IP), res);
4248 
4249 	if (res & DMA_ECMD_ECRSP_IP) {
4250 		ret = -ETIMEDOUT;
4251 		goto err;
4252 	}
4253 
4254 	ret = ecmd_get_status_code(res);
4255 err:
4256 	raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
4257 
4258 	return ret;
4259 }
4260 
4261 MODULE_IMPORT_NS("GENERIC_PT_IOMMU");
4262