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