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