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