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