linux/drivers/iommu/amd_iommu.c
<<
>>
Prefs
   1/*
   2 * Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
   3 * Author: Joerg Roedel <joerg.roedel@amd.com>
   4 *         Leo Duran <leo.duran@amd.com>
   5 *
   6 * This program is free software; you can redistribute it and/or modify it
   7 * under the terms of the GNU General Public License version 2 as published
   8 * by the Free Software Foundation.
   9 *
  10 * This program is distributed in the hope that it will be useful,
  11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13 * GNU General Public License for more details.
  14 *
  15 * You should have received a copy of the GNU General Public License
  16 * along with this program; if not, write to the Free Software
  17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  18 */
  19
  20#include <linux/ratelimit.h>
  21#include <linux/pci.h>
  22#include <linux/pci-ats.h>
  23#include <linux/bitmap.h>
  24#include <linux/slab.h>
  25#include <linux/debugfs.h>
  26#include <linux/scatterlist.h>
  27#include <linux/dma-mapping.h>
  28#include <linux/iommu-helper.h>
  29#include <linux/iommu.h>
  30#include <linux/delay.h>
  31#include <linux/amd-iommu.h>
  32#include <linux/notifier.h>
  33#include <linux/export.h>
  34#include <linux/irq.h>
  35#include <linux/msi.h>
  36#include <asm/irq_remapping.h>
  37#include <asm/io_apic.h>
  38#include <asm/apic.h>
  39#include <asm/hw_irq.h>
  40#include <asm/msidef.h>
  41#include <asm/proto.h>
  42#include <asm/iommu.h>
  43#include <asm/gart.h>
  44#include <asm/dma.h>
  45
  46#include "amd_iommu_proto.h"
  47#include "amd_iommu_types.h"
  48#include "irq_remapping.h"
  49
  50#define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
  51
  52#define LOOP_TIMEOUT    100000
  53
  54/*
  55 * This bitmap is used to advertise the page sizes our hardware support
  56 * to the IOMMU core, which will then use this information to split
  57 * physically contiguous memory regions it is mapping into page sizes
  58 * that we support.
  59 *
  60 * Traditionally the IOMMU core just handed us the mappings directly,
  61 * after making sure the size is an order of a 4KiB page and that the
  62 * mapping has natural alignment.
  63 *
  64 * To retain this behavior, we currently advertise that we support
  65 * all page sizes that are an order of 4KiB.
  66 *
  67 * If at some point we'd like to utilize the IOMMU core's new behavior,
  68 * we could change this to advertise the real page sizes we support.
  69 */
  70#define AMD_IOMMU_PGSIZES       (~0xFFFUL)
  71
  72static DEFINE_RWLOCK(amd_iommu_devtable_lock);
  73
  74/* A list of preallocated protection domains */
  75static LIST_HEAD(iommu_pd_list);
  76static DEFINE_SPINLOCK(iommu_pd_list_lock);
  77
  78/* List of all available dev_data structures */
  79static LIST_HEAD(dev_data_list);
  80static DEFINE_SPINLOCK(dev_data_list_lock);
  81
  82LIST_HEAD(ioapic_map);
  83LIST_HEAD(hpet_map);
  84
  85/*
  86 * Domain for untranslated devices - only allocated
  87 * if iommu=pt passed on kernel cmd line.
  88 */
  89static struct protection_domain *pt_domain;
  90
  91static struct iommu_ops amd_iommu_ops;
  92
  93static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
  94int amd_iommu_max_glx_val = -1;
  95
  96static struct dma_map_ops amd_iommu_dma_ops;
  97
  98/*
  99 * general struct to manage commands send to an IOMMU
 100 */
 101struct iommu_cmd {
 102        u32 data[4];
 103};
 104
 105struct kmem_cache *amd_iommu_irq_cache;
 106
 107static void update_domain(struct protection_domain *domain);
 108static int __init alloc_passthrough_domain(void);
 109
 110/****************************************************************************
 111 *
 112 * Helper functions
 113 *
 114 ****************************************************************************/
 115
 116static struct iommu_dev_data *alloc_dev_data(u16 devid)
 117{
 118        struct iommu_dev_data *dev_data;
 119        unsigned long flags;
 120
 121        dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
 122        if (!dev_data)
 123                return NULL;
 124
 125        dev_data->devid = devid;
 126        atomic_set(&dev_data->bind, 0);
 127
 128        spin_lock_irqsave(&dev_data_list_lock, flags);
 129        list_add_tail(&dev_data->dev_data_list, &dev_data_list);
 130        spin_unlock_irqrestore(&dev_data_list_lock, flags);
 131
 132        return dev_data;
 133}
 134
 135static void free_dev_data(struct iommu_dev_data *dev_data)
 136{
 137        unsigned long flags;
 138
 139        spin_lock_irqsave(&dev_data_list_lock, flags);
 140        list_del(&dev_data->dev_data_list);
 141        spin_unlock_irqrestore(&dev_data_list_lock, flags);
 142
 143        kfree(dev_data);
 144}
 145
 146static struct iommu_dev_data *search_dev_data(u16 devid)
 147{
 148        struct iommu_dev_data *dev_data;
 149        unsigned long flags;
 150
 151        spin_lock_irqsave(&dev_data_list_lock, flags);
 152        list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
 153                if (dev_data->devid == devid)
 154                        goto out_unlock;
 155        }
 156
 157        dev_data = NULL;
 158
 159out_unlock:
 160        spin_unlock_irqrestore(&dev_data_list_lock, flags);
 161
 162        return dev_data;
 163}
 164
 165static struct iommu_dev_data *find_dev_data(u16 devid)
 166{
 167        struct iommu_dev_data *dev_data;
 168
 169        dev_data = search_dev_data(devid);
 170
 171        if (dev_data == NULL)
 172                dev_data = alloc_dev_data(devid);
 173
 174        return dev_data;
 175}
 176
 177static inline u16 get_device_id(struct device *dev)
 178{
 179        struct pci_dev *pdev = to_pci_dev(dev);
 180
 181        return calc_devid(pdev->bus->number, pdev->devfn);
 182}
 183
 184static struct iommu_dev_data *get_dev_data(struct device *dev)
 185{
 186        return dev->archdata.iommu;
 187}
 188
 189static bool pci_iommuv2_capable(struct pci_dev *pdev)
 190{
 191        static const int caps[] = {
 192                PCI_EXT_CAP_ID_ATS,
 193                PCI_EXT_CAP_ID_PRI,
 194                PCI_EXT_CAP_ID_PASID,
 195        };
 196        int i, pos;
 197
 198        for (i = 0; i < 3; ++i) {
 199                pos = pci_find_ext_capability(pdev, caps[i]);
 200                if (pos == 0)
 201                        return false;
 202        }
 203
 204        return true;
 205}
 206
 207static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
 208{
 209        struct iommu_dev_data *dev_data;
 210
 211        dev_data = get_dev_data(&pdev->dev);
 212
 213        return dev_data->errata & (1 << erratum) ? true : false;
 214}
 215
 216/*
 217 * In this function the list of preallocated protection domains is traversed to
 218 * find the domain for a specific device
 219 */
 220static struct dma_ops_domain *find_protection_domain(u16 devid)
 221{
 222        struct dma_ops_domain *entry, *ret = NULL;
 223        unsigned long flags;
 224        u16 alias = amd_iommu_alias_table[devid];
 225
 226        if (list_empty(&iommu_pd_list))
 227                return NULL;
 228
 229        spin_lock_irqsave(&iommu_pd_list_lock, flags);
 230
 231        list_for_each_entry(entry, &iommu_pd_list, list) {
 232                if (entry->target_dev == devid ||
 233                    entry->target_dev == alias) {
 234                        ret = entry;
 235                        break;
 236                }
 237        }
 238
 239        spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
 240
 241        return ret;
 242}
 243
 244/*
 245 * This function checks if the driver got a valid device from the caller to
 246 * avoid dereferencing invalid pointers.
 247 */
 248static bool check_device(struct device *dev)
 249{
 250        u16 devid;
 251
 252        if (!dev || !dev->dma_mask)
 253                return false;
 254
 255        /* No device or no PCI device */
 256        if (dev->bus != &pci_bus_type)
 257                return false;
 258
 259        devid = get_device_id(dev);
 260
 261        /* Out of our scope? */
 262        if (devid > amd_iommu_last_bdf)
 263                return false;
 264
 265        if (amd_iommu_rlookup_table[devid] == NULL)
 266                return false;
 267
 268        return true;
 269}
 270
 271static void swap_pci_ref(struct pci_dev **from, struct pci_dev *to)
 272{
 273        pci_dev_put(*from);
 274        *from = to;
 275}
 276
 277#define REQ_ACS_FLAGS   (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
 278
 279static int iommu_init_device(struct device *dev)
 280{
 281        struct pci_dev *dma_pdev = NULL, *pdev = to_pci_dev(dev);
 282        struct iommu_dev_data *dev_data;
 283        struct iommu_group *group;
 284        u16 alias;
 285        int ret;
 286
 287        if (dev->archdata.iommu)
 288                return 0;
 289
 290        dev_data = find_dev_data(get_device_id(dev));
 291        if (!dev_data)
 292                return -ENOMEM;
 293
 294        alias = amd_iommu_alias_table[dev_data->devid];
 295        if (alias != dev_data->devid) {
 296                struct iommu_dev_data *alias_data;
 297
 298                alias_data = find_dev_data(alias);
 299                if (alias_data == NULL) {
 300                        pr_err("AMD-Vi: Warning: Unhandled device %s\n",
 301                                        dev_name(dev));
 302                        free_dev_data(dev_data);
 303                        return -ENOTSUPP;
 304                }
 305                dev_data->alias_data = alias_data;
 306
 307                dma_pdev = pci_get_bus_and_slot(alias >> 8, alias & 0xff);
 308        }
 309
 310        if (dma_pdev == NULL)
 311                dma_pdev = pci_dev_get(pdev);
 312
 313        /* Account for quirked devices */
 314        swap_pci_ref(&dma_pdev, pci_get_dma_source(dma_pdev));
 315
 316        /*
 317         * If it's a multifunction device that does not support our
 318         * required ACS flags, add to the same group as function 0.
 319         */
 320        if (dma_pdev->multifunction &&
 321            !pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS))
 322                swap_pci_ref(&dma_pdev,
 323                             pci_get_slot(dma_pdev->bus,
 324                                          PCI_DEVFN(PCI_SLOT(dma_pdev->devfn),
 325                                          0)));
 326
 327        /*
 328         * Devices on the root bus go through the iommu.  If that's not us,
 329         * find the next upstream device and test ACS up to the root bus.
 330         * Finding the next device may require skipping virtual buses.
 331         */
 332        while (!pci_is_root_bus(dma_pdev->bus)) {
 333                struct pci_bus *bus = dma_pdev->bus;
 334
 335                while (!bus->self) {
 336                        if (!pci_is_root_bus(bus))
 337                                bus = bus->parent;
 338                        else
 339                                goto root_bus;
 340                }
 341
 342                if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
 343                        break;
 344
 345                swap_pci_ref(&dma_pdev, pci_dev_get(bus->self));
 346        }
 347
 348root_bus:
 349        group = iommu_group_get(&dma_pdev->dev);
 350        pci_dev_put(dma_pdev);
 351        if (!group) {
 352                group = iommu_group_alloc();
 353                if (IS_ERR(group))
 354                        return PTR_ERR(group);
 355        }
 356
 357        ret = iommu_group_add_device(group, dev);
 358
 359        iommu_group_put(group);
 360
 361        if (ret)
 362                return ret;
 363
 364        if (pci_iommuv2_capable(pdev)) {
 365                struct amd_iommu *iommu;
 366
 367                iommu              = amd_iommu_rlookup_table[dev_data->devid];
 368                dev_data->iommu_v2 = iommu->is_iommu_v2;
 369        }
 370
 371        dev->archdata.iommu = dev_data;
 372
 373        return 0;
 374}
 375
 376static void iommu_ignore_device(struct device *dev)
 377{
 378        u16 devid, alias;
 379
 380        devid = get_device_id(dev);
 381        alias = amd_iommu_alias_table[devid];
 382
 383        memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
 384        memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
 385
 386        amd_iommu_rlookup_table[devid] = NULL;
 387        amd_iommu_rlookup_table[alias] = NULL;
 388}
 389
 390static void iommu_uninit_device(struct device *dev)
 391{
 392        iommu_group_remove_device(dev);
 393
 394        /*
 395         * Nothing to do here - we keep dev_data around for unplugged devices
 396         * and reuse it when the device is re-plugged - not doing so would
 397         * introduce a ton of races.
 398         */
 399}
 400
 401void __init amd_iommu_uninit_devices(void)
 402{
 403        struct iommu_dev_data *dev_data, *n;
 404        struct pci_dev *pdev = NULL;
 405
 406        for_each_pci_dev(pdev) {
 407
 408                if (!check_device(&pdev->dev))
 409                        continue;
 410
 411                iommu_uninit_device(&pdev->dev);
 412        }
 413
 414        /* Free all of our dev_data structures */
 415        list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
 416                free_dev_data(dev_data);
 417}
 418
 419int __init amd_iommu_init_devices(void)
 420{
 421        struct pci_dev *pdev = NULL;
 422        int ret = 0;
 423
 424        for_each_pci_dev(pdev) {
 425
 426                if (!check_device(&pdev->dev))
 427                        continue;
 428
 429                ret = iommu_init_device(&pdev->dev);
 430                if (ret == -ENOTSUPP)
 431                        iommu_ignore_device(&pdev->dev);
 432                else if (ret)
 433                        goto out_free;
 434        }
 435
 436        return 0;
 437
 438out_free:
 439
 440        amd_iommu_uninit_devices();
 441
 442        return ret;
 443}
 444#ifdef CONFIG_AMD_IOMMU_STATS
 445
 446/*
 447 * Initialization code for statistics collection
 448 */
 449
 450DECLARE_STATS_COUNTER(compl_wait);
 451DECLARE_STATS_COUNTER(cnt_map_single);
 452DECLARE_STATS_COUNTER(cnt_unmap_single);
 453DECLARE_STATS_COUNTER(cnt_map_sg);
 454DECLARE_STATS_COUNTER(cnt_unmap_sg);
 455DECLARE_STATS_COUNTER(cnt_alloc_coherent);
 456DECLARE_STATS_COUNTER(cnt_free_coherent);
 457DECLARE_STATS_COUNTER(cross_page);
 458DECLARE_STATS_COUNTER(domain_flush_single);
 459DECLARE_STATS_COUNTER(domain_flush_all);
 460DECLARE_STATS_COUNTER(alloced_io_mem);
 461DECLARE_STATS_COUNTER(total_map_requests);
 462DECLARE_STATS_COUNTER(complete_ppr);
 463DECLARE_STATS_COUNTER(invalidate_iotlb);
 464DECLARE_STATS_COUNTER(invalidate_iotlb_all);
 465DECLARE_STATS_COUNTER(pri_requests);
 466
 467static struct dentry *stats_dir;
 468static struct dentry *de_fflush;
 469
 470static void amd_iommu_stats_add(struct __iommu_counter *cnt)
 471{
 472        if (stats_dir == NULL)
 473                return;
 474
 475        cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
 476                                       &cnt->value);
 477}
 478
 479static void amd_iommu_stats_init(void)
 480{
 481        stats_dir = debugfs_create_dir("amd-iommu", NULL);
 482        if (stats_dir == NULL)
 483                return;
 484
 485        de_fflush  = debugfs_create_bool("fullflush", 0444, stats_dir,
 486                                         &amd_iommu_unmap_flush);
 487
 488        amd_iommu_stats_add(&compl_wait);
 489        amd_iommu_stats_add(&cnt_map_single);
 490        amd_iommu_stats_add(&cnt_unmap_single);
 491        amd_iommu_stats_add(&cnt_map_sg);
 492        amd_iommu_stats_add(&cnt_unmap_sg);
 493        amd_iommu_stats_add(&cnt_alloc_coherent);
 494        amd_iommu_stats_add(&cnt_free_coherent);
 495        amd_iommu_stats_add(&cross_page);
 496        amd_iommu_stats_add(&domain_flush_single);
 497        amd_iommu_stats_add(&domain_flush_all);
 498        amd_iommu_stats_add(&alloced_io_mem);
 499        amd_iommu_stats_add(&total_map_requests);
 500        amd_iommu_stats_add(&complete_ppr);
 501        amd_iommu_stats_add(&invalidate_iotlb);
 502        amd_iommu_stats_add(&invalidate_iotlb_all);
 503        amd_iommu_stats_add(&pri_requests);
 504}
 505
 506#endif
 507
 508/****************************************************************************
 509 *
 510 * Interrupt handling functions
 511 *
 512 ****************************************************************************/
 513
 514static void dump_dte_entry(u16 devid)
 515{
 516        int i;
 517
 518        for (i = 0; i < 4; ++i)
 519                pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
 520                        amd_iommu_dev_table[devid].data[i]);
 521}
 522
 523static void dump_command(unsigned long phys_addr)
 524{
 525        struct iommu_cmd *cmd = phys_to_virt(phys_addr);
 526        int i;
 527
 528        for (i = 0; i < 4; ++i)
 529                pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
 530}
 531
 532static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
 533{
 534        int type, devid, domid, flags;
 535        volatile u32 *event = __evt;
 536        int count = 0;
 537        u64 address;
 538
 539retry:
 540        type    = (event[1] >> EVENT_TYPE_SHIFT)  & EVENT_TYPE_MASK;
 541        devid   = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
 542        domid   = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
 543        flags   = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
 544        address = (u64)(((u64)event[3]) << 32) | event[2];
 545
 546        if (type == 0) {
 547                /* Did we hit the erratum? */
 548                if (++count == LOOP_TIMEOUT) {
 549                        pr_err("AMD-Vi: No event written to event log\n");
 550                        return;
 551                }
 552                udelay(1);
 553                goto retry;
 554        }
 555
 556        printk(KERN_ERR "AMD-Vi: Event logged [");
 557
 558        switch (type) {
 559        case EVENT_TYPE_ILL_DEV:
 560                printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
 561                       "address=0x%016llx flags=0x%04x]\n",
 562                       PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
 563                       address, flags);
 564                dump_dte_entry(devid);
 565                break;
 566        case EVENT_TYPE_IO_FAULT:
 567                printk("IO_PAGE_FAULT device=%02x:%02x.%x "
 568                       "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
 569                       PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
 570                       domid, address, flags);
 571                break;
 572        case EVENT_TYPE_DEV_TAB_ERR:
 573                printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
 574                       "address=0x%016llx flags=0x%04x]\n",
 575                       PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
 576                       address, flags);
 577                break;
 578        case EVENT_TYPE_PAGE_TAB_ERR:
 579                printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
 580                       "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
 581                       PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
 582                       domid, address, flags);
 583                break;
 584        case EVENT_TYPE_ILL_CMD:
 585                printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
 586                dump_command(address);
 587                break;
 588        case EVENT_TYPE_CMD_HARD_ERR:
 589                printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
 590                       "flags=0x%04x]\n", address, flags);
 591                break;
 592        case EVENT_TYPE_IOTLB_INV_TO:
 593                printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
 594                       "address=0x%016llx]\n",
 595                       PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
 596                       address);
 597                break;
 598        case EVENT_TYPE_INV_DEV_REQ:
 599                printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
 600                       "address=0x%016llx flags=0x%04x]\n",
 601                       PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
 602                       address, flags);
 603                break;
 604        default:
 605                printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
 606        }
 607
 608        memset(__evt, 0, 4 * sizeof(u32));
 609}
 610
 611static void iommu_poll_events(struct amd_iommu *iommu)
 612{
 613        u32 head, tail;
 614        unsigned long flags;
 615
 616        spin_lock_irqsave(&iommu->lock, flags);
 617
 618        head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
 619        tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
 620
 621        while (head != tail) {
 622                iommu_print_event(iommu, iommu->evt_buf + head);
 623                head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
 624        }
 625
 626        writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
 627
 628        spin_unlock_irqrestore(&iommu->lock, flags);
 629}
 630
 631static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
 632{
 633        struct amd_iommu_fault fault;
 634
 635        INC_STATS_COUNTER(pri_requests);
 636
 637        if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
 638                pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
 639                return;
 640        }
 641
 642        fault.address   = raw[1];
 643        fault.pasid     = PPR_PASID(raw[0]);
 644        fault.device_id = PPR_DEVID(raw[0]);
 645        fault.tag       = PPR_TAG(raw[0]);
 646        fault.flags     = PPR_FLAGS(raw[0]);
 647
 648        atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
 649}
 650
 651static void iommu_poll_ppr_log(struct amd_iommu *iommu)
 652{
 653        unsigned long flags;
 654        u32 head, tail;
 655
 656        if (iommu->ppr_log == NULL)
 657                return;
 658
 659        /* enable ppr interrupts again */
 660        writel(MMIO_STATUS_PPR_INT_MASK, iommu->mmio_base + MMIO_STATUS_OFFSET);
 661
 662        spin_lock_irqsave(&iommu->lock, flags);
 663
 664        head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
 665        tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
 666
 667        while (head != tail) {
 668                volatile u64 *raw;
 669                u64 entry[2];
 670                int i;
 671
 672                raw = (u64 *)(iommu->ppr_log + head);
 673
 674                /*
 675                 * Hardware bug: Interrupt may arrive before the entry is
 676                 * written to memory. If this happens we need to wait for the
 677                 * entry to arrive.
 678                 */
 679                for (i = 0; i < LOOP_TIMEOUT; ++i) {
 680                        if (PPR_REQ_TYPE(raw[0]) != 0)
 681                                break;
 682                        udelay(1);
 683                }
 684
 685                /* Avoid memcpy function-call overhead */
 686                entry[0] = raw[0];
 687                entry[1] = raw[1];
 688
 689                /*
 690                 * To detect the hardware bug we need to clear the entry
 691                 * back to zero.
 692                 */
 693                raw[0] = raw[1] = 0UL;
 694
 695                /* Update head pointer of hardware ring-buffer */
 696                head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
 697                writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
 698
 699                /*
 700                 * Release iommu->lock because ppr-handling might need to
 701                 * re-acquire it
 702                 */
 703                spin_unlock_irqrestore(&iommu->lock, flags);
 704
 705                /* Handle PPR entry */
 706                iommu_handle_ppr_entry(iommu, entry);
 707
 708                spin_lock_irqsave(&iommu->lock, flags);
 709
 710                /* Refresh ring-buffer information */
 711                head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
 712                tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
 713        }
 714
 715        spin_unlock_irqrestore(&iommu->lock, flags);
 716}
 717
 718irqreturn_t amd_iommu_int_thread(int irq, void *data)
 719{
 720        struct amd_iommu *iommu;
 721
 722        for_each_iommu(iommu) {
 723                iommu_poll_events(iommu);
 724                iommu_poll_ppr_log(iommu);
 725        }
 726
 727        return IRQ_HANDLED;
 728}
 729
 730irqreturn_t amd_iommu_int_handler(int irq, void *data)
 731{
 732        return IRQ_WAKE_THREAD;
 733}
 734
 735/****************************************************************************
 736 *
 737 * IOMMU command queuing functions
 738 *
 739 ****************************************************************************/
 740
 741static int wait_on_sem(volatile u64 *sem)
 742{
 743        int i = 0;
 744
 745        while (*sem == 0 && i < LOOP_TIMEOUT) {
 746                udelay(1);
 747                i += 1;
 748        }
 749
 750        if (i == LOOP_TIMEOUT) {
 751                pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
 752                return -EIO;
 753        }
 754
 755        return 0;
 756}
 757
 758static void copy_cmd_to_buffer(struct amd_iommu *iommu,
 759                               struct iommu_cmd *cmd,
 760                               u32 tail)
 761{
 762        u8 *target;
 763
 764        target = iommu->cmd_buf + tail;
 765        tail   = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
 766
 767        /* Copy command to buffer */
 768        memcpy(target, cmd, sizeof(*cmd));
 769
 770        /* Tell the IOMMU about it */
 771        writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
 772}
 773
 774static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
 775{
 776        WARN_ON(address & 0x7ULL);
 777
 778        memset(cmd, 0, sizeof(*cmd));
 779        cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
 780        cmd->data[1] = upper_32_bits(__pa(address));
 781        cmd->data[2] = 1;
 782        CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
 783}
 784
 785static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
 786{
 787        memset(cmd, 0, sizeof(*cmd));
 788        cmd->data[0] = devid;
 789        CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
 790}
 791
 792static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
 793                                  size_t size, u16 domid, int pde)
 794{
 795        u64 pages;
 796        int s;
 797
 798        pages = iommu_num_pages(address, size, PAGE_SIZE);
 799        s     = 0;
 800
 801        if (pages > 1) {
 802                /*
 803                 * If we have to flush more than one page, flush all
 804                 * TLB entries for this domain
 805                 */
 806                address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
 807                s = 1;
 808        }
 809
 810        address &= PAGE_MASK;
 811
 812        memset(cmd, 0, sizeof(*cmd));
 813        cmd->data[1] |= domid;
 814        cmd->data[2]  = lower_32_bits(address);
 815        cmd->data[3]  = upper_32_bits(address);
 816        CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
 817        if (s) /* size bit - we flush more than one 4kb page */
 818                cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
 819        if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
 820                cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
 821}
 822
 823static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
 824                                  u64 address, size_t size)
 825{
 826        u64 pages;
 827        int s;
 828
 829        pages = iommu_num_pages(address, size, PAGE_SIZE);
 830        s     = 0;
 831
 832        if (pages > 1) {
 833                /*
 834                 * If we have to flush more than one page, flush all
 835                 * TLB entries for this domain
 836                 */
 837                address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
 838                s = 1;
 839        }
 840
 841        address &= PAGE_MASK;
 842
 843        memset(cmd, 0, sizeof(*cmd));
 844        cmd->data[0]  = devid;
 845        cmd->data[0] |= (qdep & 0xff) << 24;
 846        cmd->data[1]  = devid;
 847        cmd->data[2]  = lower_32_bits(address);
 848        cmd->data[3]  = upper_32_bits(address);
 849        CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
 850        if (s)
 851                cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
 852}
 853
 854static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
 855                                  u64 address, bool size)
 856{
 857        memset(cmd, 0, sizeof(*cmd));
 858
 859        address &= ~(0xfffULL);
 860
 861        cmd->data[0]  = pasid & PASID_MASK;
 862        cmd->data[1]  = domid;
 863        cmd->data[2]  = lower_32_bits(address);
 864        cmd->data[3]  = upper_32_bits(address);
 865        cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
 866        cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
 867        if (size)
 868                cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
 869        CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
 870}
 871
 872static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
 873                                  int qdep, u64 address, bool size)
 874{
 875        memset(cmd, 0, sizeof(*cmd));
 876
 877        address &= ~(0xfffULL);
 878
 879        cmd->data[0]  = devid;
 880        cmd->data[0] |= (pasid & 0xff) << 16;
 881        cmd->data[0] |= (qdep  & 0xff) << 24;
 882        cmd->data[1]  = devid;
 883        cmd->data[1] |= ((pasid >> 8) & 0xfff) << 16;
 884        cmd->data[2]  = lower_32_bits(address);
 885        cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
 886        cmd->data[3]  = upper_32_bits(address);
 887        if (size)
 888                cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
 889        CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
 890}
 891
 892static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
 893                               int status, int tag, bool gn)
 894{
 895        memset(cmd, 0, sizeof(*cmd));
 896
 897        cmd->data[0]  = devid;
 898        if (gn) {
 899                cmd->data[1]  = pasid & PASID_MASK;
 900                cmd->data[2]  = CMD_INV_IOMMU_PAGES_GN_MASK;
 901        }
 902        cmd->data[3]  = tag & 0x1ff;
 903        cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
 904
 905        CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
 906}
 907
 908static void build_inv_all(struct iommu_cmd *cmd)
 909{
 910        memset(cmd, 0, sizeof(*cmd));
 911        CMD_SET_TYPE(cmd, CMD_INV_ALL);
 912}
 913
 914static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
 915{
 916        memset(cmd, 0, sizeof(*cmd));
 917        cmd->data[0] = devid;
 918        CMD_SET_TYPE(cmd, CMD_INV_IRT);
 919}
 920
 921/*
 922 * Writes the command to the IOMMUs command buffer and informs the
 923 * hardware about the new command.
 924 */
 925static int iommu_queue_command_sync(struct amd_iommu *iommu,
 926                                    struct iommu_cmd *cmd,
 927                                    bool sync)
 928{
 929        u32 left, tail, head, next_tail;
 930        unsigned long flags;
 931
 932        WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
 933
 934again:
 935        spin_lock_irqsave(&iommu->lock, flags);
 936
 937        head      = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
 938        tail      = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
 939        next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
 940        left      = (head - next_tail) % iommu->cmd_buf_size;
 941
 942        if (left <= 2) {
 943                struct iommu_cmd sync_cmd;
 944                volatile u64 sem = 0;
 945                int ret;
 946
 947                build_completion_wait(&sync_cmd, (u64)&sem);
 948                copy_cmd_to_buffer(iommu, &sync_cmd, tail);
 949
 950                spin_unlock_irqrestore(&iommu->lock, flags);
 951
 952                if ((ret = wait_on_sem(&sem)) != 0)
 953                        return ret;
 954
 955                goto again;
 956        }
 957
 958        copy_cmd_to_buffer(iommu, cmd, tail);
 959
 960        /* We need to sync now to make sure all commands are processed */
 961        iommu->need_sync = sync;
 962
 963        spin_unlock_irqrestore(&iommu->lock, flags);
 964
 965        return 0;
 966}
 967
 968static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
 969{
 970        return iommu_queue_command_sync(iommu, cmd, true);
 971}
 972
 973/*
 974 * This function queues a completion wait command into the command
 975 * buffer of an IOMMU
 976 */
 977static int iommu_completion_wait(struct amd_iommu *iommu)
 978{
 979        struct iommu_cmd cmd;
 980        volatile u64 sem = 0;
 981        int ret;
 982
 983        if (!iommu->need_sync)
 984                return 0;
 985
 986        build_completion_wait(&cmd, (u64)&sem);
 987
 988        ret = iommu_queue_command_sync(iommu, &cmd, false);
 989        if (ret)
 990                return ret;
 991
 992        return wait_on_sem(&sem);
 993}
 994
 995static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
 996{
 997        struct iommu_cmd cmd;
 998
 999        build_inv_dte(&cmd, devid);
1000
1001        return iommu_queue_command(iommu, &cmd);
1002}
1003
1004static void iommu_flush_dte_all(struct amd_iommu *iommu)
1005{
1006        u32 devid;
1007
1008        for (devid = 0; devid <= 0xffff; ++devid)
1009                iommu_flush_dte(iommu, devid);
1010
1011        iommu_completion_wait(iommu);
1012}
1013
1014/*
1015 * This function uses heavy locking and may disable irqs for some time. But
1016 * this is no issue because it is only called during resume.
1017 */
1018static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1019{
1020        u32 dom_id;
1021
1022        for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1023                struct iommu_cmd cmd;
1024                build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1025                                      dom_id, 1);
1026                iommu_queue_command(iommu, &cmd);
1027        }
1028
1029        iommu_completion_wait(iommu);
1030}
1031
1032static void iommu_flush_all(struct amd_iommu *iommu)
1033{
1034        struct iommu_cmd cmd;
1035
1036        build_inv_all(&cmd);
1037
1038        iommu_queue_command(iommu, &cmd);
1039        iommu_completion_wait(iommu);
1040}
1041
1042static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1043{
1044        struct iommu_cmd cmd;
1045
1046        build_inv_irt(&cmd, devid);
1047
1048        iommu_queue_command(iommu, &cmd);
1049}
1050
1051static void iommu_flush_irt_all(struct amd_iommu *iommu)
1052{
1053        u32 devid;
1054
1055        for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1056                iommu_flush_irt(iommu, devid);
1057
1058        iommu_completion_wait(iommu);
1059}
1060
1061void iommu_flush_all_caches(struct amd_iommu *iommu)
1062{
1063        if (iommu_feature(iommu, FEATURE_IA)) {
1064                iommu_flush_all(iommu);
1065        } else {
1066                iommu_flush_dte_all(iommu);
1067                iommu_flush_irt_all(iommu);
1068                iommu_flush_tlb_all(iommu);
1069        }
1070}
1071
1072/*
1073 * Command send function for flushing on-device TLB
1074 */
1075static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1076                              u64 address, size_t size)
1077{
1078        struct amd_iommu *iommu;
1079        struct iommu_cmd cmd;
1080        int qdep;
1081
1082        qdep     = dev_data->ats.qdep;
1083        iommu    = amd_iommu_rlookup_table[dev_data->devid];
1084
1085        build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1086
1087        return iommu_queue_command(iommu, &cmd);
1088}
1089
1090/*
1091 * Command send function for invalidating a device table entry
1092 */
1093static int device_flush_dte(struct iommu_dev_data *dev_data)
1094{
1095        struct amd_iommu *iommu;
1096        int ret;
1097
1098        iommu = amd_iommu_rlookup_table[dev_data->devid];
1099
1100        ret = iommu_flush_dte(iommu, dev_data->devid);
1101        if (ret)
1102                return ret;
1103
1104        if (dev_data->ats.enabled)
1105                ret = device_flush_iotlb(dev_data, 0, ~0UL);
1106
1107        return ret;
1108}
1109
1110/*
1111 * TLB invalidation function which is called from the mapping functions.
1112 * It invalidates a single PTE if the range to flush is within a single
1113 * page. Otherwise it flushes the whole TLB of the IOMMU.
1114 */
1115static void __domain_flush_pages(struct protection_domain *domain,
1116                                 u64 address, size_t size, int pde)
1117{
1118        struct iommu_dev_data *dev_data;
1119        struct iommu_cmd cmd;
1120        int ret = 0, i;
1121
1122        build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1123
1124        for (i = 0; i < amd_iommus_present; ++i) {
1125                if (!domain->dev_iommu[i])
1126                        continue;
1127
1128                /*
1129                 * Devices of this domain are behind this IOMMU
1130                 * We need a TLB flush
1131                 */
1132                ret |= iommu_queue_command(amd_iommus[i], &cmd);
1133        }
1134
1135        list_for_each_entry(dev_data, &domain->dev_list, list) {
1136
1137                if (!dev_data->ats.enabled)
1138                        continue;
1139
1140                ret |= device_flush_iotlb(dev_data, address, size);
1141        }
1142
1143        WARN_ON(ret);
1144}
1145
1146static void domain_flush_pages(struct protection_domain *domain,
1147                               u64 address, size_t size)
1148{
1149        __domain_flush_pages(domain, address, size, 0);
1150}
1151
1152/* Flush the whole IO/TLB for a given protection domain */
1153static void domain_flush_tlb(struct protection_domain *domain)
1154{
1155        __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1156}
1157
1158/* Flush the whole IO/TLB for a given protection domain - including PDE */
1159static void domain_flush_tlb_pde(struct protection_domain *domain)
1160{
1161        __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1162}
1163
1164static void domain_flush_complete(struct protection_domain *domain)
1165{
1166        int i;
1167
1168        for (i = 0; i < amd_iommus_present; ++i) {
1169                if (!domain->dev_iommu[i])
1170                        continue;
1171
1172                /*
1173                 * Devices of this domain are behind this IOMMU
1174                 * We need to wait for completion of all commands.
1175                 */
1176                iommu_completion_wait(amd_iommus[i]);
1177        }
1178}
1179
1180
1181/*
1182 * This function flushes the DTEs for all devices in domain
1183 */
1184static void domain_flush_devices(struct protection_domain *domain)
1185{
1186        struct iommu_dev_data *dev_data;
1187
1188        list_for_each_entry(dev_data, &domain->dev_list, list)
1189                device_flush_dte(dev_data);
1190}
1191
1192/****************************************************************************
1193 *
1194 * The functions below are used the create the page table mappings for
1195 * unity mapped regions.
1196 *
1197 ****************************************************************************/
1198
1199/*
1200 * This function is used to add another level to an IO page table. Adding
1201 * another level increases the size of the address space by 9 bits to a size up
1202 * to 64 bits.
1203 */
1204static bool increase_address_space(struct protection_domain *domain,
1205                                   gfp_t gfp)
1206{
1207        u64 *pte;
1208
1209        if (domain->mode == PAGE_MODE_6_LEVEL)
1210                /* address space already 64 bit large */
1211                return false;
1212
1213        pte = (void *)get_zeroed_page(gfp);
1214        if (!pte)
1215                return false;
1216
1217        *pte             = PM_LEVEL_PDE(domain->mode,
1218                                        virt_to_phys(domain->pt_root));
1219        domain->pt_root  = pte;
1220        domain->mode    += 1;
1221        domain->updated  = true;
1222
1223        return true;
1224}
1225
1226static u64 *alloc_pte(struct protection_domain *domain,
1227                      unsigned long address,
1228                      unsigned long page_size,
1229                      u64 **pte_page,
1230                      gfp_t gfp)
1231{
1232        int level, end_lvl;
1233        u64 *pte, *page;
1234
1235        BUG_ON(!is_power_of_2(page_size));
1236
1237        while (address > PM_LEVEL_SIZE(domain->mode))
1238                increase_address_space(domain, gfp);
1239
1240        level   = domain->mode - 1;
1241        pte     = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1242        address = PAGE_SIZE_ALIGN(address, page_size);
1243        end_lvl = PAGE_SIZE_LEVEL(page_size);
1244
1245        while (level > end_lvl) {
1246                if (!IOMMU_PTE_PRESENT(*pte)) {
1247                        page = (u64 *)get_zeroed_page(gfp);
1248                        if (!page)
1249                                return NULL;
1250                        *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1251                }
1252
1253                /* No level skipping support yet */
1254                if (PM_PTE_LEVEL(*pte) != level)
1255                        return NULL;
1256
1257                level -= 1;
1258
1259                pte = IOMMU_PTE_PAGE(*pte);
1260
1261                if (pte_page && level == end_lvl)
1262                        *pte_page = pte;
1263
1264                pte = &pte[PM_LEVEL_INDEX(level, address)];
1265        }
1266
1267        return pte;
1268}
1269
1270/*
1271 * This function checks if there is a PTE for a given dma address. If
1272 * there is one, it returns the pointer to it.
1273 */
1274static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
1275{
1276        int level;
1277        u64 *pte;
1278
1279        if (address > PM_LEVEL_SIZE(domain->mode))
1280                return NULL;
1281
1282        level   =  domain->mode - 1;
1283        pte     = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1284
1285        while (level > 0) {
1286
1287                /* Not Present */
1288                if (!IOMMU_PTE_PRESENT(*pte))
1289                        return NULL;
1290
1291                /* Large PTE */
1292                if (PM_PTE_LEVEL(*pte) == 0x07) {
1293                        unsigned long pte_mask, __pte;
1294
1295                        /*
1296                         * If we have a series of large PTEs, make
1297                         * sure to return a pointer to the first one.
1298                         */
1299                        pte_mask = PTE_PAGE_SIZE(*pte);
1300                        pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1301                        __pte    = ((unsigned long)pte) & pte_mask;
1302
1303                        return (u64 *)__pte;
1304                }
1305
1306                /* No level skipping support yet */
1307                if (PM_PTE_LEVEL(*pte) != level)
1308                        return NULL;
1309
1310                level -= 1;
1311
1312                /* Walk to the next level */
1313                pte = IOMMU_PTE_PAGE(*pte);
1314                pte = &pte[PM_LEVEL_INDEX(level, address)];
1315        }
1316
1317        return pte;
1318}
1319
1320/*
1321 * Generic mapping functions. It maps a physical address into a DMA
1322 * address space. It allocates the page table pages if necessary.
1323 * In the future it can be extended to a generic mapping function
1324 * supporting all features of AMD IOMMU page tables like level skipping
1325 * and full 64 bit address spaces.
1326 */
1327static int iommu_map_page(struct protection_domain *dom,
1328                          unsigned long bus_addr,
1329                          unsigned long phys_addr,
1330                          int prot,
1331                          unsigned long page_size)
1332{
1333        u64 __pte, *pte;
1334        int i, count;
1335
1336        if (!(prot & IOMMU_PROT_MASK))
1337                return -EINVAL;
1338
1339        bus_addr  = PAGE_ALIGN(bus_addr);
1340        phys_addr = PAGE_ALIGN(phys_addr);
1341        count     = PAGE_SIZE_PTE_COUNT(page_size);
1342        pte       = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1343
1344        for (i = 0; i < count; ++i)
1345                if (IOMMU_PTE_PRESENT(pte[i]))
1346                        return -EBUSY;
1347
1348        if (page_size > PAGE_SIZE) {
1349                __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1350                __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1351        } else
1352                __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1353
1354        if (prot & IOMMU_PROT_IR)
1355                __pte |= IOMMU_PTE_IR;
1356        if (prot & IOMMU_PROT_IW)
1357                __pte |= IOMMU_PTE_IW;
1358
1359        for (i = 0; i < count; ++i)
1360                pte[i] = __pte;
1361
1362        update_domain(dom);
1363
1364        return 0;
1365}
1366
1367static unsigned long iommu_unmap_page(struct protection_domain *dom,
1368                                      unsigned long bus_addr,
1369                                      unsigned long page_size)
1370{
1371        unsigned long long unmap_size, unmapped;
1372        u64 *pte;
1373
1374        BUG_ON(!is_power_of_2(page_size));
1375
1376        unmapped = 0;
1377
1378        while (unmapped < page_size) {
1379
1380                pte = fetch_pte(dom, bus_addr);
1381
1382                if (!pte) {
1383                        /*
1384                         * No PTE for this address
1385                         * move forward in 4kb steps
1386                         */
1387                        unmap_size = PAGE_SIZE;
1388                } else if (PM_PTE_LEVEL(*pte) == 0) {
1389                        /* 4kb PTE found for this address */
1390                        unmap_size = PAGE_SIZE;
1391                        *pte       = 0ULL;
1392                } else {
1393                        int count, i;
1394
1395                        /* Large PTE found which maps this address */
1396                        unmap_size = PTE_PAGE_SIZE(*pte);
1397                        count      = PAGE_SIZE_PTE_COUNT(unmap_size);
1398                        for (i = 0; i < count; i++)
1399                                pte[i] = 0ULL;
1400                }
1401
1402                bus_addr  = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1403                unmapped += unmap_size;
1404        }
1405
1406        BUG_ON(!is_power_of_2(unmapped));
1407
1408        return unmapped;
1409}
1410
1411/*
1412 * This function checks if a specific unity mapping entry is needed for
1413 * this specific IOMMU.
1414 */
1415static int iommu_for_unity_map(struct amd_iommu *iommu,
1416                               struct unity_map_entry *entry)
1417{
1418        u16 bdf, i;
1419
1420        for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1421                bdf = amd_iommu_alias_table[i];
1422                if (amd_iommu_rlookup_table[bdf] == iommu)
1423                        return 1;
1424        }
1425
1426        return 0;
1427}
1428
1429/*
1430 * This function actually applies the mapping to the page table of the
1431 * dma_ops domain.
1432 */
1433static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1434                             struct unity_map_entry *e)
1435{
1436        u64 addr;
1437        int ret;
1438
1439        for (addr = e->address_start; addr < e->address_end;
1440             addr += PAGE_SIZE) {
1441                ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1442                                     PAGE_SIZE);
1443                if (ret)
1444                        return ret;
1445                /*
1446                 * if unity mapping is in aperture range mark the page
1447                 * as allocated in the aperture
1448                 */
1449                if (addr < dma_dom->aperture_size)
1450                        __set_bit(addr >> PAGE_SHIFT,
1451                                  dma_dom->aperture[0]->bitmap);
1452        }
1453
1454        return 0;
1455}
1456
1457/*
1458 * Init the unity mappings for a specific IOMMU in the system
1459 *
1460 * Basically iterates over all unity mapping entries and applies them to
1461 * the default domain DMA of that IOMMU if necessary.
1462 */
1463static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1464{
1465        struct unity_map_entry *entry;
1466        int ret;
1467
1468        list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1469                if (!iommu_for_unity_map(iommu, entry))
1470                        continue;
1471                ret = dma_ops_unity_map(iommu->default_dom, entry);
1472                if (ret)
1473                        return ret;
1474        }
1475
1476        return 0;
1477}
1478
1479/*
1480 * Inits the unity mappings required for a specific device
1481 */
1482static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1483                                          u16 devid)
1484{
1485        struct unity_map_entry *e;
1486        int ret;
1487
1488        list_for_each_entry(e, &amd_iommu_unity_map, list) {
1489                if (!(devid >= e->devid_start && devid <= e->devid_end))
1490                        continue;
1491                ret = dma_ops_unity_map(dma_dom, e);
1492                if (ret)
1493                        return ret;
1494        }
1495
1496        return 0;
1497}
1498
1499/****************************************************************************
1500 *
1501 * The next functions belong to the address allocator for the dma_ops
1502 * interface functions. They work like the allocators in the other IOMMU
1503 * drivers. Its basically a bitmap which marks the allocated pages in
1504 * the aperture. Maybe it could be enhanced in the future to a more
1505 * efficient allocator.
1506 *
1507 ****************************************************************************/
1508
1509/*
1510 * The address allocator core functions.
1511 *
1512 * called with domain->lock held
1513 */
1514
1515/*
1516 * Used to reserve address ranges in the aperture (e.g. for exclusion
1517 * ranges.
1518 */
1519static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1520                                      unsigned long start_page,
1521                                      unsigned int pages)
1522{
1523        unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1524
1525        if (start_page + pages > last_page)
1526                pages = last_page - start_page;
1527
1528        for (i = start_page; i < start_page + pages; ++i) {
1529                int index = i / APERTURE_RANGE_PAGES;
1530                int page  = i % APERTURE_RANGE_PAGES;
1531                __set_bit(page, dom->aperture[index]->bitmap);
1532        }
1533}
1534
1535/*
1536 * This function is used to add a new aperture range to an existing
1537 * aperture in case of dma_ops domain allocation or address allocation
1538 * failure.
1539 */
1540static int alloc_new_range(struct dma_ops_domain *dma_dom,
1541                           bool populate, gfp_t gfp)
1542{
1543        int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1544        struct amd_iommu *iommu;
1545        unsigned long i, old_size;
1546
1547#ifdef CONFIG_IOMMU_STRESS
1548        populate = false;
1549#endif
1550
1551        if (index >= APERTURE_MAX_RANGES)
1552                return -ENOMEM;
1553
1554        dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1555        if (!dma_dom->aperture[index])
1556                return -ENOMEM;
1557
1558        dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1559        if (!dma_dom->aperture[index]->bitmap)
1560                goto out_free;
1561
1562        dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1563
1564        if (populate) {
1565                unsigned long address = dma_dom->aperture_size;
1566                int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1567                u64 *pte, *pte_page;
1568
1569                for (i = 0; i < num_ptes; ++i) {
1570                        pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1571                                        &pte_page, gfp);
1572                        if (!pte)
1573                                goto out_free;
1574
1575                        dma_dom->aperture[index]->pte_pages[i] = pte_page;
1576
1577                        address += APERTURE_RANGE_SIZE / 64;
1578                }
1579        }
1580
1581        old_size                = dma_dom->aperture_size;
1582        dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1583
1584        /* Reserve address range used for MSI messages */
1585        if (old_size < MSI_ADDR_BASE_LO &&
1586            dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1587                unsigned long spage;
1588                int pages;
1589
1590                pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1591                spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1592
1593                dma_ops_reserve_addresses(dma_dom, spage, pages);
1594        }
1595
1596        /* Initialize the exclusion range if necessary */
1597        for_each_iommu(iommu) {
1598                if (iommu->exclusion_start &&
1599                    iommu->exclusion_start >= dma_dom->aperture[index]->offset
1600                    && iommu->exclusion_start < dma_dom->aperture_size) {
1601                        unsigned long startpage;
1602                        int pages = iommu_num_pages(iommu->exclusion_start,
1603                                                    iommu->exclusion_length,
1604                                                    PAGE_SIZE);
1605                        startpage = iommu->exclusion_start >> PAGE_SHIFT;
1606                        dma_ops_reserve_addresses(dma_dom, startpage, pages);
1607                }
1608        }
1609
1610        /*
1611         * Check for areas already mapped as present in the new aperture
1612         * range and mark those pages as reserved in the allocator. Such
1613         * mappings may already exist as a result of requested unity
1614         * mappings for devices.
1615         */
1616        for (i = dma_dom->aperture[index]->offset;
1617             i < dma_dom->aperture_size;
1618             i += PAGE_SIZE) {
1619                u64 *pte = fetch_pte(&dma_dom->domain, i);
1620                if (!pte || !IOMMU_PTE_PRESENT(*pte))
1621                        continue;
1622
1623                dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1624        }
1625
1626        update_domain(&dma_dom->domain);
1627
1628        return 0;
1629
1630out_free:
1631        update_domain(&dma_dom->domain);
1632
1633        free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1634
1635        kfree(dma_dom->aperture[index]);
1636        dma_dom->aperture[index] = NULL;
1637
1638        return -ENOMEM;
1639}
1640
1641static unsigned long dma_ops_area_alloc(struct device *dev,
1642                                        struct dma_ops_domain *dom,
1643                                        unsigned int pages,
1644                                        unsigned long align_mask,
1645                                        u64 dma_mask,
1646                                        unsigned long start)
1647{
1648        unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1649        int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1650        int i = start >> APERTURE_RANGE_SHIFT;
1651        unsigned long boundary_size;
1652        unsigned long address = -1;
1653        unsigned long limit;
1654
1655        next_bit >>= PAGE_SHIFT;
1656
1657        boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1658                        PAGE_SIZE) >> PAGE_SHIFT;
1659
1660        for (;i < max_index; ++i) {
1661                unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1662
1663                if (dom->aperture[i]->offset >= dma_mask)
1664                        break;
1665
1666                limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1667                                               dma_mask >> PAGE_SHIFT);
1668
1669                address = iommu_area_alloc(dom->aperture[i]->bitmap,
1670                                           limit, next_bit, pages, 0,
1671                                            boundary_size, align_mask);
1672                if (address != -1) {
1673                        address = dom->aperture[i]->offset +
1674                                  (address << PAGE_SHIFT);
1675                        dom->next_address = address + (pages << PAGE_SHIFT);
1676                        break;
1677                }
1678
1679                next_bit = 0;
1680        }
1681
1682        return address;
1683}
1684
1685static unsigned long dma_ops_alloc_addresses(struct device *dev,
1686                                             struct dma_ops_domain *dom,
1687                                             unsigned int pages,
1688                                             unsigned long align_mask,
1689                                             u64 dma_mask)
1690{
1691        unsigned long address;
1692
1693#ifdef CONFIG_IOMMU_STRESS
1694        dom->next_address = 0;
1695        dom->need_flush = true;
1696#endif
1697
1698        address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1699                                     dma_mask, dom->next_address);
1700
1701        if (address == -1) {
1702                dom->next_address = 0;
1703                address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1704                                             dma_mask, 0);
1705                dom->need_flush = true;
1706        }
1707
1708        if (unlikely(address == -1))
1709                address = DMA_ERROR_CODE;
1710
1711        WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1712
1713        return address;
1714}
1715
1716/*
1717 * The address free function.
1718 *
1719 * called with domain->lock held
1720 */
1721static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1722                                   unsigned long address,
1723                                   unsigned int pages)
1724{
1725        unsigned i = address >> APERTURE_RANGE_SHIFT;
1726        struct aperture_range *range = dom->aperture[i];
1727
1728        BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1729
1730#ifdef CONFIG_IOMMU_STRESS
1731        if (i < 4)
1732                return;
1733#endif
1734
1735        if (address >= dom->next_address)
1736                dom->need_flush = true;
1737
1738        address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1739
1740        bitmap_clear(range->bitmap, address, pages);
1741
1742}
1743
1744/****************************************************************************
1745 *
1746 * The next functions belong to the domain allocation. A domain is
1747 * allocated for every IOMMU as the default domain. If device isolation
1748 * is enabled, every device get its own domain. The most important thing
1749 * about domains is the page table mapping the DMA address space they
1750 * contain.
1751 *
1752 ****************************************************************************/
1753
1754/*
1755 * This function adds a protection domain to the global protection domain list
1756 */
1757static void add_domain_to_list(struct protection_domain *domain)
1758{
1759        unsigned long flags;
1760
1761        spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1762        list_add(&domain->list, &amd_iommu_pd_list);
1763        spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1764}
1765
1766/*
1767 * This function removes a protection domain to the global
1768 * protection domain list
1769 */
1770static void del_domain_from_list(struct protection_domain *domain)
1771{
1772        unsigned long flags;
1773
1774        spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1775        list_del(&domain->list);
1776        spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1777}
1778
1779static u16 domain_id_alloc(void)
1780{
1781        unsigned long flags;
1782        int id;
1783
1784        write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1785        id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1786        BUG_ON(id == 0);
1787        if (id > 0 && id < MAX_DOMAIN_ID)
1788                __set_bit(id, amd_iommu_pd_alloc_bitmap);
1789        else
1790                id = 0;
1791        write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1792
1793        return id;
1794}
1795
1796static void domain_id_free(int id)
1797{
1798        unsigned long flags;
1799
1800        write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1801        if (id > 0 && id < MAX_DOMAIN_ID)
1802                __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1803        write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1804}
1805
1806static void free_pagetable(struct protection_domain *domain)
1807{
1808        int i, j;
1809        u64 *p1, *p2, *p3;
1810
1811        p1 = domain->pt_root;
1812
1813        if (!p1)
1814                return;
1815
1816        for (i = 0; i < 512; ++i) {
1817                if (!IOMMU_PTE_PRESENT(p1[i]))
1818                        continue;
1819
1820                p2 = IOMMU_PTE_PAGE(p1[i]);
1821                for (j = 0; j < 512; ++j) {
1822                        if (!IOMMU_PTE_PRESENT(p2[j]))
1823                                continue;
1824                        p3 = IOMMU_PTE_PAGE(p2[j]);
1825                        free_page((unsigned long)p3);
1826                }
1827
1828                free_page((unsigned long)p2);
1829        }
1830
1831        free_page((unsigned long)p1);
1832
1833        domain->pt_root = NULL;
1834}
1835
1836static void free_gcr3_tbl_level1(u64 *tbl)
1837{
1838        u64 *ptr;
1839        int i;
1840
1841        for (i = 0; i < 512; ++i) {
1842                if (!(tbl[i] & GCR3_VALID))
1843                        continue;
1844
1845                ptr = __va(tbl[i] & PAGE_MASK);
1846
1847                free_page((unsigned long)ptr);
1848        }
1849}
1850
1851static void free_gcr3_tbl_level2(u64 *tbl)
1852{
1853        u64 *ptr;
1854        int i;
1855
1856        for (i = 0; i < 512; ++i) {
1857                if (!(tbl[i] & GCR3_VALID))
1858                        continue;
1859
1860                ptr = __va(tbl[i] & PAGE_MASK);
1861
1862                free_gcr3_tbl_level1(ptr);
1863        }
1864}
1865
1866static void free_gcr3_table(struct protection_domain *domain)
1867{
1868        if (domain->glx == 2)
1869                free_gcr3_tbl_level2(domain->gcr3_tbl);
1870        else if (domain->glx == 1)
1871                free_gcr3_tbl_level1(domain->gcr3_tbl);
1872        else if (domain->glx != 0)
1873                BUG();
1874
1875        free_page((unsigned long)domain->gcr3_tbl);
1876}
1877
1878/*
1879 * Free a domain, only used if something went wrong in the
1880 * allocation path and we need to free an already allocated page table
1881 */
1882static void dma_ops_domain_free(struct dma_ops_domain *dom)
1883{
1884        int i;
1885
1886        if (!dom)
1887                return;
1888
1889        del_domain_from_list(&dom->domain);
1890
1891        free_pagetable(&dom->domain);
1892
1893        for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1894                if (!dom->aperture[i])
1895                        continue;
1896                free_page((unsigned long)dom->aperture[i]->bitmap);
1897                kfree(dom->aperture[i]);
1898        }
1899
1900        kfree(dom);
1901}
1902
1903/*
1904 * Allocates a new protection domain usable for the dma_ops functions.
1905 * It also initializes the page table and the address allocator data
1906 * structures required for the dma_ops interface
1907 */
1908static struct dma_ops_domain *dma_ops_domain_alloc(void)
1909{
1910        struct dma_ops_domain *dma_dom;
1911
1912        dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1913        if (!dma_dom)
1914                return NULL;
1915
1916        spin_lock_init(&dma_dom->domain.lock);
1917
1918        dma_dom->domain.id = domain_id_alloc();
1919        if (dma_dom->domain.id == 0)
1920                goto free_dma_dom;
1921        INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1922        dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1923        dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1924        dma_dom->domain.flags = PD_DMA_OPS_MASK;
1925        dma_dom->domain.priv = dma_dom;
1926        if (!dma_dom->domain.pt_root)
1927                goto free_dma_dom;
1928
1929        dma_dom->need_flush = false;
1930        dma_dom->target_dev = 0xffff;
1931
1932        add_domain_to_list(&dma_dom->domain);
1933
1934        if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1935                goto free_dma_dom;
1936
1937        /*
1938         * mark the first page as allocated so we never return 0 as
1939         * a valid dma-address. So we can use 0 as error value
1940         */
1941        dma_dom->aperture[0]->bitmap[0] = 1;
1942        dma_dom->next_address = 0;
1943
1944
1945        return dma_dom;
1946
1947free_dma_dom:
1948        dma_ops_domain_free(dma_dom);
1949
1950        return NULL;
1951}
1952
1953/*
1954 * little helper function to check whether a given protection domain is a
1955 * dma_ops domain
1956 */
1957static bool dma_ops_domain(struct protection_domain *domain)
1958{
1959        return domain->flags & PD_DMA_OPS_MASK;
1960}
1961
1962static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1963{
1964        u64 pte_root = 0;
1965        u64 flags = 0;
1966
1967        if (domain->mode != PAGE_MODE_NONE)
1968                pte_root = virt_to_phys(domain->pt_root);
1969
1970        pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1971                    << DEV_ENTRY_MODE_SHIFT;
1972        pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1973
1974        flags = amd_iommu_dev_table[devid].data[1];
1975
1976        if (ats)
1977                flags |= DTE_FLAG_IOTLB;
1978
1979        if (domain->flags & PD_IOMMUV2_MASK) {
1980                u64 gcr3 = __pa(domain->gcr3_tbl);
1981                u64 glx  = domain->glx;
1982                u64 tmp;
1983
1984                pte_root |= DTE_FLAG_GV;
1985                pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1986
1987                /* First mask out possible old values for GCR3 table */
1988                tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1989                flags    &= ~tmp;
1990
1991                tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1992                flags    &= ~tmp;
1993
1994                /* Encode GCR3 table into DTE */
1995                tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1996                pte_root |= tmp;
1997
1998                tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1999                flags    |= tmp;
2000
2001                tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
2002                flags    |= tmp;
2003        }
2004
2005        flags &= ~(0xffffUL);
2006        flags |= domain->id;
2007
2008        amd_iommu_dev_table[devid].data[1]  = flags;
2009        amd_iommu_dev_table[devid].data[0]  = pte_root;
2010}
2011
2012static void clear_dte_entry(u16 devid)
2013{
2014        /* remove entry from the device table seen by the hardware */
2015        amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
2016        amd_iommu_dev_table[devid].data[1] = 0;
2017
2018        amd_iommu_apply_erratum_63(devid);
2019}
2020
2021static void do_attach(struct iommu_dev_data *dev_data,
2022                      struct protection_domain *domain)
2023{
2024        struct amd_iommu *iommu;
2025        bool ats;
2026
2027        iommu = amd_iommu_rlookup_table[dev_data->devid];
2028        ats   = dev_data->ats.enabled;
2029
2030        /* Update data structures */
2031        dev_data->domain = domain;
2032        list_add(&dev_data->list, &domain->dev_list);
2033        set_dte_entry(dev_data->devid, domain, ats);
2034
2035        /* Do reference counting */
2036        domain->dev_iommu[iommu->index] += 1;
2037        domain->dev_cnt                 += 1;
2038
2039        /* Flush the DTE entry */
2040        device_flush_dte(dev_data);
2041}
2042
2043static void do_detach(struct iommu_dev_data *dev_data)
2044{
2045        struct amd_iommu *iommu;
2046
2047        iommu = amd_iommu_rlookup_table[dev_data->devid];
2048
2049        /* decrease reference counters */
2050        dev_data->domain->dev_iommu[iommu->index] -= 1;
2051        dev_data->domain->dev_cnt                 -= 1;
2052
2053        /* Update data structures */
2054        dev_data->domain = NULL;
2055        list_del(&dev_data->list);
2056        clear_dte_entry(dev_data->devid);
2057
2058        /* Flush the DTE entry */
2059        device_flush_dte(dev_data);
2060}
2061
2062/*
2063 * If a device is not yet associated with a domain, this function does
2064 * assigns it visible for the hardware
2065 */
2066static int __attach_device(struct iommu_dev_data *dev_data,
2067                           struct protection_domain *domain)
2068{
2069        int ret;
2070
2071        /* lock domain */
2072        spin_lock(&domain->lock);
2073
2074        if (dev_data->alias_data != NULL) {
2075                struct iommu_dev_data *alias_data = dev_data->alias_data;
2076
2077                /* Some sanity checks */
2078                ret = -EBUSY;
2079                if (alias_data->domain != NULL &&
2080                                alias_data->domain != domain)
2081                        goto out_unlock;
2082
2083                if (dev_data->domain != NULL &&
2084                                dev_data->domain != domain)
2085                        goto out_unlock;
2086
2087                /* Do real assignment */
2088                if (alias_data->domain == NULL)
2089                        do_attach(alias_data, domain);
2090
2091                atomic_inc(&alias_data->bind);
2092        }
2093
2094        if (dev_data->domain == NULL)
2095                do_attach(dev_data, domain);
2096
2097        atomic_inc(&dev_data->bind);
2098
2099        ret = 0;
2100
2101out_unlock:
2102
2103        /* ready */
2104        spin_unlock(&domain->lock);
2105
2106        return ret;
2107}
2108
2109
2110static void pdev_iommuv2_disable(struct pci_dev *pdev)
2111{
2112        pci_disable_ats(pdev);
2113        pci_disable_pri(pdev);
2114        pci_disable_pasid(pdev);
2115}
2116
2117/* FIXME: Change generic reset-function to do the same */
2118static int pri_reset_while_enabled(struct pci_dev *pdev)
2119{
2120        u16 control;
2121        int pos;
2122
2123        pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2124        if (!pos)
2125                return -EINVAL;
2126
2127        pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2128        control |= PCI_PRI_CTRL_RESET;
2129        pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2130
2131        return 0;
2132}
2133
2134static int pdev_iommuv2_enable(struct pci_dev *pdev)
2135{
2136        bool reset_enable;
2137        int reqs, ret;
2138
2139        /* FIXME: Hardcode number of outstanding requests for now */
2140        reqs = 32;
2141        if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2142                reqs = 1;
2143        reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2144
2145        /* Only allow access to user-accessible pages */
2146        ret = pci_enable_pasid(pdev, 0);
2147        if (ret)
2148                goto out_err;
2149
2150        /* First reset the PRI state of the device */
2151        ret = pci_reset_pri(pdev);
2152        if (ret)
2153                goto out_err;
2154
2155        /* Enable PRI */
2156        ret = pci_enable_pri(pdev, reqs);
2157        if (ret)
2158                goto out_err;
2159
2160        if (reset_enable) {
2161                ret = pri_reset_while_enabled(pdev);
2162                if (ret)
2163                        goto out_err;
2164        }
2165
2166        ret = pci_enable_ats(pdev, PAGE_SHIFT);
2167        if (ret)
2168                goto out_err;
2169
2170        return 0;
2171
2172out_err:
2173        pci_disable_pri(pdev);
2174        pci_disable_pasid(pdev);
2175
2176        return ret;
2177}
2178
2179/* FIXME: Move this to PCI code */
2180#define PCI_PRI_TLP_OFF         (1 << 15)
2181
2182static bool pci_pri_tlp_required(struct pci_dev *pdev)
2183{
2184        u16 status;
2185        int pos;
2186
2187        pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2188        if (!pos)
2189                return false;
2190
2191        pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2192
2193        return (status & PCI_PRI_TLP_OFF) ? true : false;
2194}
2195
2196/*
2197 * If a device is not yet associated with a domain, this function
2198 * assigns it visible for the hardware
2199 */
2200static int attach_device(struct device *dev,
2201                         struct protection_domain *domain)
2202{
2203        struct pci_dev *pdev = to_pci_dev(dev);
2204        struct iommu_dev_data *dev_data;
2205        unsigned long flags;
2206        int ret;
2207
2208        dev_data = get_dev_data(dev);
2209
2210        if (domain->flags & PD_IOMMUV2_MASK) {
2211                if (!dev_data->iommu_v2 || !dev_data->passthrough)
2212                        return -EINVAL;
2213
2214                if (pdev_iommuv2_enable(pdev) != 0)
2215                        return -EINVAL;
2216
2217                dev_data->ats.enabled = true;
2218                dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
2219                dev_data->pri_tlp     = pci_pri_tlp_required(pdev);
2220        } else if (amd_iommu_iotlb_sup &&
2221                   pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2222                dev_data->ats.enabled = true;
2223                dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
2224        }
2225
2226        write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2227        ret = __attach_device(dev_data, domain);
2228        write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2229
2230        /*
2231         * We might boot into a crash-kernel here. The crashed kernel
2232         * left the caches in the IOMMU dirty. So we have to flush
2233         * here to evict all dirty stuff.
2234         */
2235        domain_flush_tlb_pde(domain);
2236
2237        return ret;
2238}
2239
2240/*
2241 * Removes a device from a protection domain (unlocked)
2242 */
2243static void __detach_device(struct iommu_dev_data *dev_data)
2244{
2245        struct protection_domain *domain;
2246        unsigned long flags;
2247
2248        BUG_ON(!dev_data->domain);
2249
2250        domain = dev_data->domain;
2251
2252        spin_lock_irqsave(&domain->lock, flags);
2253
2254        if (dev_data->alias_data != NULL) {
2255                struct iommu_dev_data *alias_data = dev_data->alias_data;
2256
2257                if (atomic_dec_and_test(&alias_data->bind))
2258                        do_detach(alias_data);
2259        }
2260
2261        if (atomic_dec_and_test(&dev_data->bind))
2262                do_detach(dev_data);
2263
2264        spin_unlock_irqrestore(&domain->lock, flags);
2265
2266        /*
2267         * If we run in passthrough mode the device must be assigned to the
2268         * passthrough domain if it is detached from any other domain.
2269         * Make sure we can deassign from the pt_domain itself.
2270         */
2271        if (dev_data->passthrough &&
2272            (dev_data->domain == NULL && domain != pt_domain))
2273                __attach_device(dev_data, pt_domain);
2274}
2275
2276/*
2277 * Removes a device from a protection domain (with devtable_lock held)
2278 */
2279static void detach_device(struct device *dev)
2280{
2281        struct protection_domain *domain;
2282        struct iommu_dev_data *dev_data;
2283        unsigned long flags;
2284
2285        dev_data = get_dev_data(dev);
2286        domain   = dev_data->domain;
2287
2288        /* lock device table */
2289        write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2290        __detach_device(dev_data);
2291        write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2292
2293        if (domain->flags & PD_IOMMUV2_MASK)
2294                pdev_iommuv2_disable(to_pci_dev(dev));
2295        else if (dev_data->ats.enabled)
2296                pci_disable_ats(to_pci_dev(dev));
2297
2298        dev_data->ats.enabled = false;
2299}
2300
2301/*
2302 * Find out the protection domain structure for a given PCI device. This
2303 * will give us the pointer to the page table root for example.
2304 */
2305static struct protection_domain *domain_for_device(struct device *dev)
2306{
2307        struct iommu_dev_data *dev_data;
2308        struct protection_domain *dom = NULL;
2309        unsigned long flags;
2310
2311        dev_data   = get_dev_data(dev);
2312
2313        if (dev_data->domain)
2314                return dev_data->domain;
2315
2316        if (dev_data->alias_data != NULL) {
2317                struct iommu_dev_data *alias_data = dev_data->alias_data;
2318
2319                read_lock_irqsave(&amd_iommu_devtable_lock, flags);
2320                if (alias_data->domain != NULL) {
2321                        __attach_device(dev_data, alias_data->domain);
2322                        dom = alias_data->domain;
2323                }
2324                read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2325        }
2326
2327        return dom;
2328}
2329
2330static int device_change_notifier(struct notifier_block *nb,
2331                                  unsigned long action, void *data)
2332{
2333        struct dma_ops_domain *dma_domain;
2334        struct protection_domain *domain;
2335        struct iommu_dev_data *dev_data;
2336        struct device *dev = data;
2337        struct amd_iommu *iommu;
2338        unsigned long flags;
2339        u16 devid;
2340
2341        if (!check_device(dev))
2342                return 0;
2343
2344        devid    = get_device_id(dev);
2345        iommu    = amd_iommu_rlookup_table[devid];
2346        dev_data = get_dev_data(dev);
2347
2348        switch (action) {
2349        case BUS_NOTIFY_UNBOUND_DRIVER:
2350
2351                domain = domain_for_device(dev);
2352
2353                if (!domain)
2354                        goto out;
2355                if (dev_data->passthrough)
2356                        break;
2357                detach_device(dev);
2358                break;
2359        case BUS_NOTIFY_ADD_DEVICE:
2360
2361                iommu_init_device(dev);
2362
2363                /*
2364                 * dev_data is still NULL and
2365                 * got initialized in iommu_init_device
2366                 */
2367                dev_data = get_dev_data(dev);
2368
2369                if (iommu_pass_through || dev_data->iommu_v2) {
2370                        dev_data->passthrough = true;
2371                        attach_device(dev, pt_domain);
2372                        break;
2373                }
2374
2375                domain = domain_for_device(dev);
2376
2377                /* allocate a protection domain if a device is added */
2378                dma_domain = find_protection_domain(devid);
2379                if (dma_domain)
2380                        goto out;
2381                dma_domain = dma_ops_domain_alloc();
2382                if (!dma_domain)
2383                        goto out;
2384                dma_domain->target_dev = devid;
2385
2386                spin_lock_irqsave(&iommu_pd_list_lock, flags);
2387                list_add_tail(&dma_domain->list, &iommu_pd_list);
2388                spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
2389
2390                dev_data = get_dev_data(dev);
2391
2392                dev->archdata.dma_ops = &amd_iommu_dma_ops;
2393
2394                break;
2395        case BUS_NOTIFY_DEL_DEVICE:
2396
2397                iommu_uninit_device(dev);
2398
2399        default:
2400                goto out;
2401        }
2402
2403        iommu_completion_wait(iommu);
2404
2405out:
2406        return 0;
2407}
2408
2409static struct notifier_block device_nb = {
2410        .notifier_call = device_change_notifier,
2411};
2412
2413void amd_iommu_init_notifier(void)
2414{
2415        bus_register_notifier(&pci_bus_type, &device_nb);
2416}
2417
2418/*****************************************************************************
2419 *
2420 * The next functions belong to the dma_ops mapping/unmapping code.
2421 *
2422 *****************************************************************************/
2423
2424/*
2425 * In the dma_ops path we only have the struct device. This function
2426 * finds the corresponding IOMMU, the protection domain and the
2427 * requestor id for a given device.
2428 * If the device is not yet associated with a domain this is also done
2429 * in this function.
2430 */
2431static struct protection_domain *get_domain(struct device *dev)
2432{
2433        struct protection_domain *domain;
2434        struct dma_ops_domain *dma_dom;
2435        u16 devid = get_device_id(dev);
2436
2437        if (!check_device(dev))
2438                return ERR_PTR(-EINVAL);
2439
2440        domain = domain_for_device(dev);
2441        if (domain != NULL && !dma_ops_domain(domain))
2442                return ERR_PTR(-EBUSY);
2443
2444        if (domain != NULL)
2445                return domain;
2446
2447        /* Device not bound yet - bind it */
2448        dma_dom = find_protection_domain(devid);
2449        if (!dma_dom)
2450                dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
2451        attach_device(dev, &dma_dom->domain);
2452        DUMP_printk("Using protection domain %d for device %s\n",
2453                    dma_dom->domain.id, dev_name(dev));
2454
2455        return &dma_dom->domain;
2456}
2457
2458static void update_device_table(struct protection_domain *domain)
2459{
2460        struct iommu_dev_data *dev_data;
2461
2462        list_for_each_entry(dev_data, &domain->dev_list, list)
2463                set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2464}
2465
2466static void update_domain(struct protection_domain *domain)
2467{
2468        if (!domain->updated)
2469                return;
2470
2471        update_device_table(domain);
2472
2473        domain_flush_devices(domain);
2474        domain_flush_tlb_pde(domain);
2475
2476        domain->updated = false;
2477}
2478
2479/*
2480 * This function fetches the PTE for a given address in the aperture
2481 */
2482static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2483                            unsigned long address)
2484{
2485        struct aperture_range *aperture;
2486        u64 *pte, *pte_page;
2487
2488        aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2489        if (!aperture)
2490                return NULL;
2491
2492        pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2493        if (!pte) {
2494                pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2495                                GFP_ATOMIC);
2496                aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2497        } else
2498                pte += PM_LEVEL_INDEX(0, address);
2499
2500        update_domain(&dom->domain);
2501
2502        return pte;
2503}
2504
2505/*
2506 * This is the generic map function. It maps one 4kb page at paddr to
2507 * the given address in the DMA address space for the domain.
2508 */
2509static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2510                                     unsigned long address,
2511                                     phys_addr_t paddr,
2512                                     int direction)
2513{
2514        u64 *pte, __pte;
2515
2516        WARN_ON(address > dom->aperture_size);
2517
2518        paddr &= PAGE_MASK;
2519
2520        pte  = dma_ops_get_pte(dom, address);
2521        if (!pte)
2522                return DMA_ERROR_CODE;
2523
2524        __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2525
2526        if (direction == DMA_TO_DEVICE)
2527                __pte |= IOMMU_PTE_IR;
2528        else if (direction == DMA_FROM_DEVICE)
2529                __pte |= IOMMU_PTE_IW;
2530        else if (direction == DMA_BIDIRECTIONAL)
2531                __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2532
2533        WARN_ON(*pte);
2534
2535        *pte = __pte;
2536
2537        return (dma_addr_t)address;
2538}
2539
2540/*
2541 * The generic unmapping function for on page in the DMA address space.
2542 */
2543static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2544                                 unsigned long address)
2545{
2546        struct aperture_range *aperture;
2547        u64 *pte;
2548
2549        if (address >= dom->aperture_size)
2550                return;
2551
2552        aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2553        if (!aperture)
2554                return;
2555
2556        pte  = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2557        if (!pte)
2558                return;
2559
2560        pte += PM_LEVEL_INDEX(0, address);
2561
2562        WARN_ON(!*pte);
2563
2564        *pte = 0ULL;
2565}
2566
2567/*
2568 * This function contains common code for mapping of a physically
2569 * contiguous memory region into DMA address space. It is used by all
2570 * mapping functions provided with this IOMMU driver.
2571 * Must be called with the domain lock held.
2572 */
2573static dma_addr_t __map_single(struct device *dev,
2574                               struct dma_ops_domain *dma_dom,
2575                               phys_addr_t paddr,
2576                               size_t size,
2577                               int dir,
2578                               bool align,
2579                               u64 dma_mask)
2580{
2581        dma_addr_t offset = paddr & ~PAGE_MASK;
2582        dma_addr_t address, start, ret;
2583        unsigned int pages;
2584        unsigned long align_mask = 0;
2585        int i;
2586
2587        pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2588        paddr &= PAGE_MASK;
2589
2590        INC_STATS_COUNTER(total_map_requests);
2591
2592        if (pages > 1)
2593                INC_STATS_COUNTER(cross_page);
2594
2595        if (align)
2596                align_mask = (1UL << get_order(size)) - 1;
2597
2598retry:
2599        address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2600                                          dma_mask);
2601        if (unlikely(address == DMA_ERROR_CODE)) {
2602                /*
2603                 * setting next_address here will let the address
2604                 * allocator only scan the new allocated range in the
2605                 * first run. This is a small optimization.
2606                 */
2607                dma_dom->next_address = dma_dom->aperture_size;
2608
2609                if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2610                        goto out;
2611
2612                /*
2613                 * aperture was successfully enlarged by 128 MB, try
2614                 * allocation again
2615                 */
2616                goto retry;
2617        }
2618
2619        start = address;
2620        for (i = 0; i < pages; ++i) {
2621                ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2622                if (ret == DMA_ERROR_CODE)
2623                        goto out_unmap;
2624
2625                paddr += PAGE_SIZE;
2626                start += PAGE_SIZE;
2627        }
2628        address += offset;
2629
2630        ADD_STATS_COUNTER(alloced_io_mem, size);
2631
2632        if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2633                domain_flush_tlb(&dma_dom->domain);
2634                dma_dom->need_flush = false;
2635        } else if (unlikely(amd_iommu_np_cache))
2636                domain_flush_pages(&dma_dom->domain, address, size);
2637
2638out:
2639        return address;
2640
2641out_unmap:
2642
2643        for (--i; i >= 0; --i) {
2644                start -= PAGE_SIZE;
2645                dma_ops_domain_unmap(dma_dom, start);
2646        }
2647
2648        dma_ops_free_addresses(dma_dom, address, pages);
2649
2650        return DMA_ERROR_CODE;
2651}
2652
2653/*
2654 * Does the reverse of the __map_single function. Must be called with
2655 * the domain lock held too
2656 */
2657static void __unmap_single(struct dma_ops_domain *dma_dom,
2658                           dma_addr_t dma_addr,
2659                           size_t size,
2660                           int dir)
2661{
2662        dma_addr_t flush_addr;
2663        dma_addr_t i, start;
2664        unsigned int pages;
2665
2666        if ((dma_addr == DMA_ERROR_CODE) ||
2667            (dma_addr + size > dma_dom->aperture_size))
2668                return;
2669
2670        flush_addr = dma_addr;
2671        pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2672        dma_addr &= PAGE_MASK;
2673        start = dma_addr;
2674
2675        for (i = 0; i < pages; ++i) {
2676                dma_ops_domain_unmap(dma_dom, start);
2677                start += PAGE_SIZE;
2678        }
2679
2680        SUB_STATS_COUNTER(alloced_io_mem, size);
2681
2682        dma_ops_free_addresses(dma_dom, dma_addr, pages);
2683
2684        if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2685                domain_flush_pages(&dma_dom->domain, flush_addr, size);
2686                dma_dom->need_flush = false;
2687        }
2688}
2689
2690/*
2691 * The exported map_single function for dma_ops.
2692 */
2693static dma_addr_t map_page(struct device *dev, struct page *page,
2694                           unsigned long offset, size_t size,
2695                           enum dma_data_direction dir,
2696                           struct dma_attrs *attrs)
2697{
2698        unsigned long flags;
2699        struct protection_domain *domain;
2700        dma_addr_t addr;
2701        u64 dma_mask;
2702        phys_addr_t paddr = page_to_phys(page) + offset;
2703
2704        INC_STATS_COUNTER(cnt_map_single);
2705
2706        domain = get_domain(dev);
2707        if (PTR_ERR(domain) == -EINVAL)
2708                return (dma_addr_t)paddr;
2709        else if (IS_ERR(domain))
2710                return DMA_ERROR_CODE;
2711
2712        dma_mask = *dev->dma_mask;
2713
2714        spin_lock_irqsave(&domain->lock, flags);
2715
2716        addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2717                            dma_mask);
2718        if (addr == DMA_ERROR_CODE)
2719                goto out;
2720
2721        domain_flush_complete(domain);
2722
2723out:
2724        spin_unlock_irqrestore(&domain->lock, flags);
2725
2726        return addr;
2727}
2728
2729/*
2730 * The exported unmap_single function for dma_ops.
2731 */
2732static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2733                       enum dma_data_direction dir, struct dma_attrs *attrs)
2734{
2735        unsigned long flags;
2736        struct protection_domain *domain;
2737
2738        INC_STATS_COUNTER(cnt_unmap_single);
2739
2740        domain = get_domain(dev);
2741        if (IS_ERR(domain))
2742                return;
2743
2744        spin_lock_irqsave(&domain->lock, flags);
2745
2746        __unmap_single(domain->priv, dma_addr, size, dir);
2747
2748        domain_flush_complete(domain);
2749
2750        spin_unlock_irqrestore(&domain->lock, flags);
2751}
2752
2753/*
2754 * This is a special map_sg function which is used if we should map a
2755 * device which is not handled by an AMD IOMMU in the system.
2756 */
2757static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2758                           int nelems, int dir)
2759{
2760        struct scatterlist *s;
2761        int i;
2762
2763        for_each_sg(sglist, s, nelems, i) {
2764                s->dma_address = (dma_addr_t)sg_phys(s);
2765                s->dma_length  = s->length;
2766        }
2767
2768        return nelems;
2769}
2770
2771/*
2772 * The exported map_sg function for dma_ops (handles scatter-gather
2773 * lists).
2774 */
2775static int map_sg(struct device *dev, struct scatterlist *sglist,
2776                  int nelems, enum dma_data_direction dir,
2777                  struct dma_attrs *attrs)
2778{
2779        unsigned long flags;
2780        struct protection_domain *domain;
2781        int i;
2782        struct scatterlist *s;
2783        phys_addr_t paddr;
2784        int mapped_elems = 0;
2785        u64 dma_mask;
2786
2787        INC_STATS_COUNTER(cnt_map_sg);
2788
2789        domain = get_domain(dev);
2790        if (PTR_ERR(domain) == -EINVAL)
2791                return map_sg_no_iommu(dev, sglist, nelems, dir);
2792        else if (IS_ERR(domain))
2793                return 0;
2794
2795        dma_mask = *dev->dma_mask;
2796
2797        spin_lock_irqsave(&domain->lock, flags);
2798
2799        for_each_sg(sglist, s, nelems, i) {
2800                paddr = sg_phys(s);
2801
2802                s->dma_address = __map_single(dev, domain->priv,
2803                                              paddr, s->length, dir, false,
2804                                              dma_mask);
2805
2806                if (s->dma_address) {
2807                        s->dma_length = s->length;
2808                        mapped_elems++;
2809                } else
2810                        goto unmap;
2811        }
2812
2813        domain_flush_complete(domain);
2814
2815out:
2816        spin_unlock_irqrestore(&domain->lock, flags);
2817
2818        return mapped_elems;
2819unmap:
2820        for_each_sg(sglist, s, mapped_elems, i) {
2821                if (s->dma_address)
2822                        __unmap_single(domain->priv, s->dma_address,
2823                                       s->dma_length, dir);
2824                s->dma_address = s->dma_length = 0;
2825        }
2826
2827        mapped_elems = 0;
2828
2829        goto out;
2830}
2831
2832/*
2833 * The exported map_sg function for dma_ops (handles scatter-gather
2834 * lists).
2835 */
2836static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2837                     int nelems, enum dma_data_direction dir,
2838                     struct dma_attrs *attrs)
2839{
2840        unsigned long flags;
2841        struct protection_domain *domain;
2842        struct scatterlist *s;
2843        int i;
2844
2845        INC_STATS_COUNTER(cnt_unmap_sg);
2846
2847        domain = get_domain(dev);
2848        if (IS_ERR(domain))
2849                return;
2850
2851        spin_lock_irqsave(&domain->lock, flags);
2852
2853        for_each_sg(sglist, s, nelems, i) {
2854                __unmap_single(domain->priv, s->dma_address,
2855                               s->dma_length, dir);
2856                s->dma_address = s->dma_length = 0;
2857        }
2858
2859        domain_flush_complete(domain);
2860
2861        spin_unlock_irqrestore(&domain->lock, flags);
2862}
2863
2864/*
2865 * The exported alloc_coherent function for dma_ops.
2866 */
2867static void *alloc_coherent(struct device *dev, size_t size,
2868                            dma_addr_t *dma_addr, gfp_t flag,
2869                            struct dma_attrs *attrs)
2870{
2871        unsigned long flags;
2872        void *virt_addr;
2873        struct protection_domain *domain;
2874        phys_addr_t paddr;
2875        u64 dma_mask = dev->coherent_dma_mask;
2876
2877        INC_STATS_COUNTER(cnt_alloc_coherent);
2878
2879        domain = get_domain(dev);
2880        if (PTR_ERR(domain) == -EINVAL) {
2881                virt_addr = (void *)__get_free_pages(flag, get_order(size));
2882                *dma_addr = __pa(virt_addr);
2883                return virt_addr;
2884        } else if (IS_ERR(domain))
2885                return NULL;
2886
2887        dma_mask  = dev->coherent_dma_mask;
2888        flag     &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2889        flag     |= __GFP_ZERO;
2890
2891        virt_addr = (void *)__get_free_pages(flag, get_order(size));
2892        if (!virt_addr)
2893                return NULL;
2894
2895        paddr = virt_to_phys(virt_addr);
2896
2897        if (!dma_mask)
2898                dma_mask = *dev->dma_mask;
2899
2900        spin_lock_irqsave(&domain->lock, flags);
2901
2902        *dma_addr = __map_single(dev, domain->priv, paddr,
2903                                 size, DMA_BIDIRECTIONAL, true, dma_mask);
2904
2905        if (*dma_addr == DMA_ERROR_CODE) {
2906                spin_unlock_irqrestore(&domain->lock, flags);
2907                goto out_free;
2908        }
2909
2910        domain_flush_complete(domain);
2911
2912        spin_unlock_irqrestore(&domain->lock, flags);
2913
2914        return virt_addr;
2915
2916out_free:
2917
2918        free_pages((unsigned long)virt_addr, get_order(size));
2919
2920        return NULL;
2921}
2922
2923/*
2924 * The exported free_coherent function for dma_ops.
2925 */
2926static void free_coherent(struct device *dev, size_t size,
2927                          void *virt_addr, dma_addr_t dma_addr,
2928                          struct dma_attrs *attrs)
2929{
2930        unsigned long flags;
2931        struct protection_domain *domain;
2932
2933        INC_STATS_COUNTER(cnt_free_coherent);
2934
2935        domain = get_domain(dev);
2936        if (IS_ERR(domain))
2937                goto free_mem;
2938
2939        spin_lock_irqsave(&domain->lock, flags);
2940
2941        __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2942
2943        domain_flush_complete(domain);
2944
2945        spin_unlock_irqrestore(&domain->lock, flags);
2946
2947free_mem:
2948        free_pages((unsigned long)virt_addr, get_order(size));
2949}
2950
2951/*
2952 * This function is called by the DMA layer to find out if we can handle a
2953 * particular device. It is part of the dma_ops.
2954 */
2955static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2956{
2957        return check_device(dev);
2958}
2959
2960/*
2961 * The function for pre-allocating protection domains.
2962 *
2963 * If the driver core informs the DMA layer if a driver grabs a device
2964 * we don't need to preallocate the protection domains anymore.
2965 * For now we have to.
2966 */
2967static void __init prealloc_protection_domains(void)
2968{
2969        struct iommu_dev_data *dev_data;
2970        struct dma_ops_domain *dma_dom;
2971        struct pci_dev *dev = NULL;
2972        u16 devid;
2973
2974        for_each_pci_dev(dev) {
2975
2976                /* Do we handle this device? */
2977                if (!check_device(&dev->dev))
2978                        continue;
2979
2980                dev_data = get_dev_data(&dev->dev);
2981                if (!amd_iommu_force_isolation && dev_data->iommu_v2) {
2982                        /* Make sure passthrough domain is allocated */
2983                        alloc_passthrough_domain();
2984                        dev_data->passthrough = true;
2985                        attach_device(&dev->dev, pt_domain);
2986                        pr_info("AMD-Vi: Using passthrough domain for device %s\n",
2987                                dev_name(&dev->dev));
2988                }
2989
2990                /* Is there already any domain for it? */
2991                if (domain_for_device(&dev->dev))
2992                        continue;
2993
2994                devid = get_device_id(&dev->dev);
2995
2996                dma_dom = dma_ops_domain_alloc();
2997                if (!dma_dom)
2998                        continue;
2999                init_unity_mappings_for_device(dma_dom, devid);
3000                dma_dom->target_dev = devid;
3001
3002                attach_device(&dev->dev, &dma_dom->domain);
3003
3004                list_add_tail(&dma_dom->list, &iommu_pd_list);
3005        }
3006}
3007
3008static struct dma_map_ops amd_iommu_dma_ops = {
3009        .alloc = alloc_coherent,
3010        .free = free_coherent,
3011        .map_page = map_page,
3012        .unmap_page = unmap_page,
3013        .map_sg = map_sg,
3014        .unmap_sg = unmap_sg,
3015        .dma_supported = amd_iommu_dma_supported,
3016};
3017
3018static unsigned device_dma_ops_init(void)
3019{
3020        struct iommu_dev_data *dev_data;
3021        struct pci_dev *pdev = NULL;
3022        unsigned unhandled = 0;
3023
3024        for_each_pci_dev(pdev) {
3025                if (!check_device(&pdev->dev)) {
3026
3027                        iommu_ignore_device(&pdev->dev);
3028
3029                        unhandled += 1;
3030                        continue;
3031                }
3032
3033                dev_data = get_dev_data(&pdev->dev);
3034
3035                if (!dev_data->passthrough)
3036                        pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
3037                else
3038                        pdev->dev.archdata.dma_ops = &nommu_dma_ops;
3039        }
3040
3041        return unhandled;
3042}
3043
3044/*
3045 * The function which clues the AMD IOMMU driver into dma_ops.
3046 */
3047
3048void __init amd_iommu_init_api(void)
3049{
3050        bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
3051}
3052
3053int __init amd_iommu_init_dma_ops(void)
3054{
3055        struct amd_iommu *iommu;
3056        int ret, unhandled;
3057
3058        /*
3059         * first allocate a default protection domain for every IOMMU we
3060         * found in the system. Devices not assigned to any other
3061         * protection domain will be assigned to the default one.
3062         */
3063        for_each_iommu(iommu) {
3064                iommu->default_dom = dma_ops_domain_alloc();
3065                if (iommu->default_dom == NULL)
3066                        return -ENOMEM;
3067                iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
3068                ret = iommu_init_unity_mappings(iommu);
3069                if (ret)
3070                        goto free_domains;
3071        }
3072
3073        /*
3074         * Pre-allocate the protection domains for each device.
3075         */
3076        prealloc_protection_domains();
3077
3078        iommu_detected = 1;
3079        swiotlb = 0;
3080
3081        /* Make the driver finally visible to the drivers */
3082        unhandled = device_dma_ops_init();
3083        if (unhandled && max_pfn > MAX_DMA32_PFN) {
3084                /* There are unhandled devices - initialize swiotlb for them */
3085                swiotlb = 1;
3086        }
3087
3088        amd_iommu_stats_init();
3089
3090        if (amd_iommu_unmap_flush)
3091                pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
3092        else
3093                pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
3094
3095        return 0;
3096
3097free_domains:
3098
3099        for_each_iommu(iommu) {
3100                if (iommu->default_dom)
3101                        dma_ops_domain_free(iommu->default_dom);
3102        }
3103
3104        return ret;
3105}
3106
3107/*****************************************************************************
3108 *
3109 * The following functions belong to the exported interface of AMD IOMMU
3110 *
3111 * This interface allows access to lower level functions of the IOMMU
3112 * like protection domain handling and assignement of devices to domains
3113 * which is not possible with the dma_ops interface.
3114 *
3115 *****************************************************************************/
3116
3117static void cleanup_domain(struct protection_domain *domain)
3118{
3119        struct iommu_dev_data *dev_data, *next;
3120        unsigned long flags;
3121
3122        write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3123
3124        list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
3125                __detach_device(dev_data);
3126                atomic_set(&dev_data->bind, 0);
3127        }
3128
3129        write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3130}
3131
3132static void protection_domain_free(struct protection_domain *domain)
3133{
3134        if (!domain)
3135                return;
3136
3137        del_domain_from_list(domain);
3138
3139        if (domain->id)
3140                domain_id_free(domain->id);
3141
3142        kfree(domain);
3143}
3144
3145static struct protection_domain *protection_domain_alloc(void)
3146{
3147        struct protection_domain *domain;
3148
3149        domain = kzalloc(sizeof(*domain), GFP_KERNEL);
3150        if (!domain)
3151                return NULL;
3152
3153        spin_lock_init(&domain->lock);
3154        mutex_init(&domain->api_lock);
3155        domain->id = domain_id_alloc();
3156        if (!domain->id)
3157                goto out_err;
3158        INIT_LIST_HEAD(&domain->dev_list);
3159
3160        add_domain_to_list(domain);
3161
3162        return domain;
3163
3164out_err:
3165        kfree(domain);
3166
3167        return NULL;
3168}
3169
3170static int __init alloc_passthrough_domain(void)
3171{
3172        if (pt_domain != NULL)
3173                return 0;
3174
3175        /* allocate passthrough domain */
3176        pt_domain = protection_domain_alloc();
3177        if (!pt_domain)
3178                return -ENOMEM;
3179
3180        pt_domain->mode = PAGE_MODE_NONE;
3181
3182        return 0;
3183}
3184static int amd_iommu_domain_init(struct iommu_domain *dom)
3185{
3186        struct protection_domain *domain;
3187
3188        domain = protection_domain_alloc();
3189        if (!domain)
3190                goto out_free;
3191
3192        domain->mode    = PAGE_MODE_3_LEVEL;
3193        domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
3194        if (!domain->pt_root)
3195                goto out_free;
3196
3197        domain->iommu_domain = dom;
3198
3199        dom->priv = domain;
3200
3201        dom->geometry.aperture_start = 0;
3202        dom->geometry.aperture_end   = ~0ULL;
3203        dom->geometry.force_aperture = true;
3204
3205        return 0;
3206
3207out_free:
3208        protection_domain_free(domain);
3209
3210        return -ENOMEM;
3211}
3212
3213static void amd_iommu_domain_destroy(struct iommu_domain *dom)
3214{
3215        struct protection_domain *domain = dom->priv;
3216
3217        if (!domain)
3218                return;
3219
3220        if (domain->dev_cnt > 0)
3221                cleanup_domain(domain);
3222
3223        BUG_ON(domain->dev_cnt != 0);
3224
3225        if (domain->mode != PAGE_MODE_NONE)
3226                free_pagetable(domain);
3227
3228        if (domain->flags & PD_IOMMUV2_MASK)
3229                free_gcr3_table(domain);
3230
3231        protection_domain_free(domain);
3232
3233        dom->priv = NULL;
3234}
3235
3236static void amd_iommu_detach_device(struct iommu_domain *dom,
3237                                    struct device *dev)
3238{
3239        struct iommu_dev_data *dev_data = dev->archdata.iommu;
3240        struct amd_iommu *iommu;
3241        u16 devid;
3242
3243        if (!check_device(dev))
3244                return;
3245
3246        devid = get_device_id(dev);
3247
3248        if (dev_data->domain != NULL)
3249                detach_device(dev);
3250
3251        iommu = amd_iommu_rlookup_table[devid];
3252        if (!iommu)
3253                return;
3254
3255        iommu_completion_wait(iommu);
3256}
3257
3258static int amd_iommu_attach_device(struct iommu_domain *dom,
3259                                   struct device *dev)
3260{
3261        struct protection_domain *domain = dom->priv;
3262        struct iommu_dev_data *dev_data;
3263        struct amd_iommu *iommu;
3264        int ret;
3265
3266        if (!check_device(dev))
3267                return -EINVAL;
3268
3269        dev_data = dev->archdata.iommu;
3270
3271        iommu = amd_iommu_rlookup_table[dev_data->devid];
3272        if (!iommu)
3273                return -EINVAL;
3274
3275        if (dev_data->domain)
3276                detach_device(dev);
3277
3278        ret = attach_device(dev, domain);
3279
3280        iommu_completion_wait(iommu);
3281
3282        return ret;
3283}
3284
3285static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3286                         phys_addr_t paddr, size_t page_size, int iommu_prot)
3287{
3288        struct protection_domain *domain = dom->priv;
3289        int prot = 0;
3290        int ret;
3291
3292        if (domain->mode == PAGE_MODE_NONE)
3293                return -EINVAL;
3294
3295        if (iommu_prot & IOMMU_READ)
3296                prot |= IOMMU_PROT_IR;
3297        if (iommu_prot & IOMMU_WRITE)
3298                prot |= IOMMU_PROT_IW;
3299
3300        mutex_lock(&domain->api_lock);
3301        ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3302        mutex_unlock(&domain->api_lock);
3303
3304        return ret;
3305}
3306
3307static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3308                           size_t page_size)
3309{
3310        struct protection_domain *domain = dom->priv;
3311        size_t unmap_size;
3312
3313        if (domain->mode == PAGE_MODE_NONE)
3314                return -EINVAL;
3315
3316        mutex_lock(&domain->api_lock);
3317        unmap_size = iommu_unmap_page(domain, iova, page_size);
3318        mutex_unlock(&domain->api_lock);
3319
3320        domain_flush_tlb_pde(domain);
3321
3322        return unmap_size;
3323}
3324
3325static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3326                                          unsigned long iova)
3327{
3328        struct protection_domain *domain = dom->priv;
3329        unsigned long offset_mask;
3330        phys_addr_t paddr;
3331        u64 *pte, __pte;
3332
3333        if (domain->mode == PAGE_MODE_NONE)
3334                return iova;
3335
3336        pte = fetch_pte(domain, iova);
3337
3338        if (!pte || !IOMMU_PTE_PRESENT(*pte))
3339                return 0;
3340
3341        if (PM_PTE_LEVEL(*pte) == 0)
3342                offset_mask = PAGE_SIZE - 1;
3343        else
3344                offset_mask = PTE_PAGE_SIZE(*pte) - 1;
3345
3346        __pte = *pte & PM_ADDR_MASK;
3347        paddr = (__pte & ~offset_mask) | (iova & offset_mask);
3348
3349        return paddr;
3350}
3351
3352static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
3353                                    unsigned long cap)
3354{
3355        switch (cap) {
3356        case IOMMU_CAP_CACHE_COHERENCY:
3357                return 1;
3358        case IOMMU_CAP_INTR_REMAP:
3359                return irq_remapping_enabled;
3360        }
3361
3362        return 0;
3363}
3364
3365static struct iommu_ops amd_iommu_ops = {
3366        .domain_init = amd_iommu_domain_init,
3367        .domain_destroy = amd_iommu_domain_destroy,
3368        .attach_dev = amd_iommu_attach_device,
3369        .detach_dev = amd_iommu_detach_device,
3370        .map = amd_iommu_map,
3371        .unmap = amd_iommu_unmap,
3372        .iova_to_phys = amd_iommu_iova_to_phys,
3373        .domain_has_cap = amd_iommu_domain_has_cap,
3374        .pgsize_bitmap  = AMD_IOMMU_PGSIZES,
3375};
3376
3377/*****************************************************************************
3378 *
3379 * The next functions do a basic initialization of IOMMU for pass through
3380 * mode
3381 *
3382 * In passthrough mode the IOMMU is initialized and enabled but not used for
3383 * DMA-API translation.
3384 *
3385 *****************************************************************************/
3386
3387int __init amd_iommu_init_passthrough(void)
3388{
3389        struct iommu_dev_data *dev_data;
3390        struct pci_dev *dev = NULL;
3391        struct amd_iommu *iommu;
3392        u16 devid;
3393        int ret;
3394
3395        ret = alloc_passthrough_domain();
3396        if (ret)
3397                return ret;
3398
3399        for_each_pci_dev(dev) {
3400                if (!check_device(&dev->dev))
3401                        continue;
3402
3403                dev_data = get_dev_data(&dev->dev);
3404                dev_data->passthrough = true;
3405
3406                devid = get_device_id(&dev->dev);
3407
3408                iommu = amd_iommu_rlookup_table[devid];
3409                if (!iommu)
3410                        continue;
3411
3412                attach_device(&dev->dev, pt_domain);
3413        }
3414
3415        amd_iommu_stats_init();
3416
3417        pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
3418
3419        return 0;
3420}
3421
3422/* IOMMUv2 specific functions */
3423int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3424{
3425        return atomic_notifier_chain_register(&ppr_notifier, nb);
3426}
3427EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3428
3429int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3430{
3431        return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3432}
3433EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3434
3435void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3436{
3437        struct protection_domain *domain = dom->priv;
3438        unsigned long flags;
3439
3440        spin_lock_irqsave(&domain->lock, flags);
3441
3442        /* Update data structure */
3443        domain->mode    = PAGE_MODE_NONE;
3444        domain->updated = true;
3445
3446        /* Make changes visible to IOMMUs */
3447        update_domain(domain);
3448
3449        /* Page-table is not visible to IOMMU anymore, so free it */
3450        free_pagetable(domain);
3451
3452        spin_unlock_irqrestore(&domain->lock, flags);
3453}
3454EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3455
3456int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3457{
3458        struct protection_domain *domain = dom->priv;
3459        unsigned long flags;
3460        int levels, ret;
3461
3462        if (pasids <= 0 || pasids > (PASID_MASK + 1))
3463                return -EINVAL;
3464
3465        /* Number of GCR3 table levels required */
3466        for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3467                levels += 1;
3468
3469        if (levels > amd_iommu_max_glx_val)
3470                return -EINVAL;
3471
3472        spin_lock_irqsave(&domain->lock, flags);
3473
3474        /*
3475         * Save us all sanity checks whether devices already in the
3476         * domain support IOMMUv2. Just force that the domain has no
3477         * devices attached when it is switched into IOMMUv2 mode.
3478         */
3479        ret = -EBUSY;
3480        if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3481                goto out;
3482
3483        ret = -ENOMEM;
3484        domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3485        if (domain->gcr3_tbl == NULL)
3486                goto out;
3487
3488        domain->glx      = levels;
3489        domain->flags   |= PD_IOMMUV2_MASK;
3490        domain->updated  = true;
3491
3492        update_domain(domain);
3493
3494        ret = 0;
3495
3496out:
3497        spin_unlock_irqrestore(&domain->lock, flags);
3498
3499        return ret;
3500}
3501EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3502
3503static int __flush_pasid(struct protection_domain *domain, int pasid,
3504                         u64 address, bool size)
3505{
3506        struct iommu_dev_data *dev_data;
3507        struct iommu_cmd cmd;
3508        int i, ret;
3509
3510        if (!(domain->flags & PD_IOMMUV2_MASK))
3511                return -EINVAL;
3512
3513        build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3514
3515        /*
3516         * IOMMU TLB needs to be flushed before Device TLB to
3517         * prevent device TLB refill from IOMMU TLB
3518         */
3519        for (i = 0; i < amd_iommus_present; ++i) {
3520                if (domain->dev_iommu[i] == 0)
3521                        continue;
3522
3523                ret = iommu_queue_command(amd_iommus[i], &cmd);
3524                if (ret != 0)
3525                        goto out;
3526        }
3527
3528        /* Wait until IOMMU TLB flushes are complete */
3529        domain_flush_complete(domain);
3530
3531        /* Now flush device TLBs */
3532        list_for_each_entry(dev_data, &domain->dev_list, list) {
3533                struct amd_iommu *iommu;
3534                int qdep;
3535
3536                BUG_ON(!dev_data->ats.enabled);
3537
3538                qdep  = dev_data->ats.qdep;
3539                iommu = amd_iommu_rlookup_table[dev_data->devid];
3540
3541                build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3542                                      qdep, address, size);
3543
3544                ret = iommu_queue_command(iommu, &cmd);
3545                if (ret != 0)
3546                        goto out;
3547        }
3548
3549        /* Wait until all device TLBs are flushed */
3550        domain_flush_complete(domain);
3551
3552        ret = 0;
3553
3554out:
3555
3556        return ret;
3557}
3558
3559static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3560                                  u64 address)
3561{
3562        INC_STATS_COUNTER(invalidate_iotlb);
3563
3564        return __flush_pasid(domain, pasid, address, false);
3565}
3566
3567int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3568                         u64 address)
3569{
3570        struct protection_domain *domain = dom->priv;
3571        unsigned long flags;
3572        int ret;
3573
3574        spin_lock_irqsave(&domain->lock, flags);
3575        ret = __amd_iommu_flush_page(domain, pasid, address);
3576        spin_unlock_irqrestore(&domain->lock, flags);
3577
3578        return ret;
3579}
3580EXPORT_SYMBOL(amd_iommu_flush_page);
3581
3582static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3583{
3584        INC_STATS_COUNTER(invalidate_iotlb_all);
3585
3586        return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3587                             true);
3588}
3589
3590int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3591{
3592        struct protection_domain *domain = dom->priv;
3593        unsigned long flags;
3594        int ret;
3595
3596        spin_lock_irqsave(&domain->lock, flags);
3597        ret = __amd_iommu_flush_tlb(domain, pasid);
3598        spin_unlock_irqrestore(&domain->lock, flags);
3599
3600        return ret;
3601}
3602EXPORT_SYMBOL(amd_iommu_flush_tlb);
3603
3604static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3605{
3606        int index;
3607        u64 *pte;
3608
3609        while (true) {
3610
3611                index = (pasid >> (9 * level)) & 0x1ff;
3612                pte   = &root[index];
3613
3614                if (level == 0)
3615                        break;
3616
3617                if (!(*pte & GCR3_VALID)) {
3618                        if (!alloc)
3619                                return NULL;
3620
3621                        root = (void *)get_zeroed_page(GFP_ATOMIC);
3622                        if (root == NULL)
3623                                return NULL;
3624
3625                        *pte = __pa(root) | GCR3_VALID;
3626                }
3627
3628                root = __va(*pte & PAGE_MASK);
3629
3630                level -= 1;
3631        }
3632
3633        return pte;
3634}
3635
3636static int __set_gcr3(struct protection_domain *domain, int pasid,
3637                      unsigned long cr3)
3638{
3639        u64 *pte;
3640
3641        if (domain->mode != PAGE_MODE_NONE)
3642                return -EINVAL;
3643
3644        pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3645        if (pte == NULL)
3646                return -ENOMEM;
3647
3648        *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3649
3650        return __amd_iommu_flush_tlb(domain, pasid);
3651}
3652
3653static int __clear_gcr3(struct protection_domain *domain, int pasid)
3654{
3655        u64 *pte;
3656
3657        if (domain->mode != PAGE_MODE_NONE)
3658                return -EINVAL;
3659
3660        pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3661        if (pte == NULL)
3662                return 0;
3663
3664        *pte = 0;
3665
3666        return __amd_iommu_flush_tlb(domain, pasid);
3667}
3668
3669int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3670                              unsigned long cr3)
3671{
3672        struct protection_domain *domain = dom->priv;
3673        unsigned long flags;
3674        int ret;
3675
3676        spin_lock_irqsave(&domain->lock, flags);
3677        ret = __set_gcr3(domain, pasid, cr3);
3678        spin_unlock_irqrestore(&domain->lock, flags);
3679
3680        return ret;
3681}
3682EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3683
3684int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3685{
3686        struct protection_domain *domain = dom->priv;
3687        unsigned long flags;
3688        int ret;
3689
3690        spin_lock_irqsave(&domain->lock, flags);
3691        ret = __clear_gcr3(domain, pasid);
3692        spin_unlock_irqrestore(&domain->lock, flags);
3693
3694        return ret;
3695}
3696EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3697
3698int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3699                           int status, int tag)
3700{
3701        struct iommu_dev_data *dev_data;
3702        struct amd_iommu *iommu;
3703        struct iommu_cmd cmd;
3704
3705        INC_STATS_COUNTER(complete_ppr);
3706
3707        dev_data = get_dev_data(&pdev->dev);
3708        iommu    = amd_iommu_rlookup_table[dev_data->devid];
3709
3710        build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3711                           tag, dev_data->pri_tlp);
3712
3713        return iommu_queue_command(iommu, &cmd);
3714}
3715EXPORT_SYMBOL(amd_iommu_complete_ppr);
3716
3717struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3718{
3719        struct protection_domain *domain;
3720
3721        domain = get_domain(&pdev->dev);
3722        if (IS_ERR(domain))
3723                return NULL;
3724
3725        /* Only return IOMMUv2 domains */
3726        if (!(domain->flags & PD_IOMMUV2_MASK))
3727                return NULL;
3728
3729        return domain->iommu_domain;
3730}
3731EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3732
3733void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3734{
3735        struct iommu_dev_data *dev_data;
3736
3737        if (!amd_iommu_v2_supported())
3738                return;
3739
3740        dev_data = get_dev_data(&pdev->dev);
3741        dev_data->errata |= (1 << erratum);
3742}
3743EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3744
3745int amd_iommu_device_info(struct pci_dev *pdev,
3746                          struct amd_iommu_device_info *info)
3747{
3748        int max_pasids;
3749        int pos;
3750
3751        if (pdev == NULL || info == NULL)
3752                return -EINVAL;
3753
3754        if (!amd_iommu_v2_supported())
3755                return -EINVAL;
3756
3757        memset(info, 0, sizeof(*info));
3758
3759        pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3760        if (pos)
3761                info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3762
3763        pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3764        if (pos)
3765                info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3766
3767        pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3768        if (pos) {
3769                int features;
3770
3771                max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3772                max_pasids = min(max_pasids, (1 << 20));
3773
3774                info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3775                info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3776
3777                features = pci_pasid_features(pdev);
3778                if (features & PCI_PASID_CAP_EXEC)
3779                        info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3780                if (features & PCI_PASID_CAP_PRIV)
3781                        info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3782        }
3783
3784        return 0;
3785}
3786EXPORT_SYMBOL(amd_iommu_device_info);
3787
3788#ifdef CONFIG_IRQ_REMAP
3789
3790/*****************************************************************************
3791 *
3792 * Interrupt Remapping Implementation
3793 *
3794 *****************************************************************************/
3795
3796union irte {
3797        u32 val;
3798        struct {
3799                u32 valid       : 1,
3800                    no_fault    : 1,
3801                    int_type    : 3,
3802                    rq_eoi      : 1,
3803                    dm          : 1,
3804                    rsvd_1      : 1,
3805                    destination : 8,
3806                    vector      : 8,
3807                    rsvd_2      : 8;
3808        } fields;
3809};
3810
3811#define DTE_IRQ_PHYS_ADDR_MASK  (((1ULL << 45)-1) << 6)
3812#define DTE_IRQ_REMAP_INTCTL    (2ULL << 60)
3813#define DTE_IRQ_TABLE_LEN       (8ULL << 1)
3814#define DTE_IRQ_REMAP_ENABLE    1ULL
3815
3816static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3817{
3818        u64 dte;
3819
3820        dte     = amd_iommu_dev_table[devid].data[2];
3821        dte     &= ~DTE_IRQ_PHYS_ADDR_MASK;
3822        dte     |= virt_to_phys(table->table);
3823        dte     |= DTE_IRQ_REMAP_INTCTL;
3824        dte     |= DTE_IRQ_TABLE_LEN;
3825        dte     |= DTE_IRQ_REMAP_ENABLE;
3826
3827        amd_iommu_dev_table[devid].data[2] = dte;
3828}
3829
3830#define IRTE_ALLOCATED (~1U)
3831
3832static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3833{
3834        struct irq_remap_table *table = NULL;
3835        struct amd_iommu *iommu;
3836        unsigned long flags;
3837        u16 alias;
3838
3839        write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3840
3841        iommu = amd_iommu_rlookup_table[devid];
3842        if (!iommu)
3843                goto out_unlock;
3844
3845        table = irq_lookup_table[devid];
3846        if (table)
3847                goto out;
3848
3849        alias = amd_iommu_alias_table[devid];
3850        table = irq_lookup_table[alias];
3851        if (table) {
3852                irq_lookup_table[devid] = table;
3853                set_dte_irq_entry(devid, table);
3854                iommu_flush_dte(iommu, devid);
3855                goto out;
3856        }
3857
3858        /* Nothing there yet, allocate new irq remapping table */
3859        table = kzalloc(sizeof(*table), GFP_ATOMIC);
3860        if (!table)
3861                goto out;
3862
3863        if (ioapic)
3864                /* Keep the first 32 indexes free for IOAPIC interrupts */
3865                table->min_index = 32;
3866
3867        table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3868        if (!table->table) {
3869                kfree(table);
3870                table = NULL;
3871                goto out;
3872        }
3873
3874        memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3875
3876        if (ioapic) {
3877                int i;
3878
3879                for (i = 0; i < 32; ++i)
3880                        table->table[i] = IRTE_ALLOCATED;
3881        }
3882
3883        irq_lookup_table[devid] = table;
3884        set_dte_irq_entry(devid, table);
3885        iommu_flush_dte(iommu, devid);
3886        if (devid != alias) {
3887                irq_lookup_table[alias] = table;
3888                set_dte_irq_entry(devid, table);
3889                iommu_flush_dte(iommu, alias);
3890        }
3891
3892out:
3893        iommu_completion_wait(iommu);
3894
3895out_unlock:
3896        write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3897
3898        return table;
3899}
3900
3901static int alloc_irq_index(struct irq_cfg *cfg, u16 devid, int count)
3902{
3903        struct irq_remap_table *table;
3904        unsigned long flags;
3905        int index, c;
3906
3907        table = get_irq_table(devid, false);
3908        if (!table)
3909                return -ENODEV;
3910
3911        spin_lock_irqsave(&table->lock, flags);
3912
3913        /* Scan table for free entries */
3914        for (c = 0, index = table->min_index;
3915             index < MAX_IRQS_PER_TABLE;
3916             ++index) {
3917                if (table->table[index] == 0)
3918                        c += 1;
3919                else
3920                        c = 0;
3921
3922                if (c == count) {
3923                        struct irq_2_iommu *irte_info;
3924
3925                        for (; c != 0; --c)
3926                                table->table[index - c + 1] = IRTE_ALLOCATED;
3927
3928                        index -= count - 1;
3929
3930                        irte_info             = &cfg->irq_2_iommu;
3931                        irte_info->sub_handle = devid;
3932                        irte_info->irte_index = index;
3933                        irte_info->iommu      = (void *)cfg;
3934
3935                        goto out;
3936                }
3937        }
3938
3939        index = -ENOSPC;
3940
3941out:
3942        spin_unlock_irqrestore(&table->lock, flags);
3943
3944        return index;
3945}
3946
3947static int get_irte(u16 devid, int index, union irte *irte)
3948{
3949        struct irq_remap_table *table;
3950        unsigned long flags;
3951
3952        table = get_irq_table(devid, false);
3953        if (!table)
3954                return -ENOMEM;
3955
3956        spin_lock_irqsave(&table->lock, flags);
3957        irte->val = table->table[index];
3958        spin_unlock_irqrestore(&table->lock, flags);
3959
3960        return 0;
3961}
3962
3963static int modify_irte(u16 devid, int index, union irte irte)
3964{
3965        struct irq_remap_table *table;
3966        struct amd_iommu *iommu;
3967        unsigned long flags;
3968
3969        iommu = amd_iommu_rlookup_table[devid];
3970        if (iommu == NULL)
3971                return -EINVAL;
3972
3973        table = get_irq_table(devid, false);
3974        if (!table)
3975                return -ENOMEM;
3976
3977        spin_lock_irqsave(&table->lock, flags);
3978        table->table[index] = irte.val;
3979        spin_unlock_irqrestore(&table->lock, flags);
3980
3981        iommu_flush_irt(iommu, devid);
3982        iommu_completion_wait(iommu);
3983
3984        return 0;
3985}
3986
3987static void free_irte(u16 devid, int index)
3988{
3989        struct irq_remap_table *table;
3990        struct amd_iommu *iommu;
3991        unsigned long flags;
3992
3993        iommu = amd_iommu_rlookup_table[devid];
3994        if (iommu == NULL)
3995                return;
3996
3997        table = get_irq_table(devid, false);
3998        if (!table)
3999                return;
4000
4001        spin_lock_irqsave(&table->lock, flags);
4002        table->table[index] = 0;
4003        spin_unlock_irqrestore(&table->lock, flags);
4004
4005        iommu_flush_irt(iommu, devid);
4006        iommu_completion_wait(iommu);
4007}
4008
4009static int setup_ioapic_entry(int irq, struct IO_APIC_route_entry *entry,
4010                              unsigned int destination, int vector,
4011                              struct io_apic_irq_attr *attr)
4012{
4013        struct irq_remap_table *table;
4014        struct irq_2_iommu *irte_info;
4015        struct irq_cfg *cfg;
4016        union irte irte;
4017        int ioapic_id;
4018        int index;
4019        int devid;
4020        int ret;
4021
4022        cfg = irq_get_chip_data(irq);
4023        if (!cfg)
4024                return -EINVAL;
4025
4026        irte_info = &cfg->irq_2_iommu;
4027        ioapic_id = mpc_ioapic_id(attr->ioapic);
4028        devid     = get_ioapic_devid(ioapic_id);
4029
4030        if (devid < 0)
4031                return devid;
4032
4033        table = get_irq_table(devid, true);
4034        if (table == NULL)
4035                return -ENOMEM;
4036
4037        index = attr->ioapic_pin;
4038
4039        /* Setup IRQ remapping info */
4040        irte_info->sub_handle = devid;
4041        irte_info->irte_index = index;
4042        irte_info->iommu      = (void *)cfg;
4043
4044        /* Setup IRTE for IOMMU */
4045        irte.val                = 0;
4046        irte.fields.vector      = vector;
4047        irte.fields.int_type    = apic->irq_delivery_mode;
4048        irte.fields.destination = destination;
4049        irte.fields.dm          = apic->irq_dest_mode;
4050        irte.fields.valid       = 1;
4051
4052        ret = modify_irte(devid, index, irte);
4053        if (ret)
4054                return ret;
4055
4056        /* Setup IOAPIC entry */
4057        memset(entry, 0, sizeof(*entry));
4058
4059        entry->vector        = index;
4060        entry->mask          = 0;
4061        entry->trigger       = attr->trigger;
4062        entry->polarity      = attr->polarity;
4063
4064        /*
4065         * Mask level triggered irqs.
4066         */
4067        if (attr->trigger)
4068                entry->mask = 1;
4069
4070        return 0;
4071}
4072
4073static int set_affinity(struct irq_data *data, const struct cpumask *mask,
4074                        bool force)
4075{
4076        struct irq_2_iommu *irte_info;
4077        unsigned int dest, irq;
4078        struct irq_cfg *cfg;
4079        union irte irte;
4080        int err;
4081
4082        if (!config_enabled(CONFIG_SMP))
4083                return -1;
4084
4085        cfg       = data->chip_data;
4086        irq       = data->irq;
4087        irte_info = &cfg->irq_2_iommu;
4088
4089        if (!cpumask_intersects(mask, cpu_online_mask))
4090                return -EINVAL;
4091
4092        if (get_irte(irte_info->sub_handle, irte_info->irte_index, &irte))
4093                return -EBUSY;
4094
4095        if (assign_irq_vector(irq, cfg, mask))
4096                return -EBUSY;
4097
4098        err = apic->cpu_mask_to_apicid_and(cfg->domain, mask, &dest);
4099        if (err) {
4100                if (assign_irq_vector(irq, cfg, data->affinity))
4101                        pr_err("AMD-Vi: Failed to recover vector for irq %d\n", irq);
4102                return err;
4103        }
4104
4105        irte.fields.vector      = cfg->vector;
4106        irte.fields.destination = dest;
4107
4108        modify_irte(irte_info->sub_handle, irte_info->irte_index, irte);
4109
4110        if (cfg->move_in_progress)
4111                send_cleanup_vector(cfg);
4112
4113        cpumask_copy(data->affinity, mask);
4114
4115        return 0;
4116}
4117
4118static int free_irq(int irq)
4119{
4120        struct irq_2_iommu *irte_info;
4121        struct irq_cfg *cfg;
4122
4123        cfg = irq_get_chip_data(irq);
4124        if (!cfg)
4125                return -EINVAL;
4126
4127        irte_info = &cfg->irq_2_iommu;
4128
4129        free_irte(irte_info->sub_handle, irte_info->irte_index);
4130
4131        return 0;
4132}
4133
4134static void compose_msi_msg(struct pci_dev *pdev,
4135                            unsigned int irq, unsigned int dest,
4136                            struct msi_msg *msg, u8 hpet_id)
4137{
4138        struct irq_2_iommu *irte_info;
4139        struct irq_cfg *cfg;
4140        union irte irte;
4141
4142        cfg = irq_get_chip_data(irq);
4143        if (!cfg)
4144                return;
4145
4146        irte_info = &cfg->irq_2_iommu;
4147
4148        irte.val                = 0;
4149        irte.fields.vector      = cfg->vector;
4150        irte.fields.int_type    = apic->irq_delivery_mode;
4151        irte.fields.destination = dest;
4152        irte.fields.dm          = apic->irq_dest_mode;
4153        irte.fields.valid       = 1;
4154
4155        modify_irte(irte_info->sub_handle, irte_info->irte_index, irte);
4156
4157        msg->address_hi = MSI_ADDR_BASE_HI;
4158        msg->address_lo = MSI_ADDR_BASE_LO;
4159        msg->data       = irte_info->irte_index;
4160}
4161
4162static int msi_alloc_irq(struct pci_dev *pdev, int irq, int nvec)
4163{
4164        struct irq_cfg *cfg;
4165        int index;
4166        u16 devid;
4167
4168        if (!pdev)
4169                return -EINVAL;
4170
4171        cfg = irq_get_chip_data(irq);
4172        if (!cfg)
4173                return -EINVAL;
4174
4175        devid = get_device_id(&pdev->dev);
4176        index = alloc_irq_index(cfg, devid, nvec);
4177
4178        return index < 0 ? MAX_IRQS_PER_TABLE : index;
4179}
4180
4181static int msi_setup_irq(struct pci_dev *pdev, unsigned int irq,
4182                         int index, int offset)
4183{
4184        struct irq_2_iommu *irte_info;
4185        struct irq_cfg *cfg;
4186        u16 devid;
4187
4188        if (!pdev)
4189                return -EINVAL;
4190
4191        cfg = irq_get_chip_data(irq);
4192        if (!cfg)
4193                return -EINVAL;
4194
4195        if (index >= MAX_IRQS_PER_TABLE)
4196                return 0;
4197
4198        devid           = get_device_id(&pdev->dev);
4199        irte_info       = &cfg->irq_2_iommu;
4200
4201        irte_info->sub_handle = devid;
4202        irte_info->irte_index = index + offset;
4203        irte_info->iommu      = (void *)cfg;
4204
4205        return 0;
4206}
4207
4208static int setup_hpet_msi(unsigned int irq, unsigned int id)
4209{
4210        struct irq_2_iommu *irte_info;
4211        struct irq_cfg *cfg;
4212        int index, devid;
4213
4214        cfg = irq_get_chip_data(irq);
4215        if (!cfg)
4216                return -EINVAL;
4217
4218        irte_info = &cfg->irq_2_iommu;
4219        devid     = get_hpet_devid(id);
4220        if (devid < 0)
4221                return devid;
4222
4223        index = alloc_irq_index(cfg, devid, 1);
4224        if (index < 0)
4225                return index;
4226
4227        irte_info->sub_handle = devid;
4228        irte_info->irte_index = index;
4229        irte_info->iommu      = (void *)cfg;
4230
4231        return 0;
4232}
4233
4234struct irq_remap_ops amd_iommu_irq_ops = {
4235        .supported              = amd_iommu_supported,
4236        .prepare                = amd_iommu_prepare,
4237        .enable                 = amd_iommu_enable,
4238        .disable                = amd_iommu_disable,
4239        .reenable               = amd_iommu_reenable,
4240        .enable_faulting        = amd_iommu_enable_faulting,
4241        .setup_ioapic_entry     = setup_ioapic_entry,
4242        .set_affinity           = set_affinity,
4243        .free_irq               = free_irq,
4244        .compose_msi_msg        = compose_msi_msg,
4245        .msi_alloc_irq          = msi_alloc_irq,
4246        .msi_setup_irq          = msi_setup_irq,
4247        .setup_hpet_msi         = setup_hpet_msi,
4248};
4249#endif
4250
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.