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