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