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