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