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