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