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