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