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