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