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