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