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