iommu/amd: Add initialization routines for AMD interrupt remapping
[firefly-linux-kernel-4.4.55.git] / drivers / iommu / amd_iommu_init.c
1 /*
2  * Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
3  * Author: Joerg Roedel <joerg.roedel@amd.com>
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/slab.h>
24 #include <linux/syscore_ops.h>
25 #include <linux/interrupt.h>
26 #include <linux/msi.h>
27 #include <linux/amd-iommu.h>
28 #include <linux/export.h>
29 #include <linux/acpi.h>
30 #include <acpi/acpi.h>
31 #include <asm/pci-direct.h>
32 #include <asm/iommu.h>
33 #include <asm/gart.h>
34 #include <asm/x86_init.h>
35 #include <asm/iommu_table.h>
36 #include <asm/io_apic.h>
37 #include <asm/irq_remapping.h>
38
39 #include "amd_iommu_proto.h"
40 #include "amd_iommu_types.h"
41 #include "irq_remapping.h"
42
43 /*
44  * definitions for the ACPI scanning code
45  */
46 #define IVRS_HEADER_LENGTH 48
47
48 #define ACPI_IVHD_TYPE                  0x10
49 #define ACPI_IVMD_TYPE_ALL              0x20
50 #define ACPI_IVMD_TYPE                  0x21
51 #define ACPI_IVMD_TYPE_RANGE            0x22
52
53 #define IVHD_DEV_ALL                    0x01
54 #define IVHD_DEV_SELECT                 0x02
55 #define IVHD_DEV_SELECT_RANGE_START     0x03
56 #define IVHD_DEV_RANGE_END              0x04
57 #define IVHD_DEV_ALIAS                  0x42
58 #define IVHD_DEV_ALIAS_RANGE            0x43
59 #define IVHD_DEV_EXT_SELECT             0x46
60 #define IVHD_DEV_EXT_SELECT_RANGE       0x47
61 #define IVHD_DEV_SPECIAL                0x48
62
63 #define IVHD_SPECIAL_IOAPIC             1
64 #define IVHD_SPECIAL_HPET               2
65
66 #define IVHD_FLAG_HT_TUN_EN_MASK        0x01
67 #define IVHD_FLAG_PASSPW_EN_MASK        0x02
68 #define IVHD_FLAG_RESPASSPW_EN_MASK     0x04
69 #define IVHD_FLAG_ISOC_EN_MASK          0x08
70
71 #define IVMD_FLAG_EXCL_RANGE            0x08
72 #define IVMD_FLAG_UNITY_MAP             0x01
73
74 #define ACPI_DEVFLAG_INITPASS           0x01
75 #define ACPI_DEVFLAG_EXTINT             0x02
76 #define ACPI_DEVFLAG_NMI                0x04
77 #define ACPI_DEVFLAG_SYSMGT1            0x10
78 #define ACPI_DEVFLAG_SYSMGT2            0x20
79 #define ACPI_DEVFLAG_LINT0              0x40
80 #define ACPI_DEVFLAG_LINT1              0x80
81 #define ACPI_DEVFLAG_ATSDIS             0x10000000
82
83 /*
84  * ACPI table definitions
85  *
86  * These data structures are laid over the table to parse the important values
87  * out of it.
88  */
89
90 /*
91  * structure describing one IOMMU in the ACPI table. Typically followed by one
92  * or more ivhd_entrys.
93  */
94 struct ivhd_header {
95         u8 type;
96         u8 flags;
97         u16 length;
98         u16 devid;
99         u16 cap_ptr;
100         u64 mmio_phys;
101         u16 pci_seg;
102         u16 info;
103         u32 reserved;
104 } __attribute__((packed));
105
106 /*
107  * A device entry describing which devices a specific IOMMU translates and
108  * which requestor ids they use.
109  */
110 struct ivhd_entry {
111         u8 type;
112         u16 devid;
113         u8 flags;
114         u32 ext;
115 } __attribute__((packed));
116
117 /*
118  * An AMD IOMMU memory definition structure. It defines things like exclusion
119  * ranges for devices and regions that should be unity mapped.
120  */
121 struct ivmd_header {
122         u8 type;
123         u8 flags;
124         u16 length;
125         u16 devid;
126         u16 aux;
127         u64 resv;
128         u64 range_start;
129         u64 range_length;
130 } __attribute__((packed));
131
132 bool amd_iommu_dump;
133 bool amd_iommu_irq_remap __read_mostly;
134
135 static bool amd_iommu_detected;
136 static bool __initdata amd_iommu_disabled;
137
138 u16 amd_iommu_last_bdf;                 /* largest PCI device id we have
139                                            to handle */
140 LIST_HEAD(amd_iommu_unity_map);         /* a list of required unity mappings
141                                            we find in ACPI */
142 u32 amd_iommu_unmap_flush;              /* if true, flush on every unmap */
143
144 LIST_HEAD(amd_iommu_list);              /* list of all AMD IOMMUs in the
145                                            system */
146
147 /* Array to assign indices to IOMMUs*/
148 struct amd_iommu *amd_iommus[MAX_IOMMUS];
149 int amd_iommus_present;
150
151 /* IOMMUs have a non-present cache? */
152 bool amd_iommu_np_cache __read_mostly;
153 bool amd_iommu_iotlb_sup __read_mostly = true;
154
155 u32 amd_iommu_max_pasids __read_mostly = ~0;
156
157 bool amd_iommu_v2_present __read_mostly;
158
159 bool amd_iommu_force_isolation __read_mostly;
160
161 /*
162  * List of protection domains - used during resume
163  */
164 LIST_HEAD(amd_iommu_pd_list);
165 spinlock_t amd_iommu_pd_lock;
166
167 /*
168  * Pointer to the device table which is shared by all AMD IOMMUs
169  * it is indexed by the PCI device id or the HT unit id and contains
170  * information about the domain the device belongs to as well as the
171  * page table root pointer.
172  */
173 struct dev_table_entry *amd_iommu_dev_table;
174
175 /*
176  * The alias table is a driver specific data structure which contains the
177  * mappings of the PCI device ids to the actual requestor ids on the IOMMU.
178  * More than one device can share the same requestor id.
179  */
180 u16 *amd_iommu_alias_table;
181
182 /*
183  * The rlookup table is used to find the IOMMU which is responsible
184  * for a specific device. It is also indexed by the PCI device id.
185  */
186 struct amd_iommu **amd_iommu_rlookup_table;
187
188 /*
189  * This table is used to find the irq remapping table for a given device id
190  * quickly.
191  */
192 struct irq_remap_table **irq_lookup_table;
193
194 /*
195  * AMD IOMMU allows up to 2^16 differend protection domains. This is a bitmap
196  * to know which ones are already in use.
197  */
198 unsigned long *amd_iommu_pd_alloc_bitmap;
199
200 static u32 dev_table_size;      /* size of the device table */
201 static u32 alias_table_size;    /* size of the alias table */
202 static u32 rlookup_table_size;  /* size if the rlookup table */
203
204 enum iommu_init_state {
205         IOMMU_START_STATE,
206         IOMMU_IVRS_DETECTED,
207         IOMMU_ACPI_FINISHED,
208         IOMMU_ENABLED,
209         IOMMU_PCI_INIT,
210         IOMMU_INTERRUPTS_EN,
211         IOMMU_DMA_OPS,
212         IOMMU_INITIALIZED,
213         IOMMU_NOT_FOUND,
214         IOMMU_INIT_ERROR,
215 };
216
217 static enum iommu_init_state init_state = IOMMU_START_STATE;
218
219 static int amd_iommu_enable_interrupts(void);
220 static int __init iommu_go_to_state(enum iommu_init_state state);
221
222 static inline void update_last_devid(u16 devid)
223 {
224         if (devid > amd_iommu_last_bdf)
225                 amd_iommu_last_bdf = devid;
226 }
227
228 static inline unsigned long tbl_size(int entry_size)
229 {
230         unsigned shift = PAGE_SHIFT +
231                          get_order(((int)amd_iommu_last_bdf + 1) * entry_size);
232
233         return 1UL << shift;
234 }
235
236 /* Access to l1 and l2 indexed register spaces */
237
238 static u32 iommu_read_l1(struct amd_iommu *iommu, u16 l1, u8 address)
239 {
240         u32 val;
241
242         pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16));
243         pci_read_config_dword(iommu->dev, 0xfc, &val);
244         return val;
245 }
246
247 static void iommu_write_l1(struct amd_iommu *iommu, u16 l1, u8 address, u32 val)
248 {
249         pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16 | 1 << 31));
250         pci_write_config_dword(iommu->dev, 0xfc, val);
251         pci_write_config_dword(iommu->dev, 0xf8, (address | l1 << 16));
252 }
253
254 static u32 iommu_read_l2(struct amd_iommu *iommu, u8 address)
255 {
256         u32 val;
257
258         pci_write_config_dword(iommu->dev, 0xf0, address);
259         pci_read_config_dword(iommu->dev, 0xf4, &val);
260         return val;
261 }
262
263 static void iommu_write_l2(struct amd_iommu *iommu, u8 address, u32 val)
264 {
265         pci_write_config_dword(iommu->dev, 0xf0, (address | 1 << 8));
266         pci_write_config_dword(iommu->dev, 0xf4, val);
267 }
268
269 /****************************************************************************
270  *
271  * AMD IOMMU MMIO register space handling functions
272  *
273  * These functions are used to program the IOMMU device registers in
274  * MMIO space required for that driver.
275  *
276  ****************************************************************************/
277
278 /*
279  * This function set the exclusion range in the IOMMU. DMA accesses to the
280  * exclusion range are passed through untranslated
281  */
282 static void iommu_set_exclusion_range(struct amd_iommu *iommu)
283 {
284         u64 start = iommu->exclusion_start & PAGE_MASK;
285         u64 limit = (start + iommu->exclusion_length) & PAGE_MASK;
286         u64 entry;
287
288         if (!iommu->exclusion_start)
289                 return;
290
291         entry = start | MMIO_EXCL_ENABLE_MASK;
292         memcpy_toio(iommu->mmio_base + MMIO_EXCL_BASE_OFFSET,
293                         &entry, sizeof(entry));
294
295         entry = limit;
296         memcpy_toio(iommu->mmio_base + MMIO_EXCL_LIMIT_OFFSET,
297                         &entry, sizeof(entry));
298 }
299
300 /* Programs the physical address of the device table into the IOMMU hardware */
301 static void iommu_set_device_table(struct amd_iommu *iommu)
302 {
303         u64 entry;
304
305         BUG_ON(iommu->mmio_base == NULL);
306
307         entry = virt_to_phys(amd_iommu_dev_table);
308         entry |= (dev_table_size >> 12) - 1;
309         memcpy_toio(iommu->mmio_base + MMIO_DEV_TABLE_OFFSET,
310                         &entry, sizeof(entry));
311 }
312
313 /* Generic functions to enable/disable certain features of the IOMMU. */
314 static void iommu_feature_enable(struct amd_iommu *iommu, u8 bit)
315 {
316         u32 ctrl;
317
318         ctrl = readl(iommu->mmio_base + MMIO_CONTROL_OFFSET);
319         ctrl |= (1 << bit);
320         writel(ctrl, iommu->mmio_base + MMIO_CONTROL_OFFSET);
321 }
322
323 static void iommu_feature_disable(struct amd_iommu *iommu, u8 bit)
324 {
325         u32 ctrl;
326
327         ctrl = readl(iommu->mmio_base + MMIO_CONTROL_OFFSET);
328         ctrl &= ~(1 << bit);
329         writel(ctrl, iommu->mmio_base + MMIO_CONTROL_OFFSET);
330 }
331
332 static void iommu_set_inv_tlb_timeout(struct amd_iommu *iommu, int timeout)
333 {
334         u32 ctrl;
335
336         ctrl = readl(iommu->mmio_base + MMIO_CONTROL_OFFSET);
337         ctrl &= ~CTRL_INV_TO_MASK;
338         ctrl |= (timeout << CONTROL_INV_TIMEOUT) & CTRL_INV_TO_MASK;
339         writel(ctrl, iommu->mmio_base + MMIO_CONTROL_OFFSET);
340 }
341
342 /* Function to enable the hardware */
343 static void iommu_enable(struct amd_iommu *iommu)
344 {
345         iommu_feature_enable(iommu, CONTROL_IOMMU_EN);
346 }
347
348 static void iommu_disable(struct amd_iommu *iommu)
349 {
350         /* Disable command buffer */
351         iommu_feature_disable(iommu, CONTROL_CMDBUF_EN);
352
353         /* Disable event logging and event interrupts */
354         iommu_feature_disable(iommu, CONTROL_EVT_INT_EN);
355         iommu_feature_disable(iommu, CONTROL_EVT_LOG_EN);
356
357         /* Disable IOMMU hardware itself */
358         iommu_feature_disable(iommu, CONTROL_IOMMU_EN);
359 }
360
361 /*
362  * mapping and unmapping functions for the IOMMU MMIO space. Each AMD IOMMU in
363  * the system has one.
364  */
365 static u8 __iomem * __init iommu_map_mmio_space(u64 address)
366 {
367         if (!request_mem_region(address, MMIO_REGION_LENGTH, "amd_iommu")) {
368                 pr_err("AMD-Vi: Can not reserve memory region %llx for mmio\n",
369                         address);
370                 pr_err("AMD-Vi: This is a BIOS bug. Please contact your hardware vendor\n");
371                 return NULL;
372         }
373
374         return (u8 __iomem *)ioremap_nocache(address, MMIO_REGION_LENGTH);
375 }
376
377 static void __init iommu_unmap_mmio_space(struct amd_iommu *iommu)
378 {
379         if (iommu->mmio_base)
380                 iounmap(iommu->mmio_base);
381         release_mem_region(iommu->mmio_phys, MMIO_REGION_LENGTH);
382 }
383
384 /****************************************************************************
385  *
386  * The functions below belong to the first pass of AMD IOMMU ACPI table
387  * parsing. In this pass we try to find out the highest device id this
388  * code has to handle. Upon this information the size of the shared data
389  * structures is determined later.
390  *
391  ****************************************************************************/
392
393 /*
394  * This function calculates the length of a given IVHD entry
395  */
396 static inline int ivhd_entry_length(u8 *ivhd)
397 {
398         return 0x04 << (*ivhd >> 6);
399 }
400
401 /*
402  * This function reads the last device id the IOMMU has to handle from the PCI
403  * capability header for this IOMMU
404  */
405 static int __init find_last_devid_on_pci(int bus, int dev, int fn, int cap_ptr)
406 {
407         u32 cap;
408
409         cap = read_pci_config(bus, dev, fn, cap_ptr+MMIO_RANGE_OFFSET);
410         update_last_devid(calc_devid(MMIO_GET_BUS(cap), MMIO_GET_LD(cap)));
411
412         return 0;
413 }
414
415 /*
416  * After reading the highest device id from the IOMMU PCI capability header
417  * this function looks if there is a higher device id defined in the ACPI table
418  */
419 static int __init find_last_devid_from_ivhd(struct ivhd_header *h)
420 {
421         u8 *p = (void *)h, *end = (void *)h;
422         struct ivhd_entry *dev;
423
424         p += sizeof(*h);
425         end += h->length;
426
427         find_last_devid_on_pci(PCI_BUS(h->devid),
428                         PCI_SLOT(h->devid),
429                         PCI_FUNC(h->devid),
430                         h->cap_ptr);
431
432         while (p < end) {
433                 dev = (struct ivhd_entry *)p;
434                 switch (dev->type) {
435                 case IVHD_DEV_SELECT:
436                 case IVHD_DEV_RANGE_END:
437                 case IVHD_DEV_ALIAS:
438                 case IVHD_DEV_EXT_SELECT:
439                         /* all the above subfield types refer to device ids */
440                         update_last_devid(dev->devid);
441                         break;
442                 default:
443                         break;
444                 }
445                 p += ivhd_entry_length(p);
446         }
447
448         WARN_ON(p != end);
449
450         return 0;
451 }
452
453 /*
454  * Iterate over all IVHD entries in the ACPI table and find the highest device
455  * id which we need to handle. This is the first of three functions which parse
456  * the ACPI table. So we check the checksum here.
457  */
458 static int __init find_last_devid_acpi(struct acpi_table_header *table)
459 {
460         int i;
461         u8 checksum = 0, *p = (u8 *)table, *end = (u8 *)table;
462         struct ivhd_header *h;
463
464         /*
465          * Validate checksum here so we don't need to do it when
466          * we actually parse the table
467          */
468         for (i = 0; i < table->length; ++i)
469                 checksum += p[i];
470         if (checksum != 0)
471                 /* ACPI table corrupt */
472                 return -ENODEV;
473
474         p += IVRS_HEADER_LENGTH;
475
476         end += table->length;
477         while (p < end) {
478                 h = (struct ivhd_header *)p;
479                 switch (h->type) {
480                 case ACPI_IVHD_TYPE:
481                         find_last_devid_from_ivhd(h);
482                         break;
483                 default:
484                         break;
485                 }
486                 p += h->length;
487         }
488         WARN_ON(p != end);
489
490         return 0;
491 }
492
493 /****************************************************************************
494  *
495  * The following functions belong the the code path which parses the ACPI table
496  * the second time. In this ACPI parsing iteration we allocate IOMMU specific
497  * data structures, initialize the device/alias/rlookup table and also
498  * basically initialize the hardware.
499  *
500  ****************************************************************************/
501
502 /*
503  * Allocates the command buffer. This buffer is per AMD IOMMU. We can
504  * write commands to that buffer later and the IOMMU will execute them
505  * asynchronously
506  */
507 static u8 * __init alloc_command_buffer(struct amd_iommu *iommu)
508 {
509         u8 *cmd_buf = (u8 *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
510                         get_order(CMD_BUFFER_SIZE));
511
512         if (cmd_buf == NULL)
513                 return NULL;
514
515         iommu->cmd_buf_size = CMD_BUFFER_SIZE | CMD_BUFFER_UNINITIALIZED;
516
517         return cmd_buf;
518 }
519
520 /*
521  * This function resets the command buffer if the IOMMU stopped fetching
522  * commands from it.
523  */
524 void amd_iommu_reset_cmd_buffer(struct amd_iommu *iommu)
525 {
526         iommu_feature_disable(iommu, CONTROL_CMDBUF_EN);
527
528         writel(0x00, iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
529         writel(0x00, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
530
531         iommu_feature_enable(iommu, CONTROL_CMDBUF_EN);
532 }
533
534 /*
535  * This function writes the command buffer address to the hardware and
536  * enables it.
537  */
538 static void iommu_enable_command_buffer(struct amd_iommu *iommu)
539 {
540         u64 entry;
541
542         BUG_ON(iommu->cmd_buf == NULL);
543
544         entry = (u64)virt_to_phys(iommu->cmd_buf);
545         entry |= MMIO_CMD_SIZE_512;
546
547         memcpy_toio(iommu->mmio_base + MMIO_CMD_BUF_OFFSET,
548                     &entry, sizeof(entry));
549
550         amd_iommu_reset_cmd_buffer(iommu);
551         iommu->cmd_buf_size &= ~(CMD_BUFFER_UNINITIALIZED);
552 }
553
554 static void __init free_command_buffer(struct amd_iommu *iommu)
555 {
556         free_pages((unsigned long)iommu->cmd_buf,
557                    get_order(iommu->cmd_buf_size & ~(CMD_BUFFER_UNINITIALIZED)));
558 }
559
560 /* allocates the memory where the IOMMU will log its events to */
561 static u8 * __init alloc_event_buffer(struct amd_iommu *iommu)
562 {
563         iommu->evt_buf = (u8 *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
564                                                 get_order(EVT_BUFFER_SIZE));
565
566         if (iommu->evt_buf == NULL)
567                 return NULL;
568
569         iommu->evt_buf_size = EVT_BUFFER_SIZE;
570
571         return iommu->evt_buf;
572 }
573
574 static void iommu_enable_event_buffer(struct amd_iommu *iommu)
575 {
576         u64 entry;
577
578         BUG_ON(iommu->evt_buf == NULL);
579
580         entry = (u64)virt_to_phys(iommu->evt_buf) | EVT_LEN_MASK;
581
582         memcpy_toio(iommu->mmio_base + MMIO_EVT_BUF_OFFSET,
583                     &entry, sizeof(entry));
584
585         /* set head and tail to zero manually */
586         writel(0x00, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
587         writel(0x00, iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
588
589         iommu_feature_enable(iommu, CONTROL_EVT_LOG_EN);
590 }
591
592 static void __init free_event_buffer(struct amd_iommu *iommu)
593 {
594         free_pages((unsigned long)iommu->evt_buf, get_order(EVT_BUFFER_SIZE));
595 }
596
597 /* allocates the memory where the IOMMU will log its events to */
598 static u8 * __init alloc_ppr_log(struct amd_iommu *iommu)
599 {
600         iommu->ppr_log = (u8 *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
601                                                 get_order(PPR_LOG_SIZE));
602
603         if (iommu->ppr_log == NULL)
604                 return NULL;
605
606         return iommu->ppr_log;
607 }
608
609 static void iommu_enable_ppr_log(struct amd_iommu *iommu)
610 {
611         u64 entry;
612
613         if (iommu->ppr_log == NULL)
614                 return;
615
616         entry = (u64)virt_to_phys(iommu->ppr_log) | PPR_LOG_SIZE_512;
617
618         memcpy_toio(iommu->mmio_base + MMIO_PPR_LOG_OFFSET,
619                     &entry, sizeof(entry));
620
621         /* set head and tail to zero manually */
622         writel(0x00, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
623         writel(0x00, iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
624
625         iommu_feature_enable(iommu, CONTROL_PPFLOG_EN);
626         iommu_feature_enable(iommu, CONTROL_PPR_EN);
627 }
628
629 static void __init free_ppr_log(struct amd_iommu *iommu)
630 {
631         if (iommu->ppr_log == NULL)
632                 return;
633
634         free_pages((unsigned long)iommu->ppr_log, get_order(PPR_LOG_SIZE));
635 }
636
637 static void iommu_enable_gt(struct amd_iommu *iommu)
638 {
639         if (!iommu_feature(iommu, FEATURE_GT))
640                 return;
641
642         iommu_feature_enable(iommu, CONTROL_GT_EN);
643 }
644
645 /* sets a specific bit in the device table entry. */
646 static void set_dev_entry_bit(u16 devid, u8 bit)
647 {
648         int i = (bit >> 6) & 0x03;
649         int _bit = bit & 0x3f;
650
651         amd_iommu_dev_table[devid].data[i] |= (1UL << _bit);
652 }
653
654 static int get_dev_entry_bit(u16 devid, u8 bit)
655 {
656         int i = (bit >> 6) & 0x03;
657         int _bit = bit & 0x3f;
658
659         return (amd_iommu_dev_table[devid].data[i] & (1UL << _bit)) >> _bit;
660 }
661
662
663 void amd_iommu_apply_erratum_63(u16 devid)
664 {
665         int sysmgt;
666
667         sysmgt = get_dev_entry_bit(devid, DEV_ENTRY_SYSMGT1) |
668                  (get_dev_entry_bit(devid, DEV_ENTRY_SYSMGT2) << 1);
669
670         if (sysmgt == 0x01)
671                 set_dev_entry_bit(devid, DEV_ENTRY_IW);
672 }
673
674 /* Writes the specific IOMMU for a device into the rlookup table */
675 static void __init set_iommu_for_device(struct amd_iommu *iommu, u16 devid)
676 {
677         amd_iommu_rlookup_table[devid] = iommu;
678 }
679
680 /*
681  * This function takes the device specific flags read from the ACPI
682  * table and sets up the device table entry with that information
683  */
684 static void __init set_dev_entry_from_acpi(struct amd_iommu *iommu,
685                                            u16 devid, u32 flags, u32 ext_flags)
686 {
687         if (flags & ACPI_DEVFLAG_INITPASS)
688                 set_dev_entry_bit(devid, DEV_ENTRY_INIT_PASS);
689         if (flags & ACPI_DEVFLAG_EXTINT)
690                 set_dev_entry_bit(devid, DEV_ENTRY_EINT_PASS);
691         if (flags & ACPI_DEVFLAG_NMI)
692                 set_dev_entry_bit(devid, DEV_ENTRY_NMI_PASS);
693         if (flags & ACPI_DEVFLAG_SYSMGT1)
694                 set_dev_entry_bit(devid, DEV_ENTRY_SYSMGT1);
695         if (flags & ACPI_DEVFLAG_SYSMGT2)
696                 set_dev_entry_bit(devid, DEV_ENTRY_SYSMGT2);
697         if (flags & ACPI_DEVFLAG_LINT0)
698                 set_dev_entry_bit(devid, DEV_ENTRY_LINT0_PASS);
699         if (flags & ACPI_DEVFLAG_LINT1)
700                 set_dev_entry_bit(devid, DEV_ENTRY_LINT1_PASS);
701
702         amd_iommu_apply_erratum_63(devid);
703
704         set_iommu_for_device(iommu, devid);
705 }
706
707 static int add_special_device(u8 type, u8 id, u16 devid)
708 {
709         struct devid_map *entry;
710         struct list_head *list;
711
712         if (type != IVHD_SPECIAL_IOAPIC && type != IVHD_SPECIAL_HPET)
713                 return -EINVAL;
714
715         entry = kzalloc(sizeof(*entry), GFP_KERNEL);
716         if (!entry)
717                 return -ENOMEM;
718
719         entry->id    = id;
720         entry->devid = devid;
721
722         if (type == IVHD_SPECIAL_IOAPIC)
723                 list = &ioapic_map;
724         else
725                 list = &hpet_map;
726
727         list_add_tail(&entry->list, list);
728
729         return 0;
730 }
731
732 /*
733  * Reads the device exclusion range from ACPI and initialize IOMMU with
734  * it
735  */
736 static void __init set_device_exclusion_range(u16 devid, struct ivmd_header *m)
737 {
738         struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
739
740         if (!(m->flags & IVMD_FLAG_EXCL_RANGE))
741                 return;
742
743         if (iommu) {
744                 /*
745                  * We only can configure exclusion ranges per IOMMU, not
746                  * per device. But we can enable the exclusion range per
747                  * device. This is done here
748                  */
749                 set_dev_entry_bit(m->devid, DEV_ENTRY_EX);
750                 iommu->exclusion_start = m->range_start;
751                 iommu->exclusion_length = m->range_length;
752         }
753 }
754
755 /*
756  * Takes a pointer to an AMD IOMMU entry in the ACPI table and
757  * initializes the hardware and our data structures with it.
758  */
759 static int __init init_iommu_from_acpi(struct amd_iommu *iommu,
760                                         struct ivhd_header *h)
761 {
762         u8 *p = (u8 *)h;
763         u8 *end = p, flags = 0;
764         u16 devid = 0, devid_start = 0, devid_to = 0;
765         u32 dev_i, ext_flags = 0;
766         bool alias = false;
767         struct ivhd_entry *e;
768
769         /*
770          * First save the recommended feature enable bits from ACPI
771          */
772         iommu->acpi_flags = h->flags;
773
774         /*
775          * Done. Now parse the device entries
776          */
777         p += sizeof(struct ivhd_header);
778         end += h->length;
779
780
781         while (p < end) {
782                 e = (struct ivhd_entry *)p;
783                 switch (e->type) {
784                 case IVHD_DEV_ALL:
785
786                         DUMP_printk("  DEV_ALL\t\t\t first devid: %02x:%02x.%x"
787                                     " last device %02x:%02x.%x flags: %02x\n",
788                                     PCI_BUS(iommu->first_device),
789                                     PCI_SLOT(iommu->first_device),
790                                     PCI_FUNC(iommu->first_device),
791                                     PCI_BUS(iommu->last_device),
792                                     PCI_SLOT(iommu->last_device),
793                                     PCI_FUNC(iommu->last_device),
794                                     e->flags);
795
796                         for (dev_i = iommu->first_device;
797                                         dev_i <= iommu->last_device; ++dev_i)
798                                 set_dev_entry_from_acpi(iommu, dev_i,
799                                                         e->flags, 0);
800                         break;
801                 case IVHD_DEV_SELECT:
802
803                         DUMP_printk("  DEV_SELECT\t\t\t devid: %02x:%02x.%x "
804                                     "flags: %02x\n",
805                                     PCI_BUS(e->devid),
806                                     PCI_SLOT(e->devid),
807                                     PCI_FUNC(e->devid),
808                                     e->flags);
809
810                         devid = e->devid;
811                         set_dev_entry_from_acpi(iommu, devid, e->flags, 0);
812                         break;
813                 case IVHD_DEV_SELECT_RANGE_START:
814
815                         DUMP_printk("  DEV_SELECT_RANGE_START\t "
816                                     "devid: %02x:%02x.%x flags: %02x\n",
817                                     PCI_BUS(e->devid),
818                                     PCI_SLOT(e->devid),
819                                     PCI_FUNC(e->devid),
820                                     e->flags);
821
822                         devid_start = e->devid;
823                         flags = e->flags;
824                         ext_flags = 0;
825                         alias = false;
826                         break;
827                 case IVHD_DEV_ALIAS:
828
829                         DUMP_printk("  DEV_ALIAS\t\t\t devid: %02x:%02x.%x "
830                                     "flags: %02x devid_to: %02x:%02x.%x\n",
831                                     PCI_BUS(e->devid),
832                                     PCI_SLOT(e->devid),
833                                     PCI_FUNC(e->devid),
834                                     e->flags,
835                                     PCI_BUS(e->ext >> 8),
836                                     PCI_SLOT(e->ext >> 8),
837                                     PCI_FUNC(e->ext >> 8));
838
839                         devid = e->devid;
840                         devid_to = e->ext >> 8;
841                         set_dev_entry_from_acpi(iommu, devid   , e->flags, 0);
842                         set_dev_entry_from_acpi(iommu, devid_to, e->flags, 0);
843                         amd_iommu_alias_table[devid] = devid_to;
844                         break;
845                 case IVHD_DEV_ALIAS_RANGE:
846
847                         DUMP_printk("  DEV_ALIAS_RANGE\t\t "
848                                     "devid: %02x:%02x.%x flags: %02x "
849                                     "devid_to: %02x:%02x.%x\n",
850                                     PCI_BUS(e->devid),
851                                     PCI_SLOT(e->devid),
852                                     PCI_FUNC(e->devid),
853                                     e->flags,
854                                     PCI_BUS(e->ext >> 8),
855                                     PCI_SLOT(e->ext >> 8),
856                                     PCI_FUNC(e->ext >> 8));
857
858                         devid_start = e->devid;
859                         flags = e->flags;
860                         devid_to = e->ext >> 8;
861                         ext_flags = 0;
862                         alias = true;
863                         break;
864                 case IVHD_DEV_EXT_SELECT:
865
866                         DUMP_printk("  DEV_EXT_SELECT\t\t devid: %02x:%02x.%x "
867                                     "flags: %02x ext: %08x\n",
868                                     PCI_BUS(e->devid),
869                                     PCI_SLOT(e->devid),
870                                     PCI_FUNC(e->devid),
871                                     e->flags, e->ext);
872
873                         devid = e->devid;
874                         set_dev_entry_from_acpi(iommu, devid, e->flags,
875                                                 e->ext);
876                         break;
877                 case IVHD_DEV_EXT_SELECT_RANGE:
878
879                         DUMP_printk("  DEV_EXT_SELECT_RANGE\t devid: "
880                                     "%02x:%02x.%x flags: %02x ext: %08x\n",
881                                     PCI_BUS(e->devid),
882                                     PCI_SLOT(e->devid),
883                                     PCI_FUNC(e->devid),
884                                     e->flags, e->ext);
885
886                         devid_start = e->devid;
887                         flags = e->flags;
888                         ext_flags = e->ext;
889                         alias = false;
890                         break;
891                 case IVHD_DEV_RANGE_END:
892
893                         DUMP_printk("  DEV_RANGE_END\t\t devid: %02x:%02x.%x\n",
894                                     PCI_BUS(e->devid),
895                                     PCI_SLOT(e->devid),
896                                     PCI_FUNC(e->devid));
897
898                         devid = e->devid;
899                         for (dev_i = devid_start; dev_i <= devid; ++dev_i) {
900                                 if (alias) {
901                                         amd_iommu_alias_table[dev_i] = devid_to;
902                                         set_dev_entry_from_acpi(iommu,
903                                                 devid_to, flags, ext_flags);
904                                 }
905                                 set_dev_entry_from_acpi(iommu, dev_i,
906                                                         flags, ext_flags);
907                         }
908                         break;
909                 case IVHD_DEV_SPECIAL: {
910                         u8 handle, type;
911                         const char *var;
912                         u16 devid;
913                         int ret;
914
915                         handle = e->ext & 0xff;
916                         devid  = (e->ext >>  8) & 0xffff;
917                         type   = (e->ext >> 24) & 0xff;
918
919                         if (type == IVHD_SPECIAL_IOAPIC)
920                                 var = "IOAPIC";
921                         else if (type == IVHD_SPECIAL_HPET)
922                                 var = "HPET";
923                         else
924                                 var = "UNKNOWN";
925
926                         DUMP_printk("  DEV_SPECIAL(%s[%d])\t\tdevid: %02x:%02x.%x\n",
927                                     var, (int)handle,
928                                     PCI_BUS(devid),
929                                     PCI_SLOT(devid),
930                                     PCI_FUNC(devid));
931
932                         set_dev_entry_from_acpi(iommu, devid, e->flags, 0);
933                         ret = add_special_device(type, handle, devid);
934                         if (ret)
935                                 return ret;
936                         break;
937                 }
938                 default:
939                         break;
940                 }
941
942                 p += ivhd_entry_length(p);
943         }
944
945         return 0;
946 }
947
948 /* Initializes the device->iommu mapping for the driver */
949 static int __init init_iommu_devices(struct amd_iommu *iommu)
950 {
951         u32 i;
952
953         for (i = iommu->first_device; i <= iommu->last_device; ++i)
954                 set_iommu_for_device(iommu, i);
955
956         return 0;
957 }
958
959 static void __init free_iommu_one(struct amd_iommu *iommu)
960 {
961         free_command_buffer(iommu);
962         free_event_buffer(iommu);
963         free_ppr_log(iommu);
964         iommu_unmap_mmio_space(iommu);
965 }
966
967 static void __init free_iommu_all(void)
968 {
969         struct amd_iommu *iommu, *next;
970
971         for_each_iommu_safe(iommu, next) {
972                 list_del(&iommu->list);
973                 free_iommu_one(iommu);
974                 kfree(iommu);
975         }
976 }
977
978 /*
979  * This function clues the initialization function for one IOMMU
980  * together and also allocates the command buffer and programs the
981  * hardware. It does NOT enable the IOMMU. This is done afterwards.
982  */
983 static int __init init_iommu_one(struct amd_iommu *iommu, struct ivhd_header *h)
984 {
985         int ret;
986
987         spin_lock_init(&iommu->lock);
988
989         /* Add IOMMU to internal data structures */
990         list_add_tail(&iommu->list, &amd_iommu_list);
991         iommu->index             = amd_iommus_present++;
992
993         if (unlikely(iommu->index >= MAX_IOMMUS)) {
994                 WARN(1, "AMD-Vi: System has more IOMMUs than supported by this driver\n");
995                 return -ENOSYS;
996         }
997
998         /* Index is fine - add IOMMU to the array */
999         amd_iommus[iommu->index] = iommu;
1000
1001         /*
1002          * Copy data from ACPI table entry to the iommu struct
1003          */
1004         iommu->devid   = h->devid;
1005         iommu->cap_ptr = h->cap_ptr;
1006         iommu->pci_seg = h->pci_seg;
1007         iommu->mmio_phys = h->mmio_phys;
1008         iommu->mmio_base = iommu_map_mmio_space(h->mmio_phys);
1009         if (!iommu->mmio_base)
1010                 return -ENOMEM;
1011
1012         iommu->cmd_buf = alloc_command_buffer(iommu);
1013         if (!iommu->cmd_buf)
1014                 return -ENOMEM;
1015
1016         iommu->evt_buf = alloc_event_buffer(iommu);
1017         if (!iommu->evt_buf)
1018                 return -ENOMEM;
1019
1020         iommu->int_enabled = false;
1021
1022         ret = init_iommu_from_acpi(iommu, h);
1023         if (ret)
1024                 return ret;
1025
1026         /*
1027          * Make sure IOMMU is not considered to translate itself. The IVRS
1028          * table tells us so, but this is a lie!
1029          */
1030         amd_iommu_rlookup_table[iommu->devid] = NULL;
1031
1032         init_iommu_devices(iommu);
1033
1034         return 0;
1035 }
1036
1037 /*
1038  * Iterates over all IOMMU entries in the ACPI table, allocates the
1039  * IOMMU structure and initializes it with init_iommu_one()
1040  */
1041 static int __init init_iommu_all(struct acpi_table_header *table)
1042 {
1043         u8 *p = (u8 *)table, *end = (u8 *)table;
1044         struct ivhd_header *h;
1045         struct amd_iommu *iommu;
1046         int ret;
1047
1048         end += table->length;
1049         p += IVRS_HEADER_LENGTH;
1050
1051         while (p < end) {
1052                 h = (struct ivhd_header *)p;
1053                 switch (*p) {
1054                 case ACPI_IVHD_TYPE:
1055
1056                         DUMP_printk("device: %02x:%02x.%01x cap: %04x "
1057                                     "seg: %d flags: %01x info %04x\n",
1058                                     PCI_BUS(h->devid), PCI_SLOT(h->devid),
1059                                     PCI_FUNC(h->devid), h->cap_ptr,
1060                                     h->pci_seg, h->flags, h->info);
1061                         DUMP_printk("       mmio-addr: %016llx\n",
1062                                     h->mmio_phys);
1063
1064                         iommu = kzalloc(sizeof(struct amd_iommu), GFP_KERNEL);
1065                         if (iommu == NULL)
1066                                 return -ENOMEM;
1067
1068                         ret = init_iommu_one(iommu, h);
1069                         if (ret)
1070                                 return ret;
1071                         break;
1072                 default:
1073                         break;
1074                 }
1075                 p += h->length;
1076
1077         }
1078         WARN_ON(p != end);
1079
1080         return 0;
1081 }
1082
1083 static int iommu_init_pci(struct amd_iommu *iommu)
1084 {
1085         int cap_ptr = iommu->cap_ptr;
1086         u32 range, misc, low, high;
1087
1088         iommu->dev = pci_get_bus_and_slot(PCI_BUS(iommu->devid),
1089                                           iommu->devid & 0xff);
1090         if (!iommu->dev)
1091                 return -ENODEV;
1092
1093         pci_read_config_dword(iommu->dev, cap_ptr + MMIO_CAP_HDR_OFFSET,
1094                               &iommu->cap);
1095         pci_read_config_dword(iommu->dev, cap_ptr + MMIO_RANGE_OFFSET,
1096                               &range);
1097         pci_read_config_dword(iommu->dev, cap_ptr + MMIO_MISC_OFFSET,
1098                               &misc);
1099
1100         iommu->first_device = calc_devid(MMIO_GET_BUS(range),
1101                                          MMIO_GET_FD(range));
1102         iommu->last_device = calc_devid(MMIO_GET_BUS(range),
1103                                         MMIO_GET_LD(range));
1104
1105         if (!(iommu->cap & (1 << IOMMU_CAP_IOTLB)))
1106                 amd_iommu_iotlb_sup = false;
1107
1108         /* read extended feature bits */
1109         low  = readl(iommu->mmio_base + MMIO_EXT_FEATURES);
1110         high = readl(iommu->mmio_base + MMIO_EXT_FEATURES + 4);
1111
1112         iommu->features = ((u64)high << 32) | low;
1113
1114         if (iommu_feature(iommu, FEATURE_GT)) {
1115                 int glxval;
1116                 u32 pasids;
1117                 u64 shift;
1118
1119                 shift   = iommu->features & FEATURE_PASID_MASK;
1120                 shift >>= FEATURE_PASID_SHIFT;
1121                 pasids  = (1 << shift);
1122
1123                 amd_iommu_max_pasids = min(amd_iommu_max_pasids, pasids);
1124
1125                 glxval   = iommu->features & FEATURE_GLXVAL_MASK;
1126                 glxval >>= FEATURE_GLXVAL_SHIFT;
1127
1128                 if (amd_iommu_max_glx_val == -1)
1129                         amd_iommu_max_glx_val = glxval;
1130                 else
1131                         amd_iommu_max_glx_val = min(amd_iommu_max_glx_val, glxval);
1132         }
1133
1134         if (iommu_feature(iommu, FEATURE_GT) &&
1135             iommu_feature(iommu, FEATURE_PPR)) {
1136                 iommu->is_iommu_v2   = true;
1137                 amd_iommu_v2_present = true;
1138         }
1139
1140         if (iommu_feature(iommu, FEATURE_PPR)) {
1141                 iommu->ppr_log = alloc_ppr_log(iommu);
1142                 if (!iommu->ppr_log)
1143                         return -ENOMEM;
1144         }
1145
1146         if (iommu->cap & (1UL << IOMMU_CAP_NPCACHE))
1147                 amd_iommu_np_cache = true;
1148
1149         if (is_rd890_iommu(iommu->dev)) {
1150                 int i, j;
1151
1152                 iommu->root_pdev = pci_get_bus_and_slot(iommu->dev->bus->number,
1153                                 PCI_DEVFN(0, 0));
1154
1155                 /*
1156                  * Some rd890 systems may not be fully reconfigured by the
1157                  * BIOS, so it's necessary for us to store this information so
1158                  * it can be reprogrammed on resume
1159                  */
1160                 pci_read_config_dword(iommu->dev, iommu->cap_ptr + 4,
1161                                 &iommu->stored_addr_lo);
1162                 pci_read_config_dword(iommu->dev, iommu->cap_ptr + 8,
1163                                 &iommu->stored_addr_hi);
1164
1165                 /* Low bit locks writes to configuration space */
1166                 iommu->stored_addr_lo &= ~1;
1167
1168                 for (i = 0; i < 6; i++)
1169                         for (j = 0; j < 0x12; j++)
1170                                 iommu->stored_l1[i][j] = iommu_read_l1(iommu, i, j);
1171
1172                 for (i = 0; i < 0x83; i++)
1173                         iommu->stored_l2[i] = iommu_read_l2(iommu, i);
1174         }
1175
1176         return pci_enable_device(iommu->dev);
1177 }
1178
1179 static void print_iommu_info(void)
1180 {
1181         static const char * const feat_str[] = {
1182                 "PreF", "PPR", "X2APIC", "NX", "GT", "[5]",
1183                 "IA", "GA", "HE", "PC"
1184         };
1185         struct amd_iommu *iommu;
1186
1187         for_each_iommu(iommu) {
1188                 int i;
1189
1190                 pr_info("AMD-Vi: Found IOMMU at %s cap 0x%hx\n",
1191                         dev_name(&iommu->dev->dev), iommu->cap_ptr);
1192
1193                 if (iommu->cap & (1 << IOMMU_CAP_EFR)) {
1194                         pr_info("AMD-Vi:  Extended features: ");
1195                         for (i = 0; i < ARRAY_SIZE(feat_str); ++i) {
1196                                 if (iommu_feature(iommu, (1ULL << i)))
1197                                         pr_cont(" %s", feat_str[i]);
1198                         }
1199                 }
1200                 pr_cont("\n");
1201         }
1202 }
1203
1204 static int __init amd_iommu_init_pci(void)
1205 {
1206         struct amd_iommu *iommu;
1207         int ret = 0;
1208
1209         for_each_iommu(iommu) {
1210                 ret = iommu_init_pci(iommu);
1211                 if (ret)
1212                         break;
1213         }
1214
1215         ret = amd_iommu_init_devices();
1216
1217         print_iommu_info();
1218
1219         return ret;
1220 }
1221
1222 /****************************************************************************
1223  *
1224  * The following functions initialize the MSI interrupts for all IOMMUs
1225  * in the system. Its a bit challenging because there could be multiple
1226  * IOMMUs per PCI BDF but we can call pci_enable_msi(x) only once per
1227  * pci_dev.
1228  *
1229  ****************************************************************************/
1230
1231 static int iommu_setup_msi(struct amd_iommu *iommu)
1232 {
1233         int r;
1234
1235         r = pci_enable_msi(iommu->dev);
1236         if (r)
1237                 return r;
1238
1239         r = request_threaded_irq(iommu->dev->irq,
1240                                  amd_iommu_int_handler,
1241                                  amd_iommu_int_thread,
1242                                  0, "AMD-Vi",
1243                                  iommu->dev);
1244
1245         if (r) {
1246                 pci_disable_msi(iommu->dev);
1247                 return r;
1248         }
1249
1250         iommu->int_enabled = true;
1251
1252         return 0;
1253 }
1254
1255 static int iommu_init_msi(struct amd_iommu *iommu)
1256 {
1257         int ret;
1258
1259         if (iommu->int_enabled)
1260                 goto enable_faults;
1261
1262         if (pci_find_capability(iommu->dev, PCI_CAP_ID_MSI))
1263                 ret = iommu_setup_msi(iommu);
1264         else
1265                 ret = -ENODEV;
1266
1267         if (ret)
1268                 return ret;
1269
1270 enable_faults:
1271         iommu_feature_enable(iommu, CONTROL_EVT_INT_EN);
1272
1273         if (iommu->ppr_log != NULL)
1274                 iommu_feature_enable(iommu, CONTROL_PPFINT_EN);
1275
1276         return 0;
1277 }
1278
1279 /****************************************************************************
1280  *
1281  * The next functions belong to the third pass of parsing the ACPI
1282  * table. In this last pass the memory mapping requirements are
1283  * gathered (like exclusion and unity mapping reanges).
1284  *
1285  ****************************************************************************/
1286
1287 static void __init free_unity_maps(void)
1288 {
1289         struct unity_map_entry *entry, *next;
1290
1291         list_for_each_entry_safe(entry, next, &amd_iommu_unity_map, list) {
1292                 list_del(&entry->list);
1293                 kfree(entry);
1294         }
1295 }
1296
1297 /* called when we find an exclusion range definition in ACPI */
1298 static int __init init_exclusion_range(struct ivmd_header *m)
1299 {
1300         int i;
1301
1302         switch (m->type) {
1303         case ACPI_IVMD_TYPE:
1304                 set_device_exclusion_range(m->devid, m);
1305                 break;
1306         case ACPI_IVMD_TYPE_ALL:
1307                 for (i = 0; i <= amd_iommu_last_bdf; ++i)
1308                         set_device_exclusion_range(i, m);
1309                 break;
1310         case ACPI_IVMD_TYPE_RANGE:
1311                 for (i = m->devid; i <= m->aux; ++i)
1312                         set_device_exclusion_range(i, m);
1313                 break;
1314         default:
1315                 break;
1316         }
1317
1318         return 0;
1319 }
1320
1321 /* called for unity map ACPI definition */
1322 static int __init init_unity_map_range(struct ivmd_header *m)
1323 {
1324         struct unity_map_entry *e = NULL;
1325         char *s;
1326
1327         e = kzalloc(sizeof(*e), GFP_KERNEL);
1328         if (e == NULL)
1329                 return -ENOMEM;
1330
1331         switch (m->type) {
1332         default:
1333                 kfree(e);
1334                 return 0;
1335         case ACPI_IVMD_TYPE:
1336                 s = "IVMD_TYPEi\t\t\t";
1337                 e->devid_start = e->devid_end = m->devid;
1338                 break;
1339         case ACPI_IVMD_TYPE_ALL:
1340                 s = "IVMD_TYPE_ALL\t\t";
1341                 e->devid_start = 0;
1342                 e->devid_end = amd_iommu_last_bdf;
1343                 break;
1344         case ACPI_IVMD_TYPE_RANGE:
1345                 s = "IVMD_TYPE_RANGE\t\t";
1346                 e->devid_start = m->devid;
1347                 e->devid_end = m->aux;
1348                 break;
1349         }
1350         e->address_start = PAGE_ALIGN(m->range_start);
1351         e->address_end = e->address_start + PAGE_ALIGN(m->range_length);
1352         e->prot = m->flags >> 1;
1353
1354         DUMP_printk("%s devid_start: %02x:%02x.%x devid_end: %02x:%02x.%x"
1355                     " range_start: %016llx range_end: %016llx flags: %x\n", s,
1356                     PCI_BUS(e->devid_start), PCI_SLOT(e->devid_start),
1357                     PCI_FUNC(e->devid_start), PCI_BUS(e->devid_end),
1358                     PCI_SLOT(e->devid_end), PCI_FUNC(e->devid_end),
1359                     e->address_start, e->address_end, m->flags);
1360
1361         list_add_tail(&e->list, &amd_iommu_unity_map);
1362
1363         return 0;
1364 }
1365
1366 /* iterates over all memory definitions we find in the ACPI table */
1367 static int __init init_memory_definitions(struct acpi_table_header *table)
1368 {
1369         u8 *p = (u8 *)table, *end = (u8 *)table;
1370         struct ivmd_header *m;
1371
1372         end += table->length;
1373         p += IVRS_HEADER_LENGTH;
1374
1375         while (p < end) {
1376                 m = (struct ivmd_header *)p;
1377                 if (m->flags & IVMD_FLAG_EXCL_RANGE)
1378                         init_exclusion_range(m);
1379                 else if (m->flags & IVMD_FLAG_UNITY_MAP)
1380                         init_unity_map_range(m);
1381
1382                 p += m->length;
1383         }
1384
1385         return 0;
1386 }
1387
1388 /*
1389  * Init the device table to not allow DMA access for devices and
1390  * suppress all page faults
1391  */
1392 static void init_device_table_dma(void)
1393 {
1394         u32 devid;
1395
1396         for (devid = 0; devid <= amd_iommu_last_bdf; ++devid) {
1397                 set_dev_entry_bit(devid, DEV_ENTRY_VALID);
1398                 set_dev_entry_bit(devid, DEV_ENTRY_TRANSLATION);
1399         }
1400 }
1401
1402 static void init_device_table(void)
1403 {
1404         u32 devid;
1405
1406         if (!amd_iommu_irq_remap)
1407                 return;
1408
1409         for (devid = 0; devid <= amd_iommu_last_bdf; ++devid)
1410                 set_dev_entry_bit(devid, DEV_ENTRY_IRQ_TBL_EN);
1411 }
1412
1413 static void iommu_init_flags(struct amd_iommu *iommu)
1414 {
1415         iommu->acpi_flags & IVHD_FLAG_HT_TUN_EN_MASK ?
1416                 iommu_feature_enable(iommu, CONTROL_HT_TUN_EN) :
1417                 iommu_feature_disable(iommu, CONTROL_HT_TUN_EN);
1418
1419         iommu->acpi_flags & IVHD_FLAG_PASSPW_EN_MASK ?
1420                 iommu_feature_enable(iommu, CONTROL_PASSPW_EN) :
1421                 iommu_feature_disable(iommu, CONTROL_PASSPW_EN);
1422
1423         iommu->acpi_flags & IVHD_FLAG_RESPASSPW_EN_MASK ?
1424                 iommu_feature_enable(iommu, CONTROL_RESPASSPW_EN) :
1425                 iommu_feature_disable(iommu, CONTROL_RESPASSPW_EN);
1426
1427         iommu->acpi_flags & IVHD_FLAG_ISOC_EN_MASK ?
1428                 iommu_feature_enable(iommu, CONTROL_ISOC_EN) :
1429                 iommu_feature_disable(iommu, CONTROL_ISOC_EN);
1430
1431         /*
1432          * make IOMMU memory accesses cache coherent
1433          */
1434         iommu_feature_enable(iommu, CONTROL_COHERENT_EN);
1435
1436         /* Set IOTLB invalidation timeout to 1s */
1437         iommu_set_inv_tlb_timeout(iommu, CTRL_INV_TO_1S);
1438 }
1439
1440 static void iommu_apply_resume_quirks(struct amd_iommu *iommu)
1441 {
1442         int i, j;
1443         u32 ioc_feature_control;
1444         struct pci_dev *pdev = iommu->root_pdev;
1445
1446         /* RD890 BIOSes may not have completely reconfigured the iommu */
1447         if (!is_rd890_iommu(iommu->dev) || !pdev)
1448                 return;
1449
1450         /*
1451          * First, we need to ensure that the iommu is enabled. This is
1452          * controlled by a register in the northbridge
1453          */
1454
1455         /* Select Northbridge indirect register 0x75 and enable writing */
1456         pci_write_config_dword(pdev, 0x60, 0x75 | (1 << 7));
1457         pci_read_config_dword(pdev, 0x64, &ioc_feature_control);
1458
1459         /* Enable the iommu */
1460         if (!(ioc_feature_control & 0x1))
1461                 pci_write_config_dword(pdev, 0x64, ioc_feature_control | 1);
1462
1463         /* Restore the iommu BAR */
1464         pci_write_config_dword(iommu->dev, iommu->cap_ptr + 4,
1465                                iommu->stored_addr_lo);
1466         pci_write_config_dword(iommu->dev, iommu->cap_ptr + 8,
1467                                iommu->stored_addr_hi);
1468
1469         /* Restore the l1 indirect regs for each of the 6 l1s */
1470         for (i = 0; i < 6; i++)
1471                 for (j = 0; j < 0x12; j++)
1472                         iommu_write_l1(iommu, i, j, iommu->stored_l1[i][j]);
1473
1474         /* Restore the l2 indirect regs */
1475         for (i = 0; i < 0x83; i++)
1476                 iommu_write_l2(iommu, i, iommu->stored_l2[i]);
1477
1478         /* Lock PCI setup registers */
1479         pci_write_config_dword(iommu->dev, iommu->cap_ptr + 4,
1480                                iommu->stored_addr_lo | 1);
1481 }
1482
1483 /*
1484  * This function finally enables all IOMMUs found in the system after
1485  * they have been initialized
1486  */
1487 static void early_enable_iommus(void)
1488 {
1489         struct amd_iommu *iommu;
1490
1491         for_each_iommu(iommu) {
1492                 iommu_disable(iommu);
1493                 iommu_init_flags(iommu);
1494                 iommu_set_device_table(iommu);
1495                 iommu_enable_command_buffer(iommu);
1496                 iommu_enable_event_buffer(iommu);
1497                 iommu_set_exclusion_range(iommu);
1498                 iommu_enable(iommu);
1499                 iommu_flush_all_caches(iommu);
1500         }
1501 }
1502
1503 static void enable_iommus_v2(void)
1504 {
1505         struct amd_iommu *iommu;
1506
1507         for_each_iommu(iommu) {
1508                 iommu_enable_ppr_log(iommu);
1509                 iommu_enable_gt(iommu);
1510         }
1511 }
1512
1513 static void enable_iommus(void)
1514 {
1515         early_enable_iommus();
1516
1517         enable_iommus_v2();
1518 }
1519
1520 static void disable_iommus(void)
1521 {
1522         struct amd_iommu *iommu;
1523
1524         for_each_iommu(iommu)
1525                 iommu_disable(iommu);
1526 }
1527
1528 /*
1529  * Suspend/Resume support
1530  * disable suspend until real resume implemented
1531  */
1532
1533 static void amd_iommu_resume(void)
1534 {
1535         struct amd_iommu *iommu;
1536
1537         for_each_iommu(iommu)
1538                 iommu_apply_resume_quirks(iommu);
1539
1540         /* re-load the hardware */
1541         enable_iommus();
1542
1543         amd_iommu_enable_interrupts();
1544 }
1545
1546 static int amd_iommu_suspend(void)
1547 {
1548         /* disable IOMMUs to go out of the way for BIOS */
1549         disable_iommus();
1550
1551         return 0;
1552 }
1553
1554 static struct syscore_ops amd_iommu_syscore_ops = {
1555         .suspend = amd_iommu_suspend,
1556         .resume = amd_iommu_resume,
1557 };
1558
1559 static void __init free_on_init_error(void)
1560 {
1561         free_pages((unsigned long)irq_lookup_table,
1562                    get_order(rlookup_table_size));
1563
1564         if (amd_iommu_irq_cache) {
1565                 kmem_cache_destroy(amd_iommu_irq_cache);
1566                 amd_iommu_irq_cache = NULL;
1567
1568         }
1569
1570         amd_iommu_uninit_devices();
1571
1572         free_pages((unsigned long)amd_iommu_pd_alloc_bitmap,
1573                    get_order(MAX_DOMAIN_ID/8));
1574
1575         free_pages((unsigned long)amd_iommu_rlookup_table,
1576                    get_order(rlookup_table_size));
1577
1578         free_pages((unsigned long)amd_iommu_alias_table,
1579                    get_order(alias_table_size));
1580
1581         free_pages((unsigned long)amd_iommu_dev_table,
1582                    get_order(dev_table_size));
1583
1584         free_iommu_all();
1585
1586         free_unity_maps();
1587
1588 #ifdef CONFIG_GART_IOMMU
1589         /*
1590          * We failed to initialize the AMD IOMMU - try fallback to GART
1591          * if possible.
1592          */
1593         gart_iommu_init();
1594
1595 #endif
1596 }
1597
1598 static bool __init check_ioapic_information(void)
1599 {
1600         int idx;
1601
1602         for (idx = 0; idx < nr_ioapics; idx++) {
1603                 int id = mpc_ioapic_id(idx);
1604
1605                 if (get_ioapic_devid(id) < 0) {
1606                         pr_err(FW_BUG "AMD-Vi: IO-APIC[%d] not in IVRS table\n", id);
1607                         pr_err("AMD-Vi: Disabling interrupt remapping due to BIOS Bug\n");
1608                         return false;
1609                 }
1610         }
1611
1612         return true;
1613 }
1614
1615 /*
1616  * This is the hardware init function for AMD IOMMU in the system.
1617  * This function is called either from amd_iommu_init or from the interrupt
1618  * remapping setup code.
1619  *
1620  * This function basically parses the ACPI table for AMD IOMMU (IVRS)
1621  * three times:
1622  *
1623  *      1 pass) Find the highest PCI device id the driver has to handle.
1624  *              Upon this information the size of the data structures is
1625  *              determined that needs to be allocated.
1626  *
1627  *      2 pass) Initialize the data structures just allocated with the
1628  *              information in the ACPI table about available AMD IOMMUs
1629  *              in the system. It also maps the PCI devices in the
1630  *              system to specific IOMMUs
1631  *
1632  *      3 pass) After the basic data structures are allocated and
1633  *              initialized we update them with information about memory
1634  *              remapping requirements parsed out of the ACPI table in
1635  *              this last pass.
1636  *
1637  * After everything is set up the IOMMUs are enabled and the necessary
1638  * hotplug and suspend notifiers are registered.
1639  */
1640 static int __init early_amd_iommu_init(void)
1641 {
1642         struct acpi_table_header *ivrs_base;
1643         acpi_size ivrs_size;
1644         acpi_status status;
1645         int i, ret = 0;
1646
1647         if (!amd_iommu_detected)
1648                 return -ENODEV;
1649
1650         status = acpi_get_table_with_size("IVRS", 0, &ivrs_base, &ivrs_size);
1651         if (status == AE_NOT_FOUND)
1652                 return -ENODEV;
1653         else if (ACPI_FAILURE(status)) {
1654                 const char *err = acpi_format_exception(status);
1655                 pr_err("AMD-Vi: IVRS table error: %s\n", err);
1656                 return -EINVAL;
1657         }
1658
1659         /*
1660          * First parse ACPI tables to find the largest Bus/Dev/Func
1661          * we need to handle. Upon this information the shared data
1662          * structures for the IOMMUs in the system will be allocated
1663          */
1664         ret = find_last_devid_acpi(ivrs_base);
1665         if (ret)
1666                 goto out;
1667
1668         dev_table_size     = tbl_size(DEV_TABLE_ENTRY_SIZE);
1669         alias_table_size   = tbl_size(ALIAS_TABLE_ENTRY_SIZE);
1670         rlookup_table_size = tbl_size(RLOOKUP_TABLE_ENTRY_SIZE);
1671
1672         /* Device table - directly used by all IOMMUs */
1673         ret = -ENOMEM;
1674         amd_iommu_dev_table = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
1675                                       get_order(dev_table_size));
1676         if (amd_iommu_dev_table == NULL)
1677                 goto out;
1678
1679         /*
1680          * Alias table - map PCI Bus/Dev/Func to Bus/Dev/Func the
1681          * IOMMU see for that device
1682          */
1683         amd_iommu_alias_table = (void *)__get_free_pages(GFP_KERNEL,
1684                         get_order(alias_table_size));
1685         if (amd_iommu_alias_table == NULL)
1686                 goto out;
1687
1688         /* IOMMU rlookup table - find the IOMMU for a specific device */
1689         amd_iommu_rlookup_table = (void *)__get_free_pages(
1690                         GFP_KERNEL | __GFP_ZERO,
1691                         get_order(rlookup_table_size));
1692         if (amd_iommu_rlookup_table == NULL)
1693                 goto out;
1694
1695         amd_iommu_pd_alloc_bitmap = (void *)__get_free_pages(
1696                                             GFP_KERNEL | __GFP_ZERO,
1697                                             get_order(MAX_DOMAIN_ID/8));
1698         if (amd_iommu_pd_alloc_bitmap == NULL)
1699                 goto out;
1700
1701         /*
1702          * let all alias entries point to itself
1703          */
1704         for (i = 0; i <= amd_iommu_last_bdf; ++i)
1705                 amd_iommu_alias_table[i] = i;
1706
1707         /*
1708          * never allocate domain 0 because its used as the non-allocated and
1709          * error value placeholder
1710          */
1711         amd_iommu_pd_alloc_bitmap[0] = 1;
1712
1713         spin_lock_init(&amd_iommu_pd_lock);
1714
1715         /*
1716          * now the data structures are allocated and basically initialized
1717          * start the real acpi table scan
1718          */
1719         ret = init_iommu_all(ivrs_base);
1720         if (ret)
1721                 goto out;
1722
1723         if (amd_iommu_irq_remap)
1724                 amd_iommu_irq_remap = check_ioapic_information();
1725
1726         if (amd_iommu_irq_remap) {
1727                 /*
1728                  * Interrupt remapping enabled, create kmem_cache for the
1729                  * remapping tables.
1730                  */
1731                 amd_iommu_irq_cache = kmem_cache_create("irq_remap_cache",
1732                                 MAX_IRQS_PER_TABLE * sizeof(u32),
1733                                 IRQ_TABLE_ALIGNMENT,
1734                                 0, NULL);
1735                 if (!amd_iommu_irq_cache)
1736                         goto out;
1737
1738                 irq_lookup_table = (void *)__get_free_pages(
1739                                 GFP_KERNEL | __GFP_ZERO,
1740                                 get_order(rlookup_table_size));
1741                 if (!irq_lookup_table)
1742                         goto out;
1743         }
1744
1745         ret = init_memory_definitions(ivrs_base);
1746         if (ret)
1747                 goto out;
1748
1749         /* init the device table */
1750         init_device_table();
1751
1752 out:
1753         /* Don't leak any ACPI memory */
1754         early_acpi_os_unmap_memory((char __iomem *)ivrs_base, ivrs_size);
1755         ivrs_base = NULL;
1756
1757         return ret;
1758 }
1759
1760 static int amd_iommu_enable_interrupts(void)
1761 {
1762         struct amd_iommu *iommu;
1763         int ret = 0;
1764
1765         for_each_iommu(iommu) {
1766                 ret = iommu_init_msi(iommu);
1767                 if (ret)
1768                         goto out;
1769         }
1770
1771 out:
1772         return ret;
1773 }
1774
1775 static bool detect_ivrs(void)
1776 {
1777         struct acpi_table_header *ivrs_base;
1778         acpi_size ivrs_size;
1779         acpi_status status;
1780
1781         status = acpi_get_table_with_size("IVRS", 0, &ivrs_base, &ivrs_size);
1782         if (status == AE_NOT_FOUND)
1783                 return false;
1784         else if (ACPI_FAILURE(status)) {
1785                 const char *err = acpi_format_exception(status);
1786                 pr_err("AMD-Vi: IVRS table error: %s\n", err);
1787                 return false;
1788         }
1789
1790         early_acpi_os_unmap_memory((char __iomem *)ivrs_base, ivrs_size);
1791
1792         /* Make sure ACS will be enabled during PCI probe */
1793         pci_request_acs();
1794
1795         if (!disable_irq_remap)
1796                 amd_iommu_irq_remap = true;
1797
1798         return true;
1799 }
1800
1801 static int amd_iommu_init_dma(void)
1802 {
1803         struct amd_iommu *iommu;
1804         int ret;
1805
1806         init_device_table_dma();
1807
1808         for_each_iommu(iommu)
1809                 iommu_flush_all_caches(iommu);
1810
1811         if (iommu_pass_through)
1812                 ret = amd_iommu_init_passthrough();
1813         else
1814                 ret = amd_iommu_init_dma_ops();
1815
1816         if (ret)
1817                 return ret;
1818
1819         amd_iommu_init_api();
1820
1821         amd_iommu_init_notifier();
1822
1823         return 0;
1824 }
1825
1826 /****************************************************************************
1827  *
1828  * AMD IOMMU Initialization State Machine
1829  *
1830  ****************************************************************************/
1831
1832 static int __init state_next(void)
1833 {
1834         int ret = 0;
1835
1836         switch (init_state) {
1837         case IOMMU_START_STATE:
1838                 if (!detect_ivrs()) {
1839                         init_state      = IOMMU_NOT_FOUND;
1840                         ret             = -ENODEV;
1841                 } else {
1842                         init_state      = IOMMU_IVRS_DETECTED;
1843                 }
1844                 break;
1845         case IOMMU_IVRS_DETECTED:
1846                 ret = early_amd_iommu_init();
1847                 init_state = ret ? IOMMU_INIT_ERROR : IOMMU_ACPI_FINISHED;
1848                 break;
1849         case IOMMU_ACPI_FINISHED:
1850                 early_enable_iommus();
1851                 register_syscore_ops(&amd_iommu_syscore_ops);
1852                 x86_platform.iommu_shutdown = disable_iommus;
1853                 init_state = IOMMU_ENABLED;
1854                 break;
1855         case IOMMU_ENABLED:
1856                 ret = amd_iommu_init_pci();
1857                 init_state = ret ? IOMMU_INIT_ERROR : IOMMU_PCI_INIT;
1858                 enable_iommus_v2();
1859                 break;
1860         case IOMMU_PCI_INIT:
1861                 ret = amd_iommu_enable_interrupts();
1862                 init_state = ret ? IOMMU_INIT_ERROR : IOMMU_INTERRUPTS_EN;
1863                 break;
1864         case IOMMU_INTERRUPTS_EN:
1865                 ret = amd_iommu_init_dma();
1866                 init_state = ret ? IOMMU_INIT_ERROR : IOMMU_DMA_OPS;
1867                 break;
1868         case IOMMU_DMA_OPS:
1869                 init_state = IOMMU_INITIALIZED;
1870                 break;
1871         case IOMMU_INITIALIZED:
1872                 /* Nothing to do */
1873                 break;
1874         case IOMMU_NOT_FOUND:
1875         case IOMMU_INIT_ERROR:
1876                 /* Error states => do nothing */
1877                 ret = -EINVAL;
1878                 break;
1879         default:
1880                 /* Unknown state */
1881                 BUG();
1882         }
1883
1884         return ret;
1885 }
1886
1887 static int __init iommu_go_to_state(enum iommu_init_state state)
1888 {
1889         int ret = 0;
1890
1891         while (init_state != state) {
1892                 ret = state_next();
1893                 if (init_state == IOMMU_NOT_FOUND ||
1894                     init_state == IOMMU_INIT_ERROR)
1895                         break;
1896         }
1897
1898         return ret;
1899 }
1900
1901 #ifdef CONFIG_IRQ_REMAP
1902 int __init amd_iommu_prepare(void)
1903 {
1904         return iommu_go_to_state(IOMMU_ACPI_FINISHED);
1905 }
1906
1907 int __init amd_iommu_supported(void)
1908 {
1909         return amd_iommu_irq_remap ? 1 : 0;
1910 }
1911
1912 int __init amd_iommu_enable(void)
1913 {
1914         int ret;
1915
1916         ret = iommu_go_to_state(IOMMU_ENABLED);
1917         if (ret)
1918                 return ret;
1919
1920         irq_remapping_enabled = 1;
1921
1922         return 0;
1923 }
1924
1925 void amd_iommu_disable(void)
1926 {
1927         amd_iommu_suspend();
1928 }
1929
1930 int amd_iommu_reenable(int mode)
1931 {
1932         amd_iommu_resume();
1933
1934         return 0;
1935 }
1936
1937 int __init amd_iommu_enable_faulting(void)
1938 {
1939         /* We enable MSI later when PCI is initialized */
1940         return 0;
1941 }
1942 #endif
1943
1944 /*
1945  * This is the core init function for AMD IOMMU hardware in the system.
1946  * This function is called from the generic x86 DMA layer initialization
1947  * code.
1948  */
1949 static int __init amd_iommu_init(void)
1950 {
1951         int ret;
1952
1953         ret = iommu_go_to_state(IOMMU_INITIALIZED);
1954         if (ret) {
1955                 disable_iommus();
1956                 free_on_init_error();
1957         }
1958
1959         return ret;
1960 }
1961
1962 /****************************************************************************
1963  *
1964  * Early detect code. This code runs at IOMMU detection time in the DMA
1965  * layer. It just looks if there is an IVRS ACPI table to detect AMD
1966  * IOMMUs
1967  *
1968  ****************************************************************************/
1969 int __init amd_iommu_detect(void)
1970 {
1971         int ret;
1972
1973         if (no_iommu || (iommu_detected && !gart_iommu_aperture))
1974                 return -ENODEV;
1975
1976         if (amd_iommu_disabled)
1977                 return -ENODEV;
1978
1979         ret = iommu_go_to_state(IOMMU_IVRS_DETECTED);
1980         if (ret)
1981                 return ret;
1982
1983         amd_iommu_detected = true;
1984         iommu_detected = 1;
1985         x86_init.iommu.iommu_init = amd_iommu_init;
1986
1987         return 0;
1988 }
1989
1990 /****************************************************************************
1991  *
1992  * Parsing functions for the AMD IOMMU specific kernel command line
1993  * options.
1994  *
1995  ****************************************************************************/
1996
1997 static int __init parse_amd_iommu_dump(char *str)
1998 {
1999         amd_iommu_dump = true;
2000
2001         return 1;
2002 }
2003
2004 static int __init parse_amd_iommu_options(char *str)
2005 {
2006         for (; *str; ++str) {
2007                 if (strncmp(str, "fullflush", 9) == 0)
2008                         amd_iommu_unmap_flush = true;
2009                 if (strncmp(str, "off", 3) == 0)
2010                         amd_iommu_disabled = true;
2011                 if (strncmp(str, "force_isolation", 15) == 0)
2012                         amd_iommu_force_isolation = true;
2013         }
2014
2015         return 1;
2016 }
2017
2018 __setup("amd_iommu_dump", parse_amd_iommu_dump);
2019 __setup("amd_iommu=", parse_amd_iommu_options);
2020
2021 IOMMU_INIT_FINISH(amd_iommu_detect,
2022                   gart_iommu_hole_init,
2023                   NULL,
2024                   NULL);
2025
2026 bool amd_iommu_v2_supported(void)
2027 {
2028         return amd_iommu_v2_present;
2029 }
2030 EXPORT_SYMBOL(amd_iommu_v2_supported);