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