xref: /linux/drivers/iommu/amd/init.c (revision 20bfd25757659ff8229eeed6f048c76f9a11a4a3)
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/syscore_ops.h>
16 #include <linux/interrupt.h>
17 #include <linux/msi.h>
18 #include <linux/irq.h>
19 #include <linux/amd-iommu.h>
20 #include <linux/export.h>
21 #include <linux/kmemleak.h>
22 #include <linux/cc_platform.h>
23 #include <linux/iopoll.h>
24 #include <asm/pci-direct.h>
25 #include <asm/iommu.h>
26 #include <asm/apic.h>
27 #include <asm/gart.h>
28 #include <asm/x86_init.h>
29 #include <asm/io_apic.h>
30 #include <asm/irq_remapping.h>
31 #include <asm/set_memory.h>
32 #include <asm/sev.h>
33 
34 #include <linux/crash_dump.h>
35 
36 #include "amd_iommu.h"
37 #include "../irq_remapping.h"
38 #include "../iommu-pages.h"
39 
40 /*
41  * definitions for the ACPI scanning code
42  */
43 #define IVRS_HEADER_LENGTH 48
44 
45 #define ACPI_IVHD_TYPE_MAX_SUPPORTED	0x40
46 #define ACPI_IVMD_TYPE_ALL              0x20
47 #define ACPI_IVMD_TYPE                  0x21
48 #define ACPI_IVMD_TYPE_RANGE            0x22
49 
50 #define IVHD_DEV_ALL                    0x01
51 #define IVHD_DEV_SELECT                 0x02
52 #define IVHD_DEV_SELECT_RANGE_START     0x03
53 #define IVHD_DEV_RANGE_END              0x04
54 #define IVHD_DEV_ALIAS                  0x42
55 #define IVHD_DEV_ALIAS_RANGE            0x43
56 #define IVHD_DEV_EXT_SELECT             0x46
57 #define IVHD_DEV_EXT_SELECT_RANGE       0x47
58 #define IVHD_DEV_SPECIAL		0x48
59 #define IVHD_DEV_ACPI_HID		0xf0
60 
61 #define UID_NOT_PRESENT                 0
62 #define UID_IS_INTEGER                  1
63 #define UID_IS_CHARACTER                2
64 
65 #define IVHD_SPECIAL_IOAPIC		1
66 #define IVHD_SPECIAL_HPET		2
67 
68 #define IVHD_FLAG_HT_TUN_EN_MASK        0x01
69 #define IVHD_FLAG_PASSPW_EN_MASK        0x02
70 #define IVHD_FLAG_RESPASSPW_EN_MASK     0x04
71 #define IVHD_FLAG_ISOC_EN_MASK          0x08
72 
73 #define IVMD_FLAG_EXCL_RANGE            0x08
74 #define IVMD_FLAG_IW                    0x04
75 #define IVMD_FLAG_IR                    0x02
76 #define IVMD_FLAG_UNITY_MAP             0x01
77 
78 #define ACPI_DEVFLAG_INITPASS           0x01
79 #define ACPI_DEVFLAG_EXTINT             0x02
80 #define ACPI_DEVFLAG_NMI                0x04
81 #define ACPI_DEVFLAG_SYSMGT1            0x10
82 #define ACPI_DEVFLAG_SYSMGT2            0x20
83 #define ACPI_DEVFLAG_LINT0              0x40
84 #define ACPI_DEVFLAG_LINT1              0x80
85 #define ACPI_DEVFLAG_ATSDIS             0x10000000
86 
87 #define IVRS_GET_SBDF_ID(seg, bus, dev, fn)	(((seg & 0xffff) << 16) | ((bus & 0xff) << 8) \
88 						 | ((dev & 0x1f) << 3) | (fn & 0x7))
89 
90 /*
91  * ACPI table definitions
92  *
93  * These data structures are laid over the table to parse the important values
94  * out of it.
95  */
96 
97 /*
98  * structure describing one IOMMU in the ACPI table. Typically followed by one
99  * or more ivhd_entrys.
100  */
101 struct ivhd_header {
102 	u8 type;
103 	u8 flags;
104 	u16 length;
105 	u16 devid;
106 	u16 cap_ptr;
107 	u64 mmio_phys;
108 	u16 pci_seg;
109 	u16 info;
110 	u32 efr_attr;
111 
112 	/* Following only valid on IVHD type 11h and 40h */
113 	u64 efr_reg; /* Exact copy of MMIO_EXT_FEATURES */
114 	u64 efr_reg2;
115 } __attribute__((packed));
116 
117 /*
118  * A device entry describing which devices a specific IOMMU translates and
119  * which requestor ids they use.
120  */
121 struct ivhd_entry {
122 	u8 type;
123 	u16 devid;
124 	u8 flags;
125 	struct_group(ext_hid,
126 		u32 ext;
127 		u32 hidh;
128 	);
129 	u64 cid;
130 	u8 uidf;
131 	u8 uidl;
132 	u8 uid;
133 } __attribute__((packed));
134 
135 int amd_iommu_evtlog_size = EVTLOG_SIZE_DEF;
136 int amd_iommu_pprlog_size = PPRLOG_SIZE_DEF;
137 
138 /*
139  * An AMD IOMMU memory definition structure. It defines things like exclusion
140  * ranges for devices and regions that should be unity mapped.
141  */
142 struct ivmd_header {
143 	u8 type;
144 	u8 flags;
145 	u16 length;
146 	u16 devid;
147 	u16 aux;
148 	u16 pci_seg;
149 	u8  resv[6];
150 	u64 range_start;
151 	u64 range_length;
152 } __attribute__((packed));
153 
154 bool amd_iommu_dump;
155 bool amd_iommu_irq_remap __read_mostly;
156 
157 enum protection_domain_mode amd_iommu_pgtable = PD_MODE_V1;
158 /* Virtual address size */
159 u8 amd_iommu_hpt_vasize;
160 /* Guest page table level */
161 int amd_iommu_gpt_level = PAGE_MODE_4_LEVEL;
162 
163 int amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_VAPIC;
164 static int amd_iommu_xt_mode = IRQ_REMAP_XAPIC_MODE;
165 
166 static bool amd_iommu_disabled __initdata;
167 static bool amd_iommu_force_enable __initdata;
168 static bool amd_iommu_irtcachedis;
169 static int amd_iommu_target_ivhd_type;
170 
171 /* Global EFR and EFR2 registers */
172 u64 amd_iommu_efr;
173 u64 amd_iommu_efr2;
174 
175 /* Host (v1) page table is not supported*/
176 bool amd_iommu_hatdis;
177 
178 /* SNP is enabled on the system? */
179 bool amd_iommu_snp_en;
180 EXPORT_SYMBOL(amd_iommu_snp_en);
181 
182 /* SNP page mode 0 support */
183 bool amd_iommu_snp_mode0_sup;
184 
185 LIST_HEAD(amd_iommu_pci_seg_list);	/* list of all PCI segments */
186 LIST_HEAD(amd_iommu_list);		/* list of all AMD IOMMUs in the system */
187 LIST_HEAD(amd_ivhd_dev_flags_list);	/* list of all IVHD device entry settings */
188 
189 /* Number of IOMMUs present in the system */
190 static int amd_iommus_present;
191 
192 /* IOMMUs have a non-present cache? */
193 bool amd_iommu_np_cache __read_mostly;
194 bool amd_iommu_iotlb_sup __read_mostly = true;
195 
196 static bool amd_iommu_pc_present __read_mostly;
197 bool amdr_ivrs_remap_support __read_mostly;
198 
199 bool amd_iommu_force_isolation __read_mostly;
200 
201 unsigned long amd_iommu_pgsize_bitmap __ro_after_init = AMD_IOMMU_PGSIZES;
202 
203 enum iommu_init_state {
204 	IOMMU_START_STATE,
205 	IOMMU_IVRS_DETECTED,
206 	IOMMU_ACPI_FINISHED,
207 	IOMMU_ENABLED,
208 	IOMMU_PCI_INIT,
209 	IOMMU_INTERRUPTS_EN,
210 	IOMMU_INITIALIZED,
211 	IOMMU_NOT_FOUND,
212 	IOMMU_INIT_ERROR,
213 	IOMMU_CMDLINE_DISABLED,
214 };
215 
216 /* Early ioapic and hpet maps from kernel command line */
217 #define EARLY_MAP_SIZE		4
218 static struct devid_map __initdata early_ioapic_map[EARLY_MAP_SIZE];
219 static struct devid_map __initdata early_hpet_map[EARLY_MAP_SIZE];
220 static struct acpihid_map_entry __initdata early_acpihid_map[EARLY_MAP_SIZE];
221 
222 static int __initdata early_ioapic_map_size;
223 static int __initdata early_hpet_map_size;
224 static int __initdata early_acpihid_map_size;
225 
226 static bool __initdata cmdline_maps;
227 
228 static enum iommu_init_state init_state = IOMMU_START_STATE;
229 
230 static int amd_iommu_enable_interrupts(void);
231 static void init_device_table_dma(struct amd_iommu_pci_seg *pci_seg);
232 
233 static bool amd_iommu_pre_enabled = true;
234 
235 static u32 amd_iommu_ivinfo __initdata;
236 
237 bool translation_pre_enabled(struct amd_iommu *iommu)
238 {
239 	return (iommu->flags & AMD_IOMMU_FLAG_TRANS_PRE_ENABLED);
240 }
241 
242 static void clear_translation_pre_enabled(struct amd_iommu *iommu)
243 {
244 	iommu->flags &= ~AMD_IOMMU_FLAG_TRANS_PRE_ENABLED;
245 }
246 
247 static void init_translation_status(struct amd_iommu *iommu)
248 {
249 	u64 ctrl;
250 
251 	ctrl = readq(iommu->mmio_base + MMIO_CONTROL_OFFSET);
252 	if (ctrl & (1<<CONTROL_IOMMU_EN))
253 		iommu->flags |= AMD_IOMMU_FLAG_TRANS_PRE_ENABLED;
254 }
255 
256 int amd_iommu_get_num_iommus(void)
257 {
258 	return amd_iommus_present;
259 }
260 
261 bool amd_iommu_ht_range_ignore(void)
262 {
263 	return check_feature2(FEATURE_HT_RANGE_IGNORE);
264 }
265 
266 /*
267  * Iterate through all the IOMMUs to get common EFR
268  * masks among all IOMMUs and warn if found inconsistency.
269  */
270 static __init void get_global_efr(void)
271 {
272 	struct amd_iommu *iommu;
273 
274 	for_each_iommu(iommu) {
275 		u64 tmp = iommu->features;
276 		u64 tmp2 = iommu->features2;
277 
278 		if (list_is_first(&iommu->list, &amd_iommu_list)) {
279 			amd_iommu_efr = tmp;
280 			amd_iommu_efr2 = tmp2;
281 			continue;
282 		}
283 
284 		if (amd_iommu_efr == tmp &&
285 		    amd_iommu_efr2 == tmp2)
286 			continue;
287 
288 		pr_err(FW_BUG
289 		       "Found inconsistent EFR/EFR2 %#llx,%#llx (global %#llx,%#llx) on iommu%d (%04x:%02x:%02x.%01x).\n",
290 		       tmp, tmp2, amd_iommu_efr, amd_iommu_efr2,
291 		       iommu->index, iommu->pci_seg->id,
292 		       PCI_BUS_NUM(iommu->devid), PCI_SLOT(iommu->devid),
293 		       PCI_FUNC(iommu->devid));
294 
295 		amd_iommu_efr &= tmp;
296 		amd_iommu_efr2 &= tmp2;
297 	}
298 
299 	pr_info("Using global IVHD EFR:%#llx, EFR2:%#llx\n", amd_iommu_efr, amd_iommu_efr2);
300 }
301 
302 /*
303  * For IVHD type 0x11/0x40, EFR is also available via IVHD.
304  * Default to IVHD EFR since it is available sooner
305  * (i.e. before PCI init).
306  */
307 static void __init early_iommu_features_init(struct amd_iommu *iommu,
308 					     struct ivhd_header *h)
309 {
310 	if (amd_iommu_ivinfo & IOMMU_IVINFO_EFRSUP) {
311 		iommu->features = h->efr_reg;
312 		iommu->features2 = h->efr_reg2;
313 	}
314 	if (amd_iommu_ivinfo & IOMMU_IVINFO_DMA_REMAP)
315 		amdr_ivrs_remap_support = true;
316 }
317 
318 /* Access to l1 and l2 indexed register spaces */
319 
320 static u32 iommu_read_l1(struct amd_iommu *iommu, u16 l1, u8 address)
321 {
322 	u32 val;
323 
324 	pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16));
325 	pci_read_config_dword(iommu->dev, 0xfc, &val);
326 	return val;
327 }
328 
329 static void iommu_write_l1(struct amd_iommu *iommu, u16 l1, u8 address, u32 val)
330 {
331 	pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16 | 1 << 31));
332 	pci_write_config_dword(iommu->dev, 0xfc, val);
333 	pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16));
334 }
335 
336 static u32 iommu_read_l2(struct amd_iommu *iommu, u8 address)
337 {
338 	u32 val;
339 
340 	pci_write_config_dword(iommu->dev, 0xf0, address);
341 	pci_read_config_dword(iommu->dev, 0xf4, &val);
342 	return val;
343 }
344 
345 static void iommu_write_l2(struct amd_iommu *iommu, u8 address, u32 val)
346 {
347 	pci_write_config_dword(iommu->dev, 0xf0, (address | 1 << 8));
348 	pci_write_config_dword(iommu->dev, 0xf4, val);
349 }
350 
351 /****************************************************************************
352  *
353  * AMD IOMMU MMIO register space handling functions
354  *
355  * These functions are used to program the IOMMU device registers in
356  * MMIO space required for that driver.
357  *
358  ****************************************************************************/
359 
360 static void iommu_set_cwwb_range(struct amd_iommu *iommu)
361 {
362 	u64 start = iommu_virt_to_phys((void *)iommu->cmd_sem);
363 	u64 entry = start & PM_ADDR_MASK;
364 
365 	if (!check_feature(FEATURE_SNP))
366 		return;
367 
368 	/* Note:
369 	 * Re-purpose Exclusion base/limit registers for Completion wait
370 	 * write-back base/limit.
371 	 */
372 	memcpy_toio(iommu->mmio_base + MMIO_EXCL_BASE_OFFSET,
373 		    &entry, sizeof(entry));
374 
375 	/* Note:
376 	 * Default to 4 Kbytes, which can be specified by setting base
377 	 * address equal to the limit address.
378 	 */
379 	memcpy_toio(iommu->mmio_base + MMIO_EXCL_LIMIT_OFFSET,
380 		    &entry, sizeof(entry));
381 }
382 
383 /* Programs the physical address of the device table into the IOMMU hardware */
384 static void iommu_set_device_table(struct amd_iommu *iommu)
385 {
386 	u64 entry;
387 	u32 dev_table_size = iommu->pci_seg->dev_table_size;
388 	void *dev_table = (void *)get_dev_table(iommu);
389 
390 	BUG_ON(iommu->mmio_base == NULL);
391 
392 	/*
393 	 * A kdump kernel that reuses the previous kernel's device table must
394 	 * leave the base register alone. It already points at that table, and
395 	 * with SNP enabled the register is locked. If reuse failed, program
396 	 * the freshly allocated table like a normal boot.
397 	 */
398 	if (iommu->pci_seg->old_dev_tbl_cpy)
399 		return;
400 
401 	entry = iommu_virt_to_phys(dev_table);
402 	entry |= (dev_table_size >> 12) - 1;
403 	memcpy_toio(iommu->mmio_base + MMIO_DEV_TABLE_OFFSET,
404 			&entry, sizeof(entry));
405 }
406 
407 static void iommu_feature_set(struct amd_iommu *iommu, u64 val, u64 mask, u8 shift)
408 {
409 	u64 ctrl;
410 
411 	ctrl = readq(iommu->mmio_base +  MMIO_CONTROL_OFFSET);
412 	mask <<= shift;
413 	ctrl &= ~mask;
414 	ctrl |= (val << shift) & mask;
415 	writeq(ctrl, iommu->mmio_base +  MMIO_CONTROL_OFFSET);
416 }
417 
418 /* Generic functions to enable/disable certain features of the IOMMU. */
419 void iommu_feature_enable(struct amd_iommu *iommu, u8 bit)
420 {
421 	iommu_feature_set(iommu, 1ULL, 1ULL, bit);
422 }
423 
424 static void iommu_feature_disable(struct amd_iommu *iommu, u8 bit)
425 {
426 	iommu_feature_set(iommu, 0ULL, 1ULL, bit);
427 }
428 
429 /* Function to enable the hardware */
430 static void iommu_enable(struct amd_iommu *iommu)
431 {
432 	iommu_feature_enable(iommu, CONTROL_IOMMU_EN);
433 }
434 
435 static void iommu_disable(struct amd_iommu *iommu)
436 {
437 	if (!iommu->mmio_base)
438 		return;
439 
440 	/* Disable command buffer */
441 	iommu_feature_disable(iommu, CONTROL_CMDBUF_EN);
442 
443 	/* Disable event logging and event interrupts */
444 	iommu_feature_disable(iommu, CONTROL_EVT_INT_EN);
445 	iommu_feature_disable(iommu, CONTROL_EVT_LOG_EN);
446 
447 	/* Disable IOMMU GA_LOG */
448 	iommu_feature_disable(iommu, CONTROL_GALOG_EN);
449 	iommu_feature_disable(iommu, CONTROL_GAINT_EN);
450 
451 	/* Disable IOMMU PPR logging */
452 	iommu_feature_disable(iommu, CONTROL_PPRLOG_EN);
453 	iommu_feature_disable(iommu, CONTROL_PPRINT_EN);
454 
455 	/* Disable IOMMU hardware itself */
456 	iommu_feature_disable(iommu, CONTROL_IOMMU_EN);
457 
458 	/* Clear IRTE cache disabling bit */
459 	iommu_feature_disable(iommu, CONTROL_IRTCACHEDIS);
460 }
461 
462 /*
463  * mapping and unmapping functions for the IOMMU MMIO space. Each AMD IOMMU in
464  * the system has one.
465  */
466 static u8 __iomem * __init iommu_map_mmio_space(u64 address, u64 end)
467 {
468 	if (!request_mem_region(address, end, "amd_iommu")) {
469 		pr_err("Can not reserve memory region %llx-%llx for mmio\n",
470 			address, end);
471 		pr_err("This is a BIOS bug. Please contact your hardware vendor\n");
472 		return NULL;
473 	}
474 
475 	return (u8 __iomem *)ioremap(address, end);
476 }
477 
478 static void __init iommu_unmap_mmio_space(struct amd_iommu *iommu)
479 {
480 	if (iommu->mmio_base)
481 		iounmap(iommu->mmio_base);
482 	release_mem_region(iommu->mmio_phys, iommu->mmio_phys_end);
483 }
484 
485 static inline u32 get_ivhd_header_size(struct ivhd_header *h)
486 {
487 	u32 size = 0;
488 
489 	switch (h->type) {
490 	case 0x10:
491 		size = 24;
492 		break;
493 	case 0x11:
494 	case 0x40:
495 		size = 40;
496 		break;
497 	}
498 	return size;
499 }
500 
501 /****************************************************************************
502  *
503  * The functions below belong to the first pass of AMD IOMMU ACPI table
504  * parsing. In this pass we try to find out the highest device id this
505  * code has to handle. Upon this information the size of the shared data
506  * structures is determined later.
507  *
508  ****************************************************************************/
509 
510 /*
511  * This function calculates the length of a given IVHD entry
512  */
513 static inline int ivhd_entry_length(u8 *ivhd)
514 {
515 	u32 type = ((struct ivhd_entry *)ivhd)->type;
516 
517 	if (type < 0x80) {
518 		return 0x04 << (*ivhd >> 6);
519 	} else if (type == IVHD_DEV_ACPI_HID) {
520 		/* For ACPI_HID, offset 21 is uid len */
521 		return *((u8 *)ivhd + 21) + 22;
522 	}
523 	return 0;
524 }
525 
526 /*
527  * After reading the highest device id from the IOMMU PCI capability header
528  * this function looks if there is a higher device id defined in the ACPI table
529  */
530 static int __init find_last_devid_from_ivhd(struct ivhd_header *h)
531 {
532 	u8 *p = (void *)h, *end = (void *)h;
533 	struct ivhd_entry *dev;
534 	int last_devid = -EINVAL;
535 
536 	u32 ivhd_size = get_ivhd_header_size(h);
537 
538 	if (!ivhd_size) {
539 		pr_err("Unsupported IVHD type %#x\n", h->type);
540 		return -EINVAL;
541 	}
542 
543 	p += ivhd_size;
544 	end += h->length;
545 
546 	while (p < end) {
547 		dev = (struct ivhd_entry *)p;
548 		switch (dev->type) {
549 		case IVHD_DEV_ALL:
550 			/* Use maximum BDF value for DEV_ALL */
551 			return 0xffff;
552 		case IVHD_DEV_SELECT:
553 		case IVHD_DEV_RANGE_END:
554 		case IVHD_DEV_ALIAS:
555 		case IVHD_DEV_EXT_SELECT:
556 			/* all the above subfield types refer to device ids */
557 			if (dev->devid > last_devid)
558 				last_devid = dev->devid;
559 			break;
560 		default:
561 			break;
562 		}
563 		p += ivhd_entry_length(p);
564 	}
565 
566 	WARN_ON(p != end);
567 
568 	return last_devid;
569 }
570 
571 static int __init check_ivrs_checksum(struct acpi_table_header *table)
572 {
573 	int i;
574 	u8 checksum = 0, *p = (u8 *)table;
575 
576 	for (i = 0; i < table->length; ++i)
577 		checksum += p[i];
578 	if (checksum != 0) {
579 		/* ACPI table corrupt */
580 		pr_err(FW_BUG "IVRS invalid checksum\n");
581 		return -ENODEV;
582 	}
583 
584 	return 0;
585 }
586 
587 /*
588  * Iterate over all IVHD entries in the ACPI table and find the highest device
589  * id which we need to handle. This is the first of three functions which parse
590  * the ACPI table. So we check the checksum here.
591  */
592 static int __init find_last_devid_acpi(struct acpi_table_header *table, u16 pci_seg)
593 {
594 	u8 *p = (u8 *)table, *end = (u8 *)table;
595 	struct ivhd_header *h;
596 	int last_devid, last_bdf = 0;
597 
598 	p += IVRS_HEADER_LENGTH;
599 
600 	end += table->length;
601 	while (p < end) {
602 		h = (struct ivhd_header *)p;
603 		if (h->pci_seg == pci_seg &&
604 		    h->type == amd_iommu_target_ivhd_type) {
605 			last_devid = find_last_devid_from_ivhd(h);
606 
607 			if (last_devid < 0)
608 				return -EINVAL;
609 			if (last_devid > last_bdf)
610 				last_bdf = last_devid;
611 		}
612 		p += h->length;
613 	}
614 	WARN_ON(p != end);
615 
616 	return last_bdf;
617 }
618 
619 /****************************************************************************
620  *
621  * The following functions belong to the code path which parses the ACPI table
622  * the second time. In this ACPI parsing iteration we allocate IOMMU specific
623  * data structures, initialize the per PCI segment device/alias/rlookup table
624  * and also basically initialize the hardware.
625  *
626  ****************************************************************************/
627 
628 /* Allocate per PCI segment device table */
629 static inline int __init alloc_dev_table(struct amd_iommu_pci_seg *pci_seg)
630 {
631 	gfp_t gfp = GFP_KERNEL;
632 
633 	/*
634 	 * Keep normal kernel device tables below 4G because a later kdump
635 	 * kernel only trusts and reuses old tables below that limit. A kdump
636 	 * kernel's new table is either discarded when reuse succeeds or
637 	 * programmed after the IOMMU is disabled, so the table does not
638 	 * need DMA32 memory (which the crashkernel may not have).
639 	 */
640 	if (!is_kdump_kernel())
641 		gfp |= GFP_DMA32;
642 
643 	pci_seg->dev_table = iommu_alloc_pages_sz(gfp, pci_seg->dev_table_size);
644 	if (!pci_seg->dev_table)
645 		return -ENOMEM;
646 
647 	return 0;
648 }
649 
650 static inline void free_dev_table(struct amd_iommu_pci_seg *pci_seg)
651 {
652 	if (is_kdump_kernel())
653 		memunmap((void *)pci_seg->dev_table);
654 	else
655 		iommu_free_pages(pci_seg->dev_table);
656 	pci_seg->dev_table = NULL;
657 }
658 
659 /* Allocate per PCI segment IOMMU rlookup table. */
660 static inline int __init alloc_rlookup_table(struct amd_iommu_pci_seg *pci_seg)
661 {
662 	pci_seg->rlookup_table = kvzalloc_objs(*pci_seg->rlookup_table,
663 					       pci_seg->last_bdf + 1);
664 	if (pci_seg->rlookup_table == NULL)
665 		return -ENOMEM;
666 
667 	return 0;
668 }
669 
670 static inline void free_rlookup_table(struct amd_iommu_pci_seg *pci_seg)
671 {
672 	kvfree(pci_seg->rlookup_table);
673 	pci_seg->rlookup_table = NULL;
674 }
675 
676 static inline int __init alloc_irq_lookup_table(struct amd_iommu_pci_seg *pci_seg)
677 {
678 	pci_seg->irq_lookup_table = kvzalloc_objs(*pci_seg->irq_lookup_table,
679 						  pci_seg->last_bdf + 1);
680 	if (pci_seg->irq_lookup_table == NULL)
681 		return -ENOMEM;
682 
683 	return 0;
684 }
685 
686 static inline void free_irq_lookup_table(struct amd_iommu_pci_seg *pci_seg)
687 {
688 	kvfree(pci_seg->irq_lookup_table);
689 	pci_seg->irq_lookup_table = NULL;
690 }
691 
692 static int __init alloc_alias_table(struct amd_iommu_pci_seg *pci_seg)
693 {
694 	int i;
695 
696 	pci_seg->alias_table = kvmalloc_objs(*pci_seg->alias_table,
697 					     pci_seg->last_bdf + 1);
698 	if (!pci_seg->alias_table)
699 		return -ENOMEM;
700 
701 	/*
702 	 * let all alias entries point to itself
703 	 */
704 	for (i = 0; i <= pci_seg->last_bdf; ++i)
705 		pci_seg->alias_table[i] = i;
706 
707 	return 0;
708 }
709 
710 static void __init free_alias_table(struct amd_iommu_pci_seg *pci_seg)
711 {
712 	kvfree(pci_seg->alias_table);
713 	pci_seg->alias_table = NULL;
714 }
715 
716 static inline void *iommu_memremap(unsigned long paddr, size_t size)
717 {
718 	phys_addr_t phys;
719 
720 	if (!paddr)
721 		return NULL;
722 
723 	/*
724 	 * Obtain true physical address in kdump kernel when SME is enabled.
725 	 * Currently, previous kernel with SME enabled and kdump kernel
726 	 * with SME support disabled is not supported.
727 	 */
728 	phys = __sme_clr(paddr);
729 
730 	if (cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
731 		return (__force void *)ioremap_encrypted(phys, size);
732 	else
733 		return memremap(phys, size, MEMREMAP_WB);
734 }
735 
736 /*
737  * Allocates the command buffer. This buffer is per AMD IOMMU. We can
738  * write commands to that buffer later and the IOMMU will execute them
739  * asynchronously
740  */
741 static int __init alloc_command_buffer(struct amd_iommu *iommu)
742 {
743 	iommu->cmd_buf = iommu_alloc_pages_sz(GFP_KERNEL, CMD_BUFFER_SIZE);
744 
745 	return iommu->cmd_buf ? 0 : -ENOMEM;
746 }
747 
748 /*
749  * Interrupt handler has processed all pending events and adjusted head
750  * and tail pointer. Reset overflow mask and restart logging again.
751  */
752 void amd_iommu_restart_log(struct amd_iommu *iommu, const char *evt_type,
753 			   u8 cntrl_intr, u8 cntrl_log,
754 			   u32 status_run_mask, u32 status_overflow_mask)
755 {
756 	u32 status;
757 
758 	status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
759 	if (status & status_run_mask)
760 		return;
761 
762 	pr_info_ratelimited("IOMMU %s log restarting\n", evt_type);
763 
764 	iommu_feature_disable(iommu, cntrl_log);
765 	iommu_feature_disable(iommu, cntrl_intr);
766 
767 	writel(status_overflow_mask, iommu->mmio_base + MMIO_STATUS_OFFSET);
768 
769 	iommu_feature_enable(iommu, cntrl_intr);
770 	iommu_feature_enable(iommu, cntrl_log);
771 }
772 
773 /*
774  * This function restarts event logging in case the IOMMU experienced
775  * an event log buffer overflow.
776  */
777 void amd_iommu_restart_event_logging(struct amd_iommu *iommu)
778 {
779 	amd_iommu_restart_log(iommu, "Event", CONTROL_EVT_INT_EN,
780 			      CONTROL_EVT_LOG_EN, MMIO_STATUS_EVT_RUN_MASK,
781 			      MMIO_STATUS_EVT_OVERFLOW_MASK);
782 }
783 
784 /*
785  * This function restarts event logging in case the IOMMU experienced
786  * GA log overflow.
787  */
788 void amd_iommu_restart_ga_log(struct amd_iommu *iommu)
789 {
790 	amd_iommu_restart_log(iommu, "GA", CONTROL_GAINT_EN,
791 			      CONTROL_GALOG_EN, MMIO_STATUS_GALOG_RUN_MASK,
792 			      MMIO_STATUS_GALOG_OVERFLOW_MASK);
793 }
794 
795 /*
796  * This function resets the command buffer if the IOMMU stopped fetching
797  * commands from it.
798  */
799 static void amd_iommu_reset_cmd_buffer(struct amd_iommu *iommu)
800 {
801 	iommu_feature_disable(iommu, CONTROL_CMDBUF_EN);
802 
803 	writel(0x00, iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
804 	writel(0x00, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
805 	iommu->cmd_buf_head = 0;
806 	iommu->cmd_buf_tail = 0;
807 
808 	iommu_feature_enable(iommu, CONTROL_CMDBUF_EN);
809 }
810 
811 /*
812  * This function writes the command buffer address to the hardware and
813  * enables it.
814  */
815 static void iommu_enable_command_buffer(struct amd_iommu *iommu)
816 {
817 	u64 entry;
818 
819 	BUG_ON(iommu->cmd_buf == NULL);
820 
821 	if (!is_kdump_kernel()) {
822 		/*
823 		 * Command buffer is re-used for kdump kernel and setting
824 		 * of MMIO register is not required.
825 		 */
826 		entry = iommu_virt_to_phys(iommu->cmd_buf);
827 		entry |= MMIO_CMD_SIZE_512;
828 		memcpy_toio(iommu->mmio_base + MMIO_CMD_BUF_OFFSET,
829 			    &entry, sizeof(entry));
830 	}
831 
832 	amd_iommu_reset_cmd_buffer(iommu);
833 }
834 
835 /*
836  * This function disables the command buffer
837  */
838 static void iommu_disable_command_buffer(struct amd_iommu *iommu)
839 {
840 	iommu_feature_disable(iommu, CONTROL_CMDBUF_EN);
841 }
842 
843 static void __init free_command_buffer(struct amd_iommu *iommu)
844 {
845 	iommu_free_pages(iommu->cmd_buf);
846 }
847 
848 void *__init iommu_alloc_4k_pages(struct amd_iommu *iommu, gfp_t gfp,
849 				  size_t size)
850 {
851 	int nid = iommu->dev ? dev_to_node(&iommu->dev->dev) : NUMA_NO_NODE;
852 	void *buf;
853 
854 	size = PAGE_ALIGN(size);
855 	buf = iommu_alloc_pages_node_sz(nid, gfp, size);
856 	if (!buf)
857 		return NULL;
858 	if (check_feature(FEATURE_SNP) &&
859 	    set_memory_4k((unsigned long)buf, size / PAGE_SIZE)) {
860 		iommu_free_pages(buf);
861 		return NULL;
862 	}
863 
864 	return buf;
865 }
866 
867 /* allocates the memory where the IOMMU will log its events to */
868 static int __init alloc_event_buffer(void)
869 {
870 	struct amd_iommu *iommu;
871 
872 	for_each_iommu(iommu) {
873 		iommu->evt_buf = iommu_alloc_4k_pages(iommu, GFP_KERNEL,
874 						      amd_iommu_evtlog_size);
875 		if (!iommu->evt_buf)
876 			return -ENOMEM;
877 	}
878 
879 	return 0;
880 }
881 
882 static void iommu_enable_event_buffer(void)
883 {
884 	struct amd_iommu *iommu;
885 	u64 entry;
886 
887 	for_each_iommu(iommu) {
888 		BUG_ON(iommu->evt_buf == NULL);
889 
890 		if (!is_kdump_kernel()) {
891 			/*
892 			 * Event buffer is re-used for kdump kernel and setting
893 			 * of MMIO register is not required.
894 			 */
895 			entry = iommu_virt_to_phys(iommu->evt_buf);
896 			entry |= (amd_iommu_evtlog_size == EVTLOG_SIZE_DEF) ?
897 				EVTLOG_LEN_MASK_DEF : EVTLOG_LEN_MASK_MAX;
898 
899 			memcpy_toio(iommu->mmio_base + MMIO_EVT_BUF_OFFSET,
900 				    &entry, sizeof(entry));
901 		}
902 
903 		/* set head and tail to zero manually */
904 		writel(0x00, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
905 		writel(0x00, iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
906 
907 		iommu_feature_enable(iommu, CONTROL_EVT_LOG_EN);
908 	}
909 }
910 
911 /*
912  * This function disables the event log buffer
913  */
914 static void iommu_disable_event_buffer(struct amd_iommu *iommu)
915 {
916 	iommu_feature_disable(iommu, CONTROL_EVT_LOG_EN);
917 }
918 
919 static void __init free_event_buffer(struct amd_iommu *iommu)
920 {
921 	iommu_free_pages(iommu->evt_buf);
922 }
923 
924 static void free_ga_log(struct amd_iommu *iommu)
925 {
926 #ifdef CONFIG_IRQ_REMAP
927 	iommu_free_pages(iommu->ga_log);
928 	iommu->ga_log = NULL;
929 	iommu_free_pages(iommu->ga_log_tail);
930 	iommu->ga_log_tail = NULL;
931 #endif
932 }
933 
934 #ifdef CONFIG_IRQ_REMAP
935 static bool iommu_ga_log_enable(struct amd_iommu *iommu)
936 {
937 	u32 status, i;
938 	u64 entry;
939 
940 	if (!iommu->ga_log)
941 		return false;
942 
943 	entry = iommu_virt_to_phys(iommu->ga_log) | GA_LOG_SIZE_512;
944 	memcpy_toio(iommu->mmio_base + MMIO_GA_LOG_BASE_OFFSET,
945 		    &entry, sizeof(entry));
946 	entry = (iommu_virt_to_phys(iommu->ga_log_tail) &
947 		 (BIT_ULL(52)-1)) & ~7ULL;
948 	memcpy_toio(iommu->mmio_base + MMIO_GA_LOG_TAIL_OFFSET,
949 		    &entry, sizeof(entry));
950 	writel(0x00, iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
951 	writel(0x00, iommu->mmio_base + MMIO_GA_TAIL_OFFSET);
952 
953 
954 	iommu_feature_enable(iommu, CONTROL_GAINT_EN);
955 	iommu_feature_enable(iommu, CONTROL_GALOG_EN);
956 
957 	for (i = 0; i < MMIO_STATUS_TIMEOUT; ++i) {
958 		status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
959 		if (status & (MMIO_STATUS_GALOG_RUN_MASK))
960 			break;
961 		udelay(10);
962 	}
963 
964 	if (WARN_ON(i >= MMIO_STATUS_TIMEOUT))
965 		return false;
966 
967 	return true;
968 }
969 #endif /* CONFIG_IRQ_REMAP */
970 
971 static int alloc_ga_log(struct amd_iommu *iommu)
972 {
973 #ifdef CONFIG_IRQ_REMAP
974 	int nid = iommu->dev ? dev_to_node(&iommu->dev->dev) : NUMA_NO_NODE;
975 
976 	iommu->ga_log = iommu_alloc_pages_node_sz(nid, GFP_KERNEL, GA_LOG_SIZE);
977 	if (!iommu->ga_log)
978 		return -ENOMEM;
979 
980 	iommu->ga_log_tail = iommu_alloc_pages_node_sz(nid, GFP_KERNEL, 8);
981 	if (!iommu->ga_log_tail) {
982 		iommu_free_pages(iommu->ga_log);
983 		iommu->ga_log = NULL;
984 		return -ENOMEM;
985 	}
986 #endif
987 
988 	return 0;
989 }
990 
991 static int __init alloc_cwwb_sem(struct amd_iommu *iommu)
992 {
993 	iommu->cmd_sem = iommu_alloc_4k_pages(iommu, GFP_KERNEL, 1);
994 	if (!iommu->cmd_sem)
995 		return -ENOMEM;
996 	iommu->cmd_sem_paddr = iommu_virt_to_phys((void *)iommu->cmd_sem);
997 	return 0;
998 }
999 
1000 static int __init remap_event_buffer(void)
1001 {
1002 	struct amd_iommu *iommu;
1003 	u64 paddr;
1004 
1005 	pr_info_once("Re-using event buffer from the previous kernel\n");
1006 	for_each_iommu(iommu) {
1007 		paddr = readq(iommu->mmio_base + MMIO_EVT_BUF_OFFSET) & PM_ADDR_MASK;
1008 		iommu->evt_buf = iommu_memremap(paddr, amd_iommu_evtlog_size);
1009 		if (!iommu->evt_buf)
1010 			return -ENOMEM;
1011 	}
1012 
1013 	return 0;
1014 }
1015 
1016 static int __init remap_command_buffer(struct amd_iommu *iommu)
1017 {
1018 	u64 paddr;
1019 
1020 	pr_info_once("Re-using command buffer from the previous kernel\n");
1021 	paddr = readq(iommu->mmio_base + MMIO_CMD_BUF_OFFSET) & PM_ADDR_MASK;
1022 	iommu->cmd_buf = iommu_memremap(paddr, CMD_BUFFER_SIZE);
1023 
1024 	return iommu->cmd_buf ? 0 : -ENOMEM;
1025 }
1026 
1027 static int __init remap_or_alloc_cwwb_sem(struct amd_iommu *iommu)
1028 {
1029 	u64 paddr;
1030 
1031 	if (check_feature(FEATURE_SNP)) {
1032 		/*
1033 		 * When SNP is enabled, the exclusion base register is used for the
1034 		 * completion wait buffer (CWB) address. Read and re-use it.
1035 		 */
1036 		pr_info_once("Re-using CWB buffers from the previous kernel\n");
1037 		paddr = readq(iommu->mmio_base + MMIO_EXCL_BASE_OFFSET) & PM_ADDR_MASK;
1038 		iommu->cmd_sem = iommu_memremap(paddr, PAGE_SIZE);
1039 		if (!iommu->cmd_sem)
1040 			return -ENOMEM;
1041 		iommu->cmd_sem_paddr = paddr;
1042 	} else {
1043 		return alloc_cwwb_sem(iommu);
1044 	}
1045 
1046 	return 0;
1047 }
1048 
1049 static int __init alloc_iommu_buffers(struct amd_iommu *iommu)
1050 {
1051 	int ret;
1052 
1053 	/*
1054 	 * Reuse/Remap the previous kernel's allocated completion wait
1055 	 * command and event buffers for kdump boot.
1056 	 */
1057 	if (is_kdump_kernel()) {
1058 		ret = remap_or_alloc_cwwb_sem(iommu);
1059 		if (ret)
1060 			return ret;
1061 
1062 		ret = remap_command_buffer(iommu);
1063 		if (ret)
1064 			return ret;
1065 	} else {
1066 		ret = alloc_cwwb_sem(iommu);
1067 		if (ret)
1068 			return ret;
1069 
1070 		ret = alloc_command_buffer(iommu);
1071 		if (ret)
1072 			return ret;
1073 	}
1074 
1075 	return 0;
1076 }
1077 
1078 static void __init free_cwwb_sem(struct amd_iommu *iommu)
1079 {
1080 	if (iommu->cmd_sem)
1081 		iommu_free_pages((void *)iommu->cmd_sem);
1082 }
1083 static void __init unmap_cwwb_sem(struct amd_iommu *iommu)
1084 {
1085 	if (iommu->cmd_sem) {
1086 		if (check_feature(FEATURE_SNP))
1087 			memunmap((void *)iommu->cmd_sem);
1088 		else
1089 			iommu_free_pages((void *)iommu->cmd_sem);
1090 	}
1091 }
1092 
1093 static void __init unmap_command_buffer(struct amd_iommu *iommu)
1094 {
1095 	memunmap((void *)iommu->cmd_buf);
1096 }
1097 
1098 static void __init unmap_event_buffer(struct amd_iommu *iommu)
1099 {
1100 	memunmap(iommu->evt_buf);
1101 }
1102 
1103 static void __init free_iommu_buffers(struct amd_iommu *iommu)
1104 {
1105 	if (is_kdump_kernel()) {
1106 		unmap_cwwb_sem(iommu);
1107 		unmap_command_buffer(iommu);
1108 		unmap_event_buffer(iommu);
1109 	} else {
1110 		free_cwwb_sem(iommu);
1111 		free_command_buffer(iommu);
1112 		free_event_buffer(iommu);
1113 	}
1114 }
1115 
1116 static void iommu_enable_xt(struct amd_iommu *iommu)
1117 {
1118 #ifdef CONFIG_IRQ_REMAP
1119 	/*
1120 	 * XT mode (32-bit APIC destination ID) requires
1121 	 * GA mode (128-bit IRTE support) as a prerequisite.
1122 	 */
1123 	if (AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir) &&
1124 	    amd_iommu_xt_mode == IRQ_REMAP_X2APIC_MODE)
1125 		iommu_feature_enable(iommu, CONTROL_XT_EN);
1126 #endif /* CONFIG_IRQ_REMAP */
1127 }
1128 
1129 static void iommu_enable_gt(struct amd_iommu *iommu)
1130 {
1131 	if (!check_feature(FEATURE_GT))
1132 		return;
1133 
1134 	iommu_feature_enable(iommu, CONTROL_GT_EN);
1135 
1136 	/*
1137 	 * This feature needs to be enabled prior to a call
1138 	 * to iommu_snp_enable(). Since this function is called
1139 	 * in early_enable_iommu(), it is safe to enable here.
1140 	 */
1141 	if (check_feature2(FEATURE_GCR3TRPMODE))
1142 		iommu_feature_enable(iommu, CONTROL_GCR3TRPMODE);
1143 }
1144 
1145 /* sets a specific bit in the device table entry. */
1146 static void set_dte_bit(struct dev_table_entry *dte, u8 bit)
1147 {
1148 	int i = (bit >> 6) & 0x03;
1149 	int _bit = bit & 0x3f;
1150 
1151 	dte->data[i] |= (1UL << _bit);
1152 }
1153 
1154 static bool __reuse_device_table(struct amd_iommu *iommu)
1155 {
1156 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
1157 	struct dev_table_entry *old_dev_tbl_entry;
1158 	u32 lo, hi, old_devtb_size, devid;
1159 	phys_addr_t old_devtb_phys;
1160 	u16 dom_id;
1161 	bool dte_v;
1162 	u64 entry;
1163 
1164 	/* Each IOMMU use separate device table with the same size */
1165 	lo = readl(iommu->mmio_base + MMIO_DEV_TABLE_OFFSET);
1166 	hi = readl(iommu->mmio_base + MMIO_DEV_TABLE_OFFSET + 4);
1167 	entry = (((u64) hi) << 32) + lo;
1168 
1169 	old_devtb_size = ((entry & ~PAGE_MASK) + 1) << 12;
1170 	if (old_devtb_size != pci_seg->dev_table_size) {
1171 		pr_err("The device table size of IOMMU:%d is not expected!\n",
1172 			iommu->index);
1173 		return false;
1174 	}
1175 
1176 	/*
1177 	 * When SME is enabled in the first kernel, the entry includes the
1178 	 * memory encryption mask(sme_me_mask), we must remove the memory
1179 	 * encryption mask to obtain the true physical address in kdump kernel.
1180 	 */
1181 	old_devtb_phys = __sme_clr(entry) & PAGE_MASK;
1182 
1183 	if (old_devtb_phys >= 0x100000000ULL) {
1184 		pr_err("The address of old device table is above 4G, not trustworthy!\n");
1185 		return false;
1186 	}
1187 
1188 	/*
1189 	 * Re-use the previous kernel's device table for kdump.
1190 	 */
1191 	pci_seg->old_dev_tbl_cpy = iommu_memremap(old_devtb_phys, pci_seg->dev_table_size);
1192 	if (pci_seg->old_dev_tbl_cpy == NULL) {
1193 		pr_err("Failed to remap memory for reusing old device table!\n");
1194 		return false;
1195 	}
1196 
1197 	for (devid = 0; devid <= pci_seg->last_bdf; devid++) {
1198 		old_dev_tbl_entry = &pci_seg->old_dev_tbl_cpy[devid];
1199 		dte_v = FIELD_GET(DTE_FLAG_V, old_dev_tbl_entry->data[0]);
1200 		dom_id = FIELD_GET(DTE_DOMID_MASK, old_dev_tbl_entry->data[1]);
1201 
1202 		if (!dte_v || !dom_id)
1203 			continue;
1204 		/*
1205 		 * ID reservation can fail with -ENOSPC when there
1206 		 * are multiple devices present in the same domain,
1207 		 * hence check only for -ENOMEM.
1208 		 */
1209 		if (amd_iommu_pdom_id_reserve(dom_id, GFP_KERNEL) == -ENOMEM)
1210 			return false;
1211 	}
1212 
1213 	return true;
1214 }
1215 
1216 static bool reuse_device_table(void)
1217 {
1218 	struct amd_iommu *iommu;
1219 	struct amd_iommu_pci_seg *pci_seg;
1220 
1221 	if (!amd_iommu_pre_enabled)
1222 		return false;
1223 
1224 	pr_warn("Translation is already enabled - trying to reuse translation structures\n");
1225 
1226 	/*
1227 	 * All IOMMUs within PCI segment shares common device table.
1228 	 * Hence reuse device table only once per PCI segment.
1229 	 */
1230 	for_each_pci_segment(pci_seg) {
1231 		for_each_iommu(iommu) {
1232 			if (pci_seg->id != iommu->pci_seg->id)
1233 				continue;
1234 			if (!__reuse_device_table(iommu))
1235 				return false;
1236 			break;
1237 		}
1238 	}
1239 
1240 	return true;
1241 }
1242 
1243 struct dev_table_entry *amd_iommu_get_ivhd_dte_flags(u16 segid, u16 devid)
1244 {
1245 	struct ivhd_dte_flags *e;
1246 	unsigned int best_len = UINT_MAX;
1247 	struct dev_table_entry *dte = NULL;
1248 
1249 	for_each_ivhd_dte_flags(e) {
1250 		/*
1251 		 * Need to go through the whole list to find the smallest range,
1252 		 * which contains the devid.
1253 		 */
1254 		if ((e->segid == segid) &&
1255 		    (e->devid_first <= devid) && (devid <= e->devid_last)) {
1256 			unsigned int len = e->devid_last - e->devid_first;
1257 
1258 			if (len < best_len) {
1259 				dte = &(e->dte);
1260 				best_len = len;
1261 			}
1262 		}
1263 	}
1264 	return dte;
1265 }
1266 
1267 static bool search_ivhd_dte_flags(u16 segid, u16 first, u16 last)
1268 {
1269 	struct ivhd_dte_flags *e;
1270 
1271 	for_each_ivhd_dte_flags(e) {
1272 		if ((e->segid == segid) &&
1273 		    (e->devid_first == first) &&
1274 		    (e->devid_last == last))
1275 			return true;
1276 	}
1277 	return false;
1278 }
1279 
1280 /*
1281  * This function takes the device specific flags read from the ACPI
1282  * table and sets up the device table entry with that information
1283  */
1284 static void __init
1285 set_dev_entry_from_acpi_range(struct amd_iommu *iommu, u16 first, u16 last,
1286 			      u32 flags, u32 ext_flags)
1287 {
1288 	int i;
1289 	struct dev_table_entry dte = {};
1290 
1291 	/* Parse IVHD DTE setting flags and store information */
1292 	if (flags) {
1293 		struct ivhd_dte_flags *d;
1294 
1295 		if (search_ivhd_dte_flags(iommu->pci_seg->id, first, last))
1296 			return;
1297 
1298 		d = kzalloc_obj(struct ivhd_dte_flags);
1299 		if (!d)
1300 			return;
1301 
1302 		pr_debug("%s: devid range %#x:%#x\n", __func__, first, last);
1303 
1304 		if (flags & ACPI_DEVFLAG_INITPASS)
1305 			set_dte_bit(&dte, DEV_ENTRY_INIT_PASS);
1306 		if (flags & ACPI_DEVFLAG_EXTINT)
1307 			set_dte_bit(&dte, DEV_ENTRY_EINT_PASS);
1308 		if (flags & ACPI_DEVFLAG_NMI)
1309 			set_dte_bit(&dte, DEV_ENTRY_NMI_PASS);
1310 		if (flags & ACPI_DEVFLAG_SYSMGT1)
1311 			set_dte_bit(&dte, DEV_ENTRY_SYSMGT1);
1312 		if (flags & ACPI_DEVFLAG_SYSMGT2)
1313 			set_dte_bit(&dte, DEV_ENTRY_SYSMGT2);
1314 		if (flags & ACPI_DEVFLAG_LINT0)
1315 			set_dte_bit(&dte, DEV_ENTRY_LINT0_PASS);
1316 		if (flags & ACPI_DEVFLAG_LINT1)
1317 			set_dte_bit(&dte, DEV_ENTRY_LINT1_PASS);
1318 
1319 		/* Apply erratum 63, which needs info in initial_dte */
1320 		if (FIELD_GET(DTE_DATA1_SYSMGT_MASK, dte.data[1]) == 0x1)
1321 			dte.data[0] |= DTE_FLAG_IW;
1322 
1323 		memcpy(&d->dte, &dte, sizeof(dte));
1324 		d->segid = iommu->pci_seg->id;
1325 		d->devid_first = first;
1326 		d->devid_last = last;
1327 		list_add_tail(&d->list, &amd_ivhd_dev_flags_list);
1328 	}
1329 
1330 	for (i = first; i <= last; i++)  {
1331 		if (flags) {
1332 			struct dev_table_entry *dev_table = get_dev_table(iommu);
1333 
1334 			memcpy(&dev_table[i], &dte, sizeof(dte));
1335 		}
1336 		amd_iommu_set_rlookup_table(iommu, i);
1337 	}
1338 }
1339 
1340 static void __init set_dev_entry_from_acpi(struct amd_iommu *iommu,
1341 					   u16 devid, u32 flags, u32 ext_flags)
1342 {
1343 	set_dev_entry_from_acpi_range(iommu, devid, devid, flags, ext_flags);
1344 }
1345 
1346 int __init add_special_device(u8 type, u8 id, u32 *devid, bool cmd_line)
1347 {
1348 	struct devid_map *entry;
1349 	struct list_head *list;
1350 
1351 	if (type == IVHD_SPECIAL_IOAPIC)
1352 		list = &ioapic_map;
1353 	else if (type == IVHD_SPECIAL_HPET)
1354 		list = &hpet_map;
1355 	else
1356 		return -EINVAL;
1357 
1358 	list_for_each_entry(entry, list, list) {
1359 		if (!(entry->id == id && entry->cmd_line))
1360 			continue;
1361 
1362 		pr_info("Command-line override present for %s id %d - ignoring\n",
1363 			type == IVHD_SPECIAL_IOAPIC ? "IOAPIC" : "HPET", id);
1364 
1365 		*devid = entry->devid;
1366 
1367 		return 0;
1368 	}
1369 
1370 	entry = kzalloc_obj(*entry);
1371 	if (!entry)
1372 		return -ENOMEM;
1373 
1374 	entry->id	= id;
1375 	entry->devid	= *devid;
1376 	entry->cmd_line	= cmd_line;
1377 
1378 	list_add_tail(&entry->list, list);
1379 
1380 	return 0;
1381 }
1382 
1383 static int __init add_acpi_hid_device(u8 *hid, u8 *uid, u32 *devid,
1384 				      bool cmd_line)
1385 {
1386 	struct acpihid_map_entry *entry;
1387 	struct list_head *list = &acpihid_map;
1388 
1389 	list_for_each_entry(entry, list, list) {
1390 		if (strcmp(entry->hid, hid) ||
1391 		    (*uid && *entry->uid && strcmp(entry->uid, uid)) ||
1392 		    !entry->cmd_line)
1393 			continue;
1394 
1395 		pr_info("Command-line override for hid:%s uid:%s\n",
1396 			hid, uid);
1397 		*devid = entry->devid;
1398 		return 0;
1399 	}
1400 
1401 	entry = kzalloc_obj(*entry);
1402 	if (!entry)
1403 		return -ENOMEM;
1404 
1405 	memcpy(entry->uid, uid, strlen(uid));
1406 	memcpy(entry->hid, hid, strlen(hid));
1407 	entry->devid = *devid;
1408 	entry->cmd_line	= cmd_line;
1409 	entry->root_devid = (entry->devid & (~0x7));
1410 
1411 	pr_info("%s, add hid:%s, uid:%s, rdevid:%#x\n",
1412 		entry->cmd_line ? "cmd" : "ivrs",
1413 		entry->hid, entry->uid, entry->root_devid);
1414 
1415 	list_add_tail(&entry->list, list);
1416 	return 0;
1417 }
1418 
1419 static int __init add_early_maps(void)
1420 {
1421 	int i, ret;
1422 
1423 	for (i = 0; i < early_ioapic_map_size; ++i) {
1424 		ret = add_special_device(IVHD_SPECIAL_IOAPIC,
1425 					 early_ioapic_map[i].id,
1426 					 &early_ioapic_map[i].devid,
1427 					 early_ioapic_map[i].cmd_line);
1428 		if (ret)
1429 			return ret;
1430 	}
1431 
1432 	for (i = 0; i < early_hpet_map_size; ++i) {
1433 		ret = add_special_device(IVHD_SPECIAL_HPET,
1434 					 early_hpet_map[i].id,
1435 					 &early_hpet_map[i].devid,
1436 					 early_hpet_map[i].cmd_line);
1437 		if (ret)
1438 			return ret;
1439 	}
1440 
1441 	for (i = 0; i < early_acpihid_map_size; ++i) {
1442 		ret = add_acpi_hid_device(early_acpihid_map[i].hid,
1443 					  early_acpihid_map[i].uid,
1444 					  &early_acpihid_map[i].devid,
1445 					  early_acpihid_map[i].cmd_line);
1446 		if (ret)
1447 			return ret;
1448 	}
1449 
1450 	return 0;
1451 }
1452 
1453 /*
1454  * Takes a pointer to an AMD IOMMU entry in the ACPI table and
1455  * initializes the hardware and our data structures with it.
1456  */
1457 static int __init init_iommu_from_acpi(struct amd_iommu *iommu,
1458 					struct ivhd_header *h)
1459 {
1460 	u8 *p = (u8 *)h;
1461 	u8 *end = p, flags = 0;
1462 	u16 devid = 0, devid_start = 0, devid_to = 0, seg_id;
1463 	u32 dev_i, ext_flags = 0;
1464 	bool alias = false;
1465 	struct ivhd_entry *e;
1466 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
1467 	u32 ivhd_size;
1468 	int ret;
1469 
1470 
1471 	ret = add_early_maps();
1472 	if (ret)
1473 		return ret;
1474 
1475 	amd_iommu_apply_ivrs_quirks();
1476 
1477 	/*
1478 	 * First save the recommended feature enable bits from ACPI
1479 	 */
1480 	iommu->acpi_flags = h->flags;
1481 
1482 	/*
1483 	 * Done. Now parse the device entries
1484 	 */
1485 	ivhd_size = get_ivhd_header_size(h);
1486 	if (!ivhd_size) {
1487 		pr_err("Unsupported IVHD type %#x\n", h->type);
1488 		return -EINVAL;
1489 	}
1490 
1491 	p += ivhd_size;
1492 
1493 	end += h->length;
1494 
1495 
1496 	while (p < end) {
1497 		e = (struct ivhd_entry *)p;
1498 		seg_id = pci_seg->id;
1499 
1500 		switch (e->type) {
1501 		case IVHD_DEV_ALL:
1502 
1503 			DUMP_printk("  DEV_ALL\t\t\tsetting: %#02x\n", e->flags);
1504 			set_dev_entry_from_acpi_range(iommu, 0, pci_seg->last_bdf, e->flags, 0);
1505 			break;
1506 		case IVHD_DEV_SELECT:
1507 
1508 			DUMP_printk("  DEV_SELECT\t\t\tdevid: %04x:%02x:%02x.%x flags: %#02x\n",
1509 				    seg_id, PCI_BUS_NUM(e->devid),
1510 				    PCI_SLOT(e->devid),
1511 				    PCI_FUNC(e->devid),
1512 				    e->flags);
1513 
1514 			devid = e->devid;
1515 			set_dev_entry_from_acpi(iommu, devid, e->flags, 0);
1516 			break;
1517 		case IVHD_DEV_SELECT_RANGE_START:
1518 
1519 			DUMP_printk("  DEV_SELECT_RANGE_START\tdevid: %04x:%02x:%02x.%x flags: %#02x\n",
1520 				    seg_id, PCI_BUS_NUM(e->devid),
1521 				    PCI_SLOT(e->devid),
1522 				    PCI_FUNC(e->devid),
1523 				    e->flags);
1524 
1525 			devid_start = e->devid;
1526 			flags = e->flags;
1527 			ext_flags = 0;
1528 			alias = false;
1529 			break;
1530 		case IVHD_DEV_ALIAS:
1531 
1532 			DUMP_printk("  DEV_ALIAS\t\t\tdevid: %04x:%02x:%02x.%x flags: %#02x devid_to: %02x:%02x.%x\n",
1533 				    seg_id, PCI_BUS_NUM(e->devid),
1534 				    PCI_SLOT(e->devid),
1535 				    PCI_FUNC(e->devid),
1536 				    e->flags,
1537 				    PCI_BUS_NUM(e->ext >> 8),
1538 				    PCI_SLOT(e->ext >> 8),
1539 				    PCI_FUNC(e->ext >> 8));
1540 
1541 			devid = e->devid;
1542 			devid_to = e->ext >> 8;
1543 			set_dev_entry_from_acpi(iommu, devid   , e->flags, 0);
1544 			set_dev_entry_from_acpi(iommu, devid_to, e->flags, 0);
1545 			pci_seg->alias_table[devid] = devid_to;
1546 			break;
1547 		case IVHD_DEV_ALIAS_RANGE:
1548 
1549 			DUMP_printk("  DEV_ALIAS_RANGE\t\tdevid: %04x:%02x:%02x.%x flags: %#02x devid_to: %04x:%02x:%02x.%x\n",
1550 				    seg_id, PCI_BUS_NUM(e->devid),
1551 				    PCI_SLOT(e->devid),
1552 				    PCI_FUNC(e->devid),
1553 				    e->flags,
1554 				    seg_id, PCI_BUS_NUM(e->ext >> 8),
1555 				    PCI_SLOT(e->ext >> 8),
1556 				    PCI_FUNC(e->ext >> 8));
1557 
1558 			devid_start = e->devid;
1559 			flags = e->flags;
1560 			devid_to = e->ext >> 8;
1561 			ext_flags = 0;
1562 			alias = true;
1563 			break;
1564 		case IVHD_DEV_EXT_SELECT:
1565 
1566 			DUMP_printk("  DEV_EXT_SELECT\t\tdevid: %04x:%02x:%02x.%x flags: %#02x ext: %08x\n",
1567 				    seg_id, PCI_BUS_NUM(e->devid),
1568 				    PCI_SLOT(e->devid),
1569 				    PCI_FUNC(e->devid),
1570 				    e->flags, e->ext);
1571 
1572 			devid = e->devid;
1573 			set_dev_entry_from_acpi(iommu, devid, e->flags,
1574 						e->ext);
1575 			break;
1576 		case IVHD_DEV_EXT_SELECT_RANGE:
1577 
1578 			DUMP_printk("  DEV_EXT_SELECT_RANGE\tdevid: %04x:%02x:%02x.%x flags: %#02x ext: %08x\n",
1579 				    seg_id, PCI_BUS_NUM(e->devid),
1580 				    PCI_SLOT(e->devid),
1581 				    PCI_FUNC(e->devid),
1582 				    e->flags, e->ext);
1583 
1584 			devid_start = e->devid;
1585 			flags = e->flags;
1586 			ext_flags = e->ext;
1587 			alias = false;
1588 			break;
1589 		case IVHD_DEV_RANGE_END:
1590 
1591 			DUMP_printk("  DEV_RANGE_END\t\tdevid: %04x:%02x:%02x.%x\n",
1592 				    seg_id, PCI_BUS_NUM(e->devid),
1593 				    PCI_SLOT(e->devid),
1594 				    PCI_FUNC(e->devid));
1595 
1596 			devid = e->devid;
1597 			if (alias) {
1598 				for (dev_i = devid_start; dev_i <= devid; ++dev_i)
1599 					pci_seg->alias_table[dev_i] = devid_to;
1600 				set_dev_entry_from_acpi(iommu, devid_to, flags, ext_flags);
1601 			}
1602 			set_dev_entry_from_acpi_range(iommu, devid_start, devid, flags, ext_flags);
1603 			break;
1604 		case IVHD_DEV_SPECIAL: {
1605 			u8 handle, type;
1606 			const char *var;
1607 			u32 devid;
1608 			int ret;
1609 
1610 			handle = e->ext & 0xff;
1611 			devid = PCI_SEG_DEVID_TO_SBDF(seg_id, (e->ext >> 8));
1612 			type   = (e->ext >> 24) & 0xff;
1613 
1614 			if (type == IVHD_SPECIAL_IOAPIC)
1615 				var = "IOAPIC";
1616 			else if (type == IVHD_SPECIAL_HPET)
1617 				var = "HPET";
1618 			else
1619 				var = "UNKNOWN";
1620 
1621 			DUMP_printk("  DEV_SPECIAL(%s[%d])\t\tdevid: %04x:%02x:%02x.%x, flags: %#02x\n",
1622 				    var, (int)handle,
1623 				    seg_id, PCI_BUS_NUM(devid),
1624 				    PCI_SLOT(devid),
1625 				    PCI_FUNC(devid),
1626 				    e->flags);
1627 
1628 			ret = add_special_device(type, handle, &devid, false);
1629 			if (ret)
1630 				return ret;
1631 
1632 			/*
1633 			 * add_special_device might update the devid in case a
1634 			 * command-line override is present. So call
1635 			 * set_dev_entry_from_acpi after add_special_device.
1636 			 */
1637 			set_dev_entry_from_acpi(iommu, devid, e->flags, 0);
1638 
1639 			break;
1640 		}
1641 		case IVHD_DEV_ACPI_HID: {
1642 			u32 devid;
1643 			u8 hid[ACPIHID_HID_LEN];
1644 			u8 uid[ACPIHID_UID_LEN];
1645 			int ret;
1646 
1647 			if (h->type != 0x40) {
1648 				pr_err(FW_BUG "Invalid IVHD device type %#x\n",
1649 				       e->type);
1650 				break;
1651 			}
1652 
1653 			BUILD_BUG_ON(sizeof(e->ext_hid) != ACPIHID_HID_LEN - 1);
1654 			memcpy(hid, &e->ext_hid, ACPIHID_HID_LEN - 1);
1655 			hid[ACPIHID_HID_LEN - 1] = '\0';
1656 
1657 			if (!(*hid)) {
1658 				pr_err(FW_BUG "Invalid HID.\n");
1659 				break;
1660 			}
1661 
1662 			uid[0] = '\0';
1663 			switch (e->uidf) {
1664 			case UID_NOT_PRESENT:
1665 
1666 				if (e->uidl != 0)
1667 					pr_warn(FW_BUG "Invalid UID length.\n");
1668 
1669 				break;
1670 			case UID_IS_INTEGER:
1671 
1672 				sprintf(uid, "%d", e->uid);
1673 
1674 				break;
1675 			case UID_IS_CHARACTER:
1676 
1677 				memcpy(uid, &e->uid, e->uidl);
1678 				uid[e->uidl] = '\0';
1679 
1680 				break;
1681 			default:
1682 				break;
1683 			}
1684 
1685 			devid = PCI_SEG_DEVID_TO_SBDF(seg_id, e->devid);
1686 			DUMP_printk("  DEV_ACPI_HID(%s[%s])\t\tdevid: %04x:%02x:%02x.%x, flags: %#02x\n",
1687 				    hid, uid, seg_id,
1688 				    PCI_BUS_NUM(devid),
1689 				    PCI_SLOT(devid),
1690 				    PCI_FUNC(devid),
1691 				    e->flags);
1692 
1693 			flags = e->flags;
1694 
1695 			ret = add_acpi_hid_device(hid, uid, &devid, false);
1696 			if (ret)
1697 				return ret;
1698 
1699 			/*
1700 			 * add_special_device might update the devid in case a
1701 			 * command-line override is present. So call
1702 			 * set_dev_entry_from_acpi after add_special_device.
1703 			 */
1704 			set_dev_entry_from_acpi(iommu, devid, e->flags, 0);
1705 
1706 			break;
1707 		}
1708 		default:
1709 			break;
1710 		}
1711 
1712 		p += ivhd_entry_length(p);
1713 	}
1714 
1715 	return 0;
1716 }
1717 
1718 /* Allocate PCI segment data structure */
1719 static struct amd_iommu_pci_seg *__init alloc_pci_segment(u16 id,
1720 					  struct acpi_table_header *ivrs_base)
1721 {
1722 	struct amd_iommu_pci_seg *pci_seg;
1723 	int last_bdf;
1724 
1725 	/*
1726 	 * First parse ACPI tables to find the largest Bus/Dev/Func we need to
1727 	 * handle in this PCI segment. Upon this information the shared data
1728 	 * structures for the PCI segments in the system will be allocated.
1729 	 */
1730 	last_bdf = find_last_devid_acpi(ivrs_base, id);
1731 	if (last_bdf < 0)
1732 		return NULL;
1733 
1734 	pci_seg = kzalloc_obj(struct amd_iommu_pci_seg);
1735 	if (pci_seg == NULL)
1736 		return NULL;
1737 
1738 	pci_seg->last_bdf = last_bdf;
1739 	DUMP_printk("PCI segment : 0x%0x, last bdf : 0x%04x\n", id, last_bdf);
1740 	pci_seg->dev_table_size =
1741 		max(roundup_pow_of_two((last_bdf + 1) * DEV_TABLE_ENTRY_SIZE),
1742 		    SZ_4K);
1743 
1744 	pci_seg->id = id;
1745 	init_llist_head(&pci_seg->dev_data_list);
1746 	INIT_LIST_HEAD(&pci_seg->unity_map);
1747 	list_add_tail(&pci_seg->list, &amd_iommu_pci_seg_list);
1748 
1749 	if (alloc_dev_table(pci_seg))
1750 		goto err_free_pci_seg;
1751 	if (alloc_alias_table(pci_seg))
1752 		goto err_free_dev_table;
1753 	if (alloc_rlookup_table(pci_seg))
1754 		goto err_free_alias_table;
1755 
1756 	return pci_seg;
1757 
1758 err_free_alias_table:
1759 	free_alias_table(pci_seg);
1760 err_free_dev_table:
1761 	free_dev_table(pci_seg);
1762 err_free_pci_seg:
1763 	list_del(&pci_seg->list);
1764 	kfree(pci_seg);
1765 	return NULL;
1766 }
1767 
1768 static struct amd_iommu_pci_seg *__init get_pci_segment(u16 id,
1769 					struct acpi_table_header *ivrs_base)
1770 {
1771 	struct amd_iommu_pci_seg *pci_seg;
1772 
1773 	for_each_pci_segment(pci_seg) {
1774 		if (pci_seg->id == id)
1775 			return pci_seg;
1776 	}
1777 
1778 	return alloc_pci_segment(id, ivrs_base);
1779 }
1780 
1781 static void __init free_pci_segments(void)
1782 {
1783 	struct amd_iommu_pci_seg *pci_seg, *next;
1784 
1785 	for_each_pci_segment_safe(pci_seg, next) {
1786 		list_del(&pci_seg->list);
1787 		free_irq_lookup_table(pci_seg);
1788 		free_rlookup_table(pci_seg);
1789 		free_alias_table(pci_seg);
1790 		free_dev_table(pci_seg);
1791 		kfree(pci_seg);
1792 	}
1793 }
1794 
1795 static void __init free_sysfs(struct amd_iommu *iommu)
1796 {
1797 	if (iommu->iommu.dev) {
1798 		iommu_device_unregister(&iommu->iommu);
1799 		iommu_device_sysfs_remove(&iommu->iommu);
1800 	}
1801 }
1802 
1803 static void __init free_iommu_one(struct amd_iommu *iommu)
1804 {
1805 	free_sysfs(iommu);
1806 	free_iommu_buffers(iommu);
1807 	amd_iommu_free_ppr_log(iommu);
1808 	free_ga_log(iommu);
1809 	iommu_unmap_mmio_space(iommu);
1810 	amd_iommu_iopf_uninit(iommu);
1811 }
1812 
1813 static void __init free_iommu_all(void)
1814 {
1815 	struct amd_iommu *iommu, *next;
1816 
1817 	for_each_iommu_safe(iommu, next) {
1818 		list_del(&iommu->list);
1819 		free_iommu_one(iommu);
1820 		kfree(iommu);
1821 	}
1822 }
1823 
1824 /*
1825  * Family15h Model 10h-1fh erratum 746 (IOMMU Logging May Stall Translations)
1826  * Workaround:
1827  *     BIOS should disable L2B micellaneous clock gating by setting
1828  *     L2_L2B_CK_GATE_CONTROL[CKGateL2BMiscDisable](D0F2xF4_x90[2]) = 1b
1829  */
1830 static void amd_iommu_erratum_746_workaround(struct amd_iommu *iommu)
1831 {
1832 	u32 value;
1833 
1834 	if ((boot_cpu_data.x86 != 0x15) ||
1835 	    (boot_cpu_data.x86_model < 0x10) ||
1836 	    (boot_cpu_data.x86_model > 0x1f))
1837 		return;
1838 
1839 	pci_write_config_dword(iommu->dev, 0xf0, 0x90);
1840 	pci_read_config_dword(iommu->dev, 0xf4, &value);
1841 
1842 	if (value & BIT(2))
1843 		return;
1844 
1845 	/* Select NB indirect register 0x90 and enable writing */
1846 	pci_write_config_dword(iommu->dev, 0xf0, 0x90 | (1 << 8));
1847 
1848 	pci_write_config_dword(iommu->dev, 0xf4, value | 0x4);
1849 	pci_info(iommu->dev, "Applying erratum 746 workaround\n");
1850 
1851 	/* Clear the enable writing bit */
1852 	pci_write_config_dword(iommu->dev, 0xf0, 0x90);
1853 }
1854 
1855 /*
1856  * Family15h Model 30h-3fh (IOMMU Mishandles ATS Write Permission)
1857  * Workaround:
1858  *     BIOS should enable ATS write permission check by setting
1859  *     L2_DEBUG_3[AtsIgnoreIWDis](D0F2xF4_x47[0]) = 1b
1860  */
1861 static void amd_iommu_ats_write_check_workaround(struct amd_iommu *iommu)
1862 {
1863 	u32 value;
1864 
1865 	if ((boot_cpu_data.x86 != 0x15) ||
1866 	    (boot_cpu_data.x86_model < 0x30) ||
1867 	    (boot_cpu_data.x86_model > 0x3f))
1868 		return;
1869 
1870 	/* Test L2_DEBUG_3[AtsIgnoreIWDis] == 1 */
1871 	value = iommu_read_l2(iommu, 0x47);
1872 
1873 	if (value & BIT(0))
1874 		return;
1875 
1876 	/* Set L2_DEBUG_3[AtsIgnoreIWDis] = 1 */
1877 	iommu_write_l2(iommu, 0x47, value | BIT(0));
1878 
1879 	pci_info(iommu->dev, "Applying ATS write check workaround\n");
1880 }
1881 
1882 /*
1883  * This function glues the initialization function for one IOMMU
1884  * together and also allocates the command buffer and programs the
1885  * hardware. It does NOT enable the IOMMU. This is done afterwards.
1886  */
1887 static int __init init_iommu_one(struct amd_iommu *iommu, struct ivhd_header *h,
1888 				 struct acpi_table_header *ivrs_base)
1889 {
1890 	struct amd_iommu_pci_seg *pci_seg;
1891 
1892 	pci_seg = get_pci_segment(h->pci_seg, ivrs_base);
1893 	if (pci_seg == NULL)
1894 		return -ENOMEM;
1895 	iommu->pci_seg = pci_seg;
1896 
1897 	raw_spin_lock_init(&iommu->lock);
1898 	iommu->cmd_sem_val = 0;
1899 
1900 	/* Add IOMMU to internal data structures */
1901 	list_add_tail(&iommu->list, &amd_iommu_list);
1902 	iommu->index = amd_iommus_present++;
1903 
1904 	if (unlikely(iommu->index >= MAX_IOMMUS)) {
1905 		WARN(1, "System has more IOMMUs than supported by this driver\n");
1906 		return -ENOSYS;
1907 	}
1908 
1909 	/*
1910 	 * Copy data from ACPI table entry to the iommu struct
1911 	 */
1912 	iommu->devid   = h->devid;
1913 	iommu->cap_ptr = h->cap_ptr;
1914 	iommu->mmio_phys = h->mmio_phys;
1915 
1916 	switch (h->type) {
1917 	case 0x10:
1918 		/* Check if IVHD EFR contains proper max banks/counters */
1919 		if ((h->efr_attr != 0) &&
1920 		    ((h->efr_attr & (0xF << 13)) != 0) &&
1921 		    ((h->efr_attr & (0x3F << 17)) != 0))
1922 			iommu->mmio_phys_end = MMIO_REG_END_OFFSET;
1923 		else
1924 			iommu->mmio_phys_end = MMIO_CNTR_CONF_OFFSET;
1925 
1926 		/* GAM requires GA mode. */
1927 		if ((h->efr_attr & (0x1 << IOMMU_FEAT_GASUP_SHIFT)) == 0)
1928 			amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_LEGACY;
1929 		break;
1930 	case 0x11:
1931 	case 0x40:
1932 		if (h->efr_reg & (1 << 9))
1933 			iommu->mmio_phys_end = MMIO_REG_END_OFFSET;
1934 		else
1935 			iommu->mmio_phys_end = MMIO_CNTR_CONF_OFFSET;
1936 
1937 		if (h->efr_attr & BIT(IOMMU_IVHD_ATTR_HATDIS_SHIFT)) {
1938 			pr_warn_once("Host Address Translation is not supported.\n");
1939 			amd_iommu_hatdis = true;
1940 		}
1941 
1942 		/* XT and GAM require GA mode. */
1943 		if ((h->efr_reg & (0x1 << IOMMU_EFR_GASUP_SHIFT)) == 0) {
1944 			amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_LEGACY;
1945 			break;
1946 		} else {
1947 			if (h->efr_reg & BIT(IOMMU_EFR_XTSUP_SHIFT))
1948 				amd_iommu_xt_mode = IRQ_REMAP_X2APIC_MODE;
1949 		}
1950 
1951 		early_iommu_features_init(iommu, h);
1952 
1953 		break;
1954 	default:
1955 		return -EINVAL;
1956 	}
1957 
1958 	iommu->mmio_base = iommu_map_mmio_space(iommu->mmio_phys,
1959 						iommu->mmio_phys_end);
1960 	if (!iommu->mmio_base)
1961 		return -ENOMEM;
1962 
1963 	if (amd_iommu_perfopt_clear(iommu))
1964 		pr_err("IOMMU%d: failed to clear PerfOpt\n", iommu->index);
1965 
1966 	return init_iommu_from_acpi(iommu, h);
1967 }
1968 
1969 static int __init init_iommu_one_late(struct amd_iommu *iommu)
1970 {
1971 	int ret;
1972 
1973 	ret = alloc_iommu_buffers(iommu);
1974 	if (ret)
1975 		return ret;
1976 
1977 	iommu->int_enabled = false;
1978 
1979 	init_translation_status(iommu);
1980 	if (translation_pre_enabled(iommu) && !is_kdump_kernel()) {
1981 		iommu_disable(iommu);
1982 		clear_translation_pre_enabled(iommu);
1983 		pr_warn("Translation was enabled for IOMMU:%d but we are not in kdump mode\n",
1984 			iommu->index);
1985 	}
1986 	if (amd_iommu_pre_enabled)
1987 		amd_iommu_pre_enabled = translation_pre_enabled(iommu);
1988 
1989 	if (amd_iommu_irq_remap) {
1990 		ret = amd_iommu_create_irq_domain(iommu);
1991 		if (ret)
1992 			return ret;
1993 	}
1994 
1995 	/*
1996 	 * Make sure IOMMU is not considered to translate itself. The IVRS
1997 	 * table tells us so, but this is a lie!
1998 	 */
1999 	iommu->pci_seg->rlookup_table[iommu->devid] = NULL;
2000 
2001 	return 0;
2002 }
2003 
2004 /**
2005  * get_highest_supported_ivhd_type - Look up the appropriate IVHD type
2006  * @ivrs: Pointer to the IVRS header
2007  *
2008  * This function search through all IVDB of the maximum supported IVHD
2009  */
2010 static u8 get_highest_supported_ivhd_type(struct acpi_table_header *ivrs)
2011 {
2012 	u8 *base = (u8 *)ivrs;
2013 	struct ivhd_header *ivhd = (struct ivhd_header *)
2014 					(base + IVRS_HEADER_LENGTH);
2015 	u8 last_type = ivhd->type;
2016 	u16 devid = ivhd->devid;
2017 
2018 	while (((u8 *)ivhd - base < ivrs->length) &&
2019 	       (ivhd->type <= ACPI_IVHD_TYPE_MAX_SUPPORTED)) {
2020 		u8 *p = (u8 *) ivhd;
2021 
2022 		if (ivhd->devid == devid)
2023 			last_type = ivhd->type;
2024 		ivhd = (struct ivhd_header *)(p + ivhd->length);
2025 	}
2026 
2027 	return last_type;
2028 }
2029 
2030 /*
2031  * Iterates over all IOMMU entries in the ACPI table, allocates the
2032  * IOMMU structure and initializes it with init_iommu_one()
2033  */
2034 static int __init init_iommu_all(struct acpi_table_header *table)
2035 {
2036 	u8 *p = (u8 *)table, *end = (u8 *)table;
2037 	struct ivhd_header *h;
2038 	struct amd_iommu *iommu;
2039 	int ret;
2040 
2041 	end += table->length;
2042 	p += IVRS_HEADER_LENGTH;
2043 
2044 	/* Phase 1: Process all IVHD blocks */
2045 	while (p < end) {
2046 		h = (struct ivhd_header *)p;
2047 		if (*p == amd_iommu_target_ivhd_type) {
2048 
2049 			DUMP_printk("device: %04x:%02x:%02x.%01x cap: %04x "
2050 				    "flags: %01x info %04x\n",
2051 				    h->pci_seg, PCI_BUS_NUM(h->devid),
2052 				    PCI_SLOT(h->devid), PCI_FUNC(h->devid),
2053 				    h->cap_ptr, h->flags, h->info);
2054 			DUMP_printk("       mmio-addr: %016llx\n",
2055 				    h->mmio_phys);
2056 
2057 			iommu = kzalloc_obj(struct amd_iommu);
2058 			if (iommu == NULL)
2059 				return -ENOMEM;
2060 
2061 			ret = init_iommu_one(iommu, h, table);
2062 			if (ret)
2063 				return ret;
2064 		}
2065 		p += h->length;
2066 
2067 	}
2068 	WARN_ON(p != end);
2069 
2070 	/* Phase 2 : Early feature support check */
2071 	get_global_efr();
2072 
2073 	/* Phase 3 : Enabling IOMMU features */
2074 	for_each_iommu(iommu) {
2075 		ret = init_iommu_one_late(iommu);
2076 		if (ret)
2077 			return ret;
2078 	}
2079 
2080 	return 0;
2081 }
2082 
2083 static void init_iommu_perf_ctr(struct amd_iommu *iommu)
2084 {
2085 	u64 val;
2086 	struct pci_dev *pdev = iommu->dev;
2087 
2088 	if (!check_feature(FEATURE_PC))
2089 		return;
2090 
2091 	amd_iommu_pc_present = true;
2092 
2093 	pci_info(pdev, "IOMMU performance counters supported\n");
2094 
2095 	val = readl(iommu->mmio_base + MMIO_CNTR_CONF_OFFSET);
2096 	iommu->max_banks = (u8) ((val >> 12) & 0x3f);
2097 	iommu->max_counters = (u8) ((val >> 7) & 0xf);
2098 
2099 	return;
2100 }
2101 
2102 static ssize_t amd_iommu_show_cap(struct device *dev,
2103 				  struct device_attribute *attr,
2104 				  char *buf)
2105 {
2106 	struct amd_iommu *iommu = dev_to_amd_iommu(dev);
2107 	return sysfs_emit(buf, "%x\n", iommu->cap);
2108 }
2109 static DEVICE_ATTR(cap, S_IRUGO, amd_iommu_show_cap, NULL);
2110 
2111 static ssize_t amd_iommu_show_features(struct device *dev,
2112 				       struct device_attribute *attr,
2113 				       char *buf)
2114 {
2115 	return sysfs_emit(buf, "%llx:%llx\n", amd_iommu_efr, amd_iommu_efr2);
2116 }
2117 static DEVICE_ATTR(features, S_IRUGO, amd_iommu_show_features, NULL);
2118 
2119 static struct attribute *amd_iommu_attrs[] = {
2120 	&dev_attr_cap.attr,
2121 	&dev_attr_features.attr,
2122 	NULL,
2123 };
2124 
2125 static struct attribute_group amd_iommu_group = {
2126 	.name = "amd-iommu",
2127 	.attrs = amd_iommu_attrs,
2128 };
2129 
2130 static const struct attribute_group *amd_iommu_groups[] = {
2131 	&amd_iommu_group,
2132 	NULL,
2133 };
2134 
2135 /*
2136  * Note: IVHD 0x11 and 0x40 also contains exact copy
2137  * of the IOMMU Extended Feature Register [MMIO Offset 0030h].
2138  * Default to EFR in IVHD since it is available sooner (i.e. before PCI init).
2139  */
2140 static void __init late_iommu_features_init(struct amd_iommu *iommu)
2141 {
2142 	u64 features, features2;
2143 
2144 	if (!(iommu->cap & (1 << IOMMU_CAP_EFR)))
2145 		return;
2146 
2147 	/* read extended feature bits */
2148 	features = readq(iommu->mmio_base + MMIO_EXT_FEATURES);
2149 	features2 = readq(iommu->mmio_base + MMIO_EXT_FEATURES2);
2150 
2151 	if (!amd_iommu_efr) {
2152 		amd_iommu_efr = features;
2153 		amd_iommu_efr2 = features2;
2154 		return;
2155 	}
2156 
2157 	/*
2158 	 * Sanity check and warn if EFR values from
2159 	 * IVHD and MMIO conflict.
2160 	 */
2161 	if (features != amd_iommu_efr ||
2162 	    features2 != amd_iommu_efr2) {
2163 		pr_warn(FW_WARN
2164 			"EFR mismatch. Use IVHD EFR (%#llx : %#llx), EFR2 (%#llx : %#llx).\n",
2165 			features, amd_iommu_efr,
2166 			features2, amd_iommu_efr2);
2167 	}
2168 }
2169 
2170 /* Must be called after SNP support check is complete (iommu_snp_enable()) */
2171 static bool check_vapic_support(void)
2172 {
2173 	if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir))
2174 		return false;
2175 
2176 	if (!check_feature(FEATURE_GAM_VAPIC)) {
2177 		amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_LEGACY_GA;
2178 		return false;
2179 	}
2180 
2181 	if (amd_iommu_snp_en &&
2182 	    !FEATURE_SNPAVICSUP_GAM(amd_iommu_efr2)) {
2183 		pr_warn("Force to disable Virtual APIC due to SNP\n");
2184 		amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_LEGACY_GA;
2185 		return false;
2186 	}
2187 
2188 	return true;
2189 }
2190 
2191 static int __init iommu_init_pci(struct amd_iommu *iommu)
2192 {
2193 	int cap_ptr = iommu->cap_ptr;
2194 	int ret;
2195 
2196 	iommu->dev = pci_get_domain_bus_and_slot(iommu->pci_seg->id,
2197 						 PCI_BUS_NUM(iommu->devid),
2198 						 iommu->devid & 0xff);
2199 	if (!iommu->dev)
2200 		return -ENODEV;
2201 
2202 	/* ACPI _PRT won't have an IRQ for IOMMU */
2203 	iommu->dev->irq_managed = 1;
2204 
2205 	pci_read_config_dword(iommu->dev, cap_ptr + MMIO_CAP_HDR_OFFSET,
2206 			      &iommu->cap);
2207 
2208 	if (!(iommu->cap & (1 << IOMMU_CAP_IOTLB)))
2209 		amd_iommu_iotlb_sup = false;
2210 
2211 	late_iommu_features_init(iommu);
2212 
2213 	if (check_feature(FEATURE_GT)) {
2214 		int glxval;
2215 		u64 pasmax;
2216 
2217 		pasmax = FIELD_GET(FEATURE_PASMAX, amd_iommu_efr);
2218 		iommu->iommu.max_pasids = (1 << (pasmax + 1)) - 1;
2219 
2220 		BUG_ON(iommu->iommu.max_pasids & ~PASID_MASK);
2221 
2222 		glxval = FIELD_GET(FEATURE_GLX, amd_iommu_efr);
2223 
2224 		if (amd_iommu_max_glx_val == -1)
2225 			amd_iommu_max_glx_val = glxval;
2226 		else
2227 			amd_iommu_max_glx_val = min(amd_iommu_max_glx_val, glxval);
2228 
2229 		iommu_enable_gt(iommu);
2230 	}
2231 
2232 	if (check_feature(FEATURE_PPR) && amd_iommu_alloc_ppr_log(iommu))
2233 		return -ENOMEM;
2234 
2235 	if (check_vapic_support()) {
2236 		ret = alloc_ga_log(iommu);
2237 		if (ret)
2238 			return ret;
2239 	}
2240 
2241 	if (iommu->cap & (1UL << IOMMU_CAP_NPCACHE)) {
2242 		pr_info("Using strict mode due to virtualization\n");
2243 		iommu_set_dma_strict();
2244 		amd_iommu_np_cache = true;
2245 	}
2246 
2247 	init_iommu_perf_ctr(iommu);
2248 
2249 	if (is_rd890_iommu(iommu->dev)) {
2250 		int i, j;
2251 
2252 		iommu->root_pdev =
2253 			pci_get_domain_bus_and_slot(iommu->pci_seg->id,
2254 						    iommu->dev->bus->number,
2255 						    PCI_DEVFN(0, 0));
2256 
2257 		/*
2258 		 * Some rd890 systems may not be fully reconfigured by the
2259 		 * BIOS, so it's necessary for us to store this information so
2260 		 * it can be reprogrammed on resume
2261 		 */
2262 		pci_read_config_dword(iommu->dev, iommu->cap_ptr + 4,
2263 				&iommu->stored_addr_lo);
2264 		pci_read_config_dword(iommu->dev, iommu->cap_ptr + 8,
2265 				&iommu->stored_addr_hi);
2266 
2267 		/* Low bit locks writes to configuration space */
2268 		iommu->stored_addr_lo &= ~1;
2269 
2270 		for (i = 0; i < 6; i++)
2271 			for (j = 0; j < 0x12; j++)
2272 				iommu->stored_l1[i][j] = iommu_read_l1(iommu, i, j);
2273 
2274 		for (i = 0; i < 0x83; i++)
2275 			iommu->stored_l2[i] = iommu_read_l2(iommu, i);
2276 	}
2277 
2278 	amd_iommu_erratum_746_workaround(iommu);
2279 	amd_iommu_ats_write_check_workaround(iommu);
2280 
2281 	ret = iommu_device_sysfs_add(&iommu->iommu, &iommu->dev->dev,
2282 			       amd_iommu_groups, "ivhd%d", iommu->index);
2283 	if (ret)
2284 		return ret;
2285 
2286 	/*
2287 	 * Allocate per IOMMU IOPF queue here so that in attach device path,
2288 	 * PRI capable device can be added to IOPF queue
2289 	 */
2290 	if (amd_iommu_gt_ppr_supported()) {
2291 		ret = amd_iommu_iopf_init(iommu);
2292 		if (ret)
2293 			return ret;
2294 	}
2295 
2296 	ret = iommu_device_register(&iommu->iommu, &amd_iommu_ops, NULL);
2297 	if (ret || amd_iommu_pgtable == PD_MODE_NONE) {
2298 		/*
2299 		 * Remove sysfs if DMA translation is not supported by the
2300 		 * IOMMU. Do not return an error to enable IRQ remapping
2301 		 * in state_next(), DTE[V, TV] must eventually be set to 0.
2302 		 */
2303 		iommu_device_sysfs_remove(&iommu->iommu);
2304 	}
2305 
2306 	return pci_enable_device(iommu->dev);
2307 }
2308 
2309 static void print_iommu_info(void)
2310 {
2311 	int i;
2312 	static const char * const feat_str[] = {
2313 		"PreF", "PPR", "X2APIC", "NX", "GT", "[5]",
2314 		"IA", "GA", "HE", "PC"
2315 	};
2316 
2317 	if (amd_iommu_efr) {
2318 		pr_info("Extended features (%#llx, %#llx):", amd_iommu_efr, amd_iommu_efr2);
2319 
2320 		for (i = 0; i < ARRAY_SIZE(feat_str); ++i) {
2321 			if (check_feature(1ULL << i))
2322 				pr_cont(" %s", feat_str[i]);
2323 		}
2324 
2325 		if (check_feature(FEATURE_GAM_VAPIC))
2326 			pr_cont(" GA_vAPIC");
2327 
2328 		if (check_feature(FEATURE_SNP))
2329 			pr_cont(" SNP");
2330 
2331 		if (check_feature2(FEATURE_SEVSNPIO_SUP))
2332 			pr_cont(" SEV-TIO");
2333 
2334 		pr_cont("\n");
2335 	}
2336 
2337 	if (irq_remapping_enabled) {
2338 		pr_info("Interrupt remapping enabled\n");
2339 		if (amd_iommu_xt_mode == IRQ_REMAP_X2APIC_MODE)
2340 			pr_info("X2APIC enabled\n");
2341 	}
2342 	if (amd_iommu_pgtable == PD_MODE_V2) {
2343 		pr_info("V2 page table enabled (Paging mode : %d level)\n",
2344 			amd_iommu_gpt_level);
2345 	}
2346 }
2347 
2348 static int __init amd_iommu_init_pci(void)
2349 {
2350 	struct amd_iommu *iommu;
2351 	struct amd_iommu_pci_seg *pci_seg;
2352 	int ret;
2353 
2354 	/* Init global identity domain before registering IOMMU */
2355 	amd_iommu_init_identity_domain();
2356 
2357 	for_each_iommu(iommu) {
2358 		ret = iommu_init_pci(iommu);
2359 		if (ret) {
2360 			pr_err("IOMMU%d: Failed to initialize IOMMU Hardware (error=%d)!\n",
2361 			       iommu->index, ret);
2362 			goto out;
2363 		}
2364 		/* Need to setup range after PCI init */
2365 		iommu_set_cwwb_range(iommu);
2366 	}
2367 
2368 	/*
2369 	 * Order is important here to make sure any unity map requirements are
2370 	 * fulfilled. The unity mappings are created and written to the device
2371 	 * table during the iommu_init_pci() call.
2372 	 *
2373 	 * After that we call init_device_table_dma() to make sure any
2374 	 * uninitialized DTE will block DMA, and in the end we flush the caches
2375 	 * of all IOMMUs to make sure the changes to the device table are
2376 	 * active.
2377 	 */
2378 	for_each_pci_segment(pci_seg)
2379 		init_device_table_dma(pci_seg);
2380 
2381 	for_each_iommu(iommu)
2382 		amd_iommu_flush_all_caches(iommu);
2383 
2384 	print_iommu_info();
2385 
2386 out:
2387 	return ret;
2388 }
2389 
2390 /****************************************************************************
2391  *
2392  * The following functions initialize the MSI interrupts for all IOMMUs
2393  * in the system. It's a bit challenging because there could be multiple
2394  * IOMMUs per PCI BDF but we can call pci_enable_msi(x) only once per
2395  * pci_dev.
2396  *
2397  ****************************************************************************/
2398 
2399 static int iommu_setup_msi(struct amd_iommu *iommu)
2400 {
2401 	int r;
2402 
2403 	r = pci_enable_msi(iommu->dev);
2404 	if (r)
2405 		return r;
2406 
2407 	r = request_threaded_irq(iommu->dev->irq, NULL, amd_iommu_int_thread,
2408 				 IRQF_ONESHOT, "AMD-Vi", iommu);
2409 	if (r) {
2410 		pci_disable_msi(iommu->dev);
2411 		return r;
2412 	}
2413 
2414 	return 0;
2415 }
2416 
2417 union intcapxt {
2418 	u64	capxt;
2419 	struct {
2420 		u64	reserved_0		:  2,
2421 			dest_mode_logical	:  1,
2422 			reserved_1		:  5,
2423 			destid_0_23		: 24,
2424 			vector			:  8,
2425 			reserved_2		: 16,
2426 			destid_24_31		:  8;
2427 	};
2428 } __attribute__ ((packed));
2429 
2430 
2431 static struct irq_chip intcapxt_controller;
2432 
2433 static int intcapxt_irqdomain_activate(struct irq_domain *domain,
2434 				       struct irq_data *irqd, bool reserve)
2435 {
2436 	return 0;
2437 }
2438 
2439 static void intcapxt_irqdomain_deactivate(struct irq_domain *domain,
2440 					  struct irq_data *irqd)
2441 {
2442 }
2443 
2444 
2445 static int intcapxt_irqdomain_alloc(struct irq_domain *domain, unsigned int virq,
2446 				    unsigned int nr_irqs, void *arg)
2447 {
2448 	struct irq_alloc_info *info = arg;
2449 	int i, ret;
2450 
2451 	if (!info || info->type != X86_IRQ_ALLOC_TYPE_AMDVI)
2452 		return -EINVAL;
2453 
2454 	ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
2455 	if (ret < 0)
2456 		return ret;
2457 
2458 	for (i = virq; i < virq + nr_irqs; i++) {
2459 		struct irq_data *irqd = irq_domain_get_irq_data(domain, i);
2460 
2461 		irqd->chip = &intcapxt_controller;
2462 		irqd->hwirq = info->hwirq;
2463 		irqd->chip_data = info->data;
2464 		__irq_set_handler(i, handle_edge_irq, 0, "edge");
2465 	}
2466 
2467 	return ret;
2468 }
2469 
2470 static void intcapxt_irqdomain_free(struct irq_domain *domain, unsigned int virq,
2471 				    unsigned int nr_irqs)
2472 {
2473 	irq_domain_free_irqs_top(domain, virq, nr_irqs);
2474 }
2475 
2476 
2477 static void intcapxt_unmask_irq(struct irq_data *irqd)
2478 {
2479 	struct amd_iommu *iommu = irqd->chip_data;
2480 	struct irq_cfg *cfg = irqd_cfg(irqd);
2481 	union intcapxt xt;
2482 
2483 	xt.capxt = 0ULL;
2484 	xt.dest_mode_logical = apic->dest_mode_logical;
2485 	xt.vector = cfg->vector;
2486 	xt.destid_0_23 = cfg->dest_apicid & GENMASK(23, 0);
2487 	xt.destid_24_31 = cfg->dest_apicid >> 24;
2488 
2489 	writeq(xt.capxt, iommu->mmio_base + irqd->hwirq);
2490 }
2491 
2492 static void intcapxt_mask_irq(struct irq_data *irqd)
2493 {
2494 	struct amd_iommu *iommu = irqd->chip_data;
2495 
2496 	writeq(0, iommu->mmio_base + irqd->hwirq);
2497 }
2498 
2499 
2500 static int intcapxt_set_affinity(struct irq_data *irqd,
2501 				 const struct cpumask *mask, bool force)
2502 {
2503 	struct irq_data *parent = irqd->parent_data;
2504 	int ret;
2505 
2506 	ret = parent->chip->irq_set_affinity(parent, mask, force);
2507 	if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
2508 		return ret;
2509 	return 0;
2510 }
2511 
2512 static int intcapxt_set_wake(struct irq_data *irqd, unsigned int on)
2513 {
2514 	return on ? -EOPNOTSUPP : 0;
2515 }
2516 
2517 static struct irq_chip intcapxt_controller = {
2518 	.name			= "IOMMU-MSI",
2519 	.irq_unmask		= intcapxt_unmask_irq,
2520 	.irq_mask		= intcapxt_mask_irq,
2521 	.irq_ack		= irq_chip_ack_parent,
2522 	.irq_retrigger		= irq_chip_retrigger_hierarchy,
2523 	.irq_set_affinity       = intcapxt_set_affinity,
2524 	.irq_set_wake		= intcapxt_set_wake,
2525 	.flags			= IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_MOVE_DEFERRED,
2526 };
2527 
2528 static const struct irq_domain_ops intcapxt_domain_ops = {
2529 	.alloc			= intcapxt_irqdomain_alloc,
2530 	.free			= intcapxt_irqdomain_free,
2531 	.activate		= intcapxt_irqdomain_activate,
2532 	.deactivate		= intcapxt_irqdomain_deactivate,
2533 };
2534 
2535 
2536 static struct irq_domain *iommu_irqdomain;
2537 
2538 static struct irq_domain *iommu_get_irqdomain(void)
2539 {
2540 	struct fwnode_handle *fn;
2541 
2542 	/* No need for locking here (yet) as the init is single-threaded */
2543 	if (iommu_irqdomain)
2544 		return iommu_irqdomain;
2545 
2546 	fn = irq_domain_alloc_named_fwnode("AMD-Vi-MSI");
2547 	if (!fn)
2548 		return NULL;
2549 
2550 	iommu_irqdomain = irq_domain_create_hierarchy(x86_vector_domain, 0, 0,
2551 						      fn, &intcapxt_domain_ops,
2552 						      NULL);
2553 	if (!iommu_irqdomain)
2554 		irq_domain_free_fwnode(fn);
2555 
2556 	return iommu_irqdomain;
2557 }
2558 
2559 static int __iommu_setup_intcapxt(struct amd_iommu *iommu, const char *devname,
2560 				  int hwirq, irq_handler_t thread_fn)
2561 {
2562 	struct irq_domain *domain;
2563 	struct irq_alloc_info info;
2564 	int irq, ret;
2565 	int node = dev_to_node(&iommu->dev->dev);
2566 
2567 	domain = iommu_get_irqdomain();
2568 	if (!domain)
2569 		return -ENXIO;
2570 
2571 	init_irq_alloc_info(&info, NULL);
2572 	info.type = X86_IRQ_ALLOC_TYPE_AMDVI;
2573 	info.data = iommu;
2574 	info.hwirq = hwirq;
2575 
2576 	irq = irq_domain_alloc_irqs(domain, 1, node, &info);
2577 	if (irq < 0) {
2578 		irq_domain_remove(domain);
2579 		return irq;
2580 	}
2581 
2582 	ret = request_threaded_irq(irq, NULL, thread_fn, IRQF_ONESHOT, devname,
2583 				   iommu);
2584 	if (ret) {
2585 		irq_domain_free_irqs(irq, 1);
2586 		irq_domain_remove(domain);
2587 		return ret;
2588 	}
2589 
2590 	return 0;
2591 }
2592 
2593 static int iommu_setup_intcapxt(struct amd_iommu *iommu)
2594 {
2595 	int ret;
2596 
2597 	snprintf(iommu->evt_irq_name, sizeof(iommu->evt_irq_name),
2598 		 "AMD-Vi%d-Evt", iommu->index);
2599 	ret = __iommu_setup_intcapxt(iommu, iommu->evt_irq_name,
2600 				     MMIO_INTCAPXT_EVT_OFFSET,
2601 				     amd_iommu_int_thread_evtlog);
2602 	if (ret)
2603 		return ret;
2604 
2605 	snprintf(iommu->ppr_irq_name, sizeof(iommu->ppr_irq_name),
2606 		 "AMD-Vi%d-PPR", iommu->index);
2607 	ret = __iommu_setup_intcapxt(iommu, iommu->ppr_irq_name,
2608 				     MMIO_INTCAPXT_PPR_OFFSET,
2609 				     amd_iommu_int_thread_pprlog);
2610 	if (ret)
2611 		return ret;
2612 
2613 #ifdef CONFIG_IRQ_REMAP
2614 	snprintf(iommu->ga_irq_name, sizeof(iommu->ga_irq_name),
2615 		 "AMD-Vi%d-GA", iommu->index);
2616 	ret = __iommu_setup_intcapxt(iommu, iommu->ga_irq_name,
2617 				     MMIO_INTCAPXT_GALOG_OFFSET,
2618 				     amd_iommu_int_thread_galog);
2619 #endif
2620 
2621 	return ret;
2622 }
2623 
2624 static int iommu_init_irq(struct amd_iommu *iommu)
2625 {
2626 	int ret;
2627 
2628 	if (iommu->int_enabled)
2629 		goto enable_faults;
2630 
2631 	if (amd_iommu_xt_mode == IRQ_REMAP_X2APIC_MODE)
2632 		ret = iommu_setup_intcapxt(iommu);
2633 	else if (iommu->dev->msi_cap)
2634 		ret = iommu_setup_msi(iommu);
2635 	else
2636 		ret = -ENODEV;
2637 
2638 	if (ret)
2639 		return ret;
2640 
2641 	iommu->int_enabled = true;
2642 enable_faults:
2643 
2644 	if (amd_iommu_xt_mode == IRQ_REMAP_X2APIC_MODE)
2645 		iommu_feature_enable(iommu, CONTROL_INTCAPXT_EN);
2646 
2647 	iommu_feature_enable(iommu, CONTROL_EVT_INT_EN);
2648 
2649 	return 0;
2650 }
2651 
2652 /****************************************************************************
2653  *
2654  * The next functions belong to the third pass of parsing the ACPI
2655  * table. In this last pass the memory mapping requirements are
2656  * gathered (like exclusion and unity mapping ranges).
2657  *
2658  ****************************************************************************/
2659 
2660 static void __init free_unity_maps(void)
2661 {
2662 	struct unity_map_entry *entry, *next;
2663 	struct amd_iommu_pci_seg *p, *pci_seg;
2664 
2665 	for_each_pci_segment_safe(pci_seg, p) {
2666 		list_for_each_entry_safe(entry, next, &pci_seg->unity_map, list) {
2667 			list_del(&entry->list);
2668 			kfree(entry);
2669 		}
2670 	}
2671 }
2672 
2673 /* called for unity map ACPI definition */
2674 static int __init init_unity_map_range(struct ivmd_header *m,
2675 				       struct acpi_table_header *ivrs_base)
2676 {
2677 	struct unity_map_entry *e = NULL;
2678 	struct amd_iommu_pci_seg *pci_seg;
2679 	char *s;
2680 
2681 	pci_seg = get_pci_segment(m->pci_seg, ivrs_base);
2682 	if (pci_seg == NULL)
2683 		return -ENOMEM;
2684 
2685 	e = kzalloc_obj(*e);
2686 	if (e == NULL)
2687 		return -ENOMEM;
2688 
2689 	switch (m->type) {
2690 	default:
2691 		kfree(e);
2692 		return 0;
2693 	case ACPI_IVMD_TYPE:
2694 		s = "IVMD_TYPEi\t\t\t";
2695 		e->devid_start = e->devid_end = m->devid;
2696 		break;
2697 	case ACPI_IVMD_TYPE_ALL:
2698 		s = "IVMD_TYPE_ALL\t\t";
2699 		e->devid_start = 0;
2700 		e->devid_end = pci_seg->last_bdf;
2701 		break;
2702 	case ACPI_IVMD_TYPE_RANGE:
2703 		s = "IVMD_TYPE_RANGE\t\t";
2704 		e->devid_start = m->devid;
2705 		e->devid_end = m->aux;
2706 		break;
2707 	}
2708 	e->address_start = PAGE_ALIGN(m->range_start);
2709 	e->address_end = e->address_start + PAGE_ALIGN(m->range_length);
2710 	e->prot = m->flags >> 1;
2711 
2712 	/*
2713 	 * Treat per-device exclusion ranges as r/w unity-mapped regions
2714 	 * since some buggy BIOSes might lead to the overwritten exclusion
2715 	 * range (exclusion_start and exclusion_length members). This
2716 	 * happens when there are multiple exclusion ranges (IVMD entries)
2717 	 * defined in ACPI table.
2718 	 */
2719 	if (m->flags & IVMD_FLAG_EXCL_RANGE)
2720 		e->prot = (IVMD_FLAG_IW | IVMD_FLAG_IR) >> 1;
2721 
2722 	DUMP_printk("%s devid_start: %04x:%02x:%02x.%x devid_end: "
2723 		    "%04x:%02x:%02x.%x range_start: %016llx range_end: %016llx"
2724 		    " flags: %x\n", s, m->pci_seg,
2725 		    PCI_BUS_NUM(e->devid_start), PCI_SLOT(e->devid_start),
2726 		    PCI_FUNC(e->devid_start), m->pci_seg,
2727 		    PCI_BUS_NUM(e->devid_end),
2728 		    PCI_SLOT(e->devid_end), PCI_FUNC(e->devid_end),
2729 		    e->address_start, e->address_end, m->flags);
2730 
2731 	list_add_tail(&e->list, &pci_seg->unity_map);
2732 
2733 	return 0;
2734 }
2735 
2736 /* iterates over all memory definitions we find in the ACPI table */
2737 static int __init init_memory_definitions(struct acpi_table_header *table)
2738 {
2739 	u8 *p = (u8 *)table, *end = (u8 *)table;
2740 	struct ivmd_header *m;
2741 
2742 	end += table->length;
2743 	p += IVRS_HEADER_LENGTH;
2744 
2745 	while (p < end) {
2746 		m = (struct ivmd_header *)p;
2747 		if (m->flags & (IVMD_FLAG_UNITY_MAP | IVMD_FLAG_EXCL_RANGE))
2748 			init_unity_map_range(m, table);
2749 
2750 		p += m->length;
2751 	}
2752 
2753 	return 0;
2754 }
2755 
2756 /*
2757  * Init the device table to not allow DMA access for devices
2758  */
2759 static void init_device_table_dma(struct amd_iommu_pci_seg *pci_seg)
2760 {
2761 	u32 devid;
2762 	struct dev_table_entry *dev_table = pci_seg->dev_table;
2763 
2764 	if (!dev_table || amd_iommu_pgtable == PD_MODE_NONE)
2765 		return;
2766 
2767 	for (devid = 0; devid <= pci_seg->last_bdf; ++devid) {
2768 		set_dte_bit(&dev_table[devid], DEV_ENTRY_VALID);
2769 		if (!amd_iommu_snp_en)
2770 			set_dte_bit(&dev_table[devid], DEV_ENTRY_TRANSLATION);
2771 	}
2772 }
2773 
2774 static void __init uninit_device_table_dma(struct amd_iommu_pci_seg *pci_seg)
2775 {
2776 	u32 devid;
2777 	struct dev_table_entry *dev_table = pci_seg->dev_table;
2778 
2779 	if (dev_table == NULL)
2780 		return;
2781 
2782 	for (devid = 0; devid <= pci_seg->last_bdf; ++devid) {
2783 		dev_table[devid].data[0] = 0ULL;
2784 		dev_table[devid].data[1] = 0ULL;
2785 	}
2786 }
2787 
2788 static void init_device_table(void)
2789 {
2790 	struct amd_iommu_pci_seg *pci_seg;
2791 	u32 devid;
2792 
2793 	if (!amd_iommu_irq_remap)
2794 		return;
2795 
2796 	for_each_pci_segment(pci_seg) {
2797 		for (devid = 0; devid <= pci_seg->last_bdf; ++devid)
2798 			set_dte_bit(&pci_seg->dev_table[devid], DEV_ENTRY_IRQ_TBL_EN);
2799 	}
2800 }
2801 
2802 static void iommu_init_flags(struct amd_iommu *iommu)
2803 {
2804 	iommu->acpi_flags & IVHD_FLAG_HT_TUN_EN_MASK ?
2805 		iommu_feature_enable(iommu, CONTROL_HT_TUN_EN) :
2806 		iommu_feature_disable(iommu, CONTROL_HT_TUN_EN);
2807 
2808 	iommu->acpi_flags & IVHD_FLAG_PASSPW_EN_MASK ?
2809 		iommu_feature_enable(iommu, CONTROL_PASSPW_EN) :
2810 		iommu_feature_disable(iommu, CONTROL_PASSPW_EN);
2811 
2812 	iommu->acpi_flags & IVHD_FLAG_RESPASSPW_EN_MASK ?
2813 		iommu_feature_enable(iommu, CONTROL_RESPASSPW_EN) :
2814 		iommu_feature_disable(iommu, CONTROL_RESPASSPW_EN);
2815 
2816 	iommu->acpi_flags & IVHD_FLAG_ISOC_EN_MASK ?
2817 		iommu_feature_enable(iommu, CONTROL_ISOC_EN) :
2818 		iommu_feature_disable(iommu, CONTROL_ISOC_EN);
2819 
2820 	/*
2821 	 * make IOMMU memory accesses cache coherent
2822 	 */
2823 	iommu_feature_enable(iommu, CONTROL_COHERENT_EN);
2824 
2825 	/* Set IOTLB invalidation timeout to 1s */
2826 	iommu_feature_set(iommu, CTRL_INV_TO_1S, CTRL_INV_TO_MASK, CONTROL_INV_TIMEOUT);
2827 
2828 	/* Enable Enhanced Peripheral Page Request Handling */
2829 	if (check_feature(FEATURE_EPHSUP))
2830 		iommu_feature_enable(iommu, CONTROL_EPH_EN);
2831 }
2832 
2833 static void iommu_apply_resume_quirks(struct amd_iommu *iommu)
2834 {
2835 	int i, j;
2836 	u32 ioc_feature_control;
2837 	struct pci_dev *pdev = iommu->root_pdev;
2838 
2839 	/* RD890 BIOSes may not have completely reconfigured the iommu */
2840 	if (!is_rd890_iommu(iommu->dev) || !pdev)
2841 		return;
2842 
2843 	/*
2844 	 * First, we need to ensure that the iommu is enabled. This is
2845 	 * controlled by a register in the northbridge
2846 	 */
2847 
2848 	/* Select Northbridge indirect register 0x75 and enable writing */
2849 	pci_write_config_dword(pdev, 0x60, 0x75 | (1 << 7));
2850 	pci_read_config_dword(pdev, 0x64, &ioc_feature_control);
2851 
2852 	/* Enable the iommu */
2853 	if (!(ioc_feature_control & 0x1))
2854 		pci_write_config_dword(pdev, 0x64, ioc_feature_control | 1);
2855 
2856 	/* Restore the iommu BAR */
2857 	pci_write_config_dword(iommu->dev, iommu->cap_ptr + 4,
2858 			       iommu->stored_addr_lo);
2859 	pci_write_config_dword(iommu->dev, iommu->cap_ptr + 8,
2860 			       iommu->stored_addr_hi);
2861 
2862 	/* Restore the l1 indirect regs for each of the 6 l1s */
2863 	for (i = 0; i < 6; i++)
2864 		for (j = 0; j < 0x12; j++)
2865 			iommu_write_l1(iommu, i, j, iommu->stored_l1[i][j]);
2866 
2867 	/* Restore the l2 indirect regs */
2868 	for (i = 0; i < 0x83; i++)
2869 		iommu_write_l2(iommu, i, iommu->stored_l2[i]);
2870 
2871 	/* Lock PCI setup registers */
2872 	pci_write_config_dword(iommu->dev, iommu->cap_ptr + 4,
2873 			       iommu->stored_addr_lo | 1);
2874 }
2875 
2876 static void iommu_enable_ga(struct amd_iommu *iommu)
2877 {
2878 #ifdef CONFIG_IRQ_REMAP
2879 	switch (amd_iommu_guest_ir) {
2880 	case AMD_IOMMU_GUEST_IR_VAPIC:
2881 	case AMD_IOMMU_GUEST_IR_LEGACY_GA:
2882 		iommu_feature_enable(iommu, CONTROL_GA_EN);
2883 		iommu->irte_ops = &irte_128_ops;
2884 		break;
2885 	default:
2886 		iommu->irte_ops = &irte_32_ops;
2887 		break;
2888 	}
2889 #endif
2890 }
2891 
2892 static void iommu_disable_irtcachedis(struct amd_iommu *iommu)
2893 {
2894 	iommu_feature_disable(iommu, CONTROL_IRTCACHEDIS);
2895 }
2896 
2897 static void iommu_enable_irtcachedis(struct amd_iommu *iommu)
2898 {
2899 	u64 ctrl;
2900 
2901 	if (!amd_iommu_irtcachedis)
2902 		return;
2903 
2904 	/*
2905 	 * Note:
2906 	 * The support for IRTCacheDis feature is dertermined by
2907 	 * checking if the bit is writable.
2908 	 */
2909 	iommu_feature_enable(iommu, CONTROL_IRTCACHEDIS);
2910 	ctrl = readq(iommu->mmio_base +  MMIO_CONTROL_OFFSET);
2911 	ctrl &= (1ULL << CONTROL_IRTCACHEDIS);
2912 	if (ctrl)
2913 		iommu->irtcachedis_enabled = true;
2914 	pr_info("iommu%d (%#06x) : IRT cache is %s\n",
2915 		iommu->index, iommu->devid,
2916 		iommu->irtcachedis_enabled ? "disabled" : "enabled");
2917 }
2918 
2919 static void iommu_enable_2k_int(struct amd_iommu *iommu)
2920 {
2921 	if (!FEATURE_NUM_INT_REMAP_SUP_2K(amd_iommu_efr2))
2922 		return;
2923 
2924 	iommu_feature_set(iommu,
2925 			  CONTROL_NUM_INT_REMAP_MODE_2K,
2926 			  CONTROL_NUM_INT_REMAP_MODE_MASK,
2927 			  CONTROL_NUM_INT_REMAP_MODE);
2928 }
2929 
2930 static void early_enable_iommu(struct amd_iommu *iommu)
2931 {
2932 	iommu_disable(iommu);
2933 	iommu_init_flags(iommu);
2934 	iommu_set_device_table(iommu);
2935 	iommu_enable_command_buffer(iommu);
2936 	iommu_enable_gt(iommu);
2937 	iommu_enable_ga(iommu);
2938 	iommu_enable_xt(iommu);
2939 	iommu_enable_irtcachedis(iommu);
2940 	iommu_enable_2k_int(iommu);
2941 	iommu_enable(iommu);
2942 	amd_iommu_flush_all_caches(iommu);
2943 }
2944 
2945 /*
2946  * This function finally enables all IOMMUs found in the system after
2947  * they have been initialized.
2948  *
2949  * Or if in kdump kernel and IOMMUs are all pre-enabled, try to reuse
2950  * the old content of device table entries. Not this case or reuse failed,
2951  * just continue as normal kernel does.
2952  */
2953 static void early_enable_iommus(void)
2954 {
2955 	struct amd_iommu *iommu;
2956 	struct amd_iommu_pci_seg *pci_seg;
2957 
2958 	if (!reuse_device_table()) {
2959 		/*
2960 		 * If come here because of failure in reusing device table from old
2961 		 * kernel with all IOMMUs enabled, print error message and try to
2962 		 * free allocated old_dev_tbl_cpy.
2963 		 */
2964 		if (amd_iommu_pre_enabled) {
2965 			pr_err("Failed to reuse DEV table from previous kernel.\n");
2966 			/*
2967 			 * Bail out early if unable to remap/reuse DEV table from
2968 			 * previous kernel if SNP enabled as IOMMU commands will
2969 			 * time out without DEV table and cause kdump boot panic.
2970 			 */
2971 			BUG_ON(check_feature(FEATURE_SNP));
2972 		}
2973 
2974 		for_each_pci_segment(pci_seg) {
2975 			if (pci_seg->old_dev_tbl_cpy != NULL) {
2976 				memunmap((void *)pci_seg->old_dev_tbl_cpy);
2977 				pci_seg->old_dev_tbl_cpy = NULL;
2978 			}
2979 		}
2980 
2981 		for_each_iommu(iommu) {
2982 			clear_translation_pre_enabled(iommu);
2983 			early_enable_iommu(iommu);
2984 		}
2985 	} else {
2986 		pr_info("Reused DEV table from previous kernel.\n");
2987 
2988 		for_each_pci_segment(pci_seg) {
2989 			iommu_free_pages(pci_seg->dev_table);
2990 			pci_seg->dev_table = pci_seg->old_dev_tbl_cpy;
2991 		}
2992 
2993 		for_each_iommu(iommu) {
2994 			iommu_disable_command_buffer(iommu);
2995 			iommu_disable_event_buffer(iommu);
2996 			iommu_disable_irtcachedis(iommu);
2997 			iommu_enable_command_buffer(iommu);
2998 			iommu_enable_ga(iommu);
2999 			iommu_enable_xt(iommu);
3000 			iommu_enable_irtcachedis(iommu);
3001 			iommu_enable_2k_int(iommu);
3002 			iommu_set_device_table(iommu);
3003 			amd_iommu_flush_all_caches(iommu);
3004 		}
3005 	}
3006 }
3007 
3008 static void enable_iommus_ppr(void)
3009 {
3010 	struct amd_iommu *iommu;
3011 
3012 	if (!amd_iommu_gt_ppr_supported())
3013 		return;
3014 
3015 	for_each_iommu(iommu)
3016 		amd_iommu_enable_ppr_log(iommu);
3017 }
3018 
3019 static void enable_iommus_vapic(void)
3020 {
3021 #ifdef CONFIG_IRQ_REMAP
3022 	u32 status, i;
3023 	struct amd_iommu *iommu;
3024 
3025 	for_each_iommu(iommu) {
3026 		/*
3027 		 * Disable GALog if already running. It could have been enabled
3028 		 * in the previous boot before kdump.
3029 		 */
3030 		status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
3031 		if (!(status & MMIO_STATUS_GALOG_RUN_MASK))
3032 			continue;
3033 
3034 		iommu_feature_disable(iommu, CONTROL_GALOG_EN);
3035 		iommu_feature_disable(iommu, CONTROL_GAINT_EN);
3036 
3037 		/*
3038 		 * Need to set and poll check the GALOGRun bit to zero before
3039 		 * we can set/ modify GA Log registers safely.
3040 		 */
3041 		for (i = 0; i < MMIO_STATUS_TIMEOUT; ++i) {
3042 			status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
3043 			if (!(status & MMIO_STATUS_GALOG_RUN_MASK))
3044 				break;
3045 			udelay(10);
3046 		}
3047 
3048 		if (WARN_ON(i >= MMIO_STATUS_TIMEOUT))
3049 			return;
3050 	}
3051 
3052 	if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir))
3053 		return;
3054 
3055 	/* Enabling GAM and SNPAVIC support */
3056 	for_each_iommu(iommu) {
3057 		if (!iommu_ga_log_enable(iommu))
3058 			return;
3059 
3060 		iommu_feature_enable(iommu, CONTROL_GAM_EN);
3061 		if (amd_iommu_snp_en)
3062 			iommu_feature_enable(iommu, CONTROL_SNPAVIC_EN);
3063 	}
3064 
3065 	amd_iommu_irq_ops.capability |= (1 << IRQ_POSTING_CAP);
3066 	pr_info("Virtual APIC enabled\n");
3067 #endif
3068 }
3069 
3070 static int clear_perfopt_all(void)
3071 {
3072 	struct amd_iommu *iommu;
3073 	int err, ret = 0;
3074 
3075 	for_each_iommu(iommu) {
3076 		err = amd_iommu_perfopt_clear(iommu);
3077 		if (err)
3078 			ret = err;
3079 	}
3080 
3081 	return ret;
3082 }
3083 
3084 static int restore_perfopt_all(void)
3085 {
3086 	struct amd_iommu *iommu;
3087 	int err, ret = 0;
3088 
3089 	for_each_iommu(iommu) {
3090 		err = amd_iommu_perfopt_restore(iommu);
3091 		if (err)
3092 			ret = err;
3093 	}
3094 
3095 	return ret;
3096 }
3097 
3098 static void disable_iommus(void)
3099 {
3100 	struct amd_iommu *iommu;
3101 
3102 	/*
3103 	 * PerfOpt is an optional performance bit, so a failure to clear it must
3104 	 * not skip the mandatory disable below. This also runs from the void
3105 	 * amd_iommu_disable() shutdown/kexec path, which cannot report an error.
3106 	 */
3107 	if (clear_perfopt_all())
3108 		pr_err("Failed to clear PerfOpt while disabling IOMMUs\n");
3109 
3110 	for_each_iommu(iommu)
3111 		iommu_disable(iommu);
3112 
3113 #ifdef CONFIG_IRQ_REMAP
3114 	if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir))
3115 		amd_iommu_irq_ops.capability &= ~(1 << IRQ_POSTING_CAP);
3116 #endif
3117 }
3118 
3119 /*
3120  * Suspend/Resume support
3121  * disable suspend until real resume implemented
3122  */
3123 
3124 static void amd_iommu_resume(void *data)
3125 {
3126 	struct amd_iommu *iommu;
3127 
3128 	for_each_iommu(iommu)
3129 		iommu_apply_resume_quirks(iommu);
3130 
3131 	/* re-load the hardware */
3132 	for_each_iommu(iommu)
3133 		early_enable_iommu(iommu);
3134 
3135 	/* early_enable_iommu() cleared PERF_OPT_EN; re-assert it from the refcount. */
3136 	if (restore_perfopt_all())
3137 		pr_err("Failed to restore PerfOpt after IOMMU resume\n");
3138 
3139 	iommu_enable_event_buffer();
3140 	amd_iommu_enable_interrupts();
3141 }
3142 
3143 static int amd_iommu_suspend(void *data)
3144 {
3145 	/* disable IOMMUs to go out of the way for BIOS */
3146 	disable_iommus();
3147 
3148 	return 0;
3149 }
3150 
3151 static const struct syscore_ops amd_iommu_syscore_ops = {
3152 	.suspend = amd_iommu_suspend,
3153 	.resume = amd_iommu_resume,
3154 };
3155 
3156 static struct syscore amd_iommu_syscore = {
3157 	.ops = &amd_iommu_syscore_ops,
3158 };
3159 
3160 static void __init free_iommu_resources(void)
3161 {
3162 	free_iommu_all();
3163 	free_pci_segments();
3164 }
3165 
3166 static bool __init check_sb_ioapic(int devid)
3167 {
3168 	u8 bus = PCI_BUS_NUM(devid);
3169 	u8 devfn = devid & 0xff;
3170 	u16 val;
3171 
3172 	val = read_pci_config_16(bus, PCI_SLOT(devfn), PCI_FUNC(devfn),
3173 				 PCI_CLASS_DEVICE);
3174 
3175 	/*
3176 	 * The SB IOAPIC is integrated into the FCH (Southbridge), which is
3177 	 * exposed as an SMBus or ISA bridge in PCI config space.
3178 	 */
3179 	return val == PCI_CLASS_SERIAL_SMBUS || val == PCI_CLASS_BRIDGE_ISA;
3180 }
3181 
3182 /*
3183  * The Southbridge IOAPIC is assigned a GSI Base of 0 (handling interrupts
3184  * 0 through 23).
3185  */
3186 static int __init get_sb_ioapic_id(void)
3187 {
3188 	int idx = mp_find_ioapic(0);
3189 
3190 	if (idx < 0)
3191 		return -ENODEV;
3192 
3193 	return mpc_ioapic_id(idx);
3194 }
3195 
3196 static bool __init check_ioapic_information(void)
3197 {
3198 	const char *fw_bug = FW_BUG;
3199 	bool ret, has_sb_ioapic;
3200 	int idx, sb_apicid;
3201 
3202 	has_sb_ioapic = false;
3203 	ret           = true;
3204 
3205 	/*
3206 	 * If we have map overrides on the kernel command line the
3207 	 * messages in this function might not describe firmware bugs
3208 	 * anymore - so be careful
3209 	 */
3210 	if (cmdline_maps)
3211 		fw_bug = "";
3212 
3213 	sb_apicid = get_sb_ioapic_id();
3214 	if (sb_apicid < 0) {
3215 		/*
3216 		 * Lack of SB IOAPIC registration is not a firmware bug,
3217 		 * e.g. kernel booted with noapic or noacpi.
3218 		 */
3219 		fw_bug = "";
3220 		goto out;
3221 	}
3222 
3223 	for (idx = 0; idx < nr_ioapics; idx++) {
3224 		int devid, id = mpc_ioapic_id(idx);
3225 
3226 		devid = get_ioapic_devid(id);
3227 		if (devid < 0) {
3228 			pr_err("%s: IOAPIC[%d] not in IVRS table\n",
3229 				fw_bug, id);
3230 			ret = false;
3231 		} else if (id == sb_apicid && check_sb_ioapic(devid)) {
3232 			has_sb_ioapic = true;
3233 		}
3234 	}
3235 out:
3236 	if (!has_sb_ioapic) {
3237 		/*
3238 		 * We expect the SB IOAPIC to be listed in the IVRS
3239 		 * table. The system timer is connected to the SB IOAPIC
3240 		 * and if we don't have it in the list the system will
3241 		 * panic at boot time.  This situation usually happens
3242 		 * when the BIOS is buggy and provides us the wrong
3243 		 * device id for the IOAPIC in the system.
3244 		 */
3245 		pr_err("%s: No southbridge IOAPIC found\n", fw_bug);
3246 		ret = false;
3247 	}
3248 
3249 	if (!ret)
3250 		pr_err("Disabling interrupt remapping\n");
3251 
3252 	return ret;
3253 }
3254 
3255 static void __init free_dma_resources(void)
3256 {
3257 	amd_iommu_pdom_id_destroy();
3258 	free_unity_maps();
3259 }
3260 
3261 static void __init ivinfo_init(void *ivrs)
3262 {
3263 	amd_iommu_ivinfo = *((u32 *)(ivrs + IOMMU_IVINFO_OFFSET));
3264 }
3265 
3266 /*
3267  * This is the hardware init function for AMD IOMMU in the system.
3268  * This function is called either from amd_iommu_init or from the interrupt
3269  * remapping setup code.
3270  *
3271  * This function basically parses the ACPI table for AMD IOMMU (IVRS)
3272  * four times:
3273  *
3274  *	1 pass) Discover the most comprehensive IVHD type to use.
3275  *
3276  *	2 pass) Find the highest PCI device id the driver has to handle.
3277  *		Upon this information the size of the data structures is
3278  *		determined that needs to be allocated.
3279  *
3280  *	3 pass) Initialize the data structures just allocated with the
3281  *		information in the ACPI table about available AMD IOMMUs
3282  *		in the system. It also maps the PCI devices in the
3283  *		system to specific IOMMUs
3284  *
3285  *	4 pass) After the basic data structures are allocated and
3286  *		initialized we update them with information about memory
3287  *		remapping requirements parsed out of the ACPI table in
3288  *		this last pass.
3289  *
3290  * After everything is set up the IOMMUs are enabled and the necessary
3291  * hotplug and suspend notifiers are registered.
3292  */
3293 static int __init early_amd_iommu_init(void)
3294 {
3295 	struct acpi_table_header *ivrs_base;
3296 	int ret;
3297 	acpi_status status;
3298 	u8 efr_hats, max_vasize;
3299 
3300 	status = acpi_get_table("IVRS", 0, &ivrs_base);
3301 	if (status == AE_NOT_FOUND)
3302 		return -ENODEV;
3303 	else if (ACPI_FAILURE(status)) {
3304 		const char *err = acpi_format_exception(status);
3305 		pr_err("IVRS table error: %s\n", err);
3306 		return -EINVAL;
3307 	}
3308 
3309 	if (!boot_cpu_has(X86_FEATURE_CX16)) {
3310 		pr_err("Failed to initialize. The CMPXCHG16B feature is required.\n");
3311 		ret = -EINVAL;
3312 		goto out;
3313 	}
3314 
3315 	/*
3316 	 * Validate checksum here so we don't need to do it when
3317 	 * we actually parse the table
3318 	 */
3319 	ret = check_ivrs_checksum(ivrs_base);
3320 	if (ret)
3321 		goto out;
3322 
3323 	ivinfo_init(ivrs_base);
3324 
3325 	max_vasize = FIELD_GET(IOMMU_IVINFO_VASIZE, amd_iommu_ivinfo);
3326 	if (!max_vasize)
3327 		max_vasize = 64;
3328 
3329 	amd_iommu_target_ivhd_type = get_highest_supported_ivhd_type(ivrs_base);
3330 	DUMP_printk("Using IVHD type %#x\n", amd_iommu_target_ivhd_type);
3331 
3332 	/*
3333 	 * now the data structures are allocated and basically initialized
3334 	 * start the real acpi table scan
3335 	 */
3336 	ret = init_iommu_all(ivrs_base);
3337 	if (ret)
3338 		goto out;
3339 
3340 	/* 5 level guest page table */
3341 	if (cpu_feature_enabled(X86_FEATURE_LA57) &&
3342 	    FIELD_GET(FEATURE_GATS, amd_iommu_efr) == GUEST_PGTABLE_5_LEVEL)
3343 		amd_iommu_gpt_level = PAGE_MODE_5_LEVEL;
3344 
3345 	efr_hats = FIELD_GET(FEATURE_HATS, amd_iommu_efr);
3346 	if (efr_hats != 0x3) {
3347 		/*
3348 		 * efr[HATS] bits specify the maximum host translation level
3349 		 * supported, with LEVEL 4 being initial max level.
3350 		 */
3351 		amd_iommu_hpt_vasize = min_t(unsigned int, max_vasize,
3352 					 (efr_hats + PAGE_MODE_4_LEVEL - 1) * 9 + 21);
3353 	} else {
3354 		pr_warn_once(FW_BUG "Disable host address translation due to invalid translation level (%#x).\n",
3355 			     efr_hats);
3356 		amd_iommu_hatdis = true;
3357 	}
3358 
3359 	if (amd_iommu_pgtable == PD_MODE_V2) {
3360 		if (!amd_iommu_v2_pgtbl_supported()) {
3361 			pr_warn("Cannot enable v2 page table for DMA-API. Fallback to v1.\n");
3362 			amd_iommu_pgtable = PD_MODE_V1;
3363 		}
3364 	}
3365 
3366 	if (amd_iommu_hatdis) {
3367 		/*
3368 		 * Host (v1) page table is not available. Attempt to use
3369 		 * Guest (v2) page table.
3370 		 */
3371 		if (amd_iommu_v2_pgtbl_supported())
3372 			amd_iommu_pgtable = PD_MODE_V2;
3373 		else
3374 			amd_iommu_pgtable = PD_MODE_NONE;
3375 	}
3376 
3377 	/* Disable any previously enabled IOMMUs */
3378 	if (!is_kdump_kernel())
3379 		disable_iommus();
3380 
3381 	if (amd_iommu_irq_remap)
3382 		amd_iommu_irq_remap = check_ioapic_information();
3383 
3384 	if (amd_iommu_irq_remap) {
3385 		struct amd_iommu_pci_seg *pci_seg;
3386 		ret = -ENOMEM;
3387 		for_each_pci_segment(pci_seg) {
3388 			if (alloc_irq_lookup_table(pci_seg))
3389 				goto out;
3390 		}
3391 	}
3392 
3393 	ret = init_memory_definitions(ivrs_base);
3394 	if (ret)
3395 		goto out;
3396 
3397 	/* init the device table */
3398 	init_device_table();
3399 
3400 out:
3401 	/* Don't leak any ACPI memory */
3402 	acpi_put_table(ivrs_base);
3403 
3404 	return ret;
3405 }
3406 
3407 static int amd_iommu_enable_interrupts(void)
3408 {
3409 	struct amd_iommu *iommu;
3410 	int ret = 0;
3411 
3412 	for_each_iommu(iommu) {
3413 		ret = iommu_init_irq(iommu);
3414 		if (ret)
3415 			goto out;
3416 	}
3417 
3418 	/*
3419 	 * Interrupt handler is ready to process interrupts. Enable
3420 	 * PPR and GA log interrupt for all IOMMUs.
3421 	 */
3422 	enable_iommus_vapic();
3423 	enable_iommus_ppr();
3424 
3425 out:
3426 	return ret;
3427 }
3428 
3429 static bool __init detect_ivrs(void)
3430 {
3431 	struct acpi_table_header *ivrs_base;
3432 	acpi_status status;
3433 	int i;
3434 
3435 	status = acpi_get_table("IVRS", 0, &ivrs_base);
3436 	if (status == AE_NOT_FOUND)
3437 		return false;
3438 	else if (ACPI_FAILURE(status)) {
3439 		const char *err = acpi_format_exception(status);
3440 		pr_err("IVRS table error: %s\n", err);
3441 		return false;
3442 	}
3443 
3444 	acpi_put_table(ivrs_base);
3445 
3446 	if (amd_iommu_force_enable)
3447 		goto out;
3448 
3449 	/* Don't use IOMMU if there is Stoney Ridge graphics */
3450 	for (i = 0; i < 32; i++) {
3451 		u32 pci_id;
3452 
3453 		pci_id = read_pci_config(0, i, 0, 0);
3454 		if ((pci_id & 0xffff) == 0x1002 && (pci_id >> 16) == 0x98e4) {
3455 			pr_info("Disable IOMMU on Stoney Ridge\n");
3456 			return false;
3457 		}
3458 	}
3459 
3460 out:
3461 	/* Make sure ACS will be enabled during PCI probe */
3462 	pci_request_acs();
3463 
3464 	return true;
3465 }
3466 
3467 static __init void iommu_snp_enable(void)
3468 {
3469 #ifdef CONFIG_KVM_AMD_SEV
3470 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
3471 		return;
3472 
3473 	amd_iommu_snp_mode0_sup = check_feature2(FEATURE_SNP_PAGE_MODE0_SUP);
3474 	/*
3475 	 * If SNP page mode 0 is not enabled, then SNP support requires that IOMMU
3476 	 * must be configured with V1 page table (DTE[Mode] != 0).
3477 	 */
3478 	if (!amd_iommu_snp_mode0_sup) {
3479 		if (iommu_default_passthrough()) {
3480 			pr_warn("SNP: IOMMU configured in passthrough mode, SNP cannot be supported.\n");
3481 			goto disable_snp;
3482 		}
3483 
3484 		if (amd_iommu_pgtable != PD_MODE_V1) {
3485 			pr_warn("SNP: IOMMU is configured with V2 page table mode, SNP cannot be supported.\n");
3486 			goto disable_snp;
3487 		}
3488 	}
3489 
3490 	amd_iommu_snp_en = check_feature(FEATURE_SNP);
3491 	if (!amd_iommu_snp_en) {
3492 		pr_warn("SNP: IOMMU SNP feature not enabled, SNP cannot be supported.\n");
3493 		goto disable_snp;
3494 	}
3495 
3496 	/*
3497 	 * Enable host SNP support once SNP support is checked on IOMMU.
3498 	 */
3499 	if (snp_rmptable_init()) {
3500 		pr_warn("SNP: RMP initialization failed, SNP cannot be supported.\n");
3501 		goto disable_snp;
3502 	}
3503 
3504 	pr_info("IOMMU SNP support enabled.\n");
3505 	return;
3506 
3507 disable_snp:
3508 	cc_platform_clear(CC_ATTR_HOST_SEV_SNP);
3509 #endif
3510 }
3511 
3512 static void amd_iommu_apply_erratum_snp(void)
3513 {
3514 #ifdef CONFIG_KVM_AMD_SEV
3515 	if (!amd_iommu_snp_en)
3516 		return;
3517 
3518 	/* Errata fix for Family 0x19 */
3519 	if (boot_cpu_data.x86 != 0x19)
3520 		return;
3521 
3522 	/* Set event log buffer size to max */
3523 	amd_iommu_evtlog_size = EVTLOG_SIZE_MAX;
3524 	pr_info("Applying erratum: Increase Event log size to 0x%x\n",
3525 		amd_iommu_evtlog_size);
3526 
3527 	/*
3528 	 * Set PPR log buffer size to max.
3529 	 * (Family 0x19, model < 0x10 doesn't support PPR when SNP is enabled).
3530 	 */
3531 	if (boot_cpu_data.x86_model >= 0x10) {
3532 		amd_iommu_pprlog_size = PPRLOG_SIZE_MAX;
3533 		pr_info("Applying erratum: Increase PPR log size to 0x%x\n",
3534 			amd_iommu_pprlog_size);
3535 	}
3536 #endif
3537 }
3538 
3539 static bool amd_iommu_sme_check(void);
3540 
3541 /****************************************************************************
3542  *
3543  * AMD IOMMU Initialization State Machine
3544  *
3545  ****************************************************************************/
3546 
3547 static int __init state_next(void)
3548 {
3549 	int ret = 0;
3550 
3551 	switch (init_state) {
3552 	case IOMMU_START_STATE:
3553 		if (no_iommu || amd_iommu_disabled) {
3554 			init_state	= IOMMU_CMDLINE_DISABLED;
3555 			ret		= -EINVAL;
3556 		} else if (!amd_iommu_sme_check()) {
3557 			init_state	= IOMMU_INIT_ERROR;
3558 			ret		= -EINVAL;
3559 		} else if (!detect_ivrs()) {
3560 			init_state	= IOMMU_NOT_FOUND;
3561 			ret		= -ENODEV;
3562 		} else {
3563 			init_state	= IOMMU_IVRS_DETECTED;
3564 		}
3565 		break;
3566 	case IOMMU_IVRS_DETECTED:
3567 		ret = early_amd_iommu_init();
3568 		init_state = ret ? IOMMU_INIT_ERROR : IOMMU_ACPI_FINISHED;
3569 		break;
3570 	case IOMMU_ACPI_FINISHED:
3571 		early_enable_iommus();
3572 		x86_platform.iommu_shutdown = disable_iommus;
3573 		init_state = IOMMU_ENABLED;
3574 		break;
3575 	case IOMMU_ENABLED:
3576 		register_syscore(&amd_iommu_syscore);
3577 		iommu_snp_enable();
3578 
3579 		amd_iommu_apply_erratum_snp();
3580 
3581 		/* Allocate/enable event log buffer */
3582 		if (is_kdump_kernel())
3583 			ret = remap_event_buffer();
3584 		else
3585 			ret = alloc_event_buffer();
3586 
3587 		if (ret) {
3588 			init_state = IOMMU_INIT_ERROR;
3589 			break;
3590 		}
3591 		iommu_enable_event_buffer();
3592 
3593 		ret = amd_iommu_init_pci();
3594 		init_state = ret ? IOMMU_INIT_ERROR : IOMMU_PCI_INIT;
3595 		break;
3596 	case IOMMU_PCI_INIT:
3597 		ret = amd_iommu_enable_interrupts();
3598 		init_state = ret ? IOMMU_INIT_ERROR : IOMMU_INTERRUPTS_EN;
3599 		break;
3600 	case IOMMU_INTERRUPTS_EN:
3601 		init_state = IOMMU_INITIALIZED;
3602 		break;
3603 	case IOMMU_INITIALIZED:
3604 		/* Nothing to do */
3605 		break;
3606 	case IOMMU_NOT_FOUND:
3607 	case IOMMU_INIT_ERROR:
3608 	case IOMMU_CMDLINE_DISABLED:
3609 		/* Error states => do nothing */
3610 		ret = -EINVAL;
3611 		break;
3612 	default:
3613 		/* Unknown state */
3614 		BUG();
3615 	}
3616 
3617 	if (ret) {
3618 		free_dma_resources();
3619 		if (!irq_remapping_enabled) {
3620 			disable_iommus();
3621 			free_iommu_resources();
3622 		} else {
3623 			struct amd_iommu *iommu;
3624 			struct amd_iommu_pci_seg *pci_seg;
3625 
3626 			for_each_pci_segment(pci_seg)
3627 				uninit_device_table_dma(pci_seg);
3628 
3629 			for_each_iommu(iommu)
3630 				amd_iommu_flush_all_caches(iommu);
3631 		}
3632 	}
3633 	return ret;
3634 }
3635 
3636 static int __init iommu_go_to_state(enum iommu_init_state state)
3637 {
3638 	int ret = -EINVAL;
3639 
3640 	/*
3641 	 * Some essential housekeeping work is done by amd_iommu_detect().
3642 	 * Skipping calling it implies that the platform (e.g., Xen hypervisor)
3643 	 * has taken over the hardware. Progressing the state machine in this
3644 	 * case is worthless and fragile.
3645 	 *
3646 	 * There are several paths requesting later states, so disallow implicit
3647 	 * START_STATE => IVRS_DETECTED transition to prevent these paths from
3648 	 * accidentally progressing the state machine.
3649 	 */
3650 	if (init_state == IOMMU_START_STATE && state != IOMMU_IVRS_DETECTED)
3651 		goto out;
3652 
3653 	while (init_state != state) {
3654 		if (init_state == IOMMU_NOT_FOUND         ||
3655 		    init_state == IOMMU_INIT_ERROR        ||
3656 		    init_state == IOMMU_CMDLINE_DISABLED)
3657 			break;
3658 		ret = state_next();
3659 	}
3660 
3661 out:
3662 	/*
3663 	 * SNP platform initilazation requires IOMMUs to be fully configured.
3664 	 * If the SNP support on IOMMUs has NOT been checked, simply mark SNP
3665 	 * as unsupported. If the SNP support on IOMMUs has been checked and
3666 	 * host SNP support enabled but RMP enforcement has not been enabled
3667 	 * in IOMMUs, then the system is in a half-baked state, but can limp
3668 	 * along as all memory should be Hypervisor-Owned in the RMP. WARN,
3669 	 * but leave SNP as "supported" to avoid confusing the kernel.
3670 	 */
3671 	if (ret && cc_platform_has(CC_ATTR_HOST_SEV_SNP) &&
3672 	    !WARN_ON_ONCE(amd_iommu_snp_en))
3673 		cc_platform_clear(CC_ATTR_HOST_SEV_SNP);
3674 
3675 	return ret;
3676 }
3677 
3678 #ifdef CONFIG_IRQ_REMAP
3679 int __init amd_iommu_prepare(void)
3680 {
3681 	int ret;
3682 
3683 	amd_iommu_irq_remap = true;
3684 
3685 	ret = iommu_go_to_state(IOMMU_ACPI_FINISHED);
3686 	if (ret) {
3687 		amd_iommu_irq_remap = false;
3688 		return ret;
3689 	}
3690 
3691 	return amd_iommu_irq_remap ? 0 : -ENODEV;
3692 }
3693 
3694 int __init amd_iommu_enable(void)
3695 {
3696 	int ret;
3697 
3698 	ret = iommu_go_to_state(IOMMU_ENABLED);
3699 	if (ret)
3700 		return ret;
3701 
3702 	irq_remapping_enabled = 1;
3703 	return amd_iommu_xt_mode;
3704 }
3705 
3706 void amd_iommu_disable(void)
3707 {
3708 	amd_iommu_suspend(NULL);
3709 }
3710 
3711 int amd_iommu_reenable(int mode)
3712 {
3713 	amd_iommu_resume(NULL);
3714 
3715 	return 0;
3716 }
3717 
3718 int amd_iommu_enable_faulting(unsigned int cpu)
3719 {
3720 	/* We enable MSI later when PCI is initialized */
3721 	return 0;
3722 }
3723 #endif
3724 
3725 /*
3726  * This is the core init function for AMD IOMMU hardware in the system.
3727  * This function is called from the generic x86 DMA layer initialization
3728  * code.
3729  */
3730 static int __init amd_iommu_init(void)
3731 {
3732 	int ret;
3733 
3734 	ret = iommu_go_to_state(IOMMU_INITIALIZED);
3735 #ifdef CONFIG_GART_IOMMU
3736 	if (ret && list_empty(&amd_iommu_list)) {
3737 		/*
3738 		 * We failed to initialize the AMD IOMMU - try fallback
3739 		 * to GART if possible.
3740 		 */
3741 		gart_iommu_init();
3742 	}
3743 #endif
3744 
3745 	if (!ret)
3746 		amd_iommu_debugfs_setup();
3747 
3748 	return ret;
3749 }
3750 
3751 static bool amd_iommu_sme_check(void)
3752 {
3753 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT) ||
3754 	    (boot_cpu_data.x86 != 0x17))
3755 		return true;
3756 
3757 	/* For Fam17h, a specific level of support is required */
3758 	if (boot_cpu_data.microcode >= 0x08001205)
3759 		return true;
3760 
3761 	if ((boot_cpu_data.microcode >= 0x08001126) &&
3762 	    (boot_cpu_data.microcode <= 0x080011ff))
3763 		return true;
3764 
3765 	pr_notice("IOMMU not currently supported when SME is active\n");
3766 
3767 	return false;
3768 }
3769 
3770 /****************************************************************************
3771  *
3772  * Early detect code. This code runs at IOMMU detection time in the DMA
3773  * layer. It just looks if there is an IVRS ACPI table to detect AMD
3774  * IOMMUs
3775  *
3776  ****************************************************************************/
3777 void __init amd_iommu_detect(void)
3778 {
3779 	int ret;
3780 
3781 	ret = iommu_go_to_state(IOMMU_IVRS_DETECTED);
3782 	if (ret)
3783 		goto disable_snp;
3784 
3785 	iommu_detected = 1;
3786 	x86_init.iommu.iommu_init = amd_iommu_init;
3787 	return;
3788 
3789 disable_snp:
3790 	if (cc_platform_has(CC_ATTR_HOST_SEV_SNP))
3791 		cc_platform_clear(CC_ATTR_HOST_SEV_SNP);
3792 }
3793 
3794 /****************************************************************************
3795  *
3796  * Parsing functions for the AMD IOMMU specific kernel command line
3797  * options.
3798  *
3799  ****************************************************************************/
3800 
3801 static int __init parse_amd_iommu_dump(char *str)
3802 {
3803 	amd_iommu_dump = true;
3804 
3805 	return 1;
3806 }
3807 
3808 static int __init parse_amd_iommu_intr(char *str)
3809 {
3810 	for (; *str; ++str) {
3811 		if (strncmp(str, "legacy", 6) == 0) {
3812 			amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_LEGACY_GA;
3813 			break;
3814 		}
3815 		if (strncmp(str, "vapic", 5) == 0) {
3816 			amd_iommu_guest_ir = AMD_IOMMU_GUEST_IR_VAPIC;
3817 			break;
3818 		}
3819 	}
3820 	return 1;
3821 }
3822 
3823 static int __init parse_amd_iommu_options(char *str)
3824 {
3825 	if (!str)
3826 		return -EINVAL;
3827 
3828 	while (*str) {
3829 		if (strncmp(str, "fullflush", 9) == 0) {
3830 			pr_warn("amd_iommu=fullflush deprecated; use iommu.strict=1 instead\n");
3831 			iommu_set_dma_strict();
3832 		} else if (strncmp(str, "force_enable", 12) == 0) {
3833 			amd_iommu_force_enable = true;
3834 		} else if (strncmp(str, "off", 3) == 0) {
3835 			amd_iommu_disabled = true;
3836 		} else if (strncmp(str, "force_isolation", 15) == 0) {
3837 			amd_iommu_force_isolation = true;
3838 		} else if (strncmp(str, "pgtbl_v1", 8) == 0) {
3839 			amd_iommu_pgtable = PD_MODE_V1;
3840 		} else if (strncmp(str, "pgtbl_v2", 8) == 0) {
3841 			amd_iommu_pgtable = PD_MODE_V2;
3842 		} else if (strncmp(str, "irtcachedis", 11) == 0) {
3843 			amd_iommu_irtcachedis = true;
3844 		} else if (strncmp(str, "nohugepages", 11) == 0) {
3845 			pr_info("Restricting V1 page-sizes to 4KiB");
3846 			amd_iommu_pgsize_bitmap = AMD_IOMMU_PGSIZES_4K;
3847 		} else if (strncmp(str, "v2_pgsizes_only", 15) == 0) {
3848 			pr_info("Restricting V1 page-sizes to 4KiB/2MiB/1GiB");
3849 			amd_iommu_pgsize_bitmap = AMD_IOMMU_PGSIZES_V2;
3850 		} else {
3851 			pr_notice("Unknown option - '%s'\n", str);
3852 		}
3853 
3854 		str += strcspn(str, ",");
3855 		while (*str == ',')
3856 			str++;
3857 	}
3858 
3859 	return 1;
3860 }
3861 
3862 static int __init parse_ivrs_ioapic(char *str)
3863 {
3864 	u32 seg = 0, bus, dev, fn;
3865 	int id, i;
3866 	u32 devid;
3867 
3868 	if (sscanf(str, "=%d@%x:%x.%x", &id, &bus, &dev, &fn) == 4 ||
3869 	    sscanf(str, "=%d@%x:%x:%x.%x", &id, &seg, &bus, &dev, &fn) == 5)
3870 		goto found;
3871 
3872 	if (sscanf(str, "[%d]=%x:%x.%x", &id, &bus, &dev, &fn) == 4 ||
3873 	    sscanf(str, "[%d]=%x:%x:%x.%x", &id, &seg, &bus, &dev, &fn) == 5) {
3874 		pr_warn("ivrs_ioapic%s option format deprecated; use ivrs_ioapic=%d@%04x:%02x:%02x.%d instead\n",
3875 			str, id, seg, bus, dev, fn);
3876 		goto found;
3877 	}
3878 
3879 	pr_err("Invalid command line: ivrs_ioapic%s\n", str);
3880 	return 1;
3881 
3882 found:
3883 	if (early_ioapic_map_size == EARLY_MAP_SIZE) {
3884 		pr_err("Early IOAPIC map overflow - ignoring ivrs_ioapic%s\n",
3885 			str);
3886 		return 1;
3887 	}
3888 
3889 	devid = IVRS_GET_SBDF_ID(seg, bus, dev, fn);
3890 
3891 	cmdline_maps			= true;
3892 	i				= early_ioapic_map_size++;
3893 	early_ioapic_map[i].id		= id;
3894 	early_ioapic_map[i].devid	= devid;
3895 	early_ioapic_map[i].cmd_line	= true;
3896 
3897 	return 1;
3898 }
3899 
3900 static int __init parse_ivrs_hpet(char *str)
3901 {
3902 	u32 seg = 0, bus, dev, fn;
3903 	int id, i;
3904 	u32 devid;
3905 
3906 	if (sscanf(str, "=%d@%x:%x.%x", &id, &bus, &dev, &fn) == 4 ||
3907 	    sscanf(str, "=%d@%x:%x:%x.%x", &id, &seg, &bus, &dev, &fn) == 5)
3908 		goto found;
3909 
3910 	if (sscanf(str, "[%d]=%x:%x.%x", &id, &bus, &dev, &fn) == 4 ||
3911 	    sscanf(str, "[%d]=%x:%x:%x.%x", &id, &seg, &bus, &dev, &fn) == 5) {
3912 		pr_warn("ivrs_hpet%s option format deprecated; use ivrs_hpet=%d@%04x:%02x:%02x.%d instead\n",
3913 			str, id, seg, bus, dev, fn);
3914 		goto found;
3915 	}
3916 
3917 	pr_err("Invalid command line: ivrs_hpet%s\n", str);
3918 	return 1;
3919 
3920 found:
3921 	if (early_hpet_map_size == EARLY_MAP_SIZE) {
3922 		pr_err("Early HPET map overflow - ignoring ivrs_hpet%s\n",
3923 			str);
3924 		return 1;
3925 	}
3926 
3927 	devid = IVRS_GET_SBDF_ID(seg, bus, dev, fn);
3928 
3929 	cmdline_maps			= true;
3930 	i				= early_hpet_map_size++;
3931 	early_hpet_map[i].id		= id;
3932 	early_hpet_map[i].devid		= devid;
3933 	early_hpet_map[i].cmd_line	= true;
3934 
3935 	return 1;
3936 }
3937 
3938 #define ACPIID_LEN (ACPIHID_UID_LEN + ACPIHID_HID_LEN)
3939 
3940 static int __init parse_ivrs_acpihid(char *str)
3941 {
3942 	u32 seg = 0, bus, dev, fn;
3943 	char *hid, *uid, *p, *addr;
3944 	char acpiid[ACPIID_LEN + 1] = { }; /* size with NULL terminator */
3945 	int i;
3946 
3947 	addr = strchr(str, '@');
3948 	if (!addr) {
3949 		addr = strchr(str, '=');
3950 		if (!addr)
3951 			goto not_found;
3952 
3953 		++addr;
3954 
3955 		if (strlen(addr) > ACPIID_LEN)
3956 			goto not_found;
3957 
3958 		if (sscanf(str, "[%x:%x.%x]=%s", &bus, &dev, &fn, acpiid) == 4 ||
3959 		    sscanf(str, "[%x:%x:%x.%x]=%s", &seg, &bus, &dev, &fn, acpiid) == 5) {
3960 			pr_warn("ivrs_acpihid%s option format deprecated; use ivrs_acpihid=%s@%04x:%02x:%02x.%d instead\n",
3961 				str, acpiid, seg, bus, dev, fn);
3962 			goto found;
3963 		}
3964 		goto not_found;
3965 	}
3966 
3967 	/* We have the '@', make it the terminator to get just the acpiid */
3968 	*addr++ = 0;
3969 
3970 	if (strlen(str) > ACPIID_LEN)
3971 		goto not_found;
3972 
3973 	if (sscanf(str, "=%s", acpiid) != 1)
3974 		goto not_found;
3975 
3976 	if (sscanf(addr, "%x:%x.%x", &bus, &dev, &fn) == 3 ||
3977 	    sscanf(addr, "%x:%x:%x.%x", &seg, &bus, &dev, &fn) == 4)
3978 		goto found;
3979 
3980 not_found:
3981 	pr_err("Invalid command line: ivrs_acpihid%s\n", str);
3982 	return 1;
3983 
3984 found:
3985 	if (early_acpihid_map_size == EARLY_MAP_SIZE) {
3986 		pr_err("Early ACPI HID map overflow - ignoring ivrs_acpihid%s\n",
3987 		       str);
3988 		return 1;
3989 	}
3990 
3991 	p = acpiid;
3992 	hid = strsep(&p, ":");
3993 	uid = p;
3994 
3995 	if (!hid || !(*hid) || !uid) {
3996 		pr_err("Invalid command line: hid or uid\n");
3997 		return 1;
3998 	}
3999 
4000 	/*
4001 	 * Ignore leading zeroes after ':', so e.g., AMDI0095:00
4002 	 * will match AMDI0095:0 in the second strcmp in acpi_dev_hid_uid_match
4003 	 */
4004 	while (*uid == '0' && *(uid + 1))
4005 		uid++;
4006 
4007 	if (strlen(hid) >= ACPIHID_HID_LEN) {
4008 		pr_err("Invalid command line: hid is too long\n");
4009 		return 1;
4010 	} else if (strlen(uid) >= ACPIHID_UID_LEN) {
4011 		pr_err("Invalid command line: uid is too long\n");
4012 		return 1;
4013 	}
4014 
4015 	i = early_acpihid_map_size++;
4016 	memcpy(early_acpihid_map[i].hid, hid, strlen(hid));
4017 	memcpy(early_acpihid_map[i].uid, uid, strlen(uid));
4018 	early_acpihid_map[i].devid = IVRS_GET_SBDF_ID(seg, bus, dev, fn);
4019 	early_acpihid_map[i].cmd_line	= true;
4020 
4021 	return 1;
4022 }
4023 
4024 __setup("amd_iommu_dump",	parse_amd_iommu_dump);
4025 __setup("amd_iommu=",		parse_amd_iommu_options);
4026 __setup("amd_iommu_intr=",	parse_amd_iommu_intr);
4027 __setup("ivrs_ioapic",		parse_ivrs_ioapic);
4028 __setup("ivrs_hpet",		parse_ivrs_hpet);
4029 __setup("ivrs_acpihid",		parse_ivrs_acpihid);
4030 
4031 bool amd_iommu_pasid_supported(void)
4032 {
4033 	/* CPU page table size should match IOMMU guest page table size */
4034 	if (cpu_feature_enabled(X86_FEATURE_LA57) &&
4035 	    amd_iommu_gpt_level != PAGE_MODE_5_LEVEL)
4036 		return false;
4037 
4038 	if (!amd_iommu_gt_ppr_supported())
4039 		return false;
4040 
4041 	/*
4042 	 * If SNP page mode 0 is not supported, then DTE[Mode]=0 is prohibited
4043 	 * on SNP-enabled system (i.e. EFR[SNPSup]=1). IOMMUv2 page table
4044 	 * cannot be used without setting up IOMMUv1 page table.
4045 	 */
4046 	return (!amd_iommu_snp_en) || (amd_iommu_snp_en && amd_iommu_snp_mode0_sup);
4047 }
4048 
4049 struct amd_iommu *get_amd_iommu(unsigned int idx)
4050 {
4051 	unsigned int i = 0;
4052 	struct amd_iommu *iommu;
4053 
4054 	for_each_iommu(iommu)
4055 		if (i++ == idx)
4056 			return iommu;
4057 	return NULL;
4058 }
4059 
4060 /****************************************************************************
4061  *
4062  * IOMMU EFR Performance Counter support functionality. This code allows
4063  * access to the IOMMU PC functionality.
4064  *
4065  ****************************************************************************/
4066 
4067 u8 amd_iommu_pc_get_max_banks(unsigned int idx)
4068 {
4069 	struct amd_iommu *iommu = get_amd_iommu(idx);
4070 
4071 	if (iommu)
4072 		return iommu->max_banks;
4073 
4074 	return 0;
4075 }
4076 
4077 bool amd_iommu_pc_supported(void)
4078 {
4079 	return amd_iommu_pc_present;
4080 }
4081 
4082 u8 amd_iommu_pc_get_max_counters(unsigned int idx)
4083 {
4084 	struct amd_iommu *iommu = get_amd_iommu(idx);
4085 
4086 	if (iommu)
4087 		return iommu->max_counters;
4088 
4089 	return 0;
4090 }
4091 
4092 static int iommu_pc_get_set_reg(struct amd_iommu *iommu, u8 bank, u8 cntr,
4093 				u8 fxn, u64 *value, bool is_write)
4094 {
4095 	u32 offset;
4096 	u32 max_offset_lim;
4097 
4098 	/* Make sure the IOMMU PC resource is available */
4099 	if (!amd_iommu_pc_present)
4100 		return -ENODEV;
4101 
4102 	/* Check for valid iommu and pc register indexing */
4103 	if (WARN_ON(!iommu || (fxn > 0x28) || (fxn & 7)))
4104 		return -ENODEV;
4105 
4106 	offset = (u32)(((0x40 | bank) << 12) | (cntr << 8) | fxn);
4107 
4108 	/* Limit the offset to the hw defined mmio region aperture */
4109 	max_offset_lim = (u32)(((0x40 | iommu->max_banks) << 12) |
4110 				(iommu->max_counters << 8) | 0x28);
4111 	if ((offset < MMIO_CNTR_REG_OFFSET) ||
4112 	    (offset > max_offset_lim))
4113 		return -EINVAL;
4114 
4115 	if (is_write) {
4116 		u64 val = *value & GENMASK_ULL(47, 0);
4117 
4118 		writel((u32)val, iommu->mmio_base + offset);
4119 		writel((val >> 32), iommu->mmio_base + offset + 4);
4120 	} else {
4121 		*value = readl(iommu->mmio_base + offset + 4);
4122 		*value <<= 32;
4123 		*value |= readl(iommu->mmio_base + offset);
4124 		*value &= GENMASK_ULL(47, 0);
4125 	}
4126 
4127 	return 0;
4128 }
4129 
4130 int amd_iommu_pc_get_reg(struct amd_iommu *iommu, u8 bank, u8 cntr, u8 fxn, u64 *value)
4131 {
4132 	if (!iommu)
4133 		return -EINVAL;
4134 
4135 	return iommu_pc_get_set_reg(iommu, bank, cntr, fxn, value, false);
4136 }
4137 
4138 int amd_iommu_pc_set_reg(struct amd_iommu *iommu, u8 bank, u8 cntr, u8 fxn, u64 *value)
4139 {
4140 	if (!iommu)
4141 		return -EINVAL;
4142 
4143 	return iommu_pc_get_set_reg(iommu, bank, cntr, fxn, value, true);
4144 }
4145 
4146 #ifdef CONFIG_KVM_AMD_SEV
4147 static int iommu_page_make_shared(void *page)
4148 {
4149 	unsigned long paddr, pfn;
4150 
4151 	paddr = iommu_virt_to_phys(page);
4152 	/* Cbit maybe set in the paddr */
4153 	pfn = __sme_clr(paddr) >> PAGE_SHIFT;
4154 
4155 	if (!(pfn % PTRS_PER_PMD)) {
4156 		int ret, level;
4157 		bool assigned;
4158 
4159 		ret = snp_lookup_rmpentry(pfn, &assigned, &level);
4160 		if (ret) {
4161 			pr_warn("IOMMU PFN %lx RMP lookup failed, ret %d\n", pfn, ret);
4162 			return ret;
4163 		}
4164 
4165 		if (!assigned) {
4166 			pr_warn("IOMMU PFN %lx not assigned in RMP table\n", pfn);
4167 			return -EINVAL;
4168 		}
4169 
4170 		if (level > PG_LEVEL_4K) {
4171 			ret = psmash(pfn);
4172 			if (!ret)
4173 				goto done;
4174 
4175 			pr_warn("PSMASH failed for IOMMU PFN %lx huge RMP entry, ret: %d, level: %d\n",
4176 				pfn, ret, level);
4177 			return ret;
4178 		}
4179 	}
4180 
4181 done:
4182 	return rmp_make_shared(pfn, PG_LEVEL_4K);
4183 }
4184 
4185 static int iommu_make_shared(void *va, size_t size)
4186 {
4187 	void *page;
4188 	int ret;
4189 
4190 	if (!va)
4191 		return 0;
4192 
4193 	for (page = va; page < (va + size); page += PAGE_SIZE) {
4194 		ret = iommu_page_make_shared(page);
4195 		if (ret)
4196 			return ret;
4197 	}
4198 
4199 	return 0;
4200 }
4201 
4202 int amd_iommu_snp_disable(void)
4203 {
4204 	struct amd_iommu *iommu;
4205 	int ret;
4206 
4207 	if (!amd_iommu_snp_en)
4208 		return 0;
4209 
4210 	for_each_iommu(iommu) {
4211 		ret = iommu_make_shared(iommu->evt_buf, amd_iommu_evtlog_size);
4212 		if (ret)
4213 			return ret;
4214 
4215 		ret = iommu_make_shared(iommu->ppr_log, amd_iommu_pprlog_size);
4216 		if (ret)
4217 			return ret;
4218 
4219 		ret = iommu_make_shared((void *)iommu->cmd_sem, PAGE_SIZE);
4220 		if (ret)
4221 			return ret;
4222 	}
4223 
4224 	return 0;
4225 }
4226 EXPORT_SYMBOL_GPL(amd_iommu_snp_disable);
4227 
4228 bool amd_iommu_sev_tio_supported(void)
4229 {
4230 	return check_feature2(FEATURE_SEVSNPIO_SUP);
4231 }
4232 EXPORT_SYMBOL_GPL(amd_iommu_sev_tio_supported);
4233 #endif
4234