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