xref: /linux/drivers/iommu/amd/iommu.c (revision 1f24458a1071f006e3f7449c08ae0f12af493923)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
4  * Author: Joerg Roedel <jroedel@suse.de>
5  *         Leo Duran <leo.duran@amd.com>
6  */
7 
8 #define pr_fmt(fmt)     "AMD-Vi: " fmt
9 #define dev_fmt(fmt)    pr_fmt(fmt)
10 
11 #include <linux/ratelimit.h>
12 #include <linux/pci.h>
13 #include <linux/acpi.h>
14 #include <linux/pci-ats.h>
15 #include <linux/bitmap.h>
16 #include <linux/slab.h>
17 #include <linux/debugfs.h>
18 #include <linux/scatterlist.h>
19 #include <linux/dma-map-ops.h>
20 #include <linux/dma-direct.h>
21 #include <linux/iommu-helper.h>
22 #include <linux/delay.h>
23 #include <linux/amd-iommu.h>
24 #include <linux/notifier.h>
25 #include <linux/export.h>
26 #include <linux/irq.h>
27 #include <linux/msi.h>
28 #include <linux/irqdomain.h>
29 #include <linux/percpu.h>
30 #include <linux/io-pgtable.h>
31 #include <linux/cc_platform.h>
32 #include <asm/irq_remapping.h>
33 #include <asm/io_apic.h>
34 #include <asm/apic.h>
35 #include <asm/hw_irq.h>
36 #include <asm/proto.h>
37 #include <asm/iommu.h>
38 #include <asm/gart.h>
39 #include <asm/dma.h>
40 #include <uapi/linux/iommufd.h>
41 
42 #include "amd_iommu.h"
43 #include "../dma-iommu.h"
44 #include "../irq_remapping.h"
45 
46 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
47 
48 #define LOOP_TIMEOUT	100000
49 
50 /* IO virtual address start page frame number */
51 #define IOVA_START_PFN		(1)
52 #define IOVA_PFN(addr)		((addr) >> PAGE_SHIFT)
53 
54 /* Reserved IOVA ranges */
55 #define MSI_RANGE_START		(0xfee00000)
56 #define MSI_RANGE_END		(0xfeefffff)
57 #define HT_RANGE_START		(0xfd00000000ULL)
58 #define HT_RANGE_END		(0xffffffffffULL)
59 
60 #define DEFAULT_PGTABLE_LEVEL	PAGE_MODE_3_LEVEL
61 
62 static DEFINE_SPINLOCK(pd_bitmap_lock);
63 
64 LIST_HEAD(ioapic_map);
65 LIST_HEAD(hpet_map);
66 LIST_HEAD(acpihid_map);
67 
68 const struct iommu_ops amd_iommu_ops;
69 const struct iommu_dirty_ops amd_dirty_ops;
70 
71 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
72 int amd_iommu_max_glx_val = -1;
73 
74 /*
75  * general struct to manage commands send to an IOMMU
76  */
77 struct iommu_cmd {
78 	u32 data[4];
79 };
80 
81 struct kmem_cache *amd_iommu_irq_cache;
82 
83 static void detach_device(struct device *dev);
84 static int domain_enable_v2(struct protection_domain *domain, int pasids);
85 
86 /****************************************************************************
87  *
88  * Helper functions
89  *
90  ****************************************************************************/
91 
92 static inline int get_acpihid_device_id(struct device *dev,
93 					struct acpihid_map_entry **entry)
94 {
95 	struct acpi_device *adev = ACPI_COMPANION(dev);
96 	struct acpihid_map_entry *p;
97 
98 	if (!adev)
99 		return -ENODEV;
100 
101 	list_for_each_entry(p, &acpihid_map, list) {
102 		if (acpi_dev_hid_uid_match(adev, p->hid,
103 					   p->uid[0] ? p->uid : NULL)) {
104 			if (entry)
105 				*entry = p;
106 			return p->devid;
107 		}
108 	}
109 	return -EINVAL;
110 }
111 
112 static inline int get_device_sbdf_id(struct device *dev)
113 {
114 	int sbdf;
115 
116 	if (dev_is_pci(dev))
117 		sbdf = get_pci_sbdf_id(to_pci_dev(dev));
118 	else
119 		sbdf = get_acpihid_device_id(dev, NULL);
120 
121 	return sbdf;
122 }
123 
124 struct dev_table_entry *get_dev_table(struct amd_iommu *iommu)
125 {
126 	struct dev_table_entry *dev_table;
127 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
128 
129 	BUG_ON(pci_seg == NULL);
130 	dev_table = pci_seg->dev_table;
131 	BUG_ON(dev_table == NULL);
132 
133 	return dev_table;
134 }
135 
136 static inline u16 get_device_segment(struct device *dev)
137 {
138 	u16 seg;
139 
140 	if (dev_is_pci(dev)) {
141 		struct pci_dev *pdev = to_pci_dev(dev);
142 
143 		seg = pci_domain_nr(pdev->bus);
144 	} else {
145 		u32 devid = get_acpihid_device_id(dev, NULL);
146 
147 		seg = PCI_SBDF_TO_SEGID(devid);
148 	}
149 
150 	return seg;
151 }
152 
153 /* Writes the specific IOMMU for a device into the PCI segment rlookup table */
154 void amd_iommu_set_rlookup_table(struct amd_iommu *iommu, u16 devid)
155 {
156 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
157 
158 	pci_seg->rlookup_table[devid] = iommu;
159 }
160 
161 static struct amd_iommu *__rlookup_amd_iommu(u16 seg, u16 devid)
162 {
163 	struct amd_iommu_pci_seg *pci_seg;
164 
165 	for_each_pci_segment(pci_seg) {
166 		if (pci_seg->id == seg)
167 			return pci_seg->rlookup_table[devid];
168 	}
169 	return NULL;
170 }
171 
172 static struct amd_iommu *rlookup_amd_iommu(struct device *dev)
173 {
174 	u16 seg = get_device_segment(dev);
175 	int devid = get_device_sbdf_id(dev);
176 
177 	if (devid < 0)
178 		return NULL;
179 	return __rlookup_amd_iommu(seg, PCI_SBDF_TO_DEVID(devid));
180 }
181 
182 static struct protection_domain *to_pdomain(struct iommu_domain *dom)
183 {
184 	return container_of(dom, struct protection_domain, domain);
185 }
186 
187 static struct iommu_dev_data *alloc_dev_data(struct amd_iommu *iommu, u16 devid)
188 {
189 	struct iommu_dev_data *dev_data;
190 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
191 
192 	dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
193 	if (!dev_data)
194 		return NULL;
195 
196 	spin_lock_init(&dev_data->lock);
197 	dev_data->devid = devid;
198 	ratelimit_default_init(&dev_data->rs);
199 
200 	llist_add(&dev_data->dev_data_list, &pci_seg->dev_data_list);
201 	return dev_data;
202 }
203 
204 static struct iommu_dev_data *search_dev_data(struct amd_iommu *iommu, u16 devid)
205 {
206 	struct iommu_dev_data *dev_data;
207 	struct llist_node *node;
208 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
209 
210 	if (llist_empty(&pci_seg->dev_data_list))
211 		return NULL;
212 
213 	node = pci_seg->dev_data_list.first;
214 	llist_for_each_entry(dev_data, node, dev_data_list) {
215 		if (dev_data->devid == devid)
216 			return dev_data;
217 	}
218 
219 	return NULL;
220 }
221 
222 static int clone_alias(struct pci_dev *pdev, u16 alias, void *data)
223 {
224 	struct amd_iommu *iommu;
225 	struct dev_table_entry *dev_table;
226 	u16 devid = pci_dev_id(pdev);
227 
228 	if (devid == alias)
229 		return 0;
230 
231 	iommu = rlookup_amd_iommu(&pdev->dev);
232 	if (!iommu)
233 		return 0;
234 
235 	amd_iommu_set_rlookup_table(iommu, alias);
236 	dev_table = get_dev_table(iommu);
237 	memcpy(dev_table[alias].data,
238 	       dev_table[devid].data,
239 	       sizeof(dev_table[alias].data));
240 
241 	return 0;
242 }
243 
244 static void clone_aliases(struct amd_iommu *iommu, struct device *dev)
245 {
246 	struct pci_dev *pdev;
247 
248 	if (!dev_is_pci(dev))
249 		return;
250 	pdev = to_pci_dev(dev);
251 
252 	/*
253 	 * The IVRS alias stored in the alias table may not be
254 	 * part of the PCI DMA aliases if it's bus differs
255 	 * from the original device.
256 	 */
257 	clone_alias(pdev, iommu->pci_seg->alias_table[pci_dev_id(pdev)], NULL);
258 
259 	pci_for_each_dma_alias(pdev, clone_alias, NULL);
260 }
261 
262 static void setup_aliases(struct amd_iommu *iommu, struct device *dev)
263 {
264 	struct pci_dev *pdev = to_pci_dev(dev);
265 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
266 	u16 ivrs_alias;
267 
268 	/* For ACPI HID devices, there are no aliases */
269 	if (!dev_is_pci(dev))
270 		return;
271 
272 	/*
273 	 * Add the IVRS alias to the pci aliases if it is on the same
274 	 * bus. The IVRS table may know about a quirk that we don't.
275 	 */
276 	ivrs_alias = pci_seg->alias_table[pci_dev_id(pdev)];
277 	if (ivrs_alias != pci_dev_id(pdev) &&
278 	    PCI_BUS_NUM(ivrs_alias) == pdev->bus->number)
279 		pci_add_dma_alias(pdev, ivrs_alias & 0xff, 1);
280 
281 	clone_aliases(iommu, dev);
282 }
283 
284 static struct iommu_dev_data *find_dev_data(struct amd_iommu *iommu, u16 devid)
285 {
286 	struct iommu_dev_data *dev_data;
287 
288 	dev_data = search_dev_data(iommu, devid);
289 
290 	if (dev_data == NULL) {
291 		dev_data = alloc_dev_data(iommu, devid);
292 		if (!dev_data)
293 			return NULL;
294 
295 		if (translation_pre_enabled(iommu))
296 			dev_data->defer_attach = true;
297 	}
298 
299 	return dev_data;
300 }
301 
302 /*
303 * Find or create an IOMMU group for a acpihid device.
304 */
305 static struct iommu_group *acpihid_device_group(struct device *dev)
306 {
307 	struct acpihid_map_entry *p, *entry = NULL;
308 	int devid;
309 
310 	devid = get_acpihid_device_id(dev, &entry);
311 	if (devid < 0)
312 		return ERR_PTR(devid);
313 
314 	list_for_each_entry(p, &acpihid_map, list) {
315 		if ((devid == p->devid) && p->group)
316 			entry->group = p->group;
317 	}
318 
319 	if (!entry->group)
320 		entry->group = generic_device_group(dev);
321 	else
322 		iommu_group_ref_get(entry->group);
323 
324 	return entry->group;
325 }
326 
327 static bool pci_iommuv2_capable(struct pci_dev *pdev)
328 {
329 	static const int caps[] = {
330 		PCI_EXT_CAP_ID_PRI,
331 		PCI_EXT_CAP_ID_PASID,
332 	};
333 	int i, pos;
334 
335 	if (!pci_ats_supported(pdev))
336 		return false;
337 
338 	for (i = 0; i < 2; ++i) {
339 		pos = pci_find_ext_capability(pdev, caps[i]);
340 		if (pos == 0)
341 			return false;
342 	}
343 
344 	return true;
345 }
346 
347 /*
348  * This function checks if the driver got a valid device from the caller to
349  * avoid dereferencing invalid pointers.
350  */
351 static bool check_device(struct device *dev)
352 {
353 	struct amd_iommu_pci_seg *pci_seg;
354 	struct amd_iommu *iommu;
355 	int devid, sbdf;
356 
357 	if (!dev)
358 		return false;
359 
360 	sbdf = get_device_sbdf_id(dev);
361 	if (sbdf < 0)
362 		return false;
363 	devid = PCI_SBDF_TO_DEVID(sbdf);
364 
365 	iommu = rlookup_amd_iommu(dev);
366 	if (!iommu)
367 		return false;
368 
369 	/* Out of our scope? */
370 	pci_seg = iommu->pci_seg;
371 	if (devid > pci_seg->last_bdf)
372 		return false;
373 
374 	return true;
375 }
376 
377 static int iommu_init_device(struct amd_iommu *iommu, struct device *dev)
378 {
379 	struct iommu_dev_data *dev_data;
380 	int devid, sbdf;
381 
382 	if (dev_iommu_priv_get(dev))
383 		return 0;
384 
385 	sbdf = get_device_sbdf_id(dev);
386 	if (sbdf < 0)
387 		return sbdf;
388 
389 	devid = PCI_SBDF_TO_DEVID(sbdf);
390 	dev_data = find_dev_data(iommu, devid);
391 	if (!dev_data)
392 		return -ENOMEM;
393 
394 	dev_data->dev = dev;
395 	setup_aliases(iommu, dev);
396 
397 	/*
398 	 * By default we use passthrough mode for IOMMUv2 capable device.
399 	 * But if amd_iommu=force_isolation is set (e.g. to debug DMA to
400 	 * invalid address), we ignore the capability for the device so
401 	 * it'll be forced to go into translation mode.
402 	 */
403 	if ((iommu_default_passthrough() || !amd_iommu_force_isolation) &&
404 	    dev_is_pci(dev) && pci_iommuv2_capable(to_pci_dev(dev))) {
405 		dev_data->iommu_v2 = iommu->is_iommu_v2;
406 	}
407 
408 	dev_iommu_priv_set(dev, dev_data);
409 
410 	return 0;
411 }
412 
413 static void iommu_ignore_device(struct amd_iommu *iommu, struct device *dev)
414 {
415 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
416 	struct dev_table_entry *dev_table = get_dev_table(iommu);
417 	int devid, sbdf;
418 
419 	sbdf = get_device_sbdf_id(dev);
420 	if (sbdf < 0)
421 		return;
422 
423 	devid = PCI_SBDF_TO_DEVID(sbdf);
424 	pci_seg->rlookup_table[devid] = NULL;
425 	memset(&dev_table[devid], 0, sizeof(struct dev_table_entry));
426 
427 	setup_aliases(iommu, dev);
428 }
429 
430 static void amd_iommu_uninit_device(struct device *dev)
431 {
432 	struct iommu_dev_data *dev_data;
433 
434 	dev_data = dev_iommu_priv_get(dev);
435 	if (!dev_data)
436 		return;
437 
438 	if (dev_data->domain)
439 		detach_device(dev);
440 
441 	dev_iommu_priv_set(dev, NULL);
442 
443 	/*
444 	 * We keep dev_data around for unplugged devices and reuse it when the
445 	 * device is re-plugged - not doing so would introduce a ton of races.
446 	 */
447 }
448 
449 /****************************************************************************
450  *
451  * Interrupt handling functions
452  *
453  ****************************************************************************/
454 
455 static void dump_dte_entry(struct amd_iommu *iommu, u16 devid)
456 {
457 	int i;
458 	struct dev_table_entry *dev_table = get_dev_table(iommu);
459 
460 	for (i = 0; i < 4; ++i)
461 		pr_err("DTE[%d]: %016llx\n", i, dev_table[devid].data[i]);
462 }
463 
464 static void dump_command(unsigned long phys_addr)
465 {
466 	struct iommu_cmd *cmd = iommu_phys_to_virt(phys_addr);
467 	int i;
468 
469 	for (i = 0; i < 4; ++i)
470 		pr_err("CMD[%d]: %08x\n", i, cmd->data[i]);
471 }
472 
473 static void amd_iommu_report_rmp_hw_error(struct amd_iommu *iommu, volatile u32 *event)
474 {
475 	struct iommu_dev_data *dev_data = NULL;
476 	int devid, vmg_tag, flags;
477 	struct pci_dev *pdev;
478 	u64 spa;
479 
480 	devid   = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
481 	vmg_tag = (event[1]) & 0xFFFF;
482 	flags   = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
483 	spa     = ((u64)event[3] << 32) | (event[2] & 0xFFFFFFF8);
484 
485 	pdev = pci_get_domain_bus_and_slot(iommu->pci_seg->id, PCI_BUS_NUM(devid),
486 					   devid & 0xff);
487 	if (pdev)
488 		dev_data = dev_iommu_priv_get(&pdev->dev);
489 
490 	if (dev_data) {
491 		if (__ratelimit(&dev_data->rs)) {
492 			pci_err(pdev, "Event logged [RMP_HW_ERROR vmg_tag=0x%04x, spa=0x%llx, flags=0x%04x]\n",
493 				vmg_tag, spa, flags);
494 		}
495 	} else {
496 		pr_err_ratelimited("Event logged [RMP_HW_ERROR device=%04x:%02x:%02x.%x, vmg_tag=0x%04x, spa=0x%llx, flags=0x%04x]\n",
497 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
498 			vmg_tag, spa, flags);
499 	}
500 
501 	if (pdev)
502 		pci_dev_put(pdev);
503 }
504 
505 static void amd_iommu_report_rmp_fault(struct amd_iommu *iommu, volatile u32 *event)
506 {
507 	struct iommu_dev_data *dev_data = NULL;
508 	int devid, flags_rmp, vmg_tag, flags;
509 	struct pci_dev *pdev;
510 	u64 gpa;
511 
512 	devid     = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
513 	flags_rmp = (event[0] >> EVENT_FLAGS_SHIFT) & 0xFF;
514 	vmg_tag   = (event[1]) & 0xFFFF;
515 	flags     = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
516 	gpa       = ((u64)event[3] << 32) | event[2];
517 
518 	pdev = pci_get_domain_bus_and_slot(iommu->pci_seg->id, PCI_BUS_NUM(devid),
519 					   devid & 0xff);
520 	if (pdev)
521 		dev_data = dev_iommu_priv_get(&pdev->dev);
522 
523 	if (dev_data) {
524 		if (__ratelimit(&dev_data->rs)) {
525 			pci_err(pdev, "Event logged [RMP_PAGE_FAULT vmg_tag=0x%04x, gpa=0x%llx, flags_rmp=0x%04x, flags=0x%04x]\n",
526 				vmg_tag, gpa, flags_rmp, flags);
527 		}
528 	} else {
529 		pr_err_ratelimited("Event logged [RMP_PAGE_FAULT device=%04x:%02x:%02x.%x, vmg_tag=0x%04x, gpa=0x%llx, flags_rmp=0x%04x, flags=0x%04x]\n",
530 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
531 			vmg_tag, gpa, flags_rmp, flags);
532 	}
533 
534 	if (pdev)
535 		pci_dev_put(pdev);
536 }
537 
538 #define IS_IOMMU_MEM_TRANSACTION(flags)		\
539 	(((flags) & EVENT_FLAG_I) == 0)
540 
541 #define IS_WRITE_REQUEST(flags)			\
542 	((flags) & EVENT_FLAG_RW)
543 
544 static void amd_iommu_report_page_fault(struct amd_iommu *iommu,
545 					u16 devid, u16 domain_id,
546 					u64 address, int flags)
547 {
548 	struct iommu_dev_data *dev_data = NULL;
549 	struct pci_dev *pdev;
550 
551 	pdev = pci_get_domain_bus_and_slot(iommu->pci_seg->id, PCI_BUS_NUM(devid),
552 					   devid & 0xff);
553 	if (pdev)
554 		dev_data = dev_iommu_priv_get(&pdev->dev);
555 
556 	if (dev_data) {
557 		/*
558 		 * If this is a DMA fault (for which the I(nterrupt)
559 		 * bit will be unset), allow report_iommu_fault() to
560 		 * prevent logging it.
561 		 */
562 		if (IS_IOMMU_MEM_TRANSACTION(flags)) {
563 			/* Device not attached to domain properly */
564 			if (dev_data->domain == NULL) {
565 				pr_err_ratelimited("Event logged [Device not attached to domain properly]\n");
566 				pr_err_ratelimited("  device=%04x:%02x:%02x.%x domain=0x%04x\n",
567 						   iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid),
568 						   PCI_FUNC(devid), domain_id);
569 				goto out;
570 			}
571 
572 			if (!report_iommu_fault(&dev_data->domain->domain,
573 						&pdev->dev, address,
574 						IS_WRITE_REQUEST(flags) ?
575 							IOMMU_FAULT_WRITE :
576 							IOMMU_FAULT_READ))
577 				goto out;
578 		}
579 
580 		if (__ratelimit(&dev_data->rs)) {
581 			pci_err(pdev, "Event logged [IO_PAGE_FAULT domain=0x%04x address=0x%llx flags=0x%04x]\n",
582 				domain_id, address, flags);
583 		}
584 	} else {
585 		pr_err_ratelimited("Event logged [IO_PAGE_FAULT device=%04x:%02x:%02x.%x domain=0x%04x address=0x%llx flags=0x%04x]\n",
586 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
587 			domain_id, address, flags);
588 	}
589 
590 out:
591 	if (pdev)
592 		pci_dev_put(pdev);
593 }
594 
595 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
596 {
597 	struct device *dev = iommu->iommu.dev;
598 	int type, devid, flags, tag;
599 	volatile u32 *event = __evt;
600 	int count = 0;
601 	u64 address;
602 	u32 pasid;
603 
604 retry:
605 	type    = (event[1] >> EVENT_TYPE_SHIFT)  & EVENT_TYPE_MASK;
606 	devid   = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
607 	pasid   = (event[0] & EVENT_DOMID_MASK_HI) |
608 		  (event[1] & EVENT_DOMID_MASK_LO);
609 	flags   = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
610 	address = (u64)(((u64)event[3]) << 32) | event[2];
611 
612 	if (type == 0) {
613 		/* Did we hit the erratum? */
614 		if (++count == LOOP_TIMEOUT) {
615 			pr_err("No event written to event log\n");
616 			return;
617 		}
618 		udelay(1);
619 		goto retry;
620 	}
621 
622 	if (type == EVENT_TYPE_IO_FAULT) {
623 		amd_iommu_report_page_fault(iommu, devid, pasid, address, flags);
624 		return;
625 	}
626 
627 	switch (type) {
628 	case EVENT_TYPE_ILL_DEV:
629 		dev_err(dev, "Event logged [ILLEGAL_DEV_TABLE_ENTRY device=%04x:%02x:%02x.%x pasid=0x%05x address=0x%llx flags=0x%04x]\n",
630 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
631 			pasid, address, flags);
632 		dump_dte_entry(iommu, devid);
633 		break;
634 	case EVENT_TYPE_DEV_TAB_ERR:
635 		dev_err(dev, "Event logged [DEV_TAB_HARDWARE_ERROR device=%04x:%02x:%02x.%x "
636 			"address=0x%llx flags=0x%04x]\n",
637 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
638 			address, flags);
639 		break;
640 	case EVENT_TYPE_PAGE_TAB_ERR:
641 		dev_err(dev, "Event logged [PAGE_TAB_HARDWARE_ERROR device=%04x:%02x:%02x.%x pasid=0x%04x address=0x%llx flags=0x%04x]\n",
642 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
643 			pasid, address, flags);
644 		break;
645 	case EVENT_TYPE_ILL_CMD:
646 		dev_err(dev, "Event logged [ILLEGAL_COMMAND_ERROR address=0x%llx]\n", address);
647 		dump_command(address);
648 		break;
649 	case EVENT_TYPE_CMD_HARD_ERR:
650 		dev_err(dev, "Event logged [COMMAND_HARDWARE_ERROR address=0x%llx flags=0x%04x]\n",
651 			address, flags);
652 		break;
653 	case EVENT_TYPE_IOTLB_INV_TO:
654 		dev_err(dev, "Event logged [IOTLB_INV_TIMEOUT device=%04x:%02x:%02x.%x address=0x%llx]\n",
655 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
656 			address);
657 		break;
658 	case EVENT_TYPE_INV_DEV_REQ:
659 		dev_err(dev, "Event logged [INVALID_DEVICE_REQUEST device=%04x:%02x:%02x.%x pasid=0x%05x address=0x%llx flags=0x%04x]\n",
660 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
661 			pasid, address, flags);
662 		break;
663 	case EVENT_TYPE_RMP_FAULT:
664 		amd_iommu_report_rmp_fault(iommu, event);
665 		break;
666 	case EVENT_TYPE_RMP_HW_ERR:
667 		amd_iommu_report_rmp_hw_error(iommu, event);
668 		break;
669 	case EVENT_TYPE_INV_PPR_REQ:
670 		pasid = PPR_PASID(*((u64 *)__evt));
671 		tag = event[1] & 0x03FF;
672 		dev_err(dev, "Event logged [INVALID_PPR_REQUEST device=%04x:%02x:%02x.%x pasid=0x%05x address=0x%llx flags=0x%04x tag=0x%03x]\n",
673 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
674 			pasid, address, flags, tag);
675 		break;
676 	default:
677 		dev_err(dev, "Event logged [UNKNOWN event[0]=0x%08x event[1]=0x%08x event[2]=0x%08x event[3]=0x%08x\n",
678 			event[0], event[1], event[2], event[3]);
679 	}
680 
681 	/*
682 	 * To detect the hardware errata 732 we need to clear the
683 	 * entry back to zero. This issue does not exist on SNP
684 	 * enabled system. Also this buffer is not writeable on
685 	 * SNP enabled system.
686 	 */
687 	if (!amd_iommu_snp_en)
688 		memset(__evt, 0, 4 * sizeof(u32));
689 }
690 
691 static void iommu_poll_events(struct amd_iommu *iommu)
692 {
693 	u32 head, tail;
694 
695 	head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
696 	tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
697 
698 	while (head != tail) {
699 		iommu_print_event(iommu, iommu->evt_buf + head);
700 		head = (head + EVENT_ENTRY_SIZE) % EVT_BUFFER_SIZE;
701 	}
702 
703 	writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
704 }
705 
706 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
707 {
708 	struct amd_iommu_fault fault;
709 
710 	if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
711 		pr_err_ratelimited("Unknown PPR request received\n");
712 		return;
713 	}
714 
715 	fault.address   = raw[1];
716 	fault.pasid     = PPR_PASID(raw[0]);
717 	fault.sbdf      = PCI_SEG_DEVID_TO_SBDF(iommu->pci_seg->id, PPR_DEVID(raw[0]));
718 	fault.tag       = PPR_TAG(raw[0]);
719 	fault.flags     = PPR_FLAGS(raw[0]);
720 
721 	atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
722 }
723 
724 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
725 {
726 	u32 head, tail;
727 
728 	if (iommu->ppr_log == NULL)
729 		return;
730 
731 	head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
732 	tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
733 
734 	while (head != tail) {
735 		volatile u64 *raw;
736 		u64 entry[2];
737 		int i;
738 
739 		raw = (u64 *)(iommu->ppr_log + head);
740 
741 		/*
742 		 * Hardware bug: Interrupt may arrive before the entry is
743 		 * written to memory. If this happens we need to wait for the
744 		 * entry to arrive.
745 		 */
746 		for (i = 0; i < LOOP_TIMEOUT; ++i) {
747 			if (PPR_REQ_TYPE(raw[0]) != 0)
748 				break;
749 			udelay(1);
750 		}
751 
752 		/* Avoid memcpy function-call overhead */
753 		entry[0] = raw[0];
754 		entry[1] = raw[1];
755 
756 		/*
757 		 * To detect the hardware errata 733 we need to clear the
758 		 * entry back to zero. This issue does not exist on SNP
759 		 * enabled system. Also this buffer is not writeable on
760 		 * SNP enabled system.
761 		 */
762 		if (!amd_iommu_snp_en)
763 			raw[0] = raw[1] = 0UL;
764 
765 		/* Update head pointer of hardware ring-buffer */
766 		head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
767 		writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
768 
769 		/* Handle PPR entry */
770 		iommu_handle_ppr_entry(iommu, entry);
771 
772 		/* Refresh ring-buffer information */
773 		head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
774 		tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
775 	}
776 }
777 
778 #ifdef CONFIG_IRQ_REMAP
779 static int (*iommu_ga_log_notifier)(u32);
780 
781 int amd_iommu_register_ga_log_notifier(int (*notifier)(u32))
782 {
783 	iommu_ga_log_notifier = notifier;
784 
785 	return 0;
786 }
787 EXPORT_SYMBOL(amd_iommu_register_ga_log_notifier);
788 
789 static void iommu_poll_ga_log(struct amd_iommu *iommu)
790 {
791 	u32 head, tail;
792 
793 	if (iommu->ga_log == NULL)
794 		return;
795 
796 	head = readl(iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
797 	tail = readl(iommu->mmio_base + MMIO_GA_TAIL_OFFSET);
798 
799 	while (head != tail) {
800 		volatile u64 *raw;
801 		u64 log_entry;
802 
803 		raw = (u64 *)(iommu->ga_log + head);
804 
805 		/* Avoid memcpy function-call overhead */
806 		log_entry = *raw;
807 
808 		/* Update head pointer of hardware ring-buffer */
809 		head = (head + GA_ENTRY_SIZE) % GA_LOG_SIZE;
810 		writel(head, iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
811 
812 		/* Handle GA entry */
813 		switch (GA_REQ_TYPE(log_entry)) {
814 		case GA_GUEST_NR:
815 			if (!iommu_ga_log_notifier)
816 				break;
817 
818 			pr_debug("%s: devid=%#x, ga_tag=%#x\n",
819 				 __func__, GA_DEVID(log_entry),
820 				 GA_TAG(log_entry));
821 
822 			if (iommu_ga_log_notifier(GA_TAG(log_entry)) != 0)
823 				pr_err("GA log notifier failed.\n");
824 			break;
825 		default:
826 			break;
827 		}
828 	}
829 }
830 
831 static void
832 amd_iommu_set_pci_msi_domain(struct device *dev, struct amd_iommu *iommu)
833 {
834 	if (!irq_remapping_enabled || !dev_is_pci(dev) ||
835 	    !pci_dev_has_default_msi_parent_domain(to_pci_dev(dev)))
836 		return;
837 
838 	dev_set_msi_domain(dev, iommu->ir_domain);
839 }
840 
841 #else /* CONFIG_IRQ_REMAP */
842 static inline void
843 amd_iommu_set_pci_msi_domain(struct device *dev, struct amd_iommu *iommu) { }
844 #endif /* !CONFIG_IRQ_REMAP */
845 
846 static void amd_iommu_handle_irq(void *data, const char *evt_type,
847 				 u32 int_mask, u32 overflow_mask,
848 				 void (*int_handler)(struct amd_iommu *),
849 				 void (*overflow_handler)(struct amd_iommu *))
850 {
851 	struct amd_iommu *iommu = (struct amd_iommu *) data;
852 	u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
853 	u32 mask = int_mask | overflow_mask;
854 
855 	while (status & mask) {
856 		/* Enable interrupt sources again */
857 		writel(mask, iommu->mmio_base + MMIO_STATUS_OFFSET);
858 
859 		if (int_handler) {
860 			pr_devel("Processing IOMMU (ivhd%d) %s Log\n",
861 				 iommu->index, evt_type);
862 			int_handler(iommu);
863 		}
864 
865 		if ((status & overflow_mask) && overflow_handler)
866 			overflow_handler(iommu);
867 
868 		/*
869 		 * Hardware bug: ERBT1312
870 		 * When re-enabling interrupt (by writing 1
871 		 * to clear the bit), the hardware might also try to set
872 		 * the interrupt bit in the event status register.
873 		 * In this scenario, the bit will be set, and disable
874 		 * subsequent interrupts.
875 		 *
876 		 * Workaround: The IOMMU driver should read back the
877 		 * status register and check if the interrupt bits are cleared.
878 		 * If not, driver will need to go through the interrupt handler
879 		 * again and re-clear the bits
880 		 */
881 		status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
882 	}
883 }
884 
885 irqreturn_t amd_iommu_int_thread_evtlog(int irq, void *data)
886 {
887 	amd_iommu_handle_irq(data, "Evt", MMIO_STATUS_EVT_INT_MASK,
888 			     MMIO_STATUS_EVT_OVERFLOW_MASK,
889 			     iommu_poll_events, amd_iommu_restart_event_logging);
890 
891 	return IRQ_HANDLED;
892 }
893 
894 irqreturn_t amd_iommu_int_thread_pprlog(int irq, void *data)
895 {
896 	amd_iommu_handle_irq(data, "PPR", MMIO_STATUS_PPR_INT_MASK,
897 			     MMIO_STATUS_PPR_OVERFLOW_MASK,
898 			     iommu_poll_ppr_log, amd_iommu_restart_ppr_log);
899 
900 	return IRQ_HANDLED;
901 }
902 
903 irqreturn_t amd_iommu_int_thread_galog(int irq, void *data)
904 {
905 #ifdef CONFIG_IRQ_REMAP
906 	amd_iommu_handle_irq(data, "GA", MMIO_STATUS_GALOG_INT_MASK,
907 			     MMIO_STATUS_GALOG_OVERFLOW_MASK,
908 			     iommu_poll_ga_log, amd_iommu_restart_ga_log);
909 #endif
910 
911 	return IRQ_HANDLED;
912 }
913 
914 irqreturn_t amd_iommu_int_thread(int irq, void *data)
915 {
916 	amd_iommu_int_thread_evtlog(irq, data);
917 	amd_iommu_int_thread_pprlog(irq, data);
918 	amd_iommu_int_thread_galog(irq, data);
919 
920 	return IRQ_HANDLED;
921 }
922 
923 irqreturn_t amd_iommu_int_handler(int irq, void *data)
924 {
925 	return IRQ_WAKE_THREAD;
926 }
927 
928 /****************************************************************************
929  *
930  * IOMMU command queuing functions
931  *
932  ****************************************************************************/
933 
934 static int wait_on_sem(struct amd_iommu *iommu, u64 data)
935 {
936 	int i = 0;
937 
938 	while (*iommu->cmd_sem != data && i < LOOP_TIMEOUT) {
939 		udelay(1);
940 		i += 1;
941 	}
942 
943 	if (i == LOOP_TIMEOUT) {
944 		pr_alert("Completion-Wait loop timed out\n");
945 		return -EIO;
946 	}
947 
948 	return 0;
949 }
950 
951 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
952 			       struct iommu_cmd *cmd)
953 {
954 	u8 *target;
955 	u32 tail;
956 
957 	/* Copy command to buffer */
958 	tail = iommu->cmd_buf_tail;
959 	target = iommu->cmd_buf + tail;
960 	memcpy(target, cmd, sizeof(*cmd));
961 
962 	tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
963 	iommu->cmd_buf_tail = tail;
964 
965 	/* Tell the IOMMU about it */
966 	writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
967 }
968 
969 static void build_completion_wait(struct iommu_cmd *cmd,
970 				  struct amd_iommu *iommu,
971 				  u64 data)
972 {
973 	u64 paddr = iommu_virt_to_phys((void *)iommu->cmd_sem);
974 
975 	memset(cmd, 0, sizeof(*cmd));
976 	cmd->data[0] = lower_32_bits(paddr) | CMD_COMPL_WAIT_STORE_MASK;
977 	cmd->data[1] = upper_32_bits(paddr);
978 	cmd->data[2] = lower_32_bits(data);
979 	cmd->data[3] = upper_32_bits(data);
980 	CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
981 }
982 
983 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
984 {
985 	memset(cmd, 0, sizeof(*cmd));
986 	cmd->data[0] = devid;
987 	CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
988 }
989 
990 /*
991  * Builds an invalidation address which is suitable for one page or multiple
992  * pages. Sets the size bit (S) as needed is more than one page is flushed.
993  */
994 static inline u64 build_inv_address(u64 address, size_t size)
995 {
996 	u64 pages, end, msb_diff;
997 
998 	pages = iommu_num_pages(address, size, PAGE_SIZE);
999 
1000 	if (pages == 1)
1001 		return address & PAGE_MASK;
1002 
1003 	end = address + size - 1;
1004 
1005 	/*
1006 	 * msb_diff would hold the index of the most significant bit that
1007 	 * flipped between the start and end.
1008 	 */
1009 	msb_diff = fls64(end ^ address) - 1;
1010 
1011 	/*
1012 	 * Bits 63:52 are sign extended. If for some reason bit 51 is different
1013 	 * between the start and the end, invalidate everything.
1014 	 */
1015 	if (unlikely(msb_diff > 51)) {
1016 		address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
1017 	} else {
1018 		/*
1019 		 * The msb-bit must be clear on the address. Just set all the
1020 		 * lower bits.
1021 		 */
1022 		address |= (1ull << msb_diff) - 1;
1023 	}
1024 
1025 	/* Clear bits 11:0 */
1026 	address &= PAGE_MASK;
1027 
1028 	/* Set the size bit - we flush more than one 4kb page */
1029 	return address | CMD_INV_IOMMU_PAGES_SIZE_MASK;
1030 }
1031 
1032 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
1033 				  size_t size, u16 domid, int pde)
1034 {
1035 	u64 inv_address = build_inv_address(address, size);
1036 
1037 	memset(cmd, 0, sizeof(*cmd));
1038 	cmd->data[1] |= domid;
1039 	cmd->data[2]  = lower_32_bits(inv_address);
1040 	cmd->data[3]  = upper_32_bits(inv_address);
1041 	CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
1042 	if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
1043 		cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
1044 }
1045 
1046 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
1047 				  u64 address, size_t size)
1048 {
1049 	u64 inv_address = build_inv_address(address, size);
1050 
1051 	memset(cmd, 0, sizeof(*cmd));
1052 	cmd->data[0]  = devid;
1053 	cmd->data[0] |= (qdep & 0xff) << 24;
1054 	cmd->data[1]  = devid;
1055 	cmd->data[2]  = lower_32_bits(inv_address);
1056 	cmd->data[3]  = upper_32_bits(inv_address);
1057 	CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
1058 }
1059 
1060 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, u32 pasid,
1061 				  u64 address, bool size)
1062 {
1063 	memset(cmd, 0, sizeof(*cmd));
1064 
1065 	address &= ~(0xfffULL);
1066 
1067 	cmd->data[0]  = pasid;
1068 	cmd->data[1]  = domid;
1069 	cmd->data[2]  = lower_32_bits(address);
1070 	cmd->data[3]  = upper_32_bits(address);
1071 	cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
1072 	cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
1073 	if (size)
1074 		cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
1075 	CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
1076 }
1077 
1078 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, u32 pasid,
1079 				  int qdep, u64 address, bool size)
1080 {
1081 	memset(cmd, 0, sizeof(*cmd));
1082 
1083 	address &= ~(0xfffULL);
1084 
1085 	cmd->data[0]  = devid;
1086 	cmd->data[0] |= ((pasid >> 8) & 0xff) << 16;
1087 	cmd->data[0] |= (qdep  & 0xff) << 24;
1088 	cmd->data[1]  = devid;
1089 	cmd->data[1] |= (pasid & 0xff) << 16;
1090 	cmd->data[2]  = lower_32_bits(address);
1091 	cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
1092 	cmd->data[3]  = upper_32_bits(address);
1093 	if (size)
1094 		cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
1095 	CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
1096 }
1097 
1098 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, u32 pasid,
1099 			       int status, int tag, bool gn)
1100 {
1101 	memset(cmd, 0, sizeof(*cmd));
1102 
1103 	cmd->data[0]  = devid;
1104 	if (gn) {
1105 		cmd->data[1]  = pasid;
1106 		cmd->data[2]  = CMD_INV_IOMMU_PAGES_GN_MASK;
1107 	}
1108 	cmd->data[3]  = tag & 0x1ff;
1109 	cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
1110 
1111 	CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
1112 }
1113 
1114 static void build_inv_all(struct iommu_cmd *cmd)
1115 {
1116 	memset(cmd, 0, sizeof(*cmd));
1117 	CMD_SET_TYPE(cmd, CMD_INV_ALL);
1118 }
1119 
1120 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
1121 {
1122 	memset(cmd, 0, sizeof(*cmd));
1123 	cmd->data[0] = devid;
1124 	CMD_SET_TYPE(cmd, CMD_INV_IRT);
1125 }
1126 
1127 /*
1128  * Writes the command to the IOMMUs command buffer and informs the
1129  * hardware about the new command.
1130  */
1131 static int __iommu_queue_command_sync(struct amd_iommu *iommu,
1132 				      struct iommu_cmd *cmd,
1133 				      bool sync)
1134 {
1135 	unsigned int count = 0;
1136 	u32 left, next_tail;
1137 
1138 	next_tail = (iommu->cmd_buf_tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
1139 again:
1140 	left      = (iommu->cmd_buf_head - next_tail) % CMD_BUFFER_SIZE;
1141 
1142 	if (left <= 0x20) {
1143 		/* Skip udelay() the first time around */
1144 		if (count++) {
1145 			if (count == LOOP_TIMEOUT) {
1146 				pr_err("Command buffer timeout\n");
1147 				return -EIO;
1148 			}
1149 
1150 			udelay(1);
1151 		}
1152 
1153 		/* Update head and recheck remaining space */
1154 		iommu->cmd_buf_head = readl(iommu->mmio_base +
1155 					    MMIO_CMD_HEAD_OFFSET);
1156 
1157 		goto again;
1158 	}
1159 
1160 	copy_cmd_to_buffer(iommu, cmd);
1161 
1162 	/* Do we need to make sure all commands are processed? */
1163 	iommu->need_sync = sync;
1164 
1165 	return 0;
1166 }
1167 
1168 static int iommu_queue_command_sync(struct amd_iommu *iommu,
1169 				    struct iommu_cmd *cmd,
1170 				    bool sync)
1171 {
1172 	unsigned long flags;
1173 	int ret;
1174 
1175 	raw_spin_lock_irqsave(&iommu->lock, flags);
1176 	ret = __iommu_queue_command_sync(iommu, cmd, sync);
1177 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
1178 
1179 	return ret;
1180 }
1181 
1182 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
1183 {
1184 	return iommu_queue_command_sync(iommu, cmd, true);
1185 }
1186 
1187 /*
1188  * This function queues a completion wait command into the command
1189  * buffer of an IOMMU
1190  */
1191 static int iommu_completion_wait(struct amd_iommu *iommu)
1192 {
1193 	struct iommu_cmd cmd;
1194 	unsigned long flags;
1195 	int ret;
1196 	u64 data;
1197 
1198 	if (!iommu->need_sync)
1199 		return 0;
1200 
1201 	data = atomic64_add_return(1, &iommu->cmd_sem_val);
1202 	build_completion_wait(&cmd, iommu, data);
1203 
1204 	raw_spin_lock_irqsave(&iommu->lock, flags);
1205 
1206 	ret = __iommu_queue_command_sync(iommu, &cmd, false);
1207 	if (ret)
1208 		goto out_unlock;
1209 
1210 	ret = wait_on_sem(iommu, data);
1211 
1212 out_unlock:
1213 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
1214 
1215 	return ret;
1216 }
1217 
1218 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1219 {
1220 	struct iommu_cmd cmd;
1221 
1222 	build_inv_dte(&cmd, devid);
1223 
1224 	return iommu_queue_command(iommu, &cmd);
1225 }
1226 
1227 static void amd_iommu_flush_dte_all(struct amd_iommu *iommu)
1228 {
1229 	u32 devid;
1230 	u16 last_bdf = iommu->pci_seg->last_bdf;
1231 
1232 	for (devid = 0; devid <= last_bdf; ++devid)
1233 		iommu_flush_dte(iommu, devid);
1234 
1235 	iommu_completion_wait(iommu);
1236 }
1237 
1238 /*
1239  * This function uses heavy locking and may disable irqs for some time. But
1240  * this is no issue because it is only called during resume.
1241  */
1242 static void amd_iommu_flush_tlb_all(struct amd_iommu *iommu)
1243 {
1244 	u32 dom_id;
1245 	u16 last_bdf = iommu->pci_seg->last_bdf;
1246 
1247 	for (dom_id = 0; dom_id <= last_bdf; ++dom_id) {
1248 		struct iommu_cmd cmd;
1249 		build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1250 				      dom_id, 1);
1251 		iommu_queue_command(iommu, &cmd);
1252 	}
1253 
1254 	iommu_completion_wait(iommu);
1255 }
1256 
1257 static void amd_iommu_flush_tlb_domid(struct amd_iommu *iommu, u32 dom_id)
1258 {
1259 	struct iommu_cmd cmd;
1260 
1261 	build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1262 			      dom_id, 1);
1263 	iommu_queue_command(iommu, &cmd);
1264 
1265 	iommu_completion_wait(iommu);
1266 }
1267 
1268 static void amd_iommu_flush_all(struct amd_iommu *iommu)
1269 {
1270 	struct iommu_cmd cmd;
1271 
1272 	build_inv_all(&cmd);
1273 
1274 	iommu_queue_command(iommu, &cmd);
1275 	iommu_completion_wait(iommu);
1276 }
1277 
1278 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1279 {
1280 	struct iommu_cmd cmd;
1281 
1282 	build_inv_irt(&cmd, devid);
1283 
1284 	iommu_queue_command(iommu, &cmd);
1285 }
1286 
1287 static void amd_iommu_flush_irt_all(struct amd_iommu *iommu)
1288 {
1289 	u32 devid;
1290 	u16 last_bdf = iommu->pci_seg->last_bdf;
1291 
1292 	if (iommu->irtcachedis_enabled)
1293 		return;
1294 
1295 	for (devid = 0; devid <= last_bdf; devid++)
1296 		iommu_flush_irt(iommu, devid);
1297 
1298 	iommu_completion_wait(iommu);
1299 }
1300 
1301 void iommu_flush_all_caches(struct amd_iommu *iommu)
1302 {
1303 	if (iommu_feature(iommu, FEATURE_IA)) {
1304 		amd_iommu_flush_all(iommu);
1305 	} else {
1306 		amd_iommu_flush_dte_all(iommu);
1307 		amd_iommu_flush_irt_all(iommu);
1308 		amd_iommu_flush_tlb_all(iommu);
1309 	}
1310 }
1311 
1312 /*
1313  * Command send function for flushing on-device TLB
1314  */
1315 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1316 			      u64 address, size_t size)
1317 {
1318 	struct amd_iommu *iommu;
1319 	struct iommu_cmd cmd;
1320 	int qdep;
1321 
1322 	qdep     = dev_data->ats.qdep;
1323 	iommu    = rlookup_amd_iommu(dev_data->dev);
1324 	if (!iommu)
1325 		return -EINVAL;
1326 
1327 	build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1328 
1329 	return iommu_queue_command(iommu, &cmd);
1330 }
1331 
1332 static int device_flush_dte_alias(struct pci_dev *pdev, u16 alias, void *data)
1333 {
1334 	struct amd_iommu *iommu = data;
1335 
1336 	return iommu_flush_dte(iommu, alias);
1337 }
1338 
1339 /*
1340  * Command send function for invalidating a device table entry
1341  */
1342 static int device_flush_dte(struct iommu_dev_data *dev_data)
1343 {
1344 	struct amd_iommu *iommu;
1345 	struct pci_dev *pdev = NULL;
1346 	struct amd_iommu_pci_seg *pci_seg;
1347 	u16 alias;
1348 	int ret;
1349 
1350 	iommu = rlookup_amd_iommu(dev_data->dev);
1351 	if (!iommu)
1352 		return -EINVAL;
1353 
1354 	if (dev_is_pci(dev_data->dev))
1355 		pdev = to_pci_dev(dev_data->dev);
1356 
1357 	if (pdev)
1358 		ret = pci_for_each_dma_alias(pdev,
1359 					     device_flush_dte_alias, iommu);
1360 	else
1361 		ret = iommu_flush_dte(iommu, dev_data->devid);
1362 	if (ret)
1363 		return ret;
1364 
1365 	pci_seg = iommu->pci_seg;
1366 	alias = pci_seg->alias_table[dev_data->devid];
1367 	if (alias != dev_data->devid) {
1368 		ret = iommu_flush_dte(iommu, alias);
1369 		if (ret)
1370 			return ret;
1371 	}
1372 
1373 	if (dev_data->ats.enabled)
1374 		ret = device_flush_iotlb(dev_data, 0, ~0UL);
1375 
1376 	return ret;
1377 }
1378 
1379 /*
1380  * TLB invalidation function which is called from the mapping functions.
1381  * It invalidates a single PTE if the range to flush is within a single
1382  * page. Otherwise it flushes the whole TLB of the IOMMU.
1383  */
1384 static void __domain_flush_pages(struct protection_domain *domain,
1385 				 u64 address, size_t size, int pde)
1386 {
1387 	struct iommu_dev_data *dev_data;
1388 	struct iommu_cmd cmd;
1389 	int ret = 0, i;
1390 
1391 	build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1392 
1393 	for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
1394 		if (!domain->dev_iommu[i])
1395 			continue;
1396 
1397 		/*
1398 		 * Devices of this domain are behind this IOMMU
1399 		 * We need a TLB flush
1400 		 */
1401 		ret |= iommu_queue_command(amd_iommus[i], &cmd);
1402 	}
1403 
1404 	list_for_each_entry(dev_data, &domain->dev_list, list) {
1405 
1406 		if (!dev_data->ats.enabled)
1407 			continue;
1408 
1409 		ret |= device_flush_iotlb(dev_data, address, size);
1410 	}
1411 
1412 	WARN_ON(ret);
1413 }
1414 
1415 static void domain_flush_pages(struct protection_domain *domain,
1416 			       u64 address, size_t size, int pde)
1417 {
1418 	if (likely(!amd_iommu_np_cache)) {
1419 		__domain_flush_pages(domain, address, size, pde);
1420 		return;
1421 	}
1422 
1423 	/*
1424 	 * When NpCache is on, we infer that we run in a VM and use a vIOMMU.
1425 	 * In such setups it is best to avoid flushes of ranges which are not
1426 	 * naturally aligned, since it would lead to flushes of unmodified
1427 	 * PTEs. Such flushes would require the hypervisor to do more work than
1428 	 * necessary. Therefore, perform repeated flushes of aligned ranges
1429 	 * until you cover the range. Each iteration flushes the smaller
1430 	 * between the natural alignment of the address that we flush and the
1431 	 * greatest naturally aligned region that fits in the range.
1432 	 */
1433 	while (size != 0) {
1434 		int addr_alignment = __ffs(address);
1435 		int size_alignment = __fls(size);
1436 		int min_alignment;
1437 		size_t flush_size;
1438 
1439 		/*
1440 		 * size is always non-zero, but address might be zero, causing
1441 		 * addr_alignment to be negative. As the casting of the
1442 		 * argument in __ffs(address) to long might trim the high bits
1443 		 * of the address on x86-32, cast to long when doing the check.
1444 		 */
1445 		if (likely((unsigned long)address != 0))
1446 			min_alignment = min(addr_alignment, size_alignment);
1447 		else
1448 			min_alignment = size_alignment;
1449 
1450 		flush_size = 1ul << min_alignment;
1451 
1452 		__domain_flush_pages(domain, address, flush_size, pde);
1453 		address += flush_size;
1454 		size -= flush_size;
1455 	}
1456 }
1457 
1458 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1459 void amd_iommu_domain_flush_tlb_pde(struct protection_domain *domain)
1460 {
1461 	domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1462 }
1463 
1464 void amd_iommu_domain_flush_complete(struct protection_domain *domain)
1465 {
1466 	int i;
1467 
1468 	for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
1469 		if (domain && !domain->dev_iommu[i])
1470 			continue;
1471 
1472 		/*
1473 		 * Devices of this domain are behind this IOMMU
1474 		 * We need to wait for completion of all commands.
1475 		 */
1476 		iommu_completion_wait(amd_iommus[i]);
1477 	}
1478 }
1479 
1480 /* Flush the not present cache if it exists */
1481 static void domain_flush_np_cache(struct protection_domain *domain,
1482 		dma_addr_t iova, size_t size)
1483 {
1484 	if (unlikely(amd_iommu_np_cache)) {
1485 		unsigned long flags;
1486 
1487 		spin_lock_irqsave(&domain->lock, flags);
1488 		domain_flush_pages(domain, iova, size, 1);
1489 		amd_iommu_domain_flush_complete(domain);
1490 		spin_unlock_irqrestore(&domain->lock, flags);
1491 	}
1492 }
1493 
1494 
1495 /*
1496  * This function flushes the DTEs for all devices in domain
1497  */
1498 static void domain_flush_devices(struct protection_domain *domain)
1499 {
1500 	struct iommu_dev_data *dev_data;
1501 
1502 	list_for_each_entry(dev_data, &domain->dev_list, list)
1503 		device_flush_dte(dev_data);
1504 }
1505 
1506 /****************************************************************************
1507  *
1508  * The next functions belong to the domain allocation. A domain is
1509  * allocated for every IOMMU as the default domain. If device isolation
1510  * is enabled, every device get its own domain. The most important thing
1511  * about domains is the page table mapping the DMA address space they
1512  * contain.
1513  *
1514  ****************************************************************************/
1515 
1516 static u16 domain_id_alloc(void)
1517 {
1518 	int id;
1519 
1520 	spin_lock(&pd_bitmap_lock);
1521 	id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1522 	BUG_ON(id == 0);
1523 	if (id > 0 && id < MAX_DOMAIN_ID)
1524 		__set_bit(id, amd_iommu_pd_alloc_bitmap);
1525 	else
1526 		id = 0;
1527 	spin_unlock(&pd_bitmap_lock);
1528 
1529 	return id;
1530 }
1531 
1532 static void domain_id_free(int id)
1533 {
1534 	spin_lock(&pd_bitmap_lock);
1535 	if (id > 0 && id < MAX_DOMAIN_ID)
1536 		__clear_bit(id, amd_iommu_pd_alloc_bitmap);
1537 	spin_unlock(&pd_bitmap_lock);
1538 }
1539 
1540 static void free_gcr3_tbl_level1(u64 *tbl)
1541 {
1542 	u64 *ptr;
1543 	int i;
1544 
1545 	for (i = 0; i < 512; ++i) {
1546 		if (!(tbl[i] & GCR3_VALID))
1547 			continue;
1548 
1549 		ptr = iommu_phys_to_virt(tbl[i] & PAGE_MASK);
1550 
1551 		free_page((unsigned long)ptr);
1552 	}
1553 }
1554 
1555 static void free_gcr3_tbl_level2(u64 *tbl)
1556 {
1557 	u64 *ptr;
1558 	int i;
1559 
1560 	for (i = 0; i < 512; ++i) {
1561 		if (!(tbl[i] & GCR3_VALID))
1562 			continue;
1563 
1564 		ptr = iommu_phys_to_virt(tbl[i] & PAGE_MASK);
1565 
1566 		free_gcr3_tbl_level1(ptr);
1567 	}
1568 }
1569 
1570 static void free_gcr3_table(struct protection_domain *domain)
1571 {
1572 	if (domain->glx == 2)
1573 		free_gcr3_tbl_level2(domain->gcr3_tbl);
1574 	else if (domain->glx == 1)
1575 		free_gcr3_tbl_level1(domain->gcr3_tbl);
1576 	else
1577 		BUG_ON(domain->glx != 0);
1578 
1579 	free_page((unsigned long)domain->gcr3_tbl);
1580 }
1581 
1582 static void set_dte_entry(struct amd_iommu *iommu, u16 devid,
1583 			  struct protection_domain *domain, bool ats, bool ppr)
1584 {
1585 	u64 pte_root = 0;
1586 	u64 flags = 0;
1587 	u32 old_domid;
1588 	struct dev_table_entry *dev_table = get_dev_table(iommu);
1589 
1590 	if (domain->iop.mode != PAGE_MODE_NONE)
1591 		pte_root = iommu_virt_to_phys(domain->iop.root);
1592 
1593 	pte_root |= (domain->iop.mode & DEV_ENTRY_MODE_MASK)
1594 		    << DEV_ENTRY_MODE_SHIFT;
1595 
1596 	pte_root |= DTE_FLAG_IR | DTE_FLAG_IW | DTE_FLAG_V;
1597 
1598 	/*
1599 	 * When SNP is enabled, Only set TV bit when IOMMU
1600 	 * page translation is in use.
1601 	 */
1602 	if (!amd_iommu_snp_en || (domain->id != 0))
1603 		pte_root |= DTE_FLAG_TV;
1604 
1605 	flags = dev_table[devid].data[1];
1606 
1607 	if (ats)
1608 		flags |= DTE_FLAG_IOTLB;
1609 
1610 	if (ppr) {
1611 		if (iommu_feature(iommu, FEATURE_EPHSUP))
1612 			pte_root |= 1ULL << DEV_ENTRY_PPR;
1613 	}
1614 
1615 	if (domain->dirty_tracking)
1616 		pte_root |= DTE_FLAG_HAD;
1617 
1618 	if (domain->flags & PD_IOMMUV2_MASK) {
1619 		u64 gcr3 = iommu_virt_to_phys(domain->gcr3_tbl);
1620 		u64 glx  = domain->glx;
1621 		u64 tmp;
1622 
1623 		pte_root |= DTE_FLAG_GV;
1624 		pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1625 
1626 		/* First mask out possible old values for GCR3 table */
1627 		tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1628 		flags    &= ~tmp;
1629 
1630 		tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1631 		flags    &= ~tmp;
1632 
1633 		/* Encode GCR3 table into DTE */
1634 		tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1635 		pte_root |= tmp;
1636 
1637 		tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1638 		flags    |= tmp;
1639 
1640 		tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
1641 		flags    |= tmp;
1642 
1643 		if (amd_iommu_gpt_level == PAGE_MODE_5_LEVEL) {
1644 			dev_table[devid].data[2] |=
1645 				((u64)GUEST_PGTABLE_5_LEVEL << DTE_GPT_LEVEL_SHIFT);
1646 		}
1647 
1648 		if (domain->flags & PD_GIOV_MASK)
1649 			pte_root |= DTE_FLAG_GIOV;
1650 	}
1651 
1652 	flags &= ~DEV_DOMID_MASK;
1653 	flags |= domain->id;
1654 
1655 	old_domid = dev_table[devid].data[1] & DEV_DOMID_MASK;
1656 	dev_table[devid].data[1]  = flags;
1657 	dev_table[devid].data[0]  = pte_root;
1658 
1659 	/*
1660 	 * A kdump kernel might be replacing a domain ID that was copied from
1661 	 * the previous kernel--if so, it needs to flush the translation cache
1662 	 * entries for the old domain ID that is being overwritten
1663 	 */
1664 	if (old_domid) {
1665 		amd_iommu_flush_tlb_domid(iommu, old_domid);
1666 	}
1667 }
1668 
1669 static void clear_dte_entry(struct amd_iommu *iommu, u16 devid)
1670 {
1671 	struct dev_table_entry *dev_table = get_dev_table(iommu);
1672 
1673 	/* remove entry from the device table seen by the hardware */
1674 	dev_table[devid].data[0]  = DTE_FLAG_V;
1675 
1676 	if (!amd_iommu_snp_en)
1677 		dev_table[devid].data[0] |= DTE_FLAG_TV;
1678 
1679 	dev_table[devid].data[1] &= DTE_FLAG_MASK;
1680 
1681 	amd_iommu_apply_erratum_63(iommu, devid);
1682 }
1683 
1684 static void do_attach(struct iommu_dev_data *dev_data,
1685 		      struct protection_domain *domain)
1686 {
1687 	struct amd_iommu *iommu;
1688 	bool ats;
1689 
1690 	iommu = rlookup_amd_iommu(dev_data->dev);
1691 	if (!iommu)
1692 		return;
1693 	ats   = dev_data->ats.enabled;
1694 
1695 	/* Update data structures */
1696 	dev_data->domain = domain;
1697 	list_add(&dev_data->list, &domain->dev_list);
1698 
1699 	/* Update NUMA Node ID */
1700 	if (domain->nid == NUMA_NO_NODE)
1701 		domain->nid = dev_to_node(dev_data->dev);
1702 
1703 	/* Do reference counting */
1704 	domain->dev_iommu[iommu->index] += 1;
1705 	domain->dev_cnt                 += 1;
1706 
1707 	/* Update device table */
1708 	set_dte_entry(iommu, dev_data->devid, domain,
1709 		      ats, dev_data->iommu_v2);
1710 	clone_aliases(iommu, dev_data->dev);
1711 
1712 	device_flush_dte(dev_data);
1713 }
1714 
1715 static void do_detach(struct iommu_dev_data *dev_data)
1716 {
1717 	struct protection_domain *domain = dev_data->domain;
1718 	struct amd_iommu *iommu;
1719 
1720 	iommu = rlookup_amd_iommu(dev_data->dev);
1721 	if (!iommu)
1722 		return;
1723 
1724 	/* Update data structures */
1725 	dev_data->domain = NULL;
1726 	list_del(&dev_data->list);
1727 	clear_dte_entry(iommu, dev_data->devid);
1728 	clone_aliases(iommu, dev_data->dev);
1729 
1730 	/* Flush the DTE entry */
1731 	device_flush_dte(dev_data);
1732 
1733 	/* Flush IOTLB */
1734 	amd_iommu_domain_flush_tlb_pde(domain);
1735 
1736 	/* Wait for the flushes to finish */
1737 	amd_iommu_domain_flush_complete(domain);
1738 
1739 	/* decrease reference counters - needs to happen after the flushes */
1740 	domain->dev_iommu[iommu->index] -= 1;
1741 	domain->dev_cnt                 -= 1;
1742 }
1743 
1744 static void pdev_iommuv2_disable(struct pci_dev *pdev)
1745 {
1746 	pci_disable_ats(pdev);
1747 	pci_disable_pri(pdev);
1748 	pci_disable_pasid(pdev);
1749 }
1750 
1751 static int pdev_pri_ats_enable(struct pci_dev *pdev)
1752 {
1753 	int ret;
1754 
1755 	/* Only allow access to user-accessible pages */
1756 	ret = pci_enable_pasid(pdev, 0);
1757 	if (ret)
1758 		return ret;
1759 
1760 	/* First reset the PRI state of the device */
1761 	ret = pci_reset_pri(pdev);
1762 	if (ret)
1763 		goto out_err_pasid;
1764 
1765 	/* Enable PRI */
1766 	/* FIXME: Hardcode number of outstanding requests for now */
1767 	ret = pci_enable_pri(pdev, 32);
1768 	if (ret)
1769 		goto out_err_pasid;
1770 
1771 	ret = pci_enable_ats(pdev, PAGE_SHIFT);
1772 	if (ret)
1773 		goto out_err_pri;
1774 
1775 	return 0;
1776 
1777 out_err_pri:
1778 	pci_disable_pri(pdev);
1779 
1780 out_err_pasid:
1781 	pci_disable_pasid(pdev);
1782 
1783 	return ret;
1784 }
1785 
1786 /*
1787  * If a device is not yet associated with a domain, this function makes the
1788  * device visible in the domain
1789  */
1790 static int attach_device(struct device *dev,
1791 			 struct protection_domain *domain)
1792 {
1793 	struct iommu_dev_data *dev_data;
1794 	struct pci_dev *pdev;
1795 	unsigned long flags;
1796 	int ret;
1797 
1798 	spin_lock_irqsave(&domain->lock, flags);
1799 
1800 	dev_data = dev_iommu_priv_get(dev);
1801 
1802 	spin_lock(&dev_data->lock);
1803 
1804 	ret = -EBUSY;
1805 	if (dev_data->domain != NULL)
1806 		goto out;
1807 
1808 	if (!dev_is_pci(dev))
1809 		goto skip_ats_check;
1810 
1811 	pdev = to_pci_dev(dev);
1812 	if (domain->flags & PD_IOMMUV2_MASK) {
1813 		struct iommu_domain *def_domain = iommu_get_dma_domain(dev);
1814 
1815 		ret = -EINVAL;
1816 
1817 		/*
1818 		 * In case of using AMD_IOMMU_V1 page table mode and the device
1819 		 * is enabling for PPR/ATS support (using v2 table),
1820 		 * we need to make sure that the domain type is identity map.
1821 		 */
1822 		if ((amd_iommu_pgtable == AMD_IOMMU_V1) &&
1823 		    def_domain->type != IOMMU_DOMAIN_IDENTITY) {
1824 			goto out;
1825 		}
1826 
1827 		if (dev_data->iommu_v2) {
1828 			if (pdev_pri_ats_enable(pdev) != 0)
1829 				goto out;
1830 
1831 			dev_data->ats.enabled = true;
1832 			dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
1833 			dev_data->pri_tlp     = pci_prg_resp_pasid_required(pdev);
1834 		}
1835 	} else if (amd_iommu_iotlb_sup &&
1836 		   pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
1837 		dev_data->ats.enabled = true;
1838 		dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
1839 	}
1840 
1841 skip_ats_check:
1842 	ret = 0;
1843 
1844 	do_attach(dev_data, domain);
1845 
1846 	/*
1847 	 * We might boot into a crash-kernel here. The crashed kernel
1848 	 * left the caches in the IOMMU dirty. So we have to flush
1849 	 * here to evict all dirty stuff.
1850 	 */
1851 	amd_iommu_domain_flush_tlb_pde(domain);
1852 
1853 	amd_iommu_domain_flush_complete(domain);
1854 
1855 out:
1856 	spin_unlock(&dev_data->lock);
1857 
1858 	spin_unlock_irqrestore(&domain->lock, flags);
1859 
1860 	return ret;
1861 }
1862 
1863 /*
1864  * Removes a device from a protection domain (with devtable_lock held)
1865  */
1866 static void detach_device(struct device *dev)
1867 {
1868 	struct protection_domain *domain;
1869 	struct iommu_dev_data *dev_data;
1870 	unsigned long flags;
1871 
1872 	dev_data = dev_iommu_priv_get(dev);
1873 	domain   = dev_data->domain;
1874 
1875 	spin_lock_irqsave(&domain->lock, flags);
1876 
1877 	spin_lock(&dev_data->lock);
1878 
1879 	/*
1880 	 * First check if the device is still attached. It might already
1881 	 * be detached from its domain because the generic
1882 	 * iommu_detach_group code detached it and we try again here in
1883 	 * our alias handling.
1884 	 */
1885 	if (WARN_ON(!dev_data->domain))
1886 		goto out;
1887 
1888 	do_detach(dev_data);
1889 
1890 	if (!dev_is_pci(dev))
1891 		goto out;
1892 
1893 	if (domain->flags & PD_IOMMUV2_MASK && dev_data->iommu_v2)
1894 		pdev_iommuv2_disable(to_pci_dev(dev));
1895 	else if (dev_data->ats.enabled)
1896 		pci_disable_ats(to_pci_dev(dev));
1897 
1898 	dev_data->ats.enabled = false;
1899 
1900 out:
1901 	spin_unlock(&dev_data->lock);
1902 
1903 	spin_unlock_irqrestore(&domain->lock, flags);
1904 }
1905 
1906 static struct iommu_device *amd_iommu_probe_device(struct device *dev)
1907 {
1908 	struct iommu_device *iommu_dev;
1909 	struct amd_iommu *iommu;
1910 	int ret;
1911 
1912 	if (!check_device(dev))
1913 		return ERR_PTR(-ENODEV);
1914 
1915 	iommu = rlookup_amd_iommu(dev);
1916 	if (!iommu)
1917 		return ERR_PTR(-ENODEV);
1918 
1919 	/* Not registered yet? */
1920 	if (!iommu->iommu.ops)
1921 		return ERR_PTR(-ENODEV);
1922 
1923 	if (dev_iommu_priv_get(dev))
1924 		return &iommu->iommu;
1925 
1926 	ret = iommu_init_device(iommu, dev);
1927 	if (ret) {
1928 		if (ret != -ENOTSUPP)
1929 			dev_err(dev, "Failed to initialize - trying to proceed anyway\n");
1930 		iommu_dev = ERR_PTR(ret);
1931 		iommu_ignore_device(iommu, dev);
1932 	} else {
1933 		amd_iommu_set_pci_msi_domain(dev, iommu);
1934 		iommu_dev = &iommu->iommu;
1935 	}
1936 
1937 	iommu_completion_wait(iommu);
1938 
1939 	return iommu_dev;
1940 }
1941 
1942 static void amd_iommu_probe_finalize(struct device *dev)
1943 {
1944 	/* Domains are initialized for this device - have a look what we ended up with */
1945 	set_dma_ops(dev, NULL);
1946 	iommu_setup_dma_ops(dev, 0, U64_MAX);
1947 }
1948 
1949 static void amd_iommu_release_device(struct device *dev)
1950 {
1951 	struct amd_iommu *iommu;
1952 
1953 	if (!check_device(dev))
1954 		return;
1955 
1956 	iommu = rlookup_amd_iommu(dev);
1957 	if (!iommu)
1958 		return;
1959 
1960 	amd_iommu_uninit_device(dev);
1961 	iommu_completion_wait(iommu);
1962 }
1963 
1964 static struct iommu_group *amd_iommu_device_group(struct device *dev)
1965 {
1966 	if (dev_is_pci(dev))
1967 		return pci_device_group(dev);
1968 
1969 	return acpihid_device_group(dev);
1970 }
1971 
1972 /*****************************************************************************
1973  *
1974  * The next functions belong to the dma_ops mapping/unmapping code.
1975  *
1976  *****************************************************************************/
1977 
1978 static void update_device_table(struct protection_domain *domain)
1979 {
1980 	struct iommu_dev_data *dev_data;
1981 
1982 	list_for_each_entry(dev_data, &domain->dev_list, list) {
1983 		struct amd_iommu *iommu = rlookup_amd_iommu(dev_data->dev);
1984 
1985 		if (!iommu)
1986 			continue;
1987 		set_dte_entry(iommu, dev_data->devid, domain,
1988 			      dev_data->ats.enabled, dev_data->iommu_v2);
1989 		clone_aliases(iommu, dev_data->dev);
1990 	}
1991 }
1992 
1993 void amd_iommu_update_and_flush_device_table(struct protection_domain *domain)
1994 {
1995 	update_device_table(domain);
1996 	domain_flush_devices(domain);
1997 }
1998 
1999 void amd_iommu_domain_update(struct protection_domain *domain)
2000 {
2001 	/* Update device table */
2002 	amd_iommu_update_and_flush_device_table(domain);
2003 
2004 	/* Flush domain TLB(s) and wait for completion */
2005 	amd_iommu_domain_flush_tlb_pde(domain);
2006 	amd_iommu_domain_flush_complete(domain);
2007 }
2008 
2009 /*****************************************************************************
2010  *
2011  * The following functions belong to the exported interface of AMD IOMMU
2012  *
2013  * This interface allows access to lower level functions of the IOMMU
2014  * like protection domain handling and assignement of devices to domains
2015  * which is not possible with the dma_ops interface.
2016  *
2017  *****************************************************************************/
2018 
2019 static void cleanup_domain(struct protection_domain *domain)
2020 {
2021 	struct iommu_dev_data *entry;
2022 	unsigned long flags;
2023 
2024 	spin_lock_irqsave(&domain->lock, flags);
2025 
2026 	while (!list_empty(&domain->dev_list)) {
2027 		entry = list_first_entry(&domain->dev_list,
2028 					 struct iommu_dev_data, list);
2029 		BUG_ON(!entry->domain);
2030 		do_detach(entry);
2031 	}
2032 
2033 	spin_unlock_irqrestore(&domain->lock, flags);
2034 }
2035 
2036 static void protection_domain_free(struct protection_domain *domain)
2037 {
2038 	if (!domain)
2039 		return;
2040 
2041 	if (domain->iop.pgtbl_cfg.tlb)
2042 		free_io_pgtable_ops(&domain->iop.iop.ops);
2043 
2044 	if (domain->id)
2045 		domain_id_free(domain->id);
2046 
2047 	kfree(domain);
2048 }
2049 
2050 static int protection_domain_init_v1(struct protection_domain *domain, int mode)
2051 {
2052 	u64 *pt_root = NULL;
2053 
2054 	BUG_ON(mode < PAGE_MODE_NONE || mode > PAGE_MODE_6_LEVEL);
2055 
2056 	spin_lock_init(&domain->lock);
2057 	domain->id = domain_id_alloc();
2058 	if (!domain->id)
2059 		return -ENOMEM;
2060 	INIT_LIST_HEAD(&domain->dev_list);
2061 
2062 	if (mode != PAGE_MODE_NONE) {
2063 		pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2064 		if (!pt_root) {
2065 			domain_id_free(domain->id);
2066 			return -ENOMEM;
2067 		}
2068 	}
2069 
2070 	amd_iommu_domain_set_pgtable(domain, pt_root, mode);
2071 
2072 	return 0;
2073 }
2074 
2075 static int protection_domain_init_v2(struct protection_domain *domain)
2076 {
2077 	spin_lock_init(&domain->lock);
2078 	domain->id = domain_id_alloc();
2079 	if (!domain->id)
2080 		return -ENOMEM;
2081 	INIT_LIST_HEAD(&domain->dev_list);
2082 
2083 	domain->flags |= PD_GIOV_MASK;
2084 
2085 	domain->domain.pgsize_bitmap = AMD_IOMMU_PGSIZES_V2;
2086 
2087 	if (domain_enable_v2(domain, 1)) {
2088 		domain_id_free(domain->id);
2089 		return -ENOMEM;
2090 	}
2091 
2092 	return 0;
2093 }
2094 
2095 static struct protection_domain *protection_domain_alloc(unsigned int type)
2096 {
2097 	struct io_pgtable_ops *pgtbl_ops;
2098 	struct protection_domain *domain;
2099 	int pgtable;
2100 	int mode = DEFAULT_PGTABLE_LEVEL;
2101 	int ret;
2102 
2103 	/*
2104 	 * Force IOMMU v1 page table when iommu=pt and
2105 	 * when allocating domain for pass-through devices.
2106 	 */
2107 	if (type == IOMMU_DOMAIN_IDENTITY) {
2108 		pgtable = AMD_IOMMU_V1;
2109 		mode = PAGE_MODE_NONE;
2110 	} else if (type == IOMMU_DOMAIN_UNMANAGED) {
2111 		pgtable = AMD_IOMMU_V1;
2112 	} else if (type == IOMMU_DOMAIN_DMA || type == IOMMU_DOMAIN_DMA_FQ) {
2113 		pgtable = amd_iommu_pgtable;
2114 	} else {
2115 		return NULL;
2116 	}
2117 
2118 	domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2119 	if (!domain)
2120 		return NULL;
2121 
2122 	switch (pgtable) {
2123 	case AMD_IOMMU_V1:
2124 		ret = protection_domain_init_v1(domain, mode);
2125 		break;
2126 	case AMD_IOMMU_V2:
2127 		ret = protection_domain_init_v2(domain);
2128 		break;
2129 	default:
2130 		ret = -EINVAL;
2131 	}
2132 
2133 	if (ret)
2134 		goto out_err;
2135 
2136 	/* No need to allocate io pgtable ops in passthrough mode */
2137 	if (type == IOMMU_DOMAIN_IDENTITY)
2138 		return domain;
2139 
2140 	domain->nid = NUMA_NO_NODE;
2141 
2142 	pgtbl_ops = alloc_io_pgtable_ops(pgtable, &domain->iop.pgtbl_cfg, domain);
2143 	if (!pgtbl_ops) {
2144 		domain_id_free(domain->id);
2145 		goto out_err;
2146 	}
2147 
2148 	return domain;
2149 out_err:
2150 	kfree(domain);
2151 	return NULL;
2152 }
2153 
2154 static inline u64 dma_max_address(void)
2155 {
2156 	if (amd_iommu_pgtable == AMD_IOMMU_V1)
2157 		return ~0ULL;
2158 
2159 	/* V2 with 4/5 level page table */
2160 	return ((1ULL << PM_LEVEL_SHIFT(amd_iommu_gpt_level)) - 1);
2161 }
2162 
2163 static bool amd_iommu_hd_support(struct amd_iommu *iommu)
2164 {
2165 	return iommu && (iommu->features & FEATURE_HDSUP);
2166 }
2167 
2168 static struct iommu_domain *do_iommu_domain_alloc(unsigned int type,
2169 						  struct device *dev, u32 flags)
2170 {
2171 	bool dirty_tracking = flags & IOMMU_HWPT_ALLOC_DIRTY_TRACKING;
2172 	struct protection_domain *domain;
2173 	struct amd_iommu *iommu = NULL;
2174 
2175 	if (dev) {
2176 		iommu = rlookup_amd_iommu(dev);
2177 		if (!iommu)
2178 			return ERR_PTR(-ENODEV);
2179 	}
2180 
2181 	/*
2182 	 * Since DTE[Mode]=0 is prohibited on SNP-enabled system,
2183 	 * default to use IOMMU_DOMAIN_DMA[_FQ].
2184 	 */
2185 	if (amd_iommu_snp_en && (type == IOMMU_DOMAIN_IDENTITY))
2186 		return ERR_PTR(-EINVAL);
2187 
2188 	if (dirty_tracking && !amd_iommu_hd_support(iommu))
2189 		return ERR_PTR(-EOPNOTSUPP);
2190 
2191 	domain = protection_domain_alloc(type);
2192 	if (!domain)
2193 		return ERR_PTR(-ENOMEM);
2194 
2195 	domain->domain.geometry.aperture_start = 0;
2196 	domain->domain.geometry.aperture_end   = dma_max_address();
2197 	domain->domain.geometry.force_aperture = true;
2198 
2199 	if (iommu) {
2200 		domain->domain.type = type;
2201 		domain->domain.pgsize_bitmap = iommu->iommu.ops->pgsize_bitmap;
2202 		domain->domain.ops = iommu->iommu.ops->default_domain_ops;
2203 
2204 		if (dirty_tracking)
2205 			domain->domain.dirty_ops = &amd_dirty_ops;
2206 	}
2207 
2208 	return &domain->domain;
2209 }
2210 
2211 static struct iommu_domain *amd_iommu_domain_alloc(unsigned int type)
2212 {
2213 	struct iommu_domain *domain;
2214 
2215 	domain = do_iommu_domain_alloc(type, NULL, 0);
2216 	if (IS_ERR(domain))
2217 		return NULL;
2218 
2219 	return domain;
2220 }
2221 
2222 static struct iommu_domain *
2223 amd_iommu_domain_alloc_user(struct device *dev, u32 flags,
2224 			    struct iommu_domain *parent,
2225 			    const struct iommu_user_data *user_data)
2226 
2227 {
2228 	unsigned int type = IOMMU_DOMAIN_UNMANAGED;
2229 
2230 	if ((flags & ~IOMMU_HWPT_ALLOC_DIRTY_TRACKING) || parent || user_data)
2231 		return ERR_PTR(-EOPNOTSUPP);
2232 
2233 	return do_iommu_domain_alloc(type, dev, flags);
2234 }
2235 
2236 static void amd_iommu_domain_free(struct iommu_domain *dom)
2237 {
2238 	struct protection_domain *domain;
2239 
2240 	domain = to_pdomain(dom);
2241 
2242 	if (domain->dev_cnt > 0)
2243 		cleanup_domain(domain);
2244 
2245 	BUG_ON(domain->dev_cnt != 0);
2246 
2247 	if (!dom)
2248 		return;
2249 
2250 	if (domain->flags & PD_IOMMUV2_MASK)
2251 		free_gcr3_table(domain);
2252 
2253 	protection_domain_free(domain);
2254 }
2255 
2256 static int amd_iommu_attach_device(struct iommu_domain *dom,
2257 				   struct device *dev)
2258 {
2259 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
2260 	struct protection_domain *domain = to_pdomain(dom);
2261 	struct amd_iommu *iommu = rlookup_amd_iommu(dev);
2262 	int ret;
2263 
2264 	/*
2265 	 * Skip attach device to domain if new domain is same as
2266 	 * devices current domain
2267 	 */
2268 	if (dev_data->domain == domain)
2269 		return 0;
2270 
2271 	dev_data->defer_attach = false;
2272 
2273 	/*
2274 	 * Restrict to devices with compatible IOMMU hardware support
2275 	 * when enforcement of dirty tracking is enabled.
2276 	 */
2277 	if (dom->dirty_ops && !amd_iommu_hd_support(iommu))
2278 		return -EINVAL;
2279 
2280 	if (dev_data->domain)
2281 		detach_device(dev);
2282 
2283 	ret = attach_device(dev, domain);
2284 
2285 #ifdef CONFIG_IRQ_REMAP
2286 	if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
2287 		if (dom->type == IOMMU_DOMAIN_UNMANAGED)
2288 			dev_data->use_vapic = 1;
2289 		else
2290 			dev_data->use_vapic = 0;
2291 	}
2292 #endif
2293 
2294 	iommu_completion_wait(iommu);
2295 
2296 	return ret;
2297 }
2298 
2299 static void amd_iommu_iotlb_sync_map(struct iommu_domain *dom,
2300 				     unsigned long iova, size_t size)
2301 {
2302 	struct protection_domain *domain = to_pdomain(dom);
2303 	struct io_pgtable_ops *ops = &domain->iop.iop.ops;
2304 
2305 	if (ops->map_pages)
2306 		domain_flush_np_cache(domain, iova, size);
2307 }
2308 
2309 static int amd_iommu_map_pages(struct iommu_domain *dom, unsigned long iova,
2310 			       phys_addr_t paddr, size_t pgsize, size_t pgcount,
2311 			       int iommu_prot, gfp_t gfp, size_t *mapped)
2312 {
2313 	struct protection_domain *domain = to_pdomain(dom);
2314 	struct io_pgtable_ops *ops = &domain->iop.iop.ops;
2315 	int prot = 0;
2316 	int ret = -EINVAL;
2317 
2318 	if ((amd_iommu_pgtable == AMD_IOMMU_V1) &&
2319 	    (domain->iop.mode == PAGE_MODE_NONE))
2320 		return -EINVAL;
2321 
2322 	if (iommu_prot & IOMMU_READ)
2323 		prot |= IOMMU_PROT_IR;
2324 	if (iommu_prot & IOMMU_WRITE)
2325 		prot |= IOMMU_PROT_IW;
2326 
2327 	if (ops->map_pages) {
2328 		ret = ops->map_pages(ops, iova, paddr, pgsize,
2329 				     pgcount, prot, gfp, mapped);
2330 	}
2331 
2332 	return ret;
2333 }
2334 
2335 static void amd_iommu_iotlb_gather_add_page(struct iommu_domain *domain,
2336 					    struct iommu_iotlb_gather *gather,
2337 					    unsigned long iova, size_t size)
2338 {
2339 	/*
2340 	 * AMD's IOMMU can flush as many pages as necessary in a single flush.
2341 	 * Unless we run in a virtual machine, which can be inferred according
2342 	 * to whether "non-present cache" is on, it is probably best to prefer
2343 	 * (potentially) too extensive TLB flushing (i.e., more misses) over
2344 	 * mutliple TLB flushes (i.e., more flushes). For virtual machines the
2345 	 * hypervisor needs to synchronize the host IOMMU PTEs with those of
2346 	 * the guest, and the trade-off is different: unnecessary TLB flushes
2347 	 * should be avoided.
2348 	 */
2349 	if (amd_iommu_np_cache &&
2350 	    iommu_iotlb_gather_is_disjoint(gather, iova, size))
2351 		iommu_iotlb_sync(domain, gather);
2352 
2353 	iommu_iotlb_gather_add_range(gather, iova, size);
2354 }
2355 
2356 static size_t amd_iommu_unmap_pages(struct iommu_domain *dom, unsigned long iova,
2357 				    size_t pgsize, size_t pgcount,
2358 				    struct iommu_iotlb_gather *gather)
2359 {
2360 	struct protection_domain *domain = to_pdomain(dom);
2361 	struct io_pgtable_ops *ops = &domain->iop.iop.ops;
2362 	size_t r;
2363 
2364 	if ((amd_iommu_pgtable == AMD_IOMMU_V1) &&
2365 	    (domain->iop.mode == PAGE_MODE_NONE))
2366 		return 0;
2367 
2368 	r = (ops->unmap_pages) ? ops->unmap_pages(ops, iova, pgsize, pgcount, NULL) : 0;
2369 
2370 	if (r)
2371 		amd_iommu_iotlb_gather_add_page(dom, gather, iova, r);
2372 
2373 	return r;
2374 }
2375 
2376 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
2377 					  dma_addr_t iova)
2378 {
2379 	struct protection_domain *domain = to_pdomain(dom);
2380 	struct io_pgtable_ops *ops = &domain->iop.iop.ops;
2381 
2382 	return ops->iova_to_phys(ops, iova);
2383 }
2384 
2385 static bool amd_iommu_capable(struct device *dev, enum iommu_cap cap)
2386 {
2387 	switch (cap) {
2388 	case IOMMU_CAP_CACHE_COHERENCY:
2389 		return true;
2390 	case IOMMU_CAP_NOEXEC:
2391 		return false;
2392 	case IOMMU_CAP_PRE_BOOT_PROTECTION:
2393 		return amdr_ivrs_remap_support;
2394 	case IOMMU_CAP_ENFORCE_CACHE_COHERENCY:
2395 		return true;
2396 	case IOMMU_CAP_DEFERRED_FLUSH:
2397 		return true;
2398 	case IOMMU_CAP_DIRTY_TRACKING: {
2399 		struct amd_iommu *iommu = rlookup_amd_iommu(dev);
2400 
2401 		return amd_iommu_hd_support(iommu);
2402 	}
2403 	default:
2404 		break;
2405 	}
2406 
2407 	return false;
2408 }
2409 
2410 static int amd_iommu_set_dirty_tracking(struct iommu_domain *domain,
2411 					bool enable)
2412 {
2413 	struct protection_domain *pdomain = to_pdomain(domain);
2414 	struct dev_table_entry *dev_table;
2415 	struct iommu_dev_data *dev_data;
2416 	bool domain_flush = false;
2417 	struct amd_iommu *iommu;
2418 	unsigned long flags;
2419 	u64 pte_root;
2420 
2421 	spin_lock_irqsave(&pdomain->lock, flags);
2422 	if (!(pdomain->dirty_tracking ^ enable)) {
2423 		spin_unlock_irqrestore(&pdomain->lock, flags);
2424 		return 0;
2425 	}
2426 
2427 	list_for_each_entry(dev_data, &pdomain->dev_list, list) {
2428 		iommu = rlookup_amd_iommu(dev_data->dev);
2429 		if (!iommu)
2430 			continue;
2431 
2432 		dev_table = get_dev_table(iommu);
2433 		pte_root = dev_table[dev_data->devid].data[0];
2434 
2435 		pte_root = (enable ? pte_root | DTE_FLAG_HAD :
2436 				     pte_root & ~DTE_FLAG_HAD);
2437 
2438 		/* Flush device DTE */
2439 		dev_table[dev_data->devid].data[0] = pte_root;
2440 		device_flush_dte(dev_data);
2441 		domain_flush = true;
2442 	}
2443 
2444 	/* Flush IOTLB to mark IOPTE dirty on the next translation(s) */
2445 	if (domain_flush) {
2446 		amd_iommu_domain_flush_tlb_pde(pdomain);
2447 		amd_iommu_domain_flush_complete(pdomain);
2448 	}
2449 	pdomain->dirty_tracking = enable;
2450 	spin_unlock_irqrestore(&pdomain->lock, flags);
2451 
2452 	return 0;
2453 }
2454 
2455 static int amd_iommu_read_and_clear_dirty(struct iommu_domain *domain,
2456 					  unsigned long iova, size_t size,
2457 					  unsigned long flags,
2458 					  struct iommu_dirty_bitmap *dirty)
2459 {
2460 	struct protection_domain *pdomain = to_pdomain(domain);
2461 	struct io_pgtable_ops *ops = &pdomain->iop.iop.ops;
2462 	unsigned long lflags;
2463 
2464 	if (!ops || !ops->read_and_clear_dirty)
2465 		return -EOPNOTSUPP;
2466 
2467 	spin_lock_irqsave(&pdomain->lock, lflags);
2468 	if (!pdomain->dirty_tracking && dirty->bitmap) {
2469 		spin_unlock_irqrestore(&pdomain->lock, lflags);
2470 		return -EINVAL;
2471 	}
2472 	spin_unlock_irqrestore(&pdomain->lock, lflags);
2473 
2474 	return ops->read_and_clear_dirty(ops, iova, size, flags, dirty);
2475 }
2476 
2477 static void amd_iommu_get_resv_regions(struct device *dev,
2478 				       struct list_head *head)
2479 {
2480 	struct iommu_resv_region *region;
2481 	struct unity_map_entry *entry;
2482 	struct amd_iommu *iommu;
2483 	struct amd_iommu_pci_seg *pci_seg;
2484 	int devid, sbdf;
2485 
2486 	sbdf = get_device_sbdf_id(dev);
2487 	if (sbdf < 0)
2488 		return;
2489 
2490 	devid = PCI_SBDF_TO_DEVID(sbdf);
2491 	iommu = rlookup_amd_iommu(dev);
2492 	if (!iommu)
2493 		return;
2494 	pci_seg = iommu->pci_seg;
2495 
2496 	list_for_each_entry(entry, &pci_seg->unity_map, list) {
2497 		int type, prot = 0;
2498 		size_t length;
2499 
2500 		if (devid < entry->devid_start || devid > entry->devid_end)
2501 			continue;
2502 
2503 		type   = IOMMU_RESV_DIRECT;
2504 		length = entry->address_end - entry->address_start;
2505 		if (entry->prot & IOMMU_PROT_IR)
2506 			prot |= IOMMU_READ;
2507 		if (entry->prot & IOMMU_PROT_IW)
2508 			prot |= IOMMU_WRITE;
2509 		if (entry->prot & IOMMU_UNITY_MAP_FLAG_EXCL_RANGE)
2510 			/* Exclusion range */
2511 			type = IOMMU_RESV_RESERVED;
2512 
2513 		region = iommu_alloc_resv_region(entry->address_start,
2514 						 length, prot, type,
2515 						 GFP_KERNEL);
2516 		if (!region) {
2517 			dev_err(dev, "Out of memory allocating dm-regions\n");
2518 			return;
2519 		}
2520 		list_add_tail(&region->list, head);
2521 	}
2522 
2523 	region = iommu_alloc_resv_region(MSI_RANGE_START,
2524 					 MSI_RANGE_END - MSI_RANGE_START + 1,
2525 					 0, IOMMU_RESV_MSI, GFP_KERNEL);
2526 	if (!region)
2527 		return;
2528 	list_add_tail(&region->list, head);
2529 
2530 	region = iommu_alloc_resv_region(HT_RANGE_START,
2531 					 HT_RANGE_END - HT_RANGE_START + 1,
2532 					 0, IOMMU_RESV_RESERVED, GFP_KERNEL);
2533 	if (!region)
2534 		return;
2535 	list_add_tail(&region->list, head);
2536 }
2537 
2538 bool amd_iommu_is_attach_deferred(struct device *dev)
2539 {
2540 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
2541 
2542 	return dev_data->defer_attach;
2543 }
2544 EXPORT_SYMBOL_GPL(amd_iommu_is_attach_deferred);
2545 
2546 static void amd_iommu_flush_iotlb_all(struct iommu_domain *domain)
2547 {
2548 	struct protection_domain *dom = to_pdomain(domain);
2549 	unsigned long flags;
2550 
2551 	spin_lock_irqsave(&dom->lock, flags);
2552 	amd_iommu_domain_flush_tlb_pde(dom);
2553 	amd_iommu_domain_flush_complete(dom);
2554 	spin_unlock_irqrestore(&dom->lock, flags);
2555 }
2556 
2557 static void amd_iommu_iotlb_sync(struct iommu_domain *domain,
2558 				 struct iommu_iotlb_gather *gather)
2559 {
2560 	struct protection_domain *dom = to_pdomain(domain);
2561 	unsigned long flags;
2562 
2563 	spin_lock_irqsave(&dom->lock, flags);
2564 	domain_flush_pages(dom, gather->start, gather->end - gather->start + 1, 1);
2565 	amd_iommu_domain_flush_complete(dom);
2566 	spin_unlock_irqrestore(&dom->lock, flags);
2567 }
2568 
2569 static int amd_iommu_def_domain_type(struct device *dev)
2570 {
2571 	struct iommu_dev_data *dev_data;
2572 
2573 	dev_data = dev_iommu_priv_get(dev);
2574 	if (!dev_data)
2575 		return 0;
2576 
2577 	/*
2578 	 * Do not identity map IOMMUv2 capable devices when:
2579 	 *  - memory encryption is active, because some of those devices
2580 	 *    (AMD GPUs) don't have the encryption bit in their DMA-mask
2581 	 *    and require remapping.
2582 	 *  - SNP is enabled, because it prohibits DTE[Mode]=0.
2583 	 */
2584 	if (dev_data->iommu_v2 &&
2585 	    !cc_platform_has(CC_ATTR_MEM_ENCRYPT) &&
2586 	    !amd_iommu_snp_en) {
2587 		return IOMMU_DOMAIN_IDENTITY;
2588 	}
2589 
2590 	return 0;
2591 }
2592 
2593 static bool amd_iommu_enforce_cache_coherency(struct iommu_domain *domain)
2594 {
2595 	/* IOMMU_PTE_FC is always set */
2596 	return true;
2597 }
2598 
2599 const struct iommu_dirty_ops amd_dirty_ops = {
2600 	.set_dirty_tracking = amd_iommu_set_dirty_tracking,
2601 	.read_and_clear_dirty = amd_iommu_read_and_clear_dirty,
2602 };
2603 
2604 const struct iommu_ops amd_iommu_ops = {
2605 	.capable = amd_iommu_capable,
2606 	.domain_alloc = amd_iommu_domain_alloc,
2607 	.domain_alloc_user = amd_iommu_domain_alloc_user,
2608 	.probe_device = amd_iommu_probe_device,
2609 	.release_device = amd_iommu_release_device,
2610 	.probe_finalize = amd_iommu_probe_finalize,
2611 	.device_group = amd_iommu_device_group,
2612 	.get_resv_regions = amd_iommu_get_resv_regions,
2613 	.is_attach_deferred = amd_iommu_is_attach_deferred,
2614 	.pgsize_bitmap	= AMD_IOMMU_PGSIZES,
2615 	.def_domain_type = amd_iommu_def_domain_type,
2616 	.default_domain_ops = &(const struct iommu_domain_ops) {
2617 		.attach_dev	= amd_iommu_attach_device,
2618 		.map_pages	= amd_iommu_map_pages,
2619 		.unmap_pages	= amd_iommu_unmap_pages,
2620 		.iotlb_sync_map	= amd_iommu_iotlb_sync_map,
2621 		.iova_to_phys	= amd_iommu_iova_to_phys,
2622 		.flush_iotlb_all = amd_iommu_flush_iotlb_all,
2623 		.iotlb_sync	= amd_iommu_iotlb_sync,
2624 		.free		= amd_iommu_domain_free,
2625 		.enforce_cache_coherency = amd_iommu_enforce_cache_coherency,
2626 	}
2627 };
2628 
2629 /*****************************************************************************
2630  *
2631  * The next functions do a basic initialization of IOMMU for pass through
2632  * mode
2633  *
2634  * In passthrough mode the IOMMU is initialized and enabled but not used for
2635  * DMA-API translation.
2636  *
2637  *****************************************************************************/
2638 
2639 /* IOMMUv2 specific functions */
2640 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
2641 {
2642 	return atomic_notifier_chain_register(&ppr_notifier, nb);
2643 }
2644 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
2645 
2646 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
2647 {
2648 	return atomic_notifier_chain_unregister(&ppr_notifier, nb);
2649 }
2650 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
2651 
2652 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
2653 {
2654 	struct protection_domain *domain = to_pdomain(dom);
2655 	unsigned long flags;
2656 
2657 	spin_lock_irqsave(&domain->lock, flags);
2658 
2659 	if (domain->iop.pgtbl_cfg.tlb)
2660 		free_io_pgtable_ops(&domain->iop.iop.ops);
2661 
2662 	spin_unlock_irqrestore(&domain->lock, flags);
2663 }
2664 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
2665 
2666 /* Note: This function expects iommu_domain->lock to be held prior calling the function. */
2667 static int domain_enable_v2(struct protection_domain *domain, int pasids)
2668 {
2669 	int levels;
2670 
2671 	/* Number of GCR3 table levels required */
2672 	for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
2673 		levels += 1;
2674 
2675 	if (levels > amd_iommu_max_glx_val)
2676 		return -EINVAL;
2677 
2678 	domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
2679 	if (domain->gcr3_tbl == NULL)
2680 		return -ENOMEM;
2681 
2682 	domain->glx      = levels;
2683 	domain->flags   |= PD_IOMMUV2_MASK;
2684 
2685 	amd_iommu_domain_update(domain);
2686 
2687 	return 0;
2688 }
2689 
2690 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
2691 {
2692 	struct protection_domain *pdom = to_pdomain(dom);
2693 	unsigned long flags;
2694 	int ret;
2695 
2696 	spin_lock_irqsave(&pdom->lock, flags);
2697 
2698 	/*
2699 	 * Save us all sanity checks whether devices already in the
2700 	 * domain support IOMMUv2. Just force that the domain has no
2701 	 * devices attached when it is switched into IOMMUv2 mode.
2702 	 */
2703 	ret = -EBUSY;
2704 	if (pdom->dev_cnt > 0 || pdom->flags & PD_IOMMUV2_MASK)
2705 		goto out;
2706 
2707 	if (!pdom->gcr3_tbl)
2708 		ret = domain_enable_v2(pdom, pasids);
2709 
2710 out:
2711 	spin_unlock_irqrestore(&pdom->lock, flags);
2712 	return ret;
2713 }
2714 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
2715 
2716 static int __flush_pasid(struct protection_domain *domain, u32 pasid,
2717 			 u64 address, bool size)
2718 {
2719 	struct iommu_dev_data *dev_data;
2720 	struct iommu_cmd cmd;
2721 	int i, ret;
2722 
2723 	if (!(domain->flags & PD_IOMMUV2_MASK))
2724 		return -EINVAL;
2725 
2726 	build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
2727 
2728 	/*
2729 	 * IOMMU TLB needs to be flushed before Device TLB to
2730 	 * prevent device TLB refill from IOMMU TLB
2731 	 */
2732 	for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
2733 		if (domain->dev_iommu[i] == 0)
2734 			continue;
2735 
2736 		ret = iommu_queue_command(amd_iommus[i], &cmd);
2737 		if (ret != 0)
2738 			goto out;
2739 	}
2740 
2741 	/* Wait until IOMMU TLB flushes are complete */
2742 	amd_iommu_domain_flush_complete(domain);
2743 
2744 	/* Now flush device TLBs */
2745 	list_for_each_entry(dev_data, &domain->dev_list, list) {
2746 		struct amd_iommu *iommu;
2747 		int qdep;
2748 
2749 		/*
2750 		   There might be non-IOMMUv2 capable devices in an IOMMUv2
2751 		 * domain.
2752 		 */
2753 		if (!dev_data->ats.enabled)
2754 			continue;
2755 
2756 		qdep  = dev_data->ats.qdep;
2757 		iommu = rlookup_amd_iommu(dev_data->dev);
2758 		if (!iommu)
2759 			continue;
2760 		build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
2761 				      qdep, address, size);
2762 
2763 		ret = iommu_queue_command(iommu, &cmd);
2764 		if (ret != 0)
2765 			goto out;
2766 	}
2767 
2768 	/* Wait until all device TLBs are flushed */
2769 	amd_iommu_domain_flush_complete(domain);
2770 
2771 	ret = 0;
2772 
2773 out:
2774 
2775 	return ret;
2776 }
2777 
2778 static int __amd_iommu_flush_page(struct protection_domain *domain, u32 pasid,
2779 				  u64 address)
2780 {
2781 	return __flush_pasid(domain, pasid, address, false);
2782 }
2783 
2784 int amd_iommu_flush_page(struct iommu_domain *dom, u32 pasid,
2785 			 u64 address)
2786 {
2787 	struct protection_domain *domain = to_pdomain(dom);
2788 	unsigned long flags;
2789 	int ret;
2790 
2791 	spin_lock_irqsave(&domain->lock, flags);
2792 	ret = __amd_iommu_flush_page(domain, pasid, address);
2793 	spin_unlock_irqrestore(&domain->lock, flags);
2794 
2795 	return ret;
2796 }
2797 EXPORT_SYMBOL(amd_iommu_flush_page);
2798 
2799 static int __amd_iommu_flush_tlb(struct protection_domain *domain, u32 pasid)
2800 {
2801 	return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
2802 			     true);
2803 }
2804 
2805 int amd_iommu_flush_tlb(struct iommu_domain *dom, u32 pasid)
2806 {
2807 	struct protection_domain *domain = to_pdomain(dom);
2808 	unsigned long flags;
2809 	int ret;
2810 
2811 	spin_lock_irqsave(&domain->lock, flags);
2812 	ret = __amd_iommu_flush_tlb(domain, pasid);
2813 	spin_unlock_irqrestore(&domain->lock, flags);
2814 
2815 	return ret;
2816 }
2817 EXPORT_SYMBOL(amd_iommu_flush_tlb);
2818 
2819 static u64 *__get_gcr3_pte(u64 *root, int level, u32 pasid, bool alloc)
2820 {
2821 	int index;
2822 	u64 *pte;
2823 
2824 	while (true) {
2825 
2826 		index = (pasid >> (9 * level)) & 0x1ff;
2827 		pte   = &root[index];
2828 
2829 		if (level == 0)
2830 			break;
2831 
2832 		if (!(*pte & GCR3_VALID)) {
2833 			if (!alloc)
2834 				return NULL;
2835 
2836 			root = (void *)get_zeroed_page(GFP_ATOMIC);
2837 			if (root == NULL)
2838 				return NULL;
2839 
2840 			*pte = iommu_virt_to_phys(root) | GCR3_VALID;
2841 		}
2842 
2843 		root = iommu_phys_to_virt(*pte & PAGE_MASK);
2844 
2845 		level -= 1;
2846 	}
2847 
2848 	return pte;
2849 }
2850 
2851 static int __set_gcr3(struct protection_domain *domain, u32 pasid,
2852 		      unsigned long cr3)
2853 {
2854 	u64 *pte;
2855 
2856 	if (domain->iop.mode != PAGE_MODE_NONE)
2857 		return -EINVAL;
2858 
2859 	pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
2860 	if (pte == NULL)
2861 		return -ENOMEM;
2862 
2863 	*pte = (cr3 & PAGE_MASK) | GCR3_VALID;
2864 
2865 	return __amd_iommu_flush_tlb(domain, pasid);
2866 }
2867 
2868 static int __clear_gcr3(struct protection_domain *domain, u32 pasid)
2869 {
2870 	u64 *pte;
2871 
2872 	if (domain->iop.mode != PAGE_MODE_NONE)
2873 		return -EINVAL;
2874 
2875 	pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
2876 	if (pte == NULL)
2877 		return 0;
2878 
2879 	*pte = 0;
2880 
2881 	return __amd_iommu_flush_tlb(domain, pasid);
2882 }
2883 
2884 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, u32 pasid,
2885 			      unsigned long cr3)
2886 {
2887 	struct protection_domain *domain = to_pdomain(dom);
2888 	unsigned long flags;
2889 	int ret;
2890 
2891 	spin_lock_irqsave(&domain->lock, flags);
2892 	ret = __set_gcr3(domain, pasid, cr3);
2893 	spin_unlock_irqrestore(&domain->lock, flags);
2894 
2895 	return ret;
2896 }
2897 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
2898 
2899 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, u32 pasid)
2900 {
2901 	struct protection_domain *domain = to_pdomain(dom);
2902 	unsigned long flags;
2903 	int ret;
2904 
2905 	spin_lock_irqsave(&domain->lock, flags);
2906 	ret = __clear_gcr3(domain, pasid);
2907 	spin_unlock_irqrestore(&domain->lock, flags);
2908 
2909 	return ret;
2910 }
2911 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
2912 
2913 int amd_iommu_complete_ppr(struct pci_dev *pdev, u32 pasid,
2914 			   int status, int tag)
2915 {
2916 	struct iommu_dev_data *dev_data;
2917 	struct amd_iommu *iommu;
2918 	struct iommu_cmd cmd;
2919 
2920 	dev_data = dev_iommu_priv_get(&pdev->dev);
2921 	iommu    = rlookup_amd_iommu(&pdev->dev);
2922 	if (!iommu)
2923 		return -ENODEV;
2924 
2925 	build_complete_ppr(&cmd, dev_data->devid, pasid, status,
2926 			   tag, dev_data->pri_tlp);
2927 
2928 	return iommu_queue_command(iommu, &cmd);
2929 }
2930 EXPORT_SYMBOL(amd_iommu_complete_ppr);
2931 
2932 int amd_iommu_device_info(struct pci_dev *pdev,
2933                           struct amd_iommu_device_info *info)
2934 {
2935 	int max_pasids;
2936 	int pos;
2937 
2938 	if (pdev == NULL || info == NULL)
2939 		return -EINVAL;
2940 
2941 	if (!amd_iommu_v2_supported())
2942 		return -EINVAL;
2943 
2944 	memset(info, 0, sizeof(*info));
2945 
2946 	if (pci_ats_supported(pdev))
2947 		info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
2948 
2949 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2950 	if (pos)
2951 		info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
2952 
2953 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
2954 	if (pos) {
2955 		int features;
2956 
2957 		max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
2958 		max_pasids = min(max_pasids, (1 << 20));
2959 
2960 		info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
2961 		info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
2962 
2963 		features = pci_pasid_features(pdev);
2964 		if (features & PCI_PASID_CAP_EXEC)
2965 			info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
2966 		if (features & PCI_PASID_CAP_PRIV)
2967 			info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
2968 	}
2969 
2970 	return 0;
2971 }
2972 EXPORT_SYMBOL(amd_iommu_device_info);
2973 
2974 #ifdef CONFIG_IRQ_REMAP
2975 
2976 /*****************************************************************************
2977  *
2978  * Interrupt Remapping Implementation
2979  *
2980  *****************************************************************************/
2981 
2982 static struct irq_chip amd_ir_chip;
2983 static DEFINE_SPINLOCK(iommu_table_lock);
2984 
2985 static void iommu_flush_irt_and_complete(struct amd_iommu *iommu, u16 devid)
2986 {
2987 	int ret;
2988 	u64 data;
2989 	unsigned long flags;
2990 	struct iommu_cmd cmd, cmd2;
2991 
2992 	if (iommu->irtcachedis_enabled)
2993 		return;
2994 
2995 	build_inv_irt(&cmd, devid);
2996 	data = atomic64_add_return(1, &iommu->cmd_sem_val);
2997 	build_completion_wait(&cmd2, iommu, data);
2998 
2999 	raw_spin_lock_irqsave(&iommu->lock, flags);
3000 	ret = __iommu_queue_command_sync(iommu, &cmd, true);
3001 	if (ret)
3002 		goto out;
3003 	ret = __iommu_queue_command_sync(iommu, &cmd2, false);
3004 	if (ret)
3005 		goto out;
3006 	wait_on_sem(iommu, data);
3007 out:
3008 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
3009 }
3010 
3011 static void set_dte_irq_entry(struct amd_iommu *iommu, u16 devid,
3012 			      struct irq_remap_table *table)
3013 {
3014 	u64 dte;
3015 	struct dev_table_entry *dev_table = get_dev_table(iommu);
3016 
3017 	dte	= dev_table[devid].data[2];
3018 	dte	&= ~DTE_IRQ_PHYS_ADDR_MASK;
3019 	dte	|= iommu_virt_to_phys(table->table);
3020 	dte	|= DTE_IRQ_REMAP_INTCTL;
3021 	dte	|= DTE_INTTABLEN;
3022 	dte	|= DTE_IRQ_REMAP_ENABLE;
3023 
3024 	dev_table[devid].data[2] = dte;
3025 }
3026 
3027 static struct irq_remap_table *get_irq_table(struct amd_iommu *iommu, u16 devid)
3028 {
3029 	struct irq_remap_table *table;
3030 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
3031 
3032 	if (WARN_ONCE(!pci_seg->rlookup_table[devid],
3033 		      "%s: no iommu for devid %x:%x\n",
3034 		      __func__, pci_seg->id, devid))
3035 		return NULL;
3036 
3037 	table = pci_seg->irq_lookup_table[devid];
3038 	if (WARN_ONCE(!table, "%s: no table for devid %x:%x\n",
3039 		      __func__, pci_seg->id, devid))
3040 		return NULL;
3041 
3042 	return table;
3043 }
3044 
3045 static struct irq_remap_table *__alloc_irq_table(void)
3046 {
3047 	struct irq_remap_table *table;
3048 
3049 	table = kzalloc(sizeof(*table), GFP_KERNEL);
3050 	if (!table)
3051 		return NULL;
3052 
3053 	table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_KERNEL);
3054 	if (!table->table) {
3055 		kfree(table);
3056 		return NULL;
3057 	}
3058 	raw_spin_lock_init(&table->lock);
3059 
3060 	if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
3061 		memset(table->table, 0,
3062 		       MAX_IRQS_PER_TABLE * sizeof(u32));
3063 	else
3064 		memset(table->table, 0,
3065 		       (MAX_IRQS_PER_TABLE * (sizeof(u64) * 2)));
3066 	return table;
3067 }
3068 
3069 static void set_remap_table_entry(struct amd_iommu *iommu, u16 devid,
3070 				  struct irq_remap_table *table)
3071 {
3072 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
3073 
3074 	pci_seg->irq_lookup_table[devid] = table;
3075 	set_dte_irq_entry(iommu, devid, table);
3076 	iommu_flush_dte(iommu, devid);
3077 }
3078 
3079 static int set_remap_table_entry_alias(struct pci_dev *pdev, u16 alias,
3080 				       void *data)
3081 {
3082 	struct irq_remap_table *table = data;
3083 	struct amd_iommu_pci_seg *pci_seg;
3084 	struct amd_iommu *iommu = rlookup_amd_iommu(&pdev->dev);
3085 
3086 	if (!iommu)
3087 		return -EINVAL;
3088 
3089 	pci_seg = iommu->pci_seg;
3090 	pci_seg->irq_lookup_table[alias] = table;
3091 	set_dte_irq_entry(iommu, alias, table);
3092 	iommu_flush_dte(pci_seg->rlookup_table[alias], alias);
3093 
3094 	return 0;
3095 }
3096 
3097 static struct irq_remap_table *alloc_irq_table(struct amd_iommu *iommu,
3098 					       u16 devid, struct pci_dev *pdev)
3099 {
3100 	struct irq_remap_table *table = NULL;
3101 	struct irq_remap_table *new_table = NULL;
3102 	struct amd_iommu_pci_seg *pci_seg;
3103 	unsigned long flags;
3104 	u16 alias;
3105 
3106 	spin_lock_irqsave(&iommu_table_lock, flags);
3107 
3108 	pci_seg = iommu->pci_seg;
3109 	table = pci_seg->irq_lookup_table[devid];
3110 	if (table)
3111 		goto out_unlock;
3112 
3113 	alias = pci_seg->alias_table[devid];
3114 	table = pci_seg->irq_lookup_table[alias];
3115 	if (table) {
3116 		set_remap_table_entry(iommu, devid, table);
3117 		goto out_wait;
3118 	}
3119 	spin_unlock_irqrestore(&iommu_table_lock, flags);
3120 
3121 	/* Nothing there yet, allocate new irq remapping table */
3122 	new_table = __alloc_irq_table();
3123 	if (!new_table)
3124 		return NULL;
3125 
3126 	spin_lock_irqsave(&iommu_table_lock, flags);
3127 
3128 	table = pci_seg->irq_lookup_table[devid];
3129 	if (table)
3130 		goto out_unlock;
3131 
3132 	table = pci_seg->irq_lookup_table[alias];
3133 	if (table) {
3134 		set_remap_table_entry(iommu, devid, table);
3135 		goto out_wait;
3136 	}
3137 
3138 	table = new_table;
3139 	new_table = NULL;
3140 
3141 	if (pdev)
3142 		pci_for_each_dma_alias(pdev, set_remap_table_entry_alias,
3143 				       table);
3144 	else
3145 		set_remap_table_entry(iommu, devid, table);
3146 
3147 	if (devid != alias)
3148 		set_remap_table_entry(iommu, alias, table);
3149 
3150 out_wait:
3151 	iommu_completion_wait(iommu);
3152 
3153 out_unlock:
3154 	spin_unlock_irqrestore(&iommu_table_lock, flags);
3155 
3156 	if (new_table) {
3157 		kmem_cache_free(amd_iommu_irq_cache, new_table->table);
3158 		kfree(new_table);
3159 	}
3160 	return table;
3161 }
3162 
3163 static int alloc_irq_index(struct amd_iommu *iommu, u16 devid, int count,
3164 			   bool align, struct pci_dev *pdev)
3165 {
3166 	struct irq_remap_table *table;
3167 	int index, c, alignment = 1;
3168 	unsigned long flags;
3169 
3170 	table = alloc_irq_table(iommu, devid, pdev);
3171 	if (!table)
3172 		return -ENODEV;
3173 
3174 	if (align)
3175 		alignment = roundup_pow_of_two(count);
3176 
3177 	raw_spin_lock_irqsave(&table->lock, flags);
3178 
3179 	/* Scan table for free entries */
3180 	for (index = ALIGN(table->min_index, alignment), c = 0;
3181 	     index < MAX_IRQS_PER_TABLE;) {
3182 		if (!iommu->irte_ops->is_allocated(table, index)) {
3183 			c += 1;
3184 		} else {
3185 			c     = 0;
3186 			index = ALIGN(index + 1, alignment);
3187 			continue;
3188 		}
3189 
3190 		if (c == count)	{
3191 			for (; c != 0; --c)
3192 				iommu->irte_ops->set_allocated(table, index - c + 1);
3193 
3194 			index -= count - 1;
3195 			goto out;
3196 		}
3197 
3198 		index++;
3199 	}
3200 
3201 	index = -ENOSPC;
3202 
3203 out:
3204 	raw_spin_unlock_irqrestore(&table->lock, flags);
3205 
3206 	return index;
3207 }
3208 
3209 static int modify_irte_ga(struct amd_iommu *iommu, u16 devid, int index,
3210 			  struct irte_ga *irte)
3211 {
3212 	struct irq_remap_table *table;
3213 	struct irte_ga *entry;
3214 	unsigned long flags;
3215 	u128 old;
3216 
3217 	table = get_irq_table(iommu, devid);
3218 	if (!table)
3219 		return -ENOMEM;
3220 
3221 	raw_spin_lock_irqsave(&table->lock, flags);
3222 
3223 	entry = (struct irte_ga *)table->table;
3224 	entry = &entry[index];
3225 
3226 	/*
3227 	 * We use cmpxchg16 to atomically update the 128-bit IRTE,
3228 	 * and it cannot be updated by the hardware or other processors
3229 	 * behind us, so the return value of cmpxchg16 should be the
3230 	 * same as the old value.
3231 	 */
3232 	old = entry->irte;
3233 	WARN_ON(!try_cmpxchg128(&entry->irte, &old, irte->irte));
3234 
3235 	raw_spin_unlock_irqrestore(&table->lock, flags);
3236 
3237 	iommu_flush_irt_and_complete(iommu, devid);
3238 
3239 	return 0;
3240 }
3241 
3242 static int modify_irte(struct amd_iommu *iommu,
3243 		       u16 devid, int index, union irte *irte)
3244 {
3245 	struct irq_remap_table *table;
3246 	unsigned long flags;
3247 
3248 	table = get_irq_table(iommu, devid);
3249 	if (!table)
3250 		return -ENOMEM;
3251 
3252 	raw_spin_lock_irqsave(&table->lock, flags);
3253 	table->table[index] = irte->val;
3254 	raw_spin_unlock_irqrestore(&table->lock, flags);
3255 
3256 	iommu_flush_irt_and_complete(iommu, devid);
3257 
3258 	return 0;
3259 }
3260 
3261 static void free_irte(struct amd_iommu *iommu, u16 devid, int index)
3262 {
3263 	struct irq_remap_table *table;
3264 	unsigned long flags;
3265 
3266 	table = get_irq_table(iommu, devid);
3267 	if (!table)
3268 		return;
3269 
3270 	raw_spin_lock_irqsave(&table->lock, flags);
3271 	iommu->irte_ops->clear_allocated(table, index);
3272 	raw_spin_unlock_irqrestore(&table->lock, flags);
3273 
3274 	iommu_flush_irt_and_complete(iommu, devid);
3275 }
3276 
3277 static void irte_prepare(void *entry,
3278 			 u32 delivery_mode, bool dest_mode,
3279 			 u8 vector, u32 dest_apicid, int devid)
3280 {
3281 	union irte *irte = (union irte *) entry;
3282 
3283 	irte->val                = 0;
3284 	irte->fields.vector      = vector;
3285 	irte->fields.int_type    = delivery_mode;
3286 	irte->fields.destination = dest_apicid;
3287 	irte->fields.dm          = dest_mode;
3288 	irte->fields.valid       = 1;
3289 }
3290 
3291 static void irte_ga_prepare(void *entry,
3292 			    u32 delivery_mode, bool dest_mode,
3293 			    u8 vector, u32 dest_apicid, int devid)
3294 {
3295 	struct irte_ga *irte = (struct irte_ga *) entry;
3296 
3297 	irte->lo.val                      = 0;
3298 	irte->hi.val                      = 0;
3299 	irte->lo.fields_remap.int_type    = delivery_mode;
3300 	irte->lo.fields_remap.dm          = dest_mode;
3301 	irte->hi.fields.vector            = vector;
3302 	irte->lo.fields_remap.destination = APICID_TO_IRTE_DEST_LO(dest_apicid);
3303 	irte->hi.fields.destination       = APICID_TO_IRTE_DEST_HI(dest_apicid);
3304 	irte->lo.fields_remap.valid       = 1;
3305 }
3306 
3307 static void irte_activate(struct amd_iommu *iommu, void *entry, u16 devid, u16 index)
3308 {
3309 	union irte *irte = (union irte *) entry;
3310 
3311 	irte->fields.valid = 1;
3312 	modify_irte(iommu, devid, index, irte);
3313 }
3314 
3315 static void irte_ga_activate(struct amd_iommu *iommu, void *entry, u16 devid, u16 index)
3316 {
3317 	struct irte_ga *irte = (struct irte_ga *) entry;
3318 
3319 	irte->lo.fields_remap.valid = 1;
3320 	modify_irte_ga(iommu, devid, index, irte);
3321 }
3322 
3323 static void irte_deactivate(struct amd_iommu *iommu, void *entry, u16 devid, u16 index)
3324 {
3325 	union irte *irte = (union irte *) entry;
3326 
3327 	irte->fields.valid = 0;
3328 	modify_irte(iommu, devid, index, irte);
3329 }
3330 
3331 static void irte_ga_deactivate(struct amd_iommu *iommu, void *entry, u16 devid, u16 index)
3332 {
3333 	struct irte_ga *irte = (struct irte_ga *) entry;
3334 
3335 	irte->lo.fields_remap.valid = 0;
3336 	modify_irte_ga(iommu, devid, index, irte);
3337 }
3338 
3339 static void irte_set_affinity(struct amd_iommu *iommu, void *entry, u16 devid, u16 index,
3340 			      u8 vector, u32 dest_apicid)
3341 {
3342 	union irte *irte = (union irte *) entry;
3343 
3344 	irte->fields.vector = vector;
3345 	irte->fields.destination = dest_apicid;
3346 	modify_irte(iommu, devid, index, irte);
3347 }
3348 
3349 static void irte_ga_set_affinity(struct amd_iommu *iommu, void *entry, u16 devid, u16 index,
3350 				 u8 vector, u32 dest_apicid)
3351 {
3352 	struct irte_ga *irte = (struct irte_ga *) entry;
3353 
3354 	if (!irte->lo.fields_remap.guest_mode) {
3355 		irte->hi.fields.vector = vector;
3356 		irte->lo.fields_remap.destination =
3357 					APICID_TO_IRTE_DEST_LO(dest_apicid);
3358 		irte->hi.fields.destination =
3359 					APICID_TO_IRTE_DEST_HI(dest_apicid);
3360 		modify_irte_ga(iommu, devid, index, irte);
3361 	}
3362 }
3363 
3364 #define IRTE_ALLOCATED (~1U)
3365 static void irte_set_allocated(struct irq_remap_table *table, int index)
3366 {
3367 	table->table[index] = IRTE_ALLOCATED;
3368 }
3369 
3370 static void irte_ga_set_allocated(struct irq_remap_table *table, int index)
3371 {
3372 	struct irte_ga *ptr = (struct irte_ga *)table->table;
3373 	struct irte_ga *irte = &ptr[index];
3374 
3375 	memset(&irte->lo.val, 0, sizeof(u64));
3376 	memset(&irte->hi.val, 0, sizeof(u64));
3377 	irte->hi.fields.vector = 0xff;
3378 }
3379 
3380 static bool irte_is_allocated(struct irq_remap_table *table, int index)
3381 {
3382 	union irte *ptr = (union irte *)table->table;
3383 	union irte *irte = &ptr[index];
3384 
3385 	return irte->val != 0;
3386 }
3387 
3388 static bool irte_ga_is_allocated(struct irq_remap_table *table, int index)
3389 {
3390 	struct irte_ga *ptr = (struct irte_ga *)table->table;
3391 	struct irte_ga *irte = &ptr[index];
3392 
3393 	return irte->hi.fields.vector != 0;
3394 }
3395 
3396 static void irte_clear_allocated(struct irq_remap_table *table, int index)
3397 {
3398 	table->table[index] = 0;
3399 }
3400 
3401 static void irte_ga_clear_allocated(struct irq_remap_table *table, int index)
3402 {
3403 	struct irte_ga *ptr = (struct irte_ga *)table->table;
3404 	struct irte_ga *irte = &ptr[index];
3405 
3406 	memset(&irte->lo.val, 0, sizeof(u64));
3407 	memset(&irte->hi.val, 0, sizeof(u64));
3408 }
3409 
3410 static int get_devid(struct irq_alloc_info *info)
3411 {
3412 	switch (info->type) {
3413 	case X86_IRQ_ALLOC_TYPE_IOAPIC:
3414 		return get_ioapic_devid(info->devid);
3415 	case X86_IRQ_ALLOC_TYPE_HPET:
3416 		return get_hpet_devid(info->devid);
3417 	case X86_IRQ_ALLOC_TYPE_PCI_MSI:
3418 	case X86_IRQ_ALLOC_TYPE_PCI_MSIX:
3419 		return get_device_sbdf_id(msi_desc_to_dev(info->desc));
3420 	default:
3421 		WARN_ON_ONCE(1);
3422 		return -1;
3423 	}
3424 }
3425 
3426 struct irq_remap_ops amd_iommu_irq_ops = {
3427 	.prepare		= amd_iommu_prepare,
3428 	.enable			= amd_iommu_enable,
3429 	.disable		= amd_iommu_disable,
3430 	.reenable		= amd_iommu_reenable,
3431 	.enable_faulting	= amd_iommu_enable_faulting,
3432 };
3433 
3434 static void fill_msi_msg(struct msi_msg *msg, u32 index)
3435 {
3436 	msg->data = index;
3437 	msg->address_lo = 0;
3438 	msg->arch_addr_lo.base_address = X86_MSI_BASE_ADDRESS_LOW;
3439 	msg->address_hi = X86_MSI_BASE_ADDRESS_HIGH;
3440 }
3441 
3442 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
3443 				       struct irq_cfg *irq_cfg,
3444 				       struct irq_alloc_info *info,
3445 				       int devid, int index, int sub_handle)
3446 {
3447 	struct irq_2_irte *irte_info = &data->irq_2_irte;
3448 	struct amd_iommu *iommu = data->iommu;
3449 
3450 	if (!iommu)
3451 		return;
3452 
3453 	data->irq_2_irte.devid = devid;
3454 	data->irq_2_irte.index = index + sub_handle;
3455 	iommu->irte_ops->prepare(data->entry, apic->delivery_mode,
3456 				 apic->dest_mode_logical, irq_cfg->vector,
3457 				 irq_cfg->dest_apicid, devid);
3458 
3459 	switch (info->type) {
3460 	case X86_IRQ_ALLOC_TYPE_IOAPIC:
3461 	case X86_IRQ_ALLOC_TYPE_HPET:
3462 	case X86_IRQ_ALLOC_TYPE_PCI_MSI:
3463 	case X86_IRQ_ALLOC_TYPE_PCI_MSIX:
3464 		fill_msi_msg(&data->msi_entry, irte_info->index);
3465 		break;
3466 
3467 	default:
3468 		BUG_ON(1);
3469 		break;
3470 	}
3471 }
3472 
3473 struct amd_irte_ops irte_32_ops = {
3474 	.prepare = irte_prepare,
3475 	.activate = irte_activate,
3476 	.deactivate = irte_deactivate,
3477 	.set_affinity = irte_set_affinity,
3478 	.set_allocated = irte_set_allocated,
3479 	.is_allocated = irte_is_allocated,
3480 	.clear_allocated = irte_clear_allocated,
3481 };
3482 
3483 struct amd_irte_ops irte_128_ops = {
3484 	.prepare = irte_ga_prepare,
3485 	.activate = irte_ga_activate,
3486 	.deactivate = irte_ga_deactivate,
3487 	.set_affinity = irte_ga_set_affinity,
3488 	.set_allocated = irte_ga_set_allocated,
3489 	.is_allocated = irte_ga_is_allocated,
3490 	.clear_allocated = irte_ga_clear_allocated,
3491 };
3492 
3493 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
3494 			       unsigned int nr_irqs, void *arg)
3495 {
3496 	struct irq_alloc_info *info = arg;
3497 	struct irq_data *irq_data;
3498 	struct amd_ir_data *data = NULL;
3499 	struct amd_iommu *iommu;
3500 	struct irq_cfg *cfg;
3501 	int i, ret, devid, seg, sbdf;
3502 	int index;
3503 
3504 	if (!info)
3505 		return -EINVAL;
3506 	if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_PCI_MSI)
3507 		return -EINVAL;
3508 
3509 	sbdf = get_devid(info);
3510 	if (sbdf < 0)
3511 		return -EINVAL;
3512 
3513 	seg = PCI_SBDF_TO_SEGID(sbdf);
3514 	devid = PCI_SBDF_TO_DEVID(sbdf);
3515 	iommu = __rlookup_amd_iommu(seg, devid);
3516 	if (!iommu)
3517 		return -EINVAL;
3518 
3519 	ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
3520 	if (ret < 0)
3521 		return ret;
3522 
3523 	if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
3524 		struct irq_remap_table *table;
3525 
3526 		table = alloc_irq_table(iommu, devid, NULL);
3527 		if (table) {
3528 			if (!table->min_index) {
3529 				/*
3530 				 * Keep the first 32 indexes free for IOAPIC
3531 				 * interrupts.
3532 				 */
3533 				table->min_index = 32;
3534 				for (i = 0; i < 32; ++i)
3535 					iommu->irte_ops->set_allocated(table, i);
3536 			}
3537 			WARN_ON(table->min_index != 32);
3538 			index = info->ioapic.pin;
3539 		} else {
3540 			index = -ENOMEM;
3541 		}
3542 	} else if (info->type == X86_IRQ_ALLOC_TYPE_PCI_MSI ||
3543 		   info->type == X86_IRQ_ALLOC_TYPE_PCI_MSIX) {
3544 		bool align = (info->type == X86_IRQ_ALLOC_TYPE_PCI_MSI);
3545 
3546 		index = alloc_irq_index(iommu, devid, nr_irqs, align,
3547 					msi_desc_to_pci_dev(info->desc));
3548 	} else {
3549 		index = alloc_irq_index(iommu, devid, nr_irqs, false, NULL);
3550 	}
3551 
3552 	if (index < 0) {
3553 		pr_warn("Failed to allocate IRTE\n");
3554 		ret = index;
3555 		goto out_free_parent;
3556 	}
3557 
3558 	for (i = 0; i < nr_irqs; i++) {
3559 		irq_data = irq_domain_get_irq_data(domain, virq + i);
3560 		cfg = irq_data ? irqd_cfg(irq_data) : NULL;
3561 		if (!cfg) {
3562 			ret = -EINVAL;
3563 			goto out_free_data;
3564 		}
3565 
3566 		ret = -ENOMEM;
3567 		data = kzalloc(sizeof(*data), GFP_KERNEL);
3568 		if (!data)
3569 			goto out_free_data;
3570 
3571 		if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
3572 			data->entry = kzalloc(sizeof(union irte), GFP_KERNEL);
3573 		else
3574 			data->entry = kzalloc(sizeof(struct irte_ga),
3575 						     GFP_KERNEL);
3576 		if (!data->entry) {
3577 			kfree(data);
3578 			goto out_free_data;
3579 		}
3580 
3581 		data->iommu = iommu;
3582 		irq_data->hwirq = (devid << 16) + i;
3583 		irq_data->chip_data = data;
3584 		irq_data->chip = &amd_ir_chip;
3585 		irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
3586 		irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
3587 	}
3588 
3589 	return 0;
3590 
3591 out_free_data:
3592 	for (i--; i >= 0; i--) {
3593 		irq_data = irq_domain_get_irq_data(domain, virq + i);
3594 		if (irq_data)
3595 			kfree(irq_data->chip_data);
3596 	}
3597 	for (i = 0; i < nr_irqs; i++)
3598 		free_irte(iommu, devid, index + i);
3599 out_free_parent:
3600 	irq_domain_free_irqs_common(domain, virq, nr_irqs);
3601 	return ret;
3602 }
3603 
3604 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
3605 			       unsigned int nr_irqs)
3606 {
3607 	struct irq_2_irte *irte_info;
3608 	struct irq_data *irq_data;
3609 	struct amd_ir_data *data;
3610 	int i;
3611 
3612 	for (i = 0; i < nr_irqs; i++) {
3613 		irq_data = irq_domain_get_irq_data(domain, virq  + i);
3614 		if (irq_data && irq_data->chip_data) {
3615 			data = irq_data->chip_data;
3616 			irte_info = &data->irq_2_irte;
3617 			free_irte(data->iommu, irte_info->devid, irte_info->index);
3618 			kfree(data->entry);
3619 			kfree(data);
3620 		}
3621 	}
3622 	irq_domain_free_irqs_common(domain, virq, nr_irqs);
3623 }
3624 
3625 static void amd_ir_update_irte(struct irq_data *irqd, struct amd_iommu *iommu,
3626 			       struct amd_ir_data *ir_data,
3627 			       struct irq_2_irte *irte_info,
3628 			       struct irq_cfg *cfg);
3629 
3630 static int irq_remapping_activate(struct irq_domain *domain,
3631 				  struct irq_data *irq_data, bool reserve)
3632 {
3633 	struct amd_ir_data *data = irq_data->chip_data;
3634 	struct irq_2_irte *irte_info = &data->irq_2_irte;
3635 	struct amd_iommu *iommu = data->iommu;
3636 	struct irq_cfg *cfg = irqd_cfg(irq_data);
3637 
3638 	if (!iommu)
3639 		return 0;
3640 
3641 	iommu->irte_ops->activate(iommu, data->entry, irte_info->devid,
3642 				  irte_info->index);
3643 	amd_ir_update_irte(irq_data, iommu, data, irte_info, cfg);
3644 	return 0;
3645 }
3646 
3647 static void irq_remapping_deactivate(struct irq_domain *domain,
3648 				     struct irq_data *irq_data)
3649 {
3650 	struct amd_ir_data *data = irq_data->chip_data;
3651 	struct irq_2_irte *irte_info = &data->irq_2_irte;
3652 	struct amd_iommu *iommu = data->iommu;
3653 
3654 	if (iommu)
3655 		iommu->irte_ops->deactivate(iommu, data->entry, irte_info->devid,
3656 					    irte_info->index);
3657 }
3658 
3659 static int irq_remapping_select(struct irq_domain *d, struct irq_fwspec *fwspec,
3660 				enum irq_domain_bus_token bus_token)
3661 {
3662 	struct amd_iommu *iommu;
3663 	int devid = -1;
3664 
3665 	if (!amd_iommu_irq_remap)
3666 		return 0;
3667 
3668 	if (x86_fwspec_is_ioapic(fwspec))
3669 		devid = get_ioapic_devid(fwspec->param[0]);
3670 	else if (x86_fwspec_is_hpet(fwspec))
3671 		devid = get_hpet_devid(fwspec->param[0]);
3672 
3673 	if (devid < 0)
3674 		return 0;
3675 	iommu = __rlookup_amd_iommu((devid >> 16), (devid & 0xffff));
3676 
3677 	return iommu && iommu->ir_domain == d;
3678 }
3679 
3680 static const struct irq_domain_ops amd_ir_domain_ops = {
3681 	.select = irq_remapping_select,
3682 	.alloc = irq_remapping_alloc,
3683 	.free = irq_remapping_free,
3684 	.activate = irq_remapping_activate,
3685 	.deactivate = irq_remapping_deactivate,
3686 };
3687 
3688 int amd_iommu_activate_guest_mode(void *data)
3689 {
3690 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
3691 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
3692 	u64 valid;
3693 
3694 	if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) || !entry)
3695 		return 0;
3696 
3697 	valid = entry->lo.fields_vapic.valid;
3698 
3699 	entry->lo.val = 0;
3700 	entry->hi.val = 0;
3701 
3702 	entry->lo.fields_vapic.valid       = valid;
3703 	entry->lo.fields_vapic.guest_mode  = 1;
3704 	entry->lo.fields_vapic.ga_log_intr = 1;
3705 	entry->hi.fields.ga_root_ptr       = ir_data->ga_root_ptr;
3706 	entry->hi.fields.vector            = ir_data->ga_vector;
3707 	entry->lo.fields_vapic.ga_tag      = ir_data->ga_tag;
3708 
3709 	return modify_irte_ga(ir_data->iommu, ir_data->irq_2_irte.devid,
3710 			      ir_data->irq_2_irte.index, entry);
3711 }
3712 EXPORT_SYMBOL(amd_iommu_activate_guest_mode);
3713 
3714 int amd_iommu_deactivate_guest_mode(void *data)
3715 {
3716 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
3717 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
3718 	struct irq_cfg *cfg = ir_data->cfg;
3719 	u64 valid;
3720 
3721 	if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) ||
3722 	    !entry || !entry->lo.fields_vapic.guest_mode)
3723 		return 0;
3724 
3725 	valid = entry->lo.fields_remap.valid;
3726 
3727 	entry->lo.val = 0;
3728 	entry->hi.val = 0;
3729 
3730 	entry->lo.fields_remap.valid       = valid;
3731 	entry->lo.fields_remap.dm          = apic->dest_mode_logical;
3732 	entry->lo.fields_remap.int_type    = apic->delivery_mode;
3733 	entry->hi.fields.vector            = cfg->vector;
3734 	entry->lo.fields_remap.destination =
3735 				APICID_TO_IRTE_DEST_LO(cfg->dest_apicid);
3736 	entry->hi.fields.destination =
3737 				APICID_TO_IRTE_DEST_HI(cfg->dest_apicid);
3738 
3739 	return modify_irte_ga(ir_data->iommu, ir_data->irq_2_irte.devid,
3740 			      ir_data->irq_2_irte.index, entry);
3741 }
3742 EXPORT_SYMBOL(amd_iommu_deactivate_guest_mode);
3743 
3744 static int amd_ir_set_vcpu_affinity(struct irq_data *data, void *vcpu_info)
3745 {
3746 	int ret;
3747 	struct amd_iommu_pi_data *pi_data = vcpu_info;
3748 	struct vcpu_data *vcpu_pi_info = pi_data->vcpu_data;
3749 	struct amd_ir_data *ir_data = data->chip_data;
3750 	struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
3751 	struct iommu_dev_data *dev_data;
3752 
3753 	if (ir_data->iommu == NULL)
3754 		return -EINVAL;
3755 
3756 	dev_data = search_dev_data(ir_data->iommu, irte_info->devid);
3757 
3758 	/* Note:
3759 	 * This device has never been set up for guest mode.
3760 	 * we should not modify the IRTE
3761 	 */
3762 	if (!dev_data || !dev_data->use_vapic)
3763 		return 0;
3764 
3765 	ir_data->cfg = irqd_cfg(data);
3766 	pi_data->ir_data = ir_data;
3767 
3768 	/* Note:
3769 	 * SVM tries to set up for VAPIC mode, but we are in
3770 	 * legacy mode. So, we force legacy mode instead.
3771 	 */
3772 	if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
3773 		pr_debug("%s: Fall back to using intr legacy remap\n",
3774 			 __func__);
3775 		pi_data->is_guest_mode = false;
3776 	}
3777 
3778 	pi_data->prev_ga_tag = ir_data->cached_ga_tag;
3779 	if (pi_data->is_guest_mode) {
3780 		ir_data->ga_root_ptr = (pi_data->base >> 12);
3781 		ir_data->ga_vector = vcpu_pi_info->vector;
3782 		ir_data->ga_tag = pi_data->ga_tag;
3783 		ret = amd_iommu_activate_guest_mode(ir_data);
3784 		if (!ret)
3785 			ir_data->cached_ga_tag = pi_data->ga_tag;
3786 	} else {
3787 		ret = amd_iommu_deactivate_guest_mode(ir_data);
3788 
3789 		/*
3790 		 * This communicates the ga_tag back to the caller
3791 		 * so that it can do all the necessary clean up.
3792 		 */
3793 		if (!ret)
3794 			ir_data->cached_ga_tag = 0;
3795 	}
3796 
3797 	return ret;
3798 }
3799 
3800 
3801 static void amd_ir_update_irte(struct irq_data *irqd, struct amd_iommu *iommu,
3802 			       struct amd_ir_data *ir_data,
3803 			       struct irq_2_irte *irte_info,
3804 			       struct irq_cfg *cfg)
3805 {
3806 
3807 	/*
3808 	 * Atomically updates the IRTE with the new destination, vector
3809 	 * and flushes the interrupt entry cache.
3810 	 */
3811 	iommu->irte_ops->set_affinity(iommu, ir_data->entry, irte_info->devid,
3812 				      irte_info->index, cfg->vector,
3813 				      cfg->dest_apicid);
3814 }
3815 
3816 static int amd_ir_set_affinity(struct irq_data *data,
3817 			       const struct cpumask *mask, bool force)
3818 {
3819 	struct amd_ir_data *ir_data = data->chip_data;
3820 	struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
3821 	struct irq_cfg *cfg = irqd_cfg(data);
3822 	struct irq_data *parent = data->parent_data;
3823 	struct amd_iommu *iommu = ir_data->iommu;
3824 	int ret;
3825 
3826 	if (!iommu)
3827 		return -ENODEV;
3828 
3829 	ret = parent->chip->irq_set_affinity(parent, mask, force);
3830 	if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
3831 		return ret;
3832 
3833 	amd_ir_update_irte(data, iommu, ir_data, irte_info, cfg);
3834 	/*
3835 	 * After this point, all the interrupts will start arriving
3836 	 * at the new destination. So, time to cleanup the previous
3837 	 * vector allocation.
3838 	 */
3839 	vector_schedule_cleanup(cfg);
3840 
3841 	return IRQ_SET_MASK_OK_DONE;
3842 }
3843 
3844 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
3845 {
3846 	struct amd_ir_data *ir_data = irq_data->chip_data;
3847 
3848 	*msg = ir_data->msi_entry;
3849 }
3850 
3851 static struct irq_chip amd_ir_chip = {
3852 	.name			= "AMD-IR",
3853 	.irq_ack		= apic_ack_irq,
3854 	.irq_set_affinity	= amd_ir_set_affinity,
3855 	.irq_set_vcpu_affinity	= amd_ir_set_vcpu_affinity,
3856 	.irq_compose_msi_msg	= ir_compose_msi_msg,
3857 };
3858 
3859 static const struct msi_parent_ops amdvi_msi_parent_ops = {
3860 	.supported_flags	= X86_VECTOR_MSI_FLAGS_SUPPORTED |
3861 				  MSI_FLAG_MULTI_PCI_MSI |
3862 				  MSI_FLAG_PCI_IMS,
3863 	.prefix			= "IR-",
3864 	.init_dev_msi_info	= msi_parent_init_dev_msi_info,
3865 };
3866 
3867 static const struct msi_parent_ops virt_amdvi_msi_parent_ops = {
3868 	.supported_flags	= X86_VECTOR_MSI_FLAGS_SUPPORTED |
3869 				  MSI_FLAG_MULTI_PCI_MSI,
3870 	.prefix			= "vIR-",
3871 	.init_dev_msi_info	= msi_parent_init_dev_msi_info,
3872 };
3873 
3874 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
3875 {
3876 	struct fwnode_handle *fn;
3877 
3878 	fn = irq_domain_alloc_named_id_fwnode("AMD-IR", iommu->index);
3879 	if (!fn)
3880 		return -ENOMEM;
3881 	iommu->ir_domain = irq_domain_create_hierarchy(arch_get_ir_parent_domain(), 0, 0,
3882 						       fn, &amd_ir_domain_ops, iommu);
3883 	if (!iommu->ir_domain) {
3884 		irq_domain_free_fwnode(fn);
3885 		return -ENOMEM;
3886 	}
3887 
3888 	irq_domain_update_bus_token(iommu->ir_domain,  DOMAIN_BUS_AMDVI);
3889 	iommu->ir_domain->flags |= IRQ_DOMAIN_FLAG_MSI_PARENT |
3890 				   IRQ_DOMAIN_FLAG_ISOLATED_MSI;
3891 
3892 	if (amd_iommu_np_cache)
3893 		iommu->ir_domain->msi_parent_ops = &virt_amdvi_msi_parent_ops;
3894 	else
3895 		iommu->ir_domain->msi_parent_ops = &amdvi_msi_parent_ops;
3896 
3897 	return 0;
3898 }
3899 
3900 int amd_iommu_update_ga(int cpu, bool is_run, void *data)
3901 {
3902 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
3903 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
3904 
3905 	if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) ||
3906 	    !entry || !entry->lo.fields_vapic.guest_mode)
3907 		return 0;
3908 
3909 	if (!ir_data->iommu)
3910 		return -ENODEV;
3911 
3912 	if (cpu >= 0) {
3913 		entry->lo.fields_vapic.destination =
3914 					APICID_TO_IRTE_DEST_LO(cpu);
3915 		entry->hi.fields.destination =
3916 					APICID_TO_IRTE_DEST_HI(cpu);
3917 	}
3918 	entry->lo.fields_vapic.is_run = is_run;
3919 
3920 	return modify_irte_ga(ir_data->iommu, ir_data->irq_2_irte.devid,
3921 			      ir_data->irq_2_irte.index, entry);
3922 }
3923 EXPORT_SYMBOL(amd_iommu_update_ga);
3924 #endif
3925