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