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