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