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