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