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