xref: /openbmc/linux/drivers/iommu/amd/init.c (revision 8bdc2a19)
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/pci.h>
12 #include <linux/acpi.h>
13 #include <linux/list.h>
14 #include <linux/bitmap.h>
15 #include <linux/slab.h>
16 #include <linux/syscore_ops.h>
17 #include <linux/interrupt.h>
18 #include <linux/msi.h>
19 #include <linux/irq.h>
20 #include <linux/amd-iommu.h>
21 #include <linux/export.h>
22 #include <linux/kmemleak.h>
23 #include <linux/cc_platform.h>
24 #include <linux/iopoll.h>
25 #include <asm/pci-direct.h>
26 #include <asm/iommu.h>
27 #include <asm/apic.h>
28 #include <asm/gart.h>
29 #include <asm/x86_init.h>
30 #include <asm/io_apic.h>
31 #include <asm/irq_remapping.h>
32 #include <asm/set_memory.h>
33 
34 #include <linux/crash_dump.h>
35 
36 #include "amd_iommu.h"
37 #include "../irq_remapping.h"
38 
39 /*
40  * definitions for the ACPI scanning code
41  */
42 #define IVRS_HEADER_LENGTH 48
43 
44 #define ACPI_IVHD_TYPE_MAX_SUPPORTED	0x40
45 #define ACPI_IVMD_TYPE_ALL              0x20
46 #define ACPI_IVMD_TYPE                  0x21
47 #define ACPI_IVMD_TYPE_RANGE            0x22
48 
49 #define IVHD_DEV_ALL                    0x01
50 #define IVHD_DEV_SELECT                 0x02
51 #define IVHD_DEV_SELECT_RANGE_START     0x03
52 #define IVHD_DEV_RANGE_END              0x04
53 #define IVHD_DEV_ALIAS                  0x42
54 #define IVHD_DEV_ALIAS_RANGE            0x43
55 #define IVHD_DEV_EXT_SELECT             0x46
56 #define IVHD_DEV_EXT_SELECT_RANGE       0x47
57 #define IVHD_DEV_SPECIAL		0x48
58 #define IVHD_DEV_ACPI_HID		0xf0
59 
60 #define UID_NOT_PRESENT                 0
61 #define UID_IS_INTEGER                  1
62 #define UID_IS_CHARACTER                2
63 
64 #define IVHD_SPECIAL_IOAPIC		1
65 #define IVHD_SPECIAL_HPET		2
66 
67 #define IVHD_FLAG_HT_TUN_EN_MASK        0x01
68 #define IVHD_FLAG_PASSPW_EN_MASK        0x02
69 #define IVHD_FLAG_RESPASSPW_EN_MASK     0x04
70 #define IVHD_FLAG_ISOC_EN_MASK          0x08
71 
72 #define IVMD_FLAG_EXCL_RANGE            0x08
73 #define IVMD_FLAG_IW                    0x04
74 #define IVMD_FLAG_IR                    0x02
75 #define IVMD_FLAG_UNITY_MAP             0x01
76 
77 #define ACPI_DEVFLAG_INITPASS           0x01
78 #define ACPI_DEVFLAG_EXTINT             0x02
79 #define ACPI_DEVFLAG_NMI                0x04
80 #define ACPI_DEVFLAG_SYSMGT1            0x10
81 #define ACPI_DEVFLAG_SYSMGT2            0x20
82 #define ACPI_DEVFLAG_LINT0              0x40
83 #define ACPI_DEVFLAG_LINT1              0x80
84 #define ACPI_DEVFLAG_ATSDIS             0x10000000
85 
86 #define LOOP_TIMEOUT	100000
87 /*
88  * ACPI table definitions
89  *
90  * These data structures are laid over the table to parse the important values
91  * out of it.
92  */
93 
94 extern const struct iommu_ops amd_iommu_ops;
95 
96 /*
97  * structure describing one IOMMU in the ACPI table. Typically followed by one
98  * or more ivhd_entrys.
99  */
100 struct ivhd_header {
101 	u8 type;
102 	u8 flags;
103 	u16 length;
104 	u16 devid;
105 	u16 cap_ptr;
106 	u64 mmio_phys;
107 	u16 pci_seg;
108 	u16 info;
109 	u32 efr_attr;
110 
111 	/* Following only valid on IVHD type 11h and 40h */
112 	u64 efr_reg; /* Exact copy of MMIO_EXT_FEATURES */
113 	u64 res;
114 } __attribute__((packed));
115 
116 /*
117  * A device entry describing which devices a specific IOMMU translates and
118  * which requestor ids they use.
119  */
120 struct ivhd_entry {
121 	u8 type;
122 	u16 devid;
123 	u8 flags;
124 	struct_group(ext_hid,
125 		u32 ext;
126 		u32 hidh;
127 	);
128 	u64 cid;
129 	u8 uidf;
130 	u8 uidl;
131 	u8 uid;
132 } __attribute__((packed));
133 
134 /*
135  * An AMD IOMMU memory definition structure. It defines things like exclusion
136  * ranges for devices and regions that should be unity mapped.
137  */
138 struct ivmd_header {
139 	u8 type;
140 	u8 flags;
141 	u16 length;
142 	u16 devid;
143 	u16 aux;
144 	u64 resv;
145 	u64 range_start;
146 	u64 range_length;
147 } __attribute__((packed));
148 
149 bool amd_iommu_dump;
150 bool amd_iommu_irq_remap __read_mostly;
151 
152 enum io_pgtable_fmt amd_iommu_pgtable = AMD_IOMMU_V1;
153 
154 int amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_VAPIC;
155 static int amd_iommu_xt_mode = IRQ_REMAP_XAPIC_MODE;
156 
157 static bool amd_iommu_detected;
158 static bool amd_iommu_disabled __initdata;
159 static bool amd_iommu_force_enable __initdata;
160 static int amd_iommu_target_ivhd_type;
161 
162 u16 amd_iommu_last_bdf;			/* largest PCI device id we have
163 					   to handle */
164 LIST_HEAD(amd_iommu_unity_map);		/* a list of required unity mappings
165 					   we find in ACPI */
166 
167 LIST_HEAD(amd_iommu_list);		/* list of all AMD IOMMUs in the
168 					   system */
169 
170 /* Array to assign indices to IOMMUs*/
171 struct amd_iommu *amd_iommus[MAX_IOMMUS];
172 
173 /* Number of IOMMUs present in the system */
174 static int amd_iommus_present;
175 
176 /* IOMMUs have a non-present cache? */
177 bool amd_iommu_np_cache __read_mostly;
178 bool amd_iommu_iotlb_sup __read_mostly = true;
179 
180 u32 amd_iommu_max_pasid __read_mostly = ~0;
181 
182 bool amd_iommu_v2_present __read_mostly;
183 static bool amd_iommu_pc_present __read_mostly;
184 
185 bool amd_iommu_force_isolation __read_mostly;
186 
187 /*
188  * Pointer to the device table which is shared by all AMD IOMMUs
189  * it is indexed by the PCI device id or the HT unit id and contains
190  * information about the domain the device belongs to as well as the
191  * page table root pointer.
192  */
193 struct dev_table_entry *amd_iommu_dev_table;
194 /*
195  * Pointer to a device table which the content of old device table
196  * will be copied to. It's only be used in kdump kernel.
197  */
198 static struct dev_table_entry *old_dev_tbl_cpy;
199 
200 /*
201  * The alias table is a driver specific data structure which contains the
202  * mappings of the PCI device ids to the actual requestor ids on the IOMMU.
203  * More than one device can share the same requestor id.
204  */
205 u16 *amd_iommu_alias_table;
206 
207 /*
208  * The rlookup table is used to find the IOMMU which is responsible
209  * for a specific device. It is also indexed by the PCI device id.
210  */
211 struct amd_iommu **amd_iommu_rlookup_table;
212 
213 /*
214  * This table is used to find the irq remapping table for a given device id
215  * quickly.
216  */
217 struct irq_remap_table **irq_lookup_table;
218 
219 /*
220  * AMD IOMMU allows up to 2^16 different protection domains. This is a bitmap
221  * to know which ones are already in use.
222  */
223 unsigned long *amd_iommu_pd_alloc_bitmap;
224 
225 static u32 dev_table_size;	/* size of the device table */
226 static u32 alias_table_size;	/* size of the alias table */
227 static u32 rlookup_table_size;	/* size if the rlookup table */
228 
229 enum iommu_init_state {
230 	IOMMU_START_STATE,
231 	IOMMU_IVRS_DETECTED,
232 	IOMMU_ACPI_FINISHED,
233 	IOMMU_ENABLED,
234 	IOMMU_PCI_INIT,
235 	IOMMU_INTERRUPTS_EN,
236 	IOMMU_INITIALIZED,
237 	IOMMU_NOT_FOUND,
238 	IOMMU_INIT_ERROR,
239 	IOMMU_CMDLINE_DISABLED,
240 };
241 
242 /* Early ioapic and hpet maps from kernel command line */
243 #define EARLY_MAP_SIZE		4
244 static struct devid_map __initdata early_ioapic_map[EARLY_MAP_SIZE];
245 static struct devid_map __initdata early_hpet_map[EARLY_MAP_SIZE];
246 static struct acpihid_map_entry __initdata early_acpihid_map[EARLY_MAP_SIZE];
247 
248 static int __initdata early_ioapic_map_size;
249 static int __initdata early_hpet_map_size;
250 static int __initdata early_acpihid_map_size;
251 
252 static bool __initdata cmdline_maps;
253 
254 static enum iommu_init_state init_state = IOMMU_START_STATE;
255 
256 static int amd_iommu_enable_interrupts(void);
257 static int __init iommu_go_to_state(enum iommu_init_state state);
258 static void init_device_table_dma(void);
259 
260 static bool amd_iommu_pre_enabled = true;
261 
262 static u32 amd_iommu_ivinfo __initdata;
263 
264 bool translation_pre_enabled(struct amd_iommu *iommu)
265 {
266 	return (iommu->flags & AMD_IOMMU_FLAG_TRANS_PRE_ENABLED);
267 }
268 
269 static void clear_translation_pre_enabled(struct amd_iommu *iommu)
270 {
271 	iommu->flags &= ~AMD_IOMMU_FLAG_TRANS_PRE_ENABLED;
272 }
273 
274 static void init_translation_status(struct amd_iommu *iommu)
275 {
276 	u64 ctrl;
277 
278 	ctrl = readq(iommu->mmio_base + MMIO_CONTROL_OFFSET);
279 	if (ctrl & (1<<CONTROL_IOMMU_EN))
280 		iommu->flags |= AMD_IOMMU_FLAG_TRANS_PRE_ENABLED;
281 }
282 
283 static inline void update_last_devid(u16 devid)
284 {
285 	if (devid > amd_iommu_last_bdf)
286 		amd_iommu_last_bdf = devid;
287 }
288 
289 static inline unsigned long tbl_size(int entry_size)
290 {
291 	unsigned shift = PAGE_SHIFT +
292 			 get_order(((int)amd_iommu_last_bdf + 1) * entry_size);
293 
294 	return 1UL << shift;
295 }
296 
297 int amd_iommu_get_num_iommus(void)
298 {
299 	return amd_iommus_present;
300 }
301 
302 #ifdef CONFIG_IRQ_REMAP
303 static bool check_feature_on_all_iommus(u64 mask)
304 {
305 	bool ret = false;
306 	struct amd_iommu *iommu;
307 
308 	for_each_iommu(iommu) {
309 		ret = iommu_feature(iommu, mask);
310 		if (!ret)
311 			return false;
312 	}
313 
314 	return true;
315 }
316 #endif
317 
318 /*
319  * For IVHD type 0x11/0x40, EFR is also available via IVHD.
320  * Default to IVHD EFR since it is available sooner
321  * (i.e. before PCI init).
322  */
323 static void __init early_iommu_features_init(struct amd_iommu *iommu,
324 					     struct ivhd_header *h)
325 {
326 	if (amd_iommu_ivinfo & IOMMU_IVINFO_EFRSUP)
327 		iommu->features = h->efr_reg;
328 }
329 
330 /* Access to l1 and l2 indexed register spaces */
331 
332 static u32 iommu_read_l1(struct amd_iommu *iommu, u16 l1, u8 address)
333 {
334 	u32 val;
335 
336 	pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16));
337 	pci_read_config_dword(iommu->dev, 0xfc, &val);
338 	return val;
339 }
340 
341 static void iommu_write_l1(struct amd_iommu *iommu, u16 l1, u8 address, u32 val)
342 {
343 	pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16 | 1 << 31));
344 	pci_write_config_dword(iommu->dev, 0xfc, val);
345 	pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16));
346 }
347 
348 static u32 iommu_read_l2(struct amd_iommu *iommu, u8 address)
349 {
350 	u32 val;
351 
352 	pci_write_config_dword(iommu->dev, 0xf0, address);
353 	pci_read_config_dword(iommu->dev, 0xf4, &val);
354 	return val;
355 }
356 
357 static void iommu_write_l2(struct amd_iommu *iommu, u8 address, u32 val)
358 {
359 	pci_write_config_dword(iommu->dev, 0xf0, (address | 1 << 8));
360 	pci_write_config_dword(iommu->dev, 0xf4, val);
361 }
362 
363 /****************************************************************************
364  *
365  * AMD IOMMU MMIO register space handling functions
366  *
367  * These functions are used to program the IOMMU device registers in
368  * MMIO space required for that driver.
369  *
370  ****************************************************************************/
371 
372 /*
373  * This function set the exclusion range in the IOMMU. DMA accesses to the
374  * exclusion range are passed through untranslated
375  */
376 static void iommu_set_exclusion_range(struct amd_iommu *iommu)
377 {
378 	u64 start = iommu->exclusion_start & PAGE_MASK;
379 	u64 limit = (start + iommu->exclusion_length - 1) & PAGE_MASK;
380 	u64 entry;
381 
382 	if (!iommu->exclusion_start)
383 		return;
384 
385 	entry = start | MMIO_EXCL_ENABLE_MASK;
386 	memcpy_toio(iommu->mmio_base + MMIO_EXCL_BASE_OFFSET,
387 			&entry, sizeof(entry));
388 
389 	entry = limit;
390 	memcpy_toio(iommu->mmio_base + MMIO_EXCL_LIMIT_OFFSET,
391 			&entry, sizeof(entry));
392 }
393 
394 static void iommu_set_cwwb_range(struct amd_iommu *iommu)
395 {
396 	u64 start = iommu_virt_to_phys((void *)iommu->cmd_sem);
397 	u64 entry = start & PM_ADDR_MASK;
398 
399 	if (!iommu_feature(iommu, FEATURE_SNP))
400 		return;
401 
402 	/* Note:
403 	 * Re-purpose Exclusion base/limit registers for Completion wait
404 	 * write-back base/limit.
405 	 */
406 	memcpy_toio(iommu->mmio_base + MMIO_EXCL_BASE_OFFSET,
407 		    &entry, sizeof(entry));
408 
409 	/* Note:
410 	 * Default to 4 Kbytes, which can be specified by setting base
411 	 * address equal to the limit address.
412 	 */
413 	memcpy_toio(iommu->mmio_base + MMIO_EXCL_LIMIT_OFFSET,
414 		    &entry, sizeof(entry));
415 }
416 
417 /* Programs the physical address of the device table into the IOMMU hardware */
418 static void iommu_set_device_table(struct amd_iommu *iommu)
419 {
420 	u64 entry;
421 
422 	BUG_ON(iommu->mmio_base == NULL);
423 
424 	entry = iommu_virt_to_phys(amd_iommu_dev_table);
425 	entry |= (dev_table_size >> 12) - 1;
426 	memcpy_toio(iommu->mmio_base + MMIO_DEV_TABLE_OFFSET,
427 			&entry, sizeof(entry));
428 }
429 
430 /* Generic functions to enable/disable certain features of the IOMMU. */
431 static void iommu_feature_enable(struct amd_iommu *iommu, u8 bit)
432 {
433 	u64 ctrl;
434 
435 	ctrl = readq(iommu->mmio_base +  MMIO_CONTROL_OFFSET);
436 	ctrl |= (1ULL << bit);
437 	writeq(ctrl, iommu->mmio_base +  MMIO_CONTROL_OFFSET);
438 }
439 
440 static void iommu_feature_disable(struct amd_iommu *iommu, u8 bit)
441 {
442 	u64 ctrl;
443 
444 	ctrl = readq(iommu->mmio_base + MMIO_CONTROL_OFFSET);
445 	ctrl &= ~(1ULL << bit);
446 	writeq(ctrl, iommu->mmio_base + MMIO_CONTROL_OFFSET);
447 }
448 
449 static void iommu_set_inv_tlb_timeout(struct amd_iommu *iommu, int timeout)
450 {
451 	u64 ctrl;
452 
453 	ctrl = readq(iommu->mmio_base + MMIO_CONTROL_OFFSET);
454 	ctrl &= ~CTRL_INV_TO_MASK;
455 	ctrl |= (timeout << CONTROL_INV_TIMEOUT) & CTRL_INV_TO_MASK;
456 	writeq(ctrl, iommu->mmio_base + MMIO_CONTROL_OFFSET);
457 }
458 
459 /* Function to enable the hardware */
460 static void iommu_enable(struct amd_iommu *iommu)
461 {
462 	iommu_feature_enable(iommu, CONTROL_IOMMU_EN);
463 }
464 
465 static void iommu_disable(struct amd_iommu *iommu)
466 {
467 	if (!iommu->mmio_base)
468 		return;
469 
470 	/* Disable command buffer */
471 	iommu_feature_disable(iommu, CONTROL_CMDBUF_EN);
472 
473 	/* Disable event logging and event interrupts */
474 	iommu_feature_disable(iommu, CONTROL_EVT_INT_EN);
475 	iommu_feature_disable(iommu, CONTROL_EVT_LOG_EN);
476 
477 	/* Disable IOMMU GA_LOG */
478 	iommu_feature_disable(iommu, CONTROL_GALOG_EN);
479 	iommu_feature_disable(iommu, CONTROL_GAINT_EN);
480 
481 	/* Disable IOMMU hardware itself */
482 	iommu_feature_disable(iommu, CONTROL_IOMMU_EN);
483 }
484 
485 /*
486  * mapping and unmapping functions for the IOMMU MMIO space. Each AMD IOMMU in
487  * the system has one.
488  */
489 static u8 __iomem * __init iommu_map_mmio_space(u64 address, u64 end)
490 {
491 	if (!request_mem_region(address, end, "amd_iommu")) {
492 		pr_err("Can not reserve memory region %llx-%llx for mmio\n",
493 			address, end);
494 		pr_err("This is a BIOS bug. Please contact your hardware vendor\n");
495 		return NULL;
496 	}
497 
498 	return (u8 __iomem *)ioremap(address, end);
499 }
500 
501 static void __init iommu_unmap_mmio_space(struct amd_iommu *iommu)
502 {
503 	if (iommu->mmio_base)
504 		iounmap(iommu->mmio_base);
505 	release_mem_region(iommu->mmio_phys, iommu->mmio_phys_end);
506 }
507 
508 static inline u32 get_ivhd_header_size(struct ivhd_header *h)
509 {
510 	u32 size = 0;
511 
512 	switch (h->type) {
513 	case 0x10:
514 		size = 24;
515 		break;
516 	case 0x11:
517 	case 0x40:
518 		size = 40;
519 		break;
520 	}
521 	return size;
522 }
523 
524 /****************************************************************************
525  *
526  * The functions below belong to the first pass of AMD IOMMU ACPI table
527  * parsing. In this pass we try to find out the highest device id this
528  * code has to handle. Upon this information the size of the shared data
529  * structures is determined later.
530  *
531  ****************************************************************************/
532 
533 /*
534  * This function calculates the length of a given IVHD entry
535  */
536 static inline int ivhd_entry_length(u8 *ivhd)
537 {
538 	u32 type = ((struct ivhd_entry *)ivhd)->type;
539 
540 	if (type < 0x80) {
541 		return 0x04 << (*ivhd >> 6);
542 	} else if (type == IVHD_DEV_ACPI_HID) {
543 		/* For ACPI_HID, offset 21 is uid len */
544 		return *((u8 *)ivhd + 21) + 22;
545 	}
546 	return 0;
547 }
548 
549 /*
550  * After reading the highest device id from the IOMMU PCI capability header
551  * this function looks if there is a higher device id defined in the ACPI table
552  */
553 static int __init find_last_devid_from_ivhd(struct ivhd_header *h)
554 {
555 	u8 *p = (void *)h, *end = (void *)h;
556 	struct ivhd_entry *dev;
557 
558 	u32 ivhd_size = get_ivhd_header_size(h);
559 
560 	if (!ivhd_size) {
561 		pr_err("Unsupported IVHD type %#x\n", h->type);
562 		return -EINVAL;
563 	}
564 
565 	p += ivhd_size;
566 	end += h->length;
567 
568 	while (p < end) {
569 		dev = (struct ivhd_entry *)p;
570 		switch (dev->type) {
571 		case IVHD_DEV_ALL:
572 			/* Use maximum BDF value for DEV_ALL */
573 			update_last_devid(0xffff);
574 			break;
575 		case IVHD_DEV_SELECT:
576 		case IVHD_DEV_RANGE_END:
577 		case IVHD_DEV_ALIAS:
578 		case IVHD_DEV_EXT_SELECT:
579 			/* all the above subfield types refer to device ids */
580 			update_last_devid(dev->devid);
581 			break;
582 		default:
583 			break;
584 		}
585 		p += ivhd_entry_length(p);
586 	}
587 
588 	WARN_ON(p != end);
589 
590 	return 0;
591 }
592 
593 static int __init check_ivrs_checksum(struct acpi_table_header *table)
594 {
595 	int i;
596 	u8 checksum = 0, *p = (u8 *)table;
597 
598 	for (i = 0; i < table->length; ++i)
599 		checksum += p[i];
600 	if (checksum != 0) {
601 		/* ACPI table corrupt */
602 		pr_err(FW_BUG "IVRS invalid checksum\n");
603 		return -ENODEV;
604 	}
605 
606 	return 0;
607 }
608 
609 /*
610  * Iterate over all IVHD entries in the ACPI table and find the highest device
611  * id which we need to handle. This is the first of three functions which parse
612  * the ACPI table. So we check the checksum here.
613  */
614 static int __init find_last_devid_acpi(struct acpi_table_header *table)
615 {
616 	u8 *p = (u8 *)table, *end = (u8 *)table;
617 	struct ivhd_header *h;
618 
619 	p += IVRS_HEADER_LENGTH;
620 
621 	end += table->length;
622 	while (p < end) {
623 		h = (struct ivhd_header *)p;
624 		if (h->type == amd_iommu_target_ivhd_type) {
625 			int ret = find_last_devid_from_ivhd(h);
626 
627 			if (ret)
628 				return ret;
629 		}
630 		p += h->length;
631 	}
632 	WARN_ON(p != end);
633 
634 	return 0;
635 }
636 
637 /****************************************************************************
638  *
639  * The following functions belong to the code path which parses the ACPI table
640  * the second time. In this ACPI parsing iteration we allocate IOMMU specific
641  * data structures, initialize the device/alias/rlookup table and also
642  * basically initialize the hardware.
643  *
644  ****************************************************************************/
645 
646 /*
647  * Allocates the command buffer. This buffer is per AMD IOMMU. We can
648  * write commands to that buffer later and the IOMMU will execute them
649  * asynchronously
650  */
651 static int __init alloc_command_buffer(struct amd_iommu *iommu)
652 {
653 	iommu->cmd_buf = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
654 						  get_order(CMD_BUFFER_SIZE));
655 
656 	return iommu->cmd_buf ? 0 : -ENOMEM;
657 }
658 
659 /*
660  * This function restarts event logging in case the IOMMU experienced
661  * an event log buffer overflow.
662  */
663 void amd_iommu_restart_event_logging(struct amd_iommu *iommu)
664 {
665 	iommu_feature_disable(iommu, CONTROL_EVT_LOG_EN);
666 	iommu_feature_enable(iommu, CONTROL_EVT_LOG_EN);
667 }
668 
669 /*
670  * This function resets the command buffer if the IOMMU stopped fetching
671  * commands from it.
672  */
673 static void amd_iommu_reset_cmd_buffer(struct amd_iommu *iommu)
674 {
675 	iommu_feature_disable(iommu, CONTROL_CMDBUF_EN);
676 
677 	writel(0x00, iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
678 	writel(0x00, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
679 	iommu->cmd_buf_head = 0;
680 	iommu->cmd_buf_tail = 0;
681 
682 	iommu_feature_enable(iommu, CONTROL_CMDBUF_EN);
683 }
684 
685 /*
686  * This function writes the command buffer address to the hardware and
687  * enables it.
688  */
689 static void iommu_enable_command_buffer(struct amd_iommu *iommu)
690 {
691 	u64 entry;
692 
693 	BUG_ON(iommu->cmd_buf == NULL);
694 
695 	entry = iommu_virt_to_phys(iommu->cmd_buf);
696 	entry |= MMIO_CMD_SIZE_512;
697 
698 	memcpy_toio(iommu->mmio_base + MMIO_CMD_BUF_OFFSET,
699 		    &entry, sizeof(entry));
700 
701 	amd_iommu_reset_cmd_buffer(iommu);
702 }
703 
704 /*
705  * This function disables the command buffer
706  */
707 static void iommu_disable_command_buffer(struct amd_iommu *iommu)
708 {
709 	iommu_feature_disable(iommu, CONTROL_CMDBUF_EN);
710 }
711 
712 static void __init free_command_buffer(struct amd_iommu *iommu)
713 {
714 	free_pages((unsigned long)iommu->cmd_buf, get_order(CMD_BUFFER_SIZE));
715 }
716 
717 static void *__init iommu_alloc_4k_pages(struct amd_iommu *iommu,
718 					 gfp_t gfp, size_t size)
719 {
720 	int order = get_order(size);
721 	void *buf = (void *)__get_free_pages(gfp, order);
722 
723 	if (buf &&
724 	    iommu_feature(iommu, FEATURE_SNP) &&
725 	    set_memory_4k((unsigned long)buf, (1 << order))) {
726 		free_pages((unsigned long)buf, order);
727 		buf = NULL;
728 	}
729 
730 	return buf;
731 }
732 
733 /* allocates the memory where the IOMMU will log its events to */
734 static int __init alloc_event_buffer(struct amd_iommu *iommu)
735 {
736 	iommu->evt_buf = iommu_alloc_4k_pages(iommu, GFP_KERNEL | __GFP_ZERO,
737 					      EVT_BUFFER_SIZE);
738 
739 	return iommu->evt_buf ? 0 : -ENOMEM;
740 }
741 
742 static void iommu_enable_event_buffer(struct amd_iommu *iommu)
743 {
744 	u64 entry;
745 
746 	BUG_ON(iommu->evt_buf == NULL);
747 
748 	entry = iommu_virt_to_phys(iommu->evt_buf) | EVT_LEN_MASK;
749 
750 	memcpy_toio(iommu->mmio_base + MMIO_EVT_BUF_OFFSET,
751 		    &entry, sizeof(entry));
752 
753 	/* set head and tail to zero manually */
754 	writel(0x00, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
755 	writel(0x00, iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
756 
757 	iommu_feature_enable(iommu, CONTROL_EVT_LOG_EN);
758 }
759 
760 /*
761  * This function disables the event log buffer
762  */
763 static void iommu_disable_event_buffer(struct amd_iommu *iommu)
764 {
765 	iommu_feature_disable(iommu, CONTROL_EVT_LOG_EN);
766 }
767 
768 static void __init free_event_buffer(struct amd_iommu *iommu)
769 {
770 	free_pages((unsigned long)iommu->evt_buf, get_order(EVT_BUFFER_SIZE));
771 }
772 
773 /* allocates the memory where the IOMMU will log its events to */
774 static int __init alloc_ppr_log(struct amd_iommu *iommu)
775 {
776 	iommu->ppr_log = iommu_alloc_4k_pages(iommu, GFP_KERNEL | __GFP_ZERO,
777 					      PPR_LOG_SIZE);
778 
779 	return iommu->ppr_log ? 0 : -ENOMEM;
780 }
781 
782 static void iommu_enable_ppr_log(struct amd_iommu *iommu)
783 {
784 	u64 entry;
785 
786 	if (iommu->ppr_log == NULL)
787 		return;
788 
789 	entry = iommu_virt_to_phys(iommu->ppr_log) | PPR_LOG_SIZE_512;
790 
791 	memcpy_toio(iommu->mmio_base + MMIO_PPR_LOG_OFFSET,
792 		    &entry, sizeof(entry));
793 
794 	/* set head and tail to zero manually */
795 	writel(0x00, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
796 	writel(0x00, iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
797 
798 	iommu_feature_enable(iommu, CONTROL_PPRLOG_EN);
799 	iommu_feature_enable(iommu, CONTROL_PPR_EN);
800 }
801 
802 static void __init free_ppr_log(struct amd_iommu *iommu)
803 {
804 	free_pages((unsigned long)iommu->ppr_log, get_order(PPR_LOG_SIZE));
805 }
806 
807 static void free_ga_log(struct amd_iommu *iommu)
808 {
809 #ifdef CONFIG_IRQ_REMAP
810 	free_pages((unsigned long)iommu->ga_log, get_order(GA_LOG_SIZE));
811 	free_pages((unsigned long)iommu->ga_log_tail, get_order(8));
812 #endif
813 }
814 
815 static int iommu_ga_log_enable(struct amd_iommu *iommu)
816 {
817 #ifdef CONFIG_IRQ_REMAP
818 	u32 status, i;
819 	u64 entry;
820 
821 	if (!iommu->ga_log)
822 		return -EINVAL;
823 
824 	/* Check if already running */
825 	status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
826 	if (WARN_ON(status & (MMIO_STATUS_GALOG_RUN_MASK)))
827 		return 0;
828 
829 	entry = iommu_virt_to_phys(iommu->ga_log) | GA_LOG_SIZE_512;
830 	memcpy_toio(iommu->mmio_base + MMIO_GA_LOG_BASE_OFFSET,
831 		    &entry, sizeof(entry));
832 	entry = (iommu_virt_to_phys(iommu->ga_log_tail) &
833 		 (BIT_ULL(52)-1)) & ~7ULL;
834 	memcpy_toio(iommu->mmio_base + MMIO_GA_LOG_TAIL_OFFSET,
835 		    &entry, sizeof(entry));
836 	writel(0x00, iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
837 	writel(0x00, iommu->mmio_base + MMIO_GA_TAIL_OFFSET);
838 
839 
840 	iommu_feature_enable(iommu, CONTROL_GAINT_EN);
841 	iommu_feature_enable(iommu, CONTROL_GALOG_EN);
842 
843 	for (i = 0; i < LOOP_TIMEOUT; ++i) {
844 		status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
845 		if (status & (MMIO_STATUS_GALOG_RUN_MASK))
846 			break;
847 		udelay(10);
848 	}
849 
850 	if (WARN_ON(i >= LOOP_TIMEOUT))
851 		return -EINVAL;
852 #endif /* CONFIG_IRQ_REMAP */
853 	return 0;
854 }
855 
856 static int iommu_init_ga_log(struct amd_iommu *iommu)
857 {
858 #ifdef CONFIG_IRQ_REMAP
859 	if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir))
860 		return 0;
861 
862 	iommu->ga_log = (u8 *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
863 					get_order(GA_LOG_SIZE));
864 	if (!iommu->ga_log)
865 		goto err_out;
866 
867 	iommu->ga_log_tail = (u8 *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
868 					get_order(8));
869 	if (!iommu->ga_log_tail)
870 		goto err_out;
871 
872 	return 0;
873 err_out:
874 	free_ga_log(iommu);
875 	return -EINVAL;
876 #else
877 	return 0;
878 #endif /* CONFIG_IRQ_REMAP */
879 }
880 
881 static int __init alloc_cwwb_sem(struct amd_iommu *iommu)
882 {
883 	iommu->cmd_sem = iommu_alloc_4k_pages(iommu, GFP_KERNEL | __GFP_ZERO, 1);
884 
885 	return iommu->cmd_sem ? 0 : -ENOMEM;
886 }
887 
888 static void __init free_cwwb_sem(struct amd_iommu *iommu)
889 {
890 	if (iommu->cmd_sem)
891 		free_page((unsigned long)iommu->cmd_sem);
892 }
893 
894 static void iommu_enable_xt(struct amd_iommu *iommu)
895 {
896 #ifdef CONFIG_IRQ_REMAP
897 	/*
898 	 * XT mode (32-bit APIC destination ID) requires
899 	 * GA mode (128-bit IRTE support) as a prerequisite.
900 	 */
901 	if (AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir) &&
902 	    amd_iommu_xt_mode == IRQ_REMAP_X2APIC_MODE)
903 		iommu_feature_enable(iommu, CONTROL_XT_EN);
904 #endif /* CONFIG_IRQ_REMAP */
905 }
906 
907 static void iommu_enable_gt(struct amd_iommu *iommu)
908 {
909 	if (!iommu_feature(iommu, FEATURE_GT))
910 		return;
911 
912 	iommu_feature_enable(iommu, CONTROL_GT_EN);
913 }
914 
915 /* sets a specific bit in the device table entry. */
916 static void set_dev_entry_bit(u16 devid, u8 bit)
917 {
918 	int i = (bit >> 6) & 0x03;
919 	int _bit = bit & 0x3f;
920 
921 	amd_iommu_dev_table[devid].data[i] |= (1UL << _bit);
922 }
923 
924 static int get_dev_entry_bit(u16 devid, u8 bit)
925 {
926 	int i = (bit >> 6) & 0x03;
927 	int _bit = bit & 0x3f;
928 
929 	return (amd_iommu_dev_table[devid].data[i] & (1UL << _bit)) >> _bit;
930 }
931 
932 
933 static bool copy_device_table(void)
934 {
935 	u64 int_ctl, int_tab_len, entry = 0, last_entry = 0;
936 	struct dev_table_entry *old_devtb = NULL;
937 	u32 lo, hi, devid, old_devtb_size;
938 	phys_addr_t old_devtb_phys;
939 	struct amd_iommu *iommu;
940 	u16 dom_id, dte_v, irq_v;
941 	gfp_t gfp_flag;
942 	u64 tmp;
943 
944 	if (!amd_iommu_pre_enabled)
945 		return false;
946 
947 	pr_warn("Translation is already enabled - trying to copy translation structures\n");
948 	for_each_iommu(iommu) {
949 		/* All IOMMUs should use the same device table with the same size */
950 		lo = readl(iommu->mmio_base + MMIO_DEV_TABLE_OFFSET);
951 		hi = readl(iommu->mmio_base + MMIO_DEV_TABLE_OFFSET + 4);
952 		entry = (((u64) hi) << 32) + lo;
953 		if (last_entry && last_entry != entry) {
954 			pr_err("IOMMU:%d should use the same dev table as others!\n",
955 				iommu->index);
956 			return false;
957 		}
958 		last_entry = entry;
959 
960 		old_devtb_size = ((entry & ~PAGE_MASK) + 1) << 12;
961 		if (old_devtb_size != dev_table_size) {
962 			pr_err("The device table size of IOMMU:%d is not expected!\n",
963 				iommu->index);
964 			return false;
965 		}
966 	}
967 
968 	/*
969 	 * When SME is enabled in the first kernel, the entry includes the
970 	 * memory encryption mask(sme_me_mask), we must remove the memory
971 	 * encryption mask to obtain the true physical address in kdump kernel.
972 	 */
973 	old_devtb_phys = __sme_clr(entry) & PAGE_MASK;
974 
975 	if (old_devtb_phys >= 0x100000000ULL) {
976 		pr_err("The address of old device table is above 4G, not trustworthy!\n");
977 		return false;
978 	}
979 	old_devtb = (cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT) && is_kdump_kernel())
980 		    ? (__force void *)ioremap_encrypted(old_devtb_phys,
981 							dev_table_size)
982 		    : memremap(old_devtb_phys, dev_table_size, MEMREMAP_WB);
983 
984 	if (!old_devtb)
985 		return false;
986 
987 	gfp_flag = GFP_KERNEL | __GFP_ZERO | GFP_DMA32;
988 	old_dev_tbl_cpy = (void *)__get_free_pages(gfp_flag,
989 				get_order(dev_table_size));
990 	if (old_dev_tbl_cpy == NULL) {
991 		pr_err("Failed to allocate memory for copying old device table!\n");
992 		memunmap(old_devtb);
993 		return false;
994 	}
995 
996 	for (devid = 0; devid <= amd_iommu_last_bdf; ++devid) {
997 		old_dev_tbl_cpy[devid] = old_devtb[devid];
998 		dom_id = old_devtb[devid].data[1] & DEV_DOMID_MASK;
999 		dte_v = old_devtb[devid].data[0] & DTE_FLAG_V;
1000 
1001 		if (dte_v && dom_id) {
1002 			old_dev_tbl_cpy[devid].data[0] = old_devtb[devid].data[0];
1003 			old_dev_tbl_cpy[devid].data[1] = old_devtb[devid].data[1];
1004 			__set_bit(dom_id, amd_iommu_pd_alloc_bitmap);
1005 			/* If gcr3 table existed, mask it out */
1006 			if (old_devtb[devid].data[0] & DTE_FLAG_GV) {
1007 				tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1008 				tmp |= DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1009 				old_dev_tbl_cpy[devid].data[1] &= ~tmp;
1010 				tmp = DTE_GCR3_VAL_A(~0ULL) << DTE_GCR3_SHIFT_A;
1011 				tmp |= DTE_FLAG_GV;
1012 				old_dev_tbl_cpy[devid].data[0] &= ~tmp;
1013 			}
1014 		}
1015 
1016 		irq_v = old_devtb[devid].data[2] & DTE_IRQ_REMAP_ENABLE;
1017 		int_ctl = old_devtb[devid].data[2] & DTE_IRQ_REMAP_INTCTL_MASK;
1018 		int_tab_len = old_devtb[devid].data[2] & DTE_INTTABLEN_MASK;
1019 		if (irq_v && (int_ctl || int_tab_len)) {
1020 			if ((int_ctl != DTE_IRQ_REMAP_INTCTL) ||
1021 			    (int_tab_len != DTE_INTTABLEN)) {
1022 				pr_err("Wrong old irq remapping flag: %#x\n", devid);
1023 				memunmap(old_devtb);
1024 				return false;
1025 			}
1026 
1027 		        old_dev_tbl_cpy[devid].data[2] = old_devtb[devid].data[2];
1028 		}
1029 	}
1030 	memunmap(old_devtb);
1031 
1032 	return true;
1033 }
1034 
1035 void amd_iommu_apply_erratum_63(u16 devid)
1036 {
1037 	int sysmgt;
1038 
1039 	sysmgt = get_dev_entry_bit(devid, DEV_ENTRY_SYSMGT1) |
1040 		 (get_dev_entry_bit(devid, DEV_ENTRY_SYSMGT2) << 1);
1041 
1042 	if (sysmgt == 0x01)
1043 		set_dev_entry_bit(devid, DEV_ENTRY_IW);
1044 }
1045 
1046 /* Writes the specific IOMMU for a device into the rlookup table */
1047 static void __init set_iommu_for_device(struct amd_iommu *iommu, u16 devid)
1048 {
1049 	amd_iommu_rlookup_table[devid] = iommu;
1050 }
1051 
1052 /*
1053  * This function takes the device specific flags read from the ACPI
1054  * table and sets up the device table entry with that information
1055  */
1056 static void __init set_dev_entry_from_acpi(struct amd_iommu *iommu,
1057 					   u16 devid, u32 flags, u32 ext_flags)
1058 {
1059 	if (flags & ACPI_DEVFLAG_INITPASS)
1060 		set_dev_entry_bit(devid, DEV_ENTRY_INIT_PASS);
1061 	if (flags & ACPI_DEVFLAG_EXTINT)
1062 		set_dev_entry_bit(devid, DEV_ENTRY_EINT_PASS);
1063 	if (flags & ACPI_DEVFLAG_NMI)
1064 		set_dev_entry_bit(devid, DEV_ENTRY_NMI_PASS);
1065 	if (flags & ACPI_DEVFLAG_SYSMGT1)
1066 		set_dev_entry_bit(devid, DEV_ENTRY_SYSMGT1);
1067 	if (flags & ACPI_DEVFLAG_SYSMGT2)
1068 		set_dev_entry_bit(devid, DEV_ENTRY_SYSMGT2);
1069 	if (flags & ACPI_DEVFLAG_LINT0)
1070 		set_dev_entry_bit(devid, DEV_ENTRY_LINT0_PASS);
1071 	if (flags & ACPI_DEVFLAG_LINT1)
1072 		set_dev_entry_bit(devid, DEV_ENTRY_LINT1_PASS);
1073 
1074 	amd_iommu_apply_erratum_63(devid);
1075 
1076 	set_iommu_for_device(iommu, devid);
1077 }
1078 
1079 int __init add_special_device(u8 type, u8 id, u16 *devid, bool cmd_line)
1080 {
1081 	struct devid_map *entry;
1082 	struct list_head *list;
1083 
1084 	if (type == IVHD_SPECIAL_IOAPIC)
1085 		list = &ioapic_map;
1086 	else if (type == IVHD_SPECIAL_HPET)
1087 		list = &hpet_map;
1088 	else
1089 		return -EINVAL;
1090 
1091 	list_for_each_entry(entry, list, list) {
1092 		if (!(entry->id == id && entry->cmd_line))
1093 			continue;
1094 
1095 		pr_info("Command-line override present for %s id %d - ignoring\n",
1096 			type == IVHD_SPECIAL_IOAPIC ? "IOAPIC" : "HPET", id);
1097 
1098 		*devid = entry->devid;
1099 
1100 		return 0;
1101 	}
1102 
1103 	entry = kzalloc(sizeof(*entry), GFP_KERNEL);
1104 	if (!entry)
1105 		return -ENOMEM;
1106 
1107 	entry->id	= id;
1108 	entry->devid	= *devid;
1109 	entry->cmd_line	= cmd_line;
1110 
1111 	list_add_tail(&entry->list, list);
1112 
1113 	return 0;
1114 }
1115 
1116 static int __init add_acpi_hid_device(u8 *hid, u8 *uid, u16 *devid,
1117 				      bool cmd_line)
1118 {
1119 	struct acpihid_map_entry *entry;
1120 	struct list_head *list = &acpihid_map;
1121 
1122 	list_for_each_entry(entry, list, list) {
1123 		if (strcmp(entry->hid, hid) ||
1124 		    (*uid && *entry->uid && strcmp(entry->uid, uid)) ||
1125 		    !entry->cmd_line)
1126 			continue;
1127 
1128 		pr_info("Command-line override for hid:%s uid:%s\n",
1129 			hid, uid);
1130 		*devid = entry->devid;
1131 		return 0;
1132 	}
1133 
1134 	entry = kzalloc(sizeof(*entry), GFP_KERNEL);
1135 	if (!entry)
1136 		return -ENOMEM;
1137 
1138 	memcpy(entry->uid, uid, strlen(uid));
1139 	memcpy(entry->hid, hid, strlen(hid));
1140 	entry->devid = *devid;
1141 	entry->cmd_line	= cmd_line;
1142 	entry->root_devid = (entry->devid & (~0x7));
1143 
1144 	pr_info("%s, add hid:%s, uid:%s, rdevid:%d\n",
1145 		entry->cmd_line ? "cmd" : "ivrs",
1146 		entry->hid, entry->uid, entry->root_devid);
1147 
1148 	list_add_tail(&entry->list, list);
1149 	return 0;
1150 }
1151 
1152 static int __init add_early_maps(void)
1153 {
1154 	int i, ret;
1155 
1156 	for (i = 0; i < early_ioapic_map_size; ++i) {
1157 		ret = add_special_device(IVHD_SPECIAL_IOAPIC,
1158 					 early_ioapic_map[i].id,
1159 					 &early_ioapic_map[i].devid,
1160 					 early_ioapic_map[i].cmd_line);
1161 		if (ret)
1162 			return ret;
1163 	}
1164 
1165 	for (i = 0; i < early_hpet_map_size; ++i) {
1166 		ret = add_special_device(IVHD_SPECIAL_HPET,
1167 					 early_hpet_map[i].id,
1168 					 &early_hpet_map[i].devid,
1169 					 early_hpet_map[i].cmd_line);
1170 		if (ret)
1171 			return ret;
1172 	}
1173 
1174 	for (i = 0; i < early_acpihid_map_size; ++i) {
1175 		ret = add_acpi_hid_device(early_acpihid_map[i].hid,
1176 					  early_acpihid_map[i].uid,
1177 					  &early_acpihid_map[i].devid,
1178 					  early_acpihid_map[i].cmd_line);
1179 		if (ret)
1180 			return ret;
1181 	}
1182 
1183 	return 0;
1184 }
1185 
1186 /*
1187  * Takes a pointer to an AMD IOMMU entry in the ACPI table and
1188  * initializes the hardware and our data structures with it.
1189  */
1190 static int __init init_iommu_from_acpi(struct amd_iommu *iommu,
1191 					struct ivhd_header *h)
1192 {
1193 	u8 *p = (u8 *)h;
1194 	u8 *end = p, flags = 0;
1195 	u16 devid = 0, devid_start = 0, devid_to = 0;
1196 	u32 dev_i, ext_flags = 0;
1197 	bool alias = false;
1198 	struct ivhd_entry *e;
1199 	u32 ivhd_size;
1200 	int ret;
1201 
1202 
1203 	ret = add_early_maps();
1204 	if (ret)
1205 		return ret;
1206 
1207 	amd_iommu_apply_ivrs_quirks();
1208 
1209 	/*
1210 	 * First save the recommended feature enable bits from ACPI
1211 	 */
1212 	iommu->acpi_flags = h->flags;
1213 
1214 	/*
1215 	 * Done. Now parse the device entries
1216 	 */
1217 	ivhd_size = get_ivhd_header_size(h);
1218 	if (!ivhd_size) {
1219 		pr_err("Unsupported IVHD type %#x\n", h->type);
1220 		return -EINVAL;
1221 	}
1222 
1223 	p += ivhd_size;
1224 
1225 	end += h->length;
1226 
1227 
1228 	while (p < end) {
1229 		e = (struct ivhd_entry *)p;
1230 		switch (e->type) {
1231 		case IVHD_DEV_ALL:
1232 
1233 			DUMP_printk("  DEV_ALL\t\t\tflags: %02x\n", e->flags);
1234 
1235 			for (dev_i = 0; dev_i <= amd_iommu_last_bdf; ++dev_i)
1236 				set_dev_entry_from_acpi(iommu, dev_i, e->flags, 0);
1237 			break;
1238 		case IVHD_DEV_SELECT:
1239 
1240 			DUMP_printk("  DEV_SELECT\t\t\t devid: %02x:%02x.%x "
1241 				    "flags: %02x\n",
1242 				    PCI_BUS_NUM(e->devid),
1243 				    PCI_SLOT(e->devid),
1244 				    PCI_FUNC(e->devid),
1245 				    e->flags);
1246 
1247 			devid = e->devid;
1248 			set_dev_entry_from_acpi(iommu, devid, e->flags, 0);
1249 			break;
1250 		case IVHD_DEV_SELECT_RANGE_START:
1251 
1252 			DUMP_printk("  DEV_SELECT_RANGE_START\t "
1253 				    "devid: %02x:%02x.%x flags: %02x\n",
1254 				    PCI_BUS_NUM(e->devid),
1255 				    PCI_SLOT(e->devid),
1256 				    PCI_FUNC(e->devid),
1257 				    e->flags);
1258 
1259 			devid_start = e->devid;
1260 			flags = e->flags;
1261 			ext_flags = 0;
1262 			alias = false;
1263 			break;
1264 		case IVHD_DEV_ALIAS:
1265 
1266 			DUMP_printk("  DEV_ALIAS\t\t\t devid: %02x:%02x.%x "
1267 				    "flags: %02x devid_to: %02x:%02x.%x\n",
1268 				    PCI_BUS_NUM(e->devid),
1269 				    PCI_SLOT(e->devid),
1270 				    PCI_FUNC(e->devid),
1271 				    e->flags,
1272 				    PCI_BUS_NUM(e->ext >> 8),
1273 				    PCI_SLOT(e->ext >> 8),
1274 				    PCI_FUNC(e->ext >> 8));
1275 
1276 			devid = e->devid;
1277 			devid_to = e->ext >> 8;
1278 			set_dev_entry_from_acpi(iommu, devid   , e->flags, 0);
1279 			set_dev_entry_from_acpi(iommu, devid_to, e->flags, 0);
1280 			amd_iommu_alias_table[devid] = devid_to;
1281 			break;
1282 		case IVHD_DEV_ALIAS_RANGE:
1283 
1284 			DUMP_printk("  DEV_ALIAS_RANGE\t\t "
1285 				    "devid: %02x:%02x.%x flags: %02x "
1286 				    "devid_to: %02x:%02x.%x\n",
1287 				    PCI_BUS_NUM(e->devid),
1288 				    PCI_SLOT(e->devid),
1289 				    PCI_FUNC(e->devid),
1290 				    e->flags,
1291 				    PCI_BUS_NUM(e->ext >> 8),
1292 				    PCI_SLOT(e->ext >> 8),
1293 				    PCI_FUNC(e->ext >> 8));
1294 
1295 			devid_start = e->devid;
1296 			flags = e->flags;
1297 			devid_to = e->ext >> 8;
1298 			ext_flags = 0;
1299 			alias = true;
1300 			break;
1301 		case IVHD_DEV_EXT_SELECT:
1302 
1303 			DUMP_printk("  DEV_EXT_SELECT\t\t devid: %02x:%02x.%x "
1304 				    "flags: %02x ext: %08x\n",
1305 				    PCI_BUS_NUM(e->devid),
1306 				    PCI_SLOT(e->devid),
1307 				    PCI_FUNC(e->devid),
1308 				    e->flags, e->ext);
1309 
1310 			devid = e->devid;
1311 			set_dev_entry_from_acpi(iommu, devid, e->flags,
1312 						e->ext);
1313 			break;
1314 		case IVHD_DEV_EXT_SELECT_RANGE:
1315 
1316 			DUMP_printk("  DEV_EXT_SELECT_RANGE\t devid: "
1317 				    "%02x:%02x.%x flags: %02x ext: %08x\n",
1318 				    PCI_BUS_NUM(e->devid),
1319 				    PCI_SLOT(e->devid),
1320 				    PCI_FUNC(e->devid),
1321 				    e->flags, e->ext);
1322 
1323 			devid_start = e->devid;
1324 			flags = e->flags;
1325 			ext_flags = e->ext;
1326 			alias = false;
1327 			break;
1328 		case IVHD_DEV_RANGE_END:
1329 
1330 			DUMP_printk("  DEV_RANGE_END\t\t devid: %02x:%02x.%x\n",
1331 				    PCI_BUS_NUM(e->devid),
1332 				    PCI_SLOT(e->devid),
1333 				    PCI_FUNC(e->devid));
1334 
1335 			devid = e->devid;
1336 			for (dev_i = devid_start; dev_i <= devid; ++dev_i) {
1337 				if (alias) {
1338 					amd_iommu_alias_table[dev_i] = devid_to;
1339 					set_dev_entry_from_acpi(iommu,
1340 						devid_to, flags, ext_flags);
1341 				}
1342 				set_dev_entry_from_acpi(iommu, dev_i,
1343 							flags, ext_flags);
1344 			}
1345 			break;
1346 		case IVHD_DEV_SPECIAL: {
1347 			u8 handle, type;
1348 			const char *var;
1349 			u16 devid;
1350 			int ret;
1351 
1352 			handle = e->ext & 0xff;
1353 			devid  = (e->ext >>  8) & 0xffff;
1354 			type   = (e->ext >> 24) & 0xff;
1355 
1356 			if (type == IVHD_SPECIAL_IOAPIC)
1357 				var = "IOAPIC";
1358 			else if (type == IVHD_SPECIAL_HPET)
1359 				var = "HPET";
1360 			else
1361 				var = "UNKNOWN";
1362 
1363 			DUMP_printk("  DEV_SPECIAL(%s[%d])\t\tdevid: %02x:%02x.%x\n",
1364 				    var, (int)handle,
1365 				    PCI_BUS_NUM(devid),
1366 				    PCI_SLOT(devid),
1367 				    PCI_FUNC(devid));
1368 
1369 			ret = add_special_device(type, handle, &devid, false);
1370 			if (ret)
1371 				return ret;
1372 
1373 			/*
1374 			 * add_special_device might update the devid in case a
1375 			 * command-line override is present. So call
1376 			 * set_dev_entry_from_acpi after add_special_device.
1377 			 */
1378 			set_dev_entry_from_acpi(iommu, devid, e->flags, 0);
1379 
1380 			break;
1381 		}
1382 		case IVHD_DEV_ACPI_HID: {
1383 			u16 devid;
1384 			u8 hid[ACPIHID_HID_LEN];
1385 			u8 uid[ACPIHID_UID_LEN];
1386 			int ret;
1387 
1388 			if (h->type != 0x40) {
1389 				pr_err(FW_BUG "Invalid IVHD device type %#x\n",
1390 				       e->type);
1391 				break;
1392 			}
1393 
1394 			BUILD_BUG_ON(sizeof(e->ext_hid) != ACPIHID_HID_LEN - 1);
1395 			memcpy(hid, &e->ext_hid, ACPIHID_HID_LEN - 1);
1396 			hid[ACPIHID_HID_LEN - 1] = '\0';
1397 
1398 			if (!(*hid)) {
1399 				pr_err(FW_BUG "Invalid HID.\n");
1400 				break;
1401 			}
1402 
1403 			uid[0] = '\0';
1404 			switch (e->uidf) {
1405 			case UID_NOT_PRESENT:
1406 
1407 				if (e->uidl != 0)
1408 					pr_warn(FW_BUG "Invalid UID length.\n");
1409 
1410 				break;
1411 			case UID_IS_INTEGER:
1412 
1413 				sprintf(uid, "%d", e->uid);
1414 
1415 				break;
1416 			case UID_IS_CHARACTER:
1417 
1418 				memcpy(uid, &e->uid, e->uidl);
1419 				uid[e->uidl] = '\0';
1420 
1421 				break;
1422 			default:
1423 				break;
1424 			}
1425 
1426 			devid = e->devid;
1427 			DUMP_printk("  DEV_ACPI_HID(%s[%s])\t\tdevid: %02x:%02x.%x\n",
1428 				    hid, uid,
1429 				    PCI_BUS_NUM(devid),
1430 				    PCI_SLOT(devid),
1431 				    PCI_FUNC(devid));
1432 
1433 			flags = e->flags;
1434 
1435 			ret = add_acpi_hid_device(hid, uid, &devid, false);
1436 			if (ret)
1437 				return ret;
1438 
1439 			/*
1440 			 * add_special_device might update the devid in case a
1441 			 * command-line override is present. So call
1442 			 * set_dev_entry_from_acpi after add_special_device.
1443 			 */
1444 			set_dev_entry_from_acpi(iommu, devid, e->flags, 0);
1445 
1446 			break;
1447 		}
1448 		default:
1449 			break;
1450 		}
1451 
1452 		p += ivhd_entry_length(p);
1453 	}
1454 
1455 	return 0;
1456 }
1457 
1458 static void __init free_iommu_one(struct amd_iommu *iommu)
1459 {
1460 	free_cwwb_sem(iommu);
1461 	free_command_buffer(iommu);
1462 	free_event_buffer(iommu);
1463 	free_ppr_log(iommu);
1464 	free_ga_log(iommu);
1465 	iommu_unmap_mmio_space(iommu);
1466 }
1467 
1468 static void __init free_iommu_all(void)
1469 {
1470 	struct amd_iommu *iommu, *next;
1471 
1472 	for_each_iommu_safe(iommu, next) {
1473 		list_del(&iommu->list);
1474 		free_iommu_one(iommu);
1475 		kfree(iommu);
1476 	}
1477 }
1478 
1479 /*
1480  * Family15h Model 10h-1fh erratum 746 (IOMMU Logging May Stall Translations)
1481  * Workaround:
1482  *     BIOS should disable L2B micellaneous clock gating by setting
1483  *     L2_L2B_CK_GATE_CONTROL[CKGateL2BMiscDisable](D0F2xF4_x90[2]) = 1b
1484  */
1485 static void amd_iommu_erratum_746_workaround(struct amd_iommu *iommu)
1486 {
1487 	u32 value;
1488 
1489 	if ((boot_cpu_data.x86 != 0x15) ||
1490 	    (boot_cpu_data.x86_model < 0x10) ||
1491 	    (boot_cpu_data.x86_model > 0x1f))
1492 		return;
1493 
1494 	pci_write_config_dword(iommu->dev, 0xf0, 0x90);
1495 	pci_read_config_dword(iommu->dev, 0xf4, &value);
1496 
1497 	if (value & BIT(2))
1498 		return;
1499 
1500 	/* Select NB indirect register 0x90 and enable writing */
1501 	pci_write_config_dword(iommu->dev, 0xf0, 0x90 | (1 << 8));
1502 
1503 	pci_write_config_dword(iommu->dev, 0xf4, value | 0x4);
1504 	pci_info(iommu->dev, "Applying erratum 746 workaround\n");
1505 
1506 	/* Clear the enable writing bit */
1507 	pci_write_config_dword(iommu->dev, 0xf0, 0x90);
1508 }
1509 
1510 /*
1511  * Family15h Model 30h-3fh (IOMMU Mishandles ATS Write Permission)
1512  * Workaround:
1513  *     BIOS should enable ATS write permission check by setting
1514  *     L2_DEBUG_3[AtsIgnoreIWDis](D0F2xF4_x47[0]) = 1b
1515  */
1516 static void amd_iommu_ats_write_check_workaround(struct amd_iommu *iommu)
1517 {
1518 	u32 value;
1519 
1520 	if ((boot_cpu_data.x86 != 0x15) ||
1521 	    (boot_cpu_data.x86_model < 0x30) ||
1522 	    (boot_cpu_data.x86_model > 0x3f))
1523 		return;
1524 
1525 	/* Test L2_DEBUG_3[AtsIgnoreIWDis] == 1 */
1526 	value = iommu_read_l2(iommu, 0x47);
1527 
1528 	if (value & BIT(0))
1529 		return;
1530 
1531 	/* Set L2_DEBUG_3[AtsIgnoreIWDis] = 1 */
1532 	iommu_write_l2(iommu, 0x47, value | BIT(0));
1533 
1534 	pci_info(iommu->dev, "Applying ATS write check workaround\n");
1535 }
1536 
1537 /*
1538  * This function glues the initialization function for one IOMMU
1539  * together and also allocates the command buffer and programs the
1540  * hardware. It does NOT enable the IOMMU. This is done afterwards.
1541  */
1542 static int __init init_iommu_one(struct amd_iommu *iommu, struct ivhd_header *h)
1543 {
1544 	int ret;
1545 
1546 	raw_spin_lock_init(&iommu->lock);
1547 	iommu->cmd_sem_val = 0;
1548 
1549 	/* Add IOMMU to internal data structures */
1550 	list_add_tail(&iommu->list, &amd_iommu_list);
1551 	iommu->index = amd_iommus_present++;
1552 
1553 	if (unlikely(iommu->index >= MAX_IOMMUS)) {
1554 		WARN(1, "System has more IOMMUs than supported by this driver\n");
1555 		return -ENOSYS;
1556 	}
1557 
1558 	/* Index is fine - add IOMMU to the array */
1559 	amd_iommus[iommu->index] = iommu;
1560 
1561 	/*
1562 	 * Copy data from ACPI table entry to the iommu struct
1563 	 */
1564 	iommu->devid   = h->devid;
1565 	iommu->cap_ptr = h->cap_ptr;
1566 	iommu->pci_seg = h->pci_seg;
1567 	iommu->mmio_phys = h->mmio_phys;
1568 
1569 	switch (h->type) {
1570 	case 0x10:
1571 		/* Check if IVHD EFR contains proper max banks/counters */
1572 		if ((h->efr_attr != 0) &&
1573 		    ((h->efr_attr & (0xF << 13)) != 0) &&
1574 		    ((h->efr_attr & (0x3F << 17)) != 0))
1575 			iommu->mmio_phys_end = MMIO_REG_END_OFFSET;
1576 		else
1577 			iommu->mmio_phys_end = MMIO_CNTR_CONF_OFFSET;
1578 
1579 		/*
1580 		 * Note: GA (128-bit IRTE) mode requires cmpxchg16b supports.
1581 		 * GAM also requires GA mode. Therefore, we need to
1582 		 * check cmpxchg16b support before enabling it.
1583 		 */
1584 		if (!boot_cpu_has(X86_FEATURE_CX16) ||
1585 		    ((h->efr_attr & (0x1 << IOMMU_FEAT_GASUP_SHIFT)) == 0))
1586 			amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_LEGACY;
1587 		break;
1588 	case 0x11:
1589 	case 0x40:
1590 		if (h->efr_reg & (1 << 9))
1591 			iommu->mmio_phys_end = MMIO_REG_END_OFFSET;
1592 		else
1593 			iommu->mmio_phys_end = MMIO_CNTR_CONF_OFFSET;
1594 
1595 		/*
1596 		 * Note: GA (128-bit IRTE) mode requires cmpxchg16b supports.
1597 		 * XT, GAM also requires GA mode. Therefore, we need to
1598 		 * check cmpxchg16b support before enabling them.
1599 		 */
1600 		if (!boot_cpu_has(X86_FEATURE_CX16) ||
1601 		    ((h->efr_reg & (0x1 << IOMMU_EFR_GASUP_SHIFT)) == 0)) {
1602 			amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_LEGACY;
1603 			break;
1604 		}
1605 
1606 		if (h->efr_reg & BIT(IOMMU_EFR_XTSUP_SHIFT))
1607 			amd_iommu_xt_mode = IRQ_REMAP_X2APIC_MODE;
1608 
1609 		early_iommu_features_init(iommu, h);
1610 
1611 		break;
1612 	default:
1613 		return -EINVAL;
1614 	}
1615 
1616 	iommu->mmio_base = iommu_map_mmio_space(iommu->mmio_phys,
1617 						iommu->mmio_phys_end);
1618 	if (!iommu->mmio_base)
1619 		return -ENOMEM;
1620 
1621 	if (alloc_cwwb_sem(iommu))
1622 		return -ENOMEM;
1623 
1624 	if (alloc_command_buffer(iommu))
1625 		return -ENOMEM;
1626 
1627 	if (alloc_event_buffer(iommu))
1628 		return -ENOMEM;
1629 
1630 	iommu->int_enabled = false;
1631 
1632 	init_translation_status(iommu);
1633 	if (translation_pre_enabled(iommu) && !is_kdump_kernel()) {
1634 		iommu_disable(iommu);
1635 		clear_translation_pre_enabled(iommu);
1636 		pr_warn("Translation was enabled for IOMMU:%d but we are not in kdump mode\n",
1637 			iommu->index);
1638 	}
1639 	if (amd_iommu_pre_enabled)
1640 		amd_iommu_pre_enabled = translation_pre_enabled(iommu);
1641 
1642 	ret = init_iommu_from_acpi(iommu, h);
1643 	if (ret)
1644 		return ret;
1645 
1646 	if (amd_iommu_irq_remap) {
1647 		ret = amd_iommu_create_irq_domain(iommu);
1648 		if (ret)
1649 			return ret;
1650 	}
1651 
1652 	/*
1653 	 * Make sure IOMMU is not considered to translate itself. The IVRS
1654 	 * table tells us so, but this is a lie!
1655 	 */
1656 	amd_iommu_rlookup_table[iommu->devid] = NULL;
1657 
1658 	return 0;
1659 }
1660 
1661 /**
1662  * get_highest_supported_ivhd_type - Look up the appropriate IVHD type
1663  * @ivrs: Pointer to the IVRS header
1664  *
1665  * This function search through all IVDB of the maximum supported IVHD
1666  */
1667 static u8 get_highest_supported_ivhd_type(struct acpi_table_header *ivrs)
1668 {
1669 	u8 *base = (u8 *)ivrs;
1670 	struct ivhd_header *ivhd = (struct ivhd_header *)
1671 					(base + IVRS_HEADER_LENGTH);
1672 	u8 last_type = ivhd->type;
1673 	u16 devid = ivhd->devid;
1674 
1675 	while (((u8 *)ivhd - base < ivrs->length) &&
1676 	       (ivhd->type <= ACPI_IVHD_TYPE_MAX_SUPPORTED)) {
1677 		u8 *p = (u8 *) ivhd;
1678 
1679 		if (ivhd->devid == devid)
1680 			last_type = ivhd->type;
1681 		ivhd = (struct ivhd_header *)(p + ivhd->length);
1682 	}
1683 
1684 	return last_type;
1685 }
1686 
1687 /*
1688  * Iterates over all IOMMU entries in the ACPI table, allocates the
1689  * IOMMU structure and initializes it with init_iommu_one()
1690  */
1691 static int __init init_iommu_all(struct acpi_table_header *table)
1692 {
1693 	u8 *p = (u8 *)table, *end = (u8 *)table;
1694 	struct ivhd_header *h;
1695 	struct amd_iommu *iommu;
1696 	int ret;
1697 
1698 	end += table->length;
1699 	p += IVRS_HEADER_LENGTH;
1700 
1701 	while (p < end) {
1702 		h = (struct ivhd_header *)p;
1703 		if (*p == amd_iommu_target_ivhd_type) {
1704 
1705 			DUMP_printk("device: %02x:%02x.%01x cap: %04x "
1706 				    "seg: %d flags: %01x info %04x\n",
1707 				    PCI_BUS_NUM(h->devid), PCI_SLOT(h->devid),
1708 				    PCI_FUNC(h->devid), h->cap_ptr,
1709 				    h->pci_seg, h->flags, h->info);
1710 			DUMP_printk("       mmio-addr: %016llx\n",
1711 				    h->mmio_phys);
1712 
1713 			iommu = kzalloc(sizeof(struct amd_iommu), GFP_KERNEL);
1714 			if (iommu == NULL)
1715 				return -ENOMEM;
1716 
1717 			ret = init_iommu_one(iommu, h);
1718 			if (ret)
1719 				return ret;
1720 		}
1721 		p += h->length;
1722 
1723 	}
1724 	WARN_ON(p != end);
1725 
1726 	return 0;
1727 }
1728 
1729 static void init_iommu_perf_ctr(struct amd_iommu *iommu)
1730 {
1731 	u64 val;
1732 	struct pci_dev *pdev = iommu->dev;
1733 
1734 	if (!iommu_feature(iommu, FEATURE_PC))
1735 		return;
1736 
1737 	amd_iommu_pc_present = true;
1738 
1739 	pci_info(pdev, "IOMMU performance counters supported\n");
1740 
1741 	val = readl(iommu->mmio_base + MMIO_CNTR_CONF_OFFSET);
1742 	iommu->max_banks = (u8) ((val >> 12) & 0x3f);
1743 	iommu->max_counters = (u8) ((val >> 7) & 0xf);
1744 
1745 	return;
1746 }
1747 
1748 static ssize_t amd_iommu_show_cap(struct device *dev,
1749 				  struct device_attribute *attr,
1750 				  char *buf)
1751 {
1752 	struct amd_iommu *iommu = dev_to_amd_iommu(dev);
1753 	return sprintf(buf, "%x\n", iommu->cap);
1754 }
1755 static DEVICE_ATTR(cap, S_IRUGO, amd_iommu_show_cap, NULL);
1756 
1757 static ssize_t amd_iommu_show_features(struct device *dev,
1758 				       struct device_attribute *attr,
1759 				       char *buf)
1760 {
1761 	struct amd_iommu *iommu = dev_to_amd_iommu(dev);
1762 	return sprintf(buf, "%llx\n", iommu->features);
1763 }
1764 static DEVICE_ATTR(features, S_IRUGO, amd_iommu_show_features, NULL);
1765 
1766 static struct attribute *amd_iommu_attrs[] = {
1767 	&dev_attr_cap.attr,
1768 	&dev_attr_features.attr,
1769 	NULL,
1770 };
1771 
1772 static struct attribute_group amd_iommu_group = {
1773 	.name = "amd-iommu",
1774 	.attrs = amd_iommu_attrs,
1775 };
1776 
1777 static const struct attribute_group *amd_iommu_groups[] = {
1778 	&amd_iommu_group,
1779 	NULL,
1780 };
1781 
1782 /*
1783  * Note: IVHD 0x11 and 0x40 also contains exact copy
1784  * of the IOMMU Extended Feature Register [MMIO Offset 0030h].
1785  * Default to EFR in IVHD since it is available sooner (i.e. before PCI init).
1786  */
1787 static void __init late_iommu_features_init(struct amd_iommu *iommu)
1788 {
1789 	u64 features;
1790 
1791 	if (!(iommu->cap & (1 << IOMMU_CAP_EFR)))
1792 		return;
1793 
1794 	/* read extended feature bits */
1795 	features = readq(iommu->mmio_base + MMIO_EXT_FEATURES);
1796 
1797 	if (!iommu->features) {
1798 		iommu->features = features;
1799 		return;
1800 	}
1801 
1802 	/*
1803 	 * Sanity check and warn if EFR values from
1804 	 * IVHD and MMIO conflict.
1805 	 */
1806 	if (features != iommu->features)
1807 		pr_warn(FW_WARN "EFR mismatch. Use IVHD EFR (%#llx : %#llx).\n",
1808 			features, iommu->features);
1809 }
1810 
1811 static int __init iommu_init_pci(struct amd_iommu *iommu)
1812 {
1813 	int cap_ptr = iommu->cap_ptr;
1814 	int ret;
1815 
1816 	iommu->dev = pci_get_domain_bus_and_slot(0, PCI_BUS_NUM(iommu->devid),
1817 						 iommu->devid & 0xff);
1818 	if (!iommu->dev)
1819 		return -ENODEV;
1820 
1821 	/* Prevent binding other PCI device drivers to IOMMU devices */
1822 	iommu->dev->match_driver = false;
1823 
1824 	pci_read_config_dword(iommu->dev, cap_ptr + MMIO_CAP_HDR_OFFSET,
1825 			      &iommu->cap);
1826 
1827 	if (!(iommu->cap & (1 << IOMMU_CAP_IOTLB)))
1828 		amd_iommu_iotlb_sup = false;
1829 
1830 	late_iommu_features_init(iommu);
1831 
1832 	if (iommu_feature(iommu, FEATURE_GT)) {
1833 		int glxval;
1834 		u32 max_pasid;
1835 		u64 pasmax;
1836 
1837 		pasmax = iommu->features & FEATURE_PASID_MASK;
1838 		pasmax >>= FEATURE_PASID_SHIFT;
1839 		max_pasid  = (1 << (pasmax + 1)) - 1;
1840 
1841 		amd_iommu_max_pasid = min(amd_iommu_max_pasid, max_pasid);
1842 
1843 		BUG_ON(amd_iommu_max_pasid & ~PASID_MASK);
1844 
1845 		glxval   = iommu->features & FEATURE_GLXVAL_MASK;
1846 		glxval >>= FEATURE_GLXVAL_SHIFT;
1847 
1848 		if (amd_iommu_max_glx_val == -1)
1849 			amd_iommu_max_glx_val = glxval;
1850 		else
1851 			amd_iommu_max_glx_val = min(amd_iommu_max_glx_val, glxval);
1852 	}
1853 
1854 	if (iommu_feature(iommu, FEATURE_GT) &&
1855 	    iommu_feature(iommu, FEATURE_PPR)) {
1856 		iommu->is_iommu_v2   = true;
1857 		amd_iommu_v2_present = true;
1858 	}
1859 
1860 	if (iommu_feature(iommu, FEATURE_PPR) && alloc_ppr_log(iommu))
1861 		return -ENOMEM;
1862 
1863 	ret = iommu_init_ga_log(iommu);
1864 	if (ret)
1865 		return ret;
1866 
1867 	if (iommu->cap & (1UL << IOMMU_CAP_NPCACHE)) {
1868 		pr_info("Using strict mode due to virtualization\n");
1869 		iommu_set_dma_strict();
1870 		amd_iommu_np_cache = true;
1871 	}
1872 
1873 	init_iommu_perf_ctr(iommu);
1874 
1875 	if (is_rd890_iommu(iommu->dev)) {
1876 		int i, j;
1877 
1878 		iommu->root_pdev =
1879 			pci_get_domain_bus_and_slot(0, iommu->dev->bus->number,
1880 						    PCI_DEVFN(0, 0));
1881 
1882 		/*
1883 		 * Some rd890 systems may not be fully reconfigured by the
1884 		 * BIOS, so it's necessary for us to store this information so
1885 		 * it can be reprogrammed on resume
1886 		 */
1887 		pci_read_config_dword(iommu->dev, iommu->cap_ptr + 4,
1888 				&iommu->stored_addr_lo);
1889 		pci_read_config_dword(iommu->dev, iommu->cap_ptr + 8,
1890 				&iommu->stored_addr_hi);
1891 
1892 		/* Low bit locks writes to configuration space */
1893 		iommu->stored_addr_lo &= ~1;
1894 
1895 		for (i = 0; i < 6; i++)
1896 			for (j = 0; j < 0x12; j++)
1897 				iommu->stored_l1[i][j] = iommu_read_l1(iommu, i, j);
1898 
1899 		for (i = 0; i < 0x83; i++)
1900 			iommu->stored_l2[i] = iommu_read_l2(iommu, i);
1901 	}
1902 
1903 	amd_iommu_erratum_746_workaround(iommu);
1904 	amd_iommu_ats_write_check_workaround(iommu);
1905 
1906 	iommu_device_sysfs_add(&iommu->iommu, &iommu->dev->dev,
1907 			       amd_iommu_groups, "ivhd%d", iommu->index);
1908 	iommu_device_register(&iommu->iommu, &amd_iommu_ops, NULL);
1909 
1910 	return pci_enable_device(iommu->dev);
1911 }
1912 
1913 static void print_iommu_info(void)
1914 {
1915 	static const char * const feat_str[] = {
1916 		"PreF", "PPR", "X2APIC", "NX", "GT", "[5]",
1917 		"IA", "GA", "HE", "PC"
1918 	};
1919 	struct amd_iommu *iommu;
1920 
1921 	for_each_iommu(iommu) {
1922 		struct pci_dev *pdev = iommu->dev;
1923 		int i;
1924 
1925 		pci_info(pdev, "Found IOMMU cap 0x%x\n", iommu->cap_ptr);
1926 
1927 		if (iommu->cap & (1 << IOMMU_CAP_EFR)) {
1928 			pr_info("Extended features (%#llx):", iommu->features);
1929 
1930 			for (i = 0; i < ARRAY_SIZE(feat_str); ++i) {
1931 				if (iommu_feature(iommu, (1ULL << i)))
1932 					pr_cont(" %s", feat_str[i]);
1933 			}
1934 
1935 			if (iommu->features & FEATURE_GAM_VAPIC)
1936 				pr_cont(" GA_vAPIC");
1937 
1938 			pr_cont("\n");
1939 		}
1940 	}
1941 	if (irq_remapping_enabled) {
1942 		pr_info("Interrupt remapping enabled\n");
1943 		if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir))
1944 			pr_info("Virtual APIC enabled\n");
1945 		if (amd_iommu_xt_mode == IRQ_REMAP_X2APIC_MODE)
1946 			pr_info("X2APIC enabled\n");
1947 	}
1948 }
1949 
1950 static int __init amd_iommu_init_pci(void)
1951 {
1952 	struct amd_iommu *iommu;
1953 	int ret;
1954 
1955 	for_each_iommu(iommu) {
1956 		ret = iommu_init_pci(iommu);
1957 		if (ret) {
1958 			pr_err("IOMMU%d: Failed to initialize IOMMU Hardware (error=%d)!\n",
1959 			       iommu->index, ret);
1960 			goto out;
1961 		}
1962 		/* Need to setup range after PCI init */
1963 		iommu_set_cwwb_range(iommu);
1964 	}
1965 
1966 	/*
1967 	 * Order is important here to make sure any unity map requirements are
1968 	 * fulfilled. The unity mappings are created and written to the device
1969 	 * table during the amd_iommu_init_api() call.
1970 	 *
1971 	 * After that we call init_device_table_dma() to make sure any
1972 	 * uninitialized DTE will block DMA, and in the end we flush the caches
1973 	 * of all IOMMUs to make sure the changes to the device table are
1974 	 * active.
1975 	 */
1976 	ret = amd_iommu_init_api();
1977 	if (ret) {
1978 		pr_err("IOMMU: Failed to initialize IOMMU-API interface (error=%d)!\n",
1979 		       ret);
1980 		goto out;
1981 	}
1982 
1983 	init_device_table_dma();
1984 
1985 	for_each_iommu(iommu)
1986 		iommu_flush_all_caches(iommu);
1987 
1988 	if (!ret)
1989 		print_iommu_info();
1990 
1991 out:
1992 	return ret;
1993 }
1994 
1995 /****************************************************************************
1996  *
1997  * The following functions initialize the MSI interrupts for all IOMMUs
1998  * in the system. It's a bit challenging because there could be multiple
1999  * IOMMUs per PCI BDF but we can call pci_enable_msi(x) only once per
2000  * pci_dev.
2001  *
2002  ****************************************************************************/
2003 
2004 static int iommu_setup_msi(struct amd_iommu *iommu)
2005 {
2006 	int r;
2007 
2008 	r = pci_enable_msi(iommu->dev);
2009 	if (r)
2010 		return r;
2011 
2012 	r = request_threaded_irq(iommu->dev->irq,
2013 				 amd_iommu_int_handler,
2014 				 amd_iommu_int_thread,
2015 				 0, "AMD-Vi",
2016 				 iommu);
2017 
2018 	if (r) {
2019 		pci_disable_msi(iommu->dev);
2020 		return r;
2021 	}
2022 
2023 	return 0;
2024 }
2025 
2026 union intcapxt {
2027 	u64	capxt;
2028 	struct {
2029 		u64	reserved_0		:  2,
2030 			dest_mode_logical	:  1,
2031 			reserved_1		:  5,
2032 			destid_0_23		: 24,
2033 			vector			:  8,
2034 			reserved_2		: 16,
2035 			destid_24_31		:  8;
2036 	};
2037 } __attribute__ ((packed));
2038 
2039 
2040 static struct irq_chip intcapxt_controller;
2041 
2042 static int intcapxt_irqdomain_activate(struct irq_domain *domain,
2043 				       struct irq_data *irqd, bool reserve)
2044 {
2045 	return 0;
2046 }
2047 
2048 static void intcapxt_irqdomain_deactivate(struct irq_domain *domain,
2049 					  struct irq_data *irqd)
2050 {
2051 }
2052 
2053 
2054 static int intcapxt_irqdomain_alloc(struct irq_domain *domain, unsigned int virq,
2055 				    unsigned int nr_irqs, void *arg)
2056 {
2057 	struct irq_alloc_info *info = arg;
2058 	int i, ret;
2059 
2060 	if (!info || info->type != X86_IRQ_ALLOC_TYPE_AMDVI)
2061 		return -EINVAL;
2062 
2063 	ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
2064 	if (ret < 0)
2065 		return ret;
2066 
2067 	for (i = virq; i < virq + nr_irqs; i++) {
2068 		struct irq_data *irqd = irq_domain_get_irq_data(domain, i);
2069 
2070 		irqd->chip = &intcapxt_controller;
2071 		irqd->chip_data = info->data;
2072 		__irq_set_handler(i, handle_edge_irq, 0, "edge");
2073 	}
2074 
2075 	return ret;
2076 }
2077 
2078 static void intcapxt_irqdomain_free(struct irq_domain *domain, unsigned int virq,
2079 				    unsigned int nr_irqs)
2080 {
2081 	irq_domain_free_irqs_top(domain, virq, nr_irqs);
2082 }
2083 
2084 
2085 static void intcapxt_unmask_irq(struct irq_data *irqd)
2086 {
2087 	struct amd_iommu *iommu = irqd->chip_data;
2088 	struct irq_cfg *cfg = irqd_cfg(irqd);
2089 	union intcapxt xt;
2090 
2091 	xt.capxt = 0ULL;
2092 	xt.dest_mode_logical = apic->dest_mode_logical;
2093 	xt.vector = cfg->vector;
2094 	xt.destid_0_23 = cfg->dest_apicid & GENMASK(23, 0);
2095 	xt.destid_24_31 = cfg->dest_apicid >> 24;
2096 
2097 	/**
2098 	 * Current IOMMU implementation uses the same IRQ for all
2099 	 * 3 IOMMU interrupts.
2100 	 */
2101 	writeq(xt.capxt, iommu->mmio_base + MMIO_INTCAPXT_EVT_OFFSET);
2102 	writeq(xt.capxt, iommu->mmio_base + MMIO_INTCAPXT_PPR_OFFSET);
2103 	writeq(xt.capxt, iommu->mmio_base + MMIO_INTCAPXT_GALOG_OFFSET);
2104 }
2105 
2106 static void intcapxt_mask_irq(struct irq_data *irqd)
2107 {
2108 	struct amd_iommu *iommu = irqd->chip_data;
2109 
2110 	writeq(0, iommu->mmio_base + MMIO_INTCAPXT_EVT_OFFSET);
2111 	writeq(0, iommu->mmio_base + MMIO_INTCAPXT_PPR_OFFSET);
2112 	writeq(0, iommu->mmio_base + MMIO_INTCAPXT_GALOG_OFFSET);
2113 }
2114 
2115 
2116 static int intcapxt_set_affinity(struct irq_data *irqd,
2117 				 const struct cpumask *mask, bool force)
2118 {
2119 	struct irq_data *parent = irqd->parent_data;
2120 	int ret;
2121 
2122 	ret = parent->chip->irq_set_affinity(parent, mask, force);
2123 	if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
2124 		return ret;
2125 	return 0;
2126 }
2127 
2128 static int intcapxt_set_wake(struct irq_data *irqd, unsigned int on)
2129 {
2130 	return on ? -EOPNOTSUPP : 0;
2131 }
2132 
2133 static struct irq_chip intcapxt_controller = {
2134 	.name			= "IOMMU-MSI",
2135 	.irq_unmask		= intcapxt_unmask_irq,
2136 	.irq_mask		= intcapxt_mask_irq,
2137 	.irq_ack		= irq_chip_ack_parent,
2138 	.irq_retrigger		= irq_chip_retrigger_hierarchy,
2139 	.irq_set_affinity       = intcapxt_set_affinity,
2140 	.irq_set_wake		= intcapxt_set_wake,
2141 	.flags			= IRQCHIP_MASK_ON_SUSPEND,
2142 };
2143 
2144 static const struct irq_domain_ops intcapxt_domain_ops = {
2145 	.alloc			= intcapxt_irqdomain_alloc,
2146 	.free			= intcapxt_irqdomain_free,
2147 	.activate		= intcapxt_irqdomain_activate,
2148 	.deactivate		= intcapxt_irqdomain_deactivate,
2149 };
2150 
2151 
2152 static struct irq_domain *iommu_irqdomain;
2153 
2154 static struct irq_domain *iommu_get_irqdomain(void)
2155 {
2156 	struct fwnode_handle *fn;
2157 
2158 	/* No need for locking here (yet) as the init is single-threaded */
2159 	if (iommu_irqdomain)
2160 		return iommu_irqdomain;
2161 
2162 	fn = irq_domain_alloc_named_fwnode("AMD-Vi-MSI");
2163 	if (!fn)
2164 		return NULL;
2165 
2166 	iommu_irqdomain = irq_domain_create_hierarchy(x86_vector_domain, 0, 0,
2167 						      fn, &intcapxt_domain_ops,
2168 						      NULL);
2169 	if (!iommu_irqdomain)
2170 		irq_domain_free_fwnode(fn);
2171 
2172 	return iommu_irqdomain;
2173 }
2174 
2175 static int iommu_setup_intcapxt(struct amd_iommu *iommu)
2176 {
2177 	struct irq_domain *domain;
2178 	struct irq_alloc_info info;
2179 	int irq, ret;
2180 
2181 	domain = iommu_get_irqdomain();
2182 	if (!domain)
2183 		return -ENXIO;
2184 
2185 	init_irq_alloc_info(&info, NULL);
2186 	info.type = X86_IRQ_ALLOC_TYPE_AMDVI;
2187 	info.data = iommu;
2188 
2189 	irq = irq_domain_alloc_irqs(domain, 1, NUMA_NO_NODE, &info);
2190 	if (irq < 0) {
2191 		irq_domain_remove(domain);
2192 		return irq;
2193 	}
2194 
2195 	ret = request_threaded_irq(irq, amd_iommu_int_handler,
2196 				   amd_iommu_int_thread, 0, "AMD-Vi", iommu);
2197 	if (ret) {
2198 		irq_domain_free_irqs(irq, 1);
2199 		irq_domain_remove(domain);
2200 		return ret;
2201 	}
2202 
2203 	return 0;
2204 }
2205 
2206 static int iommu_init_irq(struct amd_iommu *iommu)
2207 {
2208 	int ret;
2209 
2210 	if (iommu->int_enabled)
2211 		goto enable_faults;
2212 
2213 	if (amd_iommu_xt_mode == IRQ_REMAP_X2APIC_MODE)
2214 		ret = iommu_setup_intcapxt(iommu);
2215 	else if (iommu->dev->msi_cap)
2216 		ret = iommu_setup_msi(iommu);
2217 	else
2218 		ret = -ENODEV;
2219 
2220 	if (ret)
2221 		return ret;
2222 
2223 	iommu->int_enabled = true;
2224 enable_faults:
2225 
2226 	if (amd_iommu_xt_mode == IRQ_REMAP_X2APIC_MODE)
2227 		iommu_feature_enable(iommu, CONTROL_INTCAPXT_EN);
2228 
2229 	iommu_feature_enable(iommu, CONTROL_EVT_INT_EN);
2230 
2231 	if (iommu->ppr_log != NULL)
2232 		iommu_feature_enable(iommu, CONTROL_PPRINT_EN);
2233 
2234 	iommu_ga_log_enable(iommu);
2235 
2236 	return 0;
2237 }
2238 
2239 /****************************************************************************
2240  *
2241  * The next functions belong to the third pass of parsing the ACPI
2242  * table. In this last pass the memory mapping requirements are
2243  * gathered (like exclusion and unity mapping ranges).
2244  *
2245  ****************************************************************************/
2246 
2247 static void __init free_unity_maps(void)
2248 {
2249 	struct unity_map_entry *entry, *next;
2250 
2251 	list_for_each_entry_safe(entry, next, &amd_iommu_unity_map, list) {
2252 		list_del(&entry->list);
2253 		kfree(entry);
2254 	}
2255 }
2256 
2257 /* called for unity map ACPI definition */
2258 static int __init init_unity_map_range(struct ivmd_header *m)
2259 {
2260 	struct unity_map_entry *e = NULL;
2261 	char *s;
2262 
2263 	e = kzalloc(sizeof(*e), GFP_KERNEL);
2264 	if (e == NULL)
2265 		return -ENOMEM;
2266 
2267 	switch (m->type) {
2268 	default:
2269 		kfree(e);
2270 		return 0;
2271 	case ACPI_IVMD_TYPE:
2272 		s = "IVMD_TYPEi\t\t\t";
2273 		e->devid_start = e->devid_end = m->devid;
2274 		break;
2275 	case ACPI_IVMD_TYPE_ALL:
2276 		s = "IVMD_TYPE_ALL\t\t";
2277 		e->devid_start = 0;
2278 		e->devid_end = amd_iommu_last_bdf;
2279 		break;
2280 	case ACPI_IVMD_TYPE_RANGE:
2281 		s = "IVMD_TYPE_RANGE\t\t";
2282 		e->devid_start = m->devid;
2283 		e->devid_end = m->aux;
2284 		break;
2285 	}
2286 	e->address_start = PAGE_ALIGN(m->range_start);
2287 	e->address_end = e->address_start + PAGE_ALIGN(m->range_length);
2288 	e->prot = m->flags >> 1;
2289 
2290 	/*
2291 	 * Treat per-device exclusion ranges as r/w unity-mapped regions
2292 	 * since some buggy BIOSes might lead to the overwritten exclusion
2293 	 * range (exclusion_start and exclusion_length members). This
2294 	 * happens when there are multiple exclusion ranges (IVMD entries)
2295 	 * defined in ACPI table.
2296 	 */
2297 	if (m->flags & IVMD_FLAG_EXCL_RANGE)
2298 		e->prot = (IVMD_FLAG_IW | IVMD_FLAG_IR) >> 1;
2299 
2300 	DUMP_printk("%s devid_start: %02x:%02x.%x devid_end: %02x:%02x.%x"
2301 		    " range_start: %016llx range_end: %016llx flags: %x\n", s,
2302 		    PCI_BUS_NUM(e->devid_start), PCI_SLOT(e->devid_start),
2303 		    PCI_FUNC(e->devid_start), PCI_BUS_NUM(e->devid_end),
2304 		    PCI_SLOT(e->devid_end), PCI_FUNC(e->devid_end),
2305 		    e->address_start, e->address_end, m->flags);
2306 
2307 	list_add_tail(&e->list, &amd_iommu_unity_map);
2308 
2309 	return 0;
2310 }
2311 
2312 /* iterates over all memory definitions we find in the ACPI table */
2313 static int __init init_memory_definitions(struct acpi_table_header *table)
2314 {
2315 	u8 *p = (u8 *)table, *end = (u8 *)table;
2316 	struct ivmd_header *m;
2317 
2318 	end += table->length;
2319 	p += IVRS_HEADER_LENGTH;
2320 
2321 	while (p < end) {
2322 		m = (struct ivmd_header *)p;
2323 		if (m->flags & (IVMD_FLAG_UNITY_MAP | IVMD_FLAG_EXCL_RANGE))
2324 			init_unity_map_range(m);
2325 
2326 		p += m->length;
2327 	}
2328 
2329 	return 0;
2330 }
2331 
2332 /*
2333  * Init the device table to not allow DMA access for devices
2334  */
2335 static void init_device_table_dma(void)
2336 {
2337 	u32 devid;
2338 
2339 	for (devid = 0; devid <= amd_iommu_last_bdf; ++devid) {
2340 		set_dev_entry_bit(devid, DEV_ENTRY_VALID);
2341 		set_dev_entry_bit(devid, DEV_ENTRY_TRANSLATION);
2342 	}
2343 }
2344 
2345 static void __init uninit_device_table_dma(void)
2346 {
2347 	u32 devid;
2348 
2349 	for (devid = 0; devid <= amd_iommu_last_bdf; ++devid) {
2350 		amd_iommu_dev_table[devid].data[0] = 0ULL;
2351 		amd_iommu_dev_table[devid].data[1] = 0ULL;
2352 	}
2353 }
2354 
2355 static void init_device_table(void)
2356 {
2357 	u32 devid;
2358 
2359 	if (!amd_iommu_irq_remap)
2360 		return;
2361 
2362 	for (devid = 0; devid <= amd_iommu_last_bdf; ++devid)
2363 		set_dev_entry_bit(devid, DEV_ENTRY_IRQ_TBL_EN);
2364 }
2365 
2366 static void iommu_init_flags(struct amd_iommu *iommu)
2367 {
2368 	iommu->acpi_flags & IVHD_FLAG_HT_TUN_EN_MASK ?
2369 		iommu_feature_enable(iommu, CONTROL_HT_TUN_EN) :
2370 		iommu_feature_disable(iommu, CONTROL_HT_TUN_EN);
2371 
2372 	iommu->acpi_flags & IVHD_FLAG_PASSPW_EN_MASK ?
2373 		iommu_feature_enable(iommu, CONTROL_PASSPW_EN) :
2374 		iommu_feature_disable(iommu, CONTROL_PASSPW_EN);
2375 
2376 	iommu->acpi_flags & IVHD_FLAG_RESPASSPW_EN_MASK ?
2377 		iommu_feature_enable(iommu, CONTROL_RESPASSPW_EN) :
2378 		iommu_feature_disable(iommu, CONTROL_RESPASSPW_EN);
2379 
2380 	iommu->acpi_flags & IVHD_FLAG_ISOC_EN_MASK ?
2381 		iommu_feature_enable(iommu, CONTROL_ISOC_EN) :
2382 		iommu_feature_disable(iommu, CONTROL_ISOC_EN);
2383 
2384 	/*
2385 	 * make IOMMU memory accesses cache coherent
2386 	 */
2387 	iommu_feature_enable(iommu, CONTROL_COHERENT_EN);
2388 
2389 	/* Set IOTLB invalidation timeout to 1s */
2390 	iommu_set_inv_tlb_timeout(iommu, CTRL_INV_TO_1S);
2391 }
2392 
2393 static void iommu_apply_resume_quirks(struct amd_iommu *iommu)
2394 {
2395 	int i, j;
2396 	u32 ioc_feature_control;
2397 	struct pci_dev *pdev = iommu->root_pdev;
2398 
2399 	/* RD890 BIOSes may not have completely reconfigured the iommu */
2400 	if (!is_rd890_iommu(iommu->dev) || !pdev)
2401 		return;
2402 
2403 	/*
2404 	 * First, we need to ensure that the iommu is enabled. This is
2405 	 * controlled by a register in the northbridge
2406 	 */
2407 
2408 	/* Select Northbridge indirect register 0x75 and enable writing */
2409 	pci_write_config_dword(pdev, 0x60, 0x75 | (1 << 7));
2410 	pci_read_config_dword(pdev, 0x64, &ioc_feature_control);
2411 
2412 	/* Enable the iommu */
2413 	if (!(ioc_feature_control & 0x1))
2414 		pci_write_config_dword(pdev, 0x64, ioc_feature_control | 1);
2415 
2416 	/* Restore the iommu BAR */
2417 	pci_write_config_dword(iommu->dev, iommu->cap_ptr + 4,
2418 			       iommu->stored_addr_lo);
2419 	pci_write_config_dword(iommu->dev, iommu->cap_ptr + 8,
2420 			       iommu->stored_addr_hi);
2421 
2422 	/* Restore the l1 indirect regs for each of the 6 l1s */
2423 	for (i = 0; i < 6; i++)
2424 		for (j = 0; j < 0x12; j++)
2425 			iommu_write_l1(iommu, i, j, iommu->stored_l1[i][j]);
2426 
2427 	/* Restore the l2 indirect regs */
2428 	for (i = 0; i < 0x83; i++)
2429 		iommu_write_l2(iommu, i, iommu->stored_l2[i]);
2430 
2431 	/* Lock PCI setup registers */
2432 	pci_write_config_dword(iommu->dev, iommu->cap_ptr + 4,
2433 			       iommu->stored_addr_lo | 1);
2434 }
2435 
2436 static void iommu_enable_ga(struct amd_iommu *iommu)
2437 {
2438 #ifdef CONFIG_IRQ_REMAP
2439 	switch (amd_iommu_guest_ir) {
2440 	case AMD_IOMMU_GUEST_IR_VAPIC:
2441 		iommu_feature_enable(iommu, CONTROL_GAM_EN);
2442 		fallthrough;
2443 	case AMD_IOMMU_GUEST_IR_LEGACY_GA:
2444 		iommu_feature_enable(iommu, CONTROL_GA_EN);
2445 		iommu->irte_ops = &irte_128_ops;
2446 		break;
2447 	default:
2448 		iommu->irte_ops = &irte_32_ops;
2449 		break;
2450 	}
2451 #endif
2452 }
2453 
2454 static void early_enable_iommu(struct amd_iommu *iommu)
2455 {
2456 	iommu_disable(iommu);
2457 	iommu_init_flags(iommu);
2458 	iommu_set_device_table(iommu);
2459 	iommu_enable_command_buffer(iommu);
2460 	iommu_enable_event_buffer(iommu);
2461 	iommu_set_exclusion_range(iommu);
2462 	iommu_enable_ga(iommu);
2463 	iommu_enable_xt(iommu);
2464 	iommu_enable(iommu);
2465 	iommu_flush_all_caches(iommu);
2466 }
2467 
2468 /*
2469  * This function finally enables all IOMMUs found in the system after
2470  * they have been initialized.
2471  *
2472  * Or if in kdump kernel and IOMMUs are all pre-enabled, try to copy
2473  * the old content of device table entries. Not this case or copy failed,
2474  * just continue as normal kernel does.
2475  */
2476 static void early_enable_iommus(void)
2477 {
2478 	struct amd_iommu *iommu;
2479 
2480 
2481 	if (!copy_device_table()) {
2482 		/*
2483 		 * If come here because of failure in copying device table from old
2484 		 * kernel with all IOMMUs enabled, print error message and try to
2485 		 * free allocated old_dev_tbl_cpy.
2486 		 */
2487 		if (amd_iommu_pre_enabled)
2488 			pr_err("Failed to copy DEV table from previous kernel.\n");
2489 		if (old_dev_tbl_cpy != NULL)
2490 			free_pages((unsigned long)old_dev_tbl_cpy,
2491 					get_order(dev_table_size));
2492 
2493 		for_each_iommu(iommu) {
2494 			clear_translation_pre_enabled(iommu);
2495 			early_enable_iommu(iommu);
2496 		}
2497 	} else {
2498 		pr_info("Copied DEV table from previous kernel.\n");
2499 		free_pages((unsigned long)amd_iommu_dev_table,
2500 				get_order(dev_table_size));
2501 		amd_iommu_dev_table = old_dev_tbl_cpy;
2502 		for_each_iommu(iommu) {
2503 			iommu_disable_command_buffer(iommu);
2504 			iommu_disable_event_buffer(iommu);
2505 			iommu_enable_command_buffer(iommu);
2506 			iommu_enable_event_buffer(iommu);
2507 			iommu_enable_ga(iommu);
2508 			iommu_enable_xt(iommu);
2509 			iommu_set_device_table(iommu);
2510 			iommu_flush_all_caches(iommu);
2511 		}
2512 	}
2513 
2514 #ifdef CONFIG_IRQ_REMAP
2515 	/*
2516 	 * Note: We have already checked GASup from IVRS table.
2517 	 *       Now, we need to make sure that GAMSup is set.
2518 	 */
2519 	if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) &&
2520 	    !check_feature_on_all_iommus(FEATURE_GAM_VAPIC))
2521 		amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_LEGACY_GA;
2522 
2523 	if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir))
2524 		amd_iommu_irq_ops.capability |= (1 << IRQ_POSTING_CAP);
2525 #endif
2526 }
2527 
2528 static void enable_iommus_v2(void)
2529 {
2530 	struct amd_iommu *iommu;
2531 
2532 	for_each_iommu(iommu) {
2533 		iommu_enable_ppr_log(iommu);
2534 		iommu_enable_gt(iommu);
2535 	}
2536 }
2537 
2538 static void enable_iommus(void)
2539 {
2540 	early_enable_iommus();
2541 
2542 	enable_iommus_v2();
2543 }
2544 
2545 static void disable_iommus(void)
2546 {
2547 	struct amd_iommu *iommu;
2548 
2549 	for_each_iommu(iommu)
2550 		iommu_disable(iommu);
2551 
2552 #ifdef CONFIG_IRQ_REMAP
2553 	if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir))
2554 		amd_iommu_irq_ops.capability &= ~(1 << IRQ_POSTING_CAP);
2555 #endif
2556 }
2557 
2558 /*
2559  * Suspend/Resume support
2560  * disable suspend until real resume implemented
2561  */
2562 
2563 static void amd_iommu_resume(void)
2564 {
2565 	struct amd_iommu *iommu;
2566 
2567 	for_each_iommu(iommu)
2568 		iommu_apply_resume_quirks(iommu);
2569 
2570 	/* re-load the hardware */
2571 	enable_iommus();
2572 
2573 	amd_iommu_enable_interrupts();
2574 }
2575 
2576 static int amd_iommu_suspend(void)
2577 {
2578 	/* disable IOMMUs to go out of the way for BIOS */
2579 	disable_iommus();
2580 
2581 	return 0;
2582 }
2583 
2584 static struct syscore_ops amd_iommu_syscore_ops = {
2585 	.suspend = amd_iommu_suspend,
2586 	.resume = amd_iommu_resume,
2587 };
2588 
2589 static void __init free_iommu_resources(void)
2590 {
2591 	kmemleak_free(irq_lookup_table);
2592 	free_pages((unsigned long)irq_lookup_table,
2593 		   get_order(rlookup_table_size));
2594 	irq_lookup_table = NULL;
2595 
2596 	kmem_cache_destroy(amd_iommu_irq_cache);
2597 	amd_iommu_irq_cache = NULL;
2598 
2599 	free_pages((unsigned long)amd_iommu_rlookup_table,
2600 		   get_order(rlookup_table_size));
2601 	amd_iommu_rlookup_table = NULL;
2602 
2603 	free_pages((unsigned long)amd_iommu_alias_table,
2604 		   get_order(alias_table_size));
2605 	amd_iommu_alias_table = NULL;
2606 
2607 	free_pages((unsigned long)amd_iommu_dev_table,
2608 		   get_order(dev_table_size));
2609 	amd_iommu_dev_table = NULL;
2610 
2611 	free_iommu_all();
2612 }
2613 
2614 /* SB IOAPIC is always on this device in AMD systems */
2615 #define IOAPIC_SB_DEVID		((0x00 << 8) | PCI_DEVFN(0x14, 0))
2616 
2617 static bool __init check_ioapic_information(void)
2618 {
2619 	const char *fw_bug = FW_BUG;
2620 	bool ret, has_sb_ioapic;
2621 	int idx;
2622 
2623 	has_sb_ioapic = false;
2624 	ret           = false;
2625 
2626 	/*
2627 	 * If we have map overrides on the kernel command line the
2628 	 * messages in this function might not describe firmware bugs
2629 	 * anymore - so be careful
2630 	 */
2631 	if (cmdline_maps)
2632 		fw_bug = "";
2633 
2634 	for (idx = 0; idx < nr_ioapics; idx++) {
2635 		int devid, id = mpc_ioapic_id(idx);
2636 
2637 		devid = get_ioapic_devid(id);
2638 		if (devid < 0) {
2639 			pr_err("%s: IOAPIC[%d] not in IVRS table\n",
2640 				fw_bug, id);
2641 			ret = false;
2642 		} else if (devid == IOAPIC_SB_DEVID) {
2643 			has_sb_ioapic = true;
2644 			ret           = true;
2645 		}
2646 	}
2647 
2648 	if (!has_sb_ioapic) {
2649 		/*
2650 		 * We expect the SB IOAPIC to be listed in the IVRS
2651 		 * table. The system timer is connected to the SB IOAPIC
2652 		 * and if we don't have it in the list the system will
2653 		 * panic at boot time.  This situation usually happens
2654 		 * when the BIOS is buggy and provides us the wrong
2655 		 * device id for the IOAPIC in the system.
2656 		 */
2657 		pr_err("%s: No southbridge IOAPIC found\n", fw_bug);
2658 	}
2659 
2660 	if (!ret)
2661 		pr_err("Disabling interrupt remapping\n");
2662 
2663 	return ret;
2664 }
2665 
2666 static void __init free_dma_resources(void)
2667 {
2668 	free_pages((unsigned long)amd_iommu_pd_alloc_bitmap,
2669 		   get_order(MAX_DOMAIN_ID/8));
2670 	amd_iommu_pd_alloc_bitmap = NULL;
2671 
2672 	free_unity_maps();
2673 }
2674 
2675 static void __init ivinfo_init(void *ivrs)
2676 {
2677 	amd_iommu_ivinfo = *((u32 *)(ivrs + IOMMU_IVINFO_OFFSET));
2678 }
2679 
2680 /*
2681  * This is the hardware init function for AMD IOMMU in the system.
2682  * This function is called either from amd_iommu_init or from the interrupt
2683  * remapping setup code.
2684  *
2685  * This function basically parses the ACPI table for AMD IOMMU (IVRS)
2686  * four times:
2687  *
2688  *	1 pass) Discover the most comprehensive IVHD type to use.
2689  *
2690  *	2 pass) Find the highest PCI device id the driver has to handle.
2691  *		Upon this information the size of the data structures is
2692  *		determined that needs to be allocated.
2693  *
2694  *	3 pass) Initialize the data structures just allocated with the
2695  *		information in the ACPI table about available AMD IOMMUs
2696  *		in the system. It also maps the PCI devices in the
2697  *		system to specific IOMMUs
2698  *
2699  *	4 pass) After the basic data structures are allocated and
2700  *		initialized we update them with information about memory
2701  *		remapping requirements parsed out of the ACPI table in
2702  *		this last pass.
2703  *
2704  * After everything is set up the IOMMUs are enabled and the necessary
2705  * hotplug and suspend notifiers are registered.
2706  */
2707 static int __init early_amd_iommu_init(void)
2708 {
2709 	struct acpi_table_header *ivrs_base;
2710 	int i, remap_cache_sz, ret;
2711 	acpi_status status;
2712 
2713 	if (!amd_iommu_detected)
2714 		return -ENODEV;
2715 
2716 	status = acpi_get_table("IVRS", 0, &ivrs_base);
2717 	if (status == AE_NOT_FOUND)
2718 		return -ENODEV;
2719 	else if (ACPI_FAILURE(status)) {
2720 		const char *err = acpi_format_exception(status);
2721 		pr_err("IVRS table error: %s\n", err);
2722 		return -EINVAL;
2723 	}
2724 
2725 	/*
2726 	 * Validate checksum here so we don't need to do it when
2727 	 * we actually parse the table
2728 	 */
2729 	ret = check_ivrs_checksum(ivrs_base);
2730 	if (ret)
2731 		goto out;
2732 
2733 	ivinfo_init(ivrs_base);
2734 
2735 	amd_iommu_target_ivhd_type = get_highest_supported_ivhd_type(ivrs_base);
2736 	DUMP_printk("Using IVHD type %#x\n", amd_iommu_target_ivhd_type);
2737 
2738 	/*
2739 	 * First parse ACPI tables to find the largest Bus/Dev/Func
2740 	 * we need to handle. Upon this information the shared data
2741 	 * structures for the IOMMUs in the system will be allocated
2742 	 */
2743 	ret = find_last_devid_acpi(ivrs_base);
2744 	if (ret)
2745 		goto out;
2746 
2747 	dev_table_size     = tbl_size(DEV_TABLE_ENTRY_SIZE);
2748 	alias_table_size   = tbl_size(ALIAS_TABLE_ENTRY_SIZE);
2749 	rlookup_table_size = tbl_size(RLOOKUP_TABLE_ENTRY_SIZE);
2750 
2751 	/* Device table - directly used by all IOMMUs */
2752 	ret = -ENOMEM;
2753 	amd_iommu_dev_table = (void *)__get_free_pages(
2754 				      GFP_KERNEL | __GFP_ZERO | GFP_DMA32,
2755 				      get_order(dev_table_size));
2756 	if (amd_iommu_dev_table == NULL)
2757 		goto out;
2758 
2759 	/*
2760 	 * Alias table - map PCI Bus/Dev/Func to Bus/Dev/Func the
2761 	 * IOMMU see for that device
2762 	 */
2763 	amd_iommu_alias_table = (void *)__get_free_pages(GFP_KERNEL,
2764 			get_order(alias_table_size));
2765 	if (amd_iommu_alias_table == NULL)
2766 		goto out;
2767 
2768 	/* IOMMU rlookup table - find the IOMMU for a specific device */
2769 	amd_iommu_rlookup_table = (void *)__get_free_pages(
2770 			GFP_KERNEL | __GFP_ZERO,
2771 			get_order(rlookup_table_size));
2772 	if (amd_iommu_rlookup_table == NULL)
2773 		goto out;
2774 
2775 	amd_iommu_pd_alloc_bitmap = (void *)__get_free_pages(
2776 					    GFP_KERNEL | __GFP_ZERO,
2777 					    get_order(MAX_DOMAIN_ID/8));
2778 	if (amd_iommu_pd_alloc_bitmap == NULL)
2779 		goto out;
2780 
2781 	/*
2782 	 * let all alias entries point to itself
2783 	 */
2784 	for (i = 0; i <= amd_iommu_last_bdf; ++i)
2785 		amd_iommu_alias_table[i] = i;
2786 
2787 	/*
2788 	 * never allocate domain 0 because its used as the non-allocated and
2789 	 * error value placeholder
2790 	 */
2791 	__set_bit(0, amd_iommu_pd_alloc_bitmap);
2792 
2793 	/*
2794 	 * now the data structures are allocated and basically initialized
2795 	 * start the real acpi table scan
2796 	 */
2797 	ret = init_iommu_all(ivrs_base);
2798 	if (ret)
2799 		goto out;
2800 
2801 	/* Disable any previously enabled IOMMUs */
2802 	if (!is_kdump_kernel() || amd_iommu_disabled)
2803 		disable_iommus();
2804 
2805 	if (amd_iommu_irq_remap)
2806 		amd_iommu_irq_remap = check_ioapic_information();
2807 
2808 	if (amd_iommu_irq_remap) {
2809 		/*
2810 		 * Interrupt remapping enabled, create kmem_cache for the
2811 		 * remapping tables.
2812 		 */
2813 		ret = -ENOMEM;
2814 		if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
2815 			remap_cache_sz = MAX_IRQS_PER_TABLE * sizeof(u32);
2816 		else
2817 			remap_cache_sz = MAX_IRQS_PER_TABLE * (sizeof(u64) * 2);
2818 		amd_iommu_irq_cache = kmem_cache_create("irq_remap_cache",
2819 							remap_cache_sz,
2820 							DTE_INTTAB_ALIGNMENT,
2821 							0, NULL);
2822 		if (!amd_iommu_irq_cache)
2823 			goto out;
2824 
2825 		irq_lookup_table = (void *)__get_free_pages(
2826 				GFP_KERNEL | __GFP_ZERO,
2827 				get_order(rlookup_table_size));
2828 		kmemleak_alloc(irq_lookup_table, rlookup_table_size,
2829 			       1, GFP_KERNEL);
2830 		if (!irq_lookup_table)
2831 			goto out;
2832 	}
2833 
2834 	ret = init_memory_definitions(ivrs_base);
2835 	if (ret)
2836 		goto out;
2837 
2838 	/* init the device table */
2839 	init_device_table();
2840 
2841 out:
2842 	/* Don't leak any ACPI memory */
2843 	acpi_put_table(ivrs_base);
2844 
2845 	return ret;
2846 }
2847 
2848 static int amd_iommu_enable_interrupts(void)
2849 {
2850 	struct amd_iommu *iommu;
2851 	int ret = 0;
2852 
2853 	for_each_iommu(iommu) {
2854 		ret = iommu_init_irq(iommu);
2855 		if (ret)
2856 			goto out;
2857 	}
2858 
2859 out:
2860 	return ret;
2861 }
2862 
2863 static bool __init detect_ivrs(void)
2864 {
2865 	struct acpi_table_header *ivrs_base;
2866 	acpi_status status;
2867 	int i;
2868 
2869 	status = acpi_get_table("IVRS", 0, &ivrs_base);
2870 	if (status == AE_NOT_FOUND)
2871 		return false;
2872 	else if (ACPI_FAILURE(status)) {
2873 		const char *err = acpi_format_exception(status);
2874 		pr_err("IVRS table error: %s\n", err);
2875 		return false;
2876 	}
2877 
2878 	acpi_put_table(ivrs_base);
2879 
2880 	if (amd_iommu_force_enable)
2881 		goto out;
2882 
2883 	/* Don't use IOMMU if there is Stoney Ridge graphics */
2884 	for (i = 0; i < 32; i++) {
2885 		u32 pci_id;
2886 
2887 		pci_id = read_pci_config(0, i, 0, 0);
2888 		if ((pci_id & 0xffff) == 0x1002 && (pci_id >> 16) == 0x98e4) {
2889 			pr_info("Disable IOMMU on Stoney Ridge\n");
2890 			return false;
2891 		}
2892 	}
2893 
2894 out:
2895 	/* Make sure ACS will be enabled during PCI probe */
2896 	pci_request_acs();
2897 
2898 	return true;
2899 }
2900 
2901 /****************************************************************************
2902  *
2903  * AMD IOMMU Initialization State Machine
2904  *
2905  ****************************************************************************/
2906 
2907 static int __init state_next(void)
2908 {
2909 	int ret = 0;
2910 
2911 	switch (init_state) {
2912 	case IOMMU_START_STATE:
2913 		if (!detect_ivrs()) {
2914 			init_state	= IOMMU_NOT_FOUND;
2915 			ret		= -ENODEV;
2916 		} else {
2917 			init_state	= IOMMU_IVRS_DETECTED;
2918 		}
2919 		break;
2920 	case IOMMU_IVRS_DETECTED:
2921 		if (amd_iommu_disabled) {
2922 			init_state = IOMMU_CMDLINE_DISABLED;
2923 			ret = -EINVAL;
2924 		} else {
2925 			ret = early_amd_iommu_init();
2926 			init_state = ret ? IOMMU_INIT_ERROR : IOMMU_ACPI_FINISHED;
2927 		}
2928 		break;
2929 	case IOMMU_ACPI_FINISHED:
2930 		early_enable_iommus();
2931 		x86_platform.iommu_shutdown = disable_iommus;
2932 		init_state = IOMMU_ENABLED;
2933 		break;
2934 	case IOMMU_ENABLED:
2935 		register_syscore_ops(&amd_iommu_syscore_ops);
2936 		ret = amd_iommu_init_pci();
2937 		init_state = ret ? IOMMU_INIT_ERROR : IOMMU_PCI_INIT;
2938 		enable_iommus_v2();
2939 		break;
2940 	case IOMMU_PCI_INIT:
2941 		ret = amd_iommu_enable_interrupts();
2942 		init_state = ret ? IOMMU_INIT_ERROR : IOMMU_INTERRUPTS_EN;
2943 		break;
2944 	case IOMMU_INTERRUPTS_EN:
2945 		init_state = IOMMU_INITIALIZED;
2946 		break;
2947 	case IOMMU_INITIALIZED:
2948 		/* Nothing to do */
2949 		break;
2950 	case IOMMU_NOT_FOUND:
2951 	case IOMMU_INIT_ERROR:
2952 	case IOMMU_CMDLINE_DISABLED:
2953 		/* Error states => do nothing */
2954 		ret = -EINVAL;
2955 		break;
2956 	default:
2957 		/* Unknown state */
2958 		BUG();
2959 	}
2960 
2961 	if (ret) {
2962 		free_dma_resources();
2963 		if (!irq_remapping_enabled) {
2964 			disable_iommus();
2965 			free_iommu_resources();
2966 		} else {
2967 			struct amd_iommu *iommu;
2968 
2969 			uninit_device_table_dma();
2970 			for_each_iommu(iommu)
2971 				iommu_flush_all_caches(iommu);
2972 		}
2973 	}
2974 	return ret;
2975 }
2976 
2977 static int __init iommu_go_to_state(enum iommu_init_state state)
2978 {
2979 	int ret = -EINVAL;
2980 
2981 	while (init_state != state) {
2982 		if (init_state == IOMMU_NOT_FOUND         ||
2983 		    init_state == IOMMU_INIT_ERROR        ||
2984 		    init_state == IOMMU_CMDLINE_DISABLED)
2985 			break;
2986 		ret = state_next();
2987 	}
2988 
2989 	return ret;
2990 }
2991 
2992 #ifdef CONFIG_IRQ_REMAP
2993 int __init amd_iommu_prepare(void)
2994 {
2995 	int ret;
2996 
2997 	amd_iommu_irq_remap = true;
2998 
2999 	ret = iommu_go_to_state(IOMMU_ACPI_FINISHED);
3000 	if (ret) {
3001 		amd_iommu_irq_remap = false;
3002 		return ret;
3003 	}
3004 
3005 	return amd_iommu_irq_remap ? 0 : -ENODEV;
3006 }
3007 
3008 int __init amd_iommu_enable(void)
3009 {
3010 	int ret;
3011 
3012 	ret = iommu_go_to_state(IOMMU_ENABLED);
3013 	if (ret)
3014 		return ret;
3015 
3016 	irq_remapping_enabled = 1;
3017 	return amd_iommu_xt_mode;
3018 }
3019 
3020 void amd_iommu_disable(void)
3021 {
3022 	amd_iommu_suspend();
3023 }
3024 
3025 int amd_iommu_reenable(int mode)
3026 {
3027 	amd_iommu_resume();
3028 
3029 	return 0;
3030 }
3031 
3032 int __init amd_iommu_enable_faulting(void)
3033 {
3034 	/* We enable MSI later when PCI is initialized */
3035 	return 0;
3036 }
3037 #endif
3038 
3039 /*
3040  * This is the core init function for AMD IOMMU hardware in the system.
3041  * This function is called from the generic x86 DMA layer initialization
3042  * code.
3043  */
3044 static int __init amd_iommu_init(void)
3045 {
3046 	struct amd_iommu *iommu;
3047 	int ret;
3048 
3049 	ret = iommu_go_to_state(IOMMU_INITIALIZED);
3050 #ifdef CONFIG_GART_IOMMU
3051 	if (ret && list_empty(&amd_iommu_list)) {
3052 		/*
3053 		 * We failed to initialize the AMD IOMMU - try fallback
3054 		 * to GART if possible.
3055 		 */
3056 		gart_iommu_init();
3057 	}
3058 #endif
3059 
3060 	for_each_iommu(iommu)
3061 		amd_iommu_debugfs_setup(iommu);
3062 
3063 	return ret;
3064 }
3065 
3066 static bool amd_iommu_sme_check(void)
3067 {
3068 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT) ||
3069 	    (boot_cpu_data.x86 != 0x17))
3070 		return true;
3071 
3072 	/* For Fam17h, a specific level of support is required */
3073 	if (boot_cpu_data.microcode >= 0x08001205)
3074 		return true;
3075 
3076 	if ((boot_cpu_data.microcode >= 0x08001126) &&
3077 	    (boot_cpu_data.microcode <= 0x080011ff))
3078 		return true;
3079 
3080 	pr_notice("IOMMU not currently supported when SME is active\n");
3081 
3082 	return false;
3083 }
3084 
3085 /****************************************************************************
3086  *
3087  * Early detect code. This code runs at IOMMU detection time in the DMA
3088  * layer. It just looks if there is an IVRS ACPI table to detect AMD
3089  * IOMMUs
3090  *
3091  ****************************************************************************/
3092 int __init amd_iommu_detect(void)
3093 {
3094 	int ret;
3095 
3096 	if (no_iommu || (iommu_detected && !gart_iommu_aperture))
3097 		return -ENODEV;
3098 
3099 	if (!amd_iommu_sme_check())
3100 		return -ENODEV;
3101 
3102 	ret = iommu_go_to_state(IOMMU_IVRS_DETECTED);
3103 	if (ret)
3104 		return ret;
3105 
3106 	amd_iommu_detected = true;
3107 	iommu_detected = 1;
3108 	x86_init.iommu.iommu_init = amd_iommu_init;
3109 
3110 	return 1;
3111 }
3112 
3113 /****************************************************************************
3114  *
3115  * Parsing functions for the AMD IOMMU specific kernel command line
3116  * options.
3117  *
3118  ****************************************************************************/
3119 
3120 static int __init parse_amd_iommu_dump(char *str)
3121 {
3122 	amd_iommu_dump = true;
3123 
3124 	return 1;
3125 }
3126 
3127 static int __init parse_amd_iommu_intr(char *str)
3128 {
3129 	for (; *str; ++str) {
3130 		if (strncmp(str, "legacy", 6) == 0) {
3131 			amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_LEGACY_GA;
3132 			break;
3133 		}
3134 		if (strncmp(str, "vapic", 5) == 0) {
3135 			amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_VAPIC;
3136 			break;
3137 		}
3138 	}
3139 	return 1;
3140 }
3141 
3142 static int __init parse_amd_iommu_options(char *str)
3143 {
3144 	for (; *str; ++str) {
3145 		if (strncmp(str, "fullflush", 9) == 0) {
3146 			pr_warn("amd_iommu=fullflush deprecated; use iommu.strict=1 instead\n");
3147 			iommu_set_dma_strict();
3148 		}
3149 		if (strncmp(str, "force_enable", 12) == 0)
3150 			amd_iommu_force_enable = true;
3151 		if (strncmp(str, "off", 3) == 0)
3152 			amd_iommu_disabled = true;
3153 		if (strncmp(str, "force_isolation", 15) == 0)
3154 			amd_iommu_force_isolation = true;
3155 	}
3156 
3157 	return 1;
3158 }
3159 
3160 static int __init parse_ivrs_ioapic(char *str)
3161 {
3162 	unsigned int bus, dev, fn;
3163 	int ret, id, i;
3164 	u16 devid;
3165 
3166 	ret = sscanf(str, "[%d]=%x:%x.%x", &id, &bus, &dev, &fn);
3167 
3168 	if (ret != 4) {
3169 		pr_err("Invalid command line: ivrs_ioapic%s\n", str);
3170 		return 1;
3171 	}
3172 
3173 	if (early_ioapic_map_size == EARLY_MAP_SIZE) {
3174 		pr_err("Early IOAPIC map overflow - ignoring ivrs_ioapic%s\n",
3175 			str);
3176 		return 1;
3177 	}
3178 
3179 	devid = ((bus & 0xff) << 8) | ((dev & 0x1f) << 3) | (fn & 0x7);
3180 
3181 	cmdline_maps			= true;
3182 	i				= early_ioapic_map_size++;
3183 	early_ioapic_map[i].id		= id;
3184 	early_ioapic_map[i].devid	= devid;
3185 	early_ioapic_map[i].cmd_line	= true;
3186 
3187 	return 1;
3188 }
3189 
3190 static int __init parse_ivrs_hpet(char *str)
3191 {
3192 	unsigned int bus, dev, fn;
3193 	int ret, id, i;
3194 	u16 devid;
3195 
3196 	ret = sscanf(str, "[%d]=%x:%x.%x", &id, &bus, &dev, &fn);
3197 
3198 	if (ret != 4) {
3199 		pr_err("Invalid command line: ivrs_hpet%s\n", str);
3200 		return 1;
3201 	}
3202 
3203 	if (early_hpet_map_size == EARLY_MAP_SIZE) {
3204 		pr_err("Early HPET map overflow - ignoring ivrs_hpet%s\n",
3205 			str);
3206 		return 1;
3207 	}
3208 
3209 	devid = ((bus & 0xff) << 8) | ((dev & 0x1f) << 3) | (fn & 0x7);
3210 
3211 	cmdline_maps			= true;
3212 	i				= early_hpet_map_size++;
3213 	early_hpet_map[i].id		= id;
3214 	early_hpet_map[i].devid		= devid;
3215 	early_hpet_map[i].cmd_line	= true;
3216 
3217 	return 1;
3218 }
3219 
3220 static int __init parse_ivrs_acpihid(char *str)
3221 {
3222 	u32 bus, dev, fn;
3223 	char *hid, *uid, *p;
3224 	char acpiid[ACPIHID_UID_LEN + ACPIHID_HID_LEN] = {0};
3225 	int ret, i;
3226 
3227 	ret = sscanf(str, "[%x:%x.%x]=%s", &bus, &dev, &fn, acpiid);
3228 	if (ret != 4) {
3229 		pr_err("Invalid command line: ivrs_acpihid(%s)\n", str);
3230 		return 1;
3231 	}
3232 
3233 	p = acpiid;
3234 	hid = strsep(&p, ":");
3235 	uid = p;
3236 
3237 	if (!hid || !(*hid) || !uid) {
3238 		pr_err("Invalid command line: hid or uid\n");
3239 		return 1;
3240 	}
3241 
3242 	i = early_acpihid_map_size++;
3243 	memcpy(early_acpihid_map[i].hid, hid, strlen(hid));
3244 	memcpy(early_acpihid_map[i].uid, uid, strlen(uid));
3245 	early_acpihid_map[i].devid =
3246 		((bus & 0xff) << 8) | ((dev & 0x1f) << 3) | (fn & 0x7);
3247 	early_acpihid_map[i].cmd_line	= true;
3248 
3249 	return 1;
3250 }
3251 
3252 __setup("amd_iommu_dump",	parse_amd_iommu_dump);
3253 __setup("amd_iommu=",		parse_amd_iommu_options);
3254 __setup("amd_iommu_intr=",	parse_amd_iommu_intr);
3255 __setup("ivrs_ioapic",		parse_ivrs_ioapic);
3256 __setup("ivrs_hpet",		parse_ivrs_hpet);
3257 __setup("ivrs_acpihid",		parse_ivrs_acpihid);
3258 
3259 bool amd_iommu_v2_supported(void)
3260 {
3261 	return amd_iommu_v2_present;
3262 }
3263 EXPORT_SYMBOL(amd_iommu_v2_supported);
3264 
3265 struct amd_iommu *get_amd_iommu(unsigned int idx)
3266 {
3267 	unsigned int i = 0;
3268 	struct amd_iommu *iommu;
3269 
3270 	for_each_iommu(iommu)
3271 		if (i++ == idx)
3272 			return iommu;
3273 	return NULL;
3274 }
3275 
3276 /****************************************************************************
3277  *
3278  * IOMMU EFR Performance Counter support functionality. This code allows
3279  * access to the IOMMU PC functionality.
3280  *
3281  ****************************************************************************/
3282 
3283 u8 amd_iommu_pc_get_max_banks(unsigned int idx)
3284 {
3285 	struct amd_iommu *iommu = get_amd_iommu(idx);
3286 
3287 	if (iommu)
3288 		return iommu->max_banks;
3289 
3290 	return 0;
3291 }
3292 EXPORT_SYMBOL(amd_iommu_pc_get_max_banks);
3293 
3294 bool amd_iommu_pc_supported(void)
3295 {
3296 	return amd_iommu_pc_present;
3297 }
3298 EXPORT_SYMBOL(amd_iommu_pc_supported);
3299 
3300 u8 amd_iommu_pc_get_max_counters(unsigned int idx)
3301 {
3302 	struct amd_iommu *iommu = get_amd_iommu(idx);
3303 
3304 	if (iommu)
3305 		return iommu->max_counters;
3306 
3307 	return 0;
3308 }
3309 EXPORT_SYMBOL(amd_iommu_pc_get_max_counters);
3310 
3311 static int iommu_pc_get_set_reg(struct amd_iommu *iommu, u8 bank, u8 cntr,
3312 				u8 fxn, u64 *value, bool is_write)
3313 {
3314 	u32 offset;
3315 	u32 max_offset_lim;
3316 
3317 	/* Make sure the IOMMU PC resource is available */
3318 	if (!amd_iommu_pc_present)
3319 		return -ENODEV;
3320 
3321 	/* Check for valid iommu and pc register indexing */
3322 	if (WARN_ON(!iommu || (fxn > 0x28) || (fxn & 7)))
3323 		return -ENODEV;
3324 
3325 	offset = (u32)(((0x40 | bank) << 12) | (cntr << 8) | fxn);
3326 
3327 	/* Limit the offset to the hw defined mmio region aperture */
3328 	max_offset_lim = (u32)(((0x40 | iommu->max_banks) << 12) |
3329 				(iommu->max_counters << 8) | 0x28);
3330 	if ((offset < MMIO_CNTR_REG_OFFSET) ||
3331 	    (offset > max_offset_lim))
3332 		return -EINVAL;
3333 
3334 	if (is_write) {
3335 		u64 val = *value & GENMASK_ULL(47, 0);
3336 
3337 		writel((u32)val, iommu->mmio_base + offset);
3338 		writel((val >> 32), iommu->mmio_base + offset + 4);
3339 	} else {
3340 		*value = readl(iommu->mmio_base + offset + 4);
3341 		*value <<= 32;
3342 		*value |= readl(iommu->mmio_base + offset);
3343 		*value &= GENMASK_ULL(47, 0);
3344 	}
3345 
3346 	return 0;
3347 }
3348 
3349 int amd_iommu_pc_get_reg(struct amd_iommu *iommu, u8 bank, u8 cntr, u8 fxn, u64 *value)
3350 {
3351 	if (!iommu)
3352 		return -EINVAL;
3353 
3354 	return iommu_pc_get_set_reg(iommu, bank, cntr, fxn, value, false);
3355 }
3356 
3357 int amd_iommu_pc_set_reg(struct amd_iommu *iommu, u8 bank, u8 cntr, u8 fxn, u64 *value)
3358 {
3359 	if (!iommu)
3360 		return -EINVAL;
3361 
3362 	return iommu_pc_get_set_reg(iommu, bank, cntr, fxn, value, true);
3363 }
3364