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