2 * Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
3 * Author: Joerg Roedel <joerg.roedel@amd.com>
4 * Leo Duran <leo.duran@amd.com>
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.
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.
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
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>
39 #include <asm/hw_irq.h>
40 #include <asm/msidef.h>
41 #include <asm/proto.h>
42 #include <asm/iommu.h>
46 #include "amd_iommu_proto.h"
47 #include "amd_iommu_types.h"
48 #include "irq_remapping.h"
50 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
52 #define LOOP_TIMEOUT 100000
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
60 * 512GB Pages are not supported due to a hardware bug
62 #define AMD_IOMMU_PGSIZES ((~0xFFFUL) & ~(2ULL << 38))
64 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
66 /* A list of preallocated protection domains */
67 static LIST_HEAD(iommu_pd_list);
68 static DEFINE_SPINLOCK(iommu_pd_list_lock);
70 /* List of all available dev_data structures */
71 static LIST_HEAD(dev_data_list);
72 static DEFINE_SPINLOCK(dev_data_list_lock);
74 LIST_HEAD(ioapic_map);
78 * Domain for untranslated devices - only allocated
79 * if iommu=pt passed on kernel cmd line.
81 static struct protection_domain *pt_domain;
83 static struct iommu_ops amd_iommu_ops;
85 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
86 int amd_iommu_max_glx_val = -1;
88 static struct dma_map_ops amd_iommu_dma_ops;
91 * general struct to manage commands send to an IOMMU
97 struct kmem_cache *amd_iommu_irq_cache;
99 static void update_domain(struct protection_domain *domain);
100 static int __init alloc_passthrough_domain(void);
102 /****************************************************************************
106 ****************************************************************************/
108 static struct iommu_dev_data *alloc_dev_data(u16 devid)
110 struct iommu_dev_data *dev_data;
113 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
117 dev_data->devid = devid;
118 atomic_set(&dev_data->bind, 0);
120 spin_lock_irqsave(&dev_data_list_lock, flags);
121 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
122 spin_unlock_irqrestore(&dev_data_list_lock, flags);
127 static void free_dev_data(struct iommu_dev_data *dev_data)
131 spin_lock_irqsave(&dev_data_list_lock, flags);
132 list_del(&dev_data->dev_data_list);
133 spin_unlock_irqrestore(&dev_data_list_lock, flags);
136 iommu_group_put(dev_data->group);
141 static struct iommu_dev_data *search_dev_data(u16 devid)
143 struct iommu_dev_data *dev_data;
146 spin_lock_irqsave(&dev_data_list_lock, flags);
147 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
148 if (dev_data->devid == devid)
155 spin_unlock_irqrestore(&dev_data_list_lock, flags);
160 static struct iommu_dev_data *find_dev_data(u16 devid)
162 struct iommu_dev_data *dev_data;
164 dev_data = search_dev_data(devid);
166 if (dev_data == NULL)
167 dev_data = alloc_dev_data(devid);
172 static inline u16 get_device_id(struct device *dev)
174 struct pci_dev *pdev = to_pci_dev(dev);
176 return calc_devid(pdev->bus->number, pdev->devfn);
179 static struct iommu_dev_data *get_dev_data(struct device *dev)
181 return dev->archdata.iommu;
184 static bool pci_iommuv2_capable(struct pci_dev *pdev)
186 static const int caps[] = {
189 PCI_EXT_CAP_ID_PASID,
193 for (i = 0; i < 3; ++i) {
194 pos = pci_find_ext_capability(pdev, caps[i]);
202 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
204 struct iommu_dev_data *dev_data;
206 dev_data = get_dev_data(&pdev->dev);
208 return dev_data->errata & (1 << erratum) ? true : false;
212 * In this function the list of preallocated protection domains is traversed to
213 * find the domain for a specific device
215 static struct dma_ops_domain *find_protection_domain(u16 devid)
217 struct dma_ops_domain *entry, *ret = NULL;
219 u16 alias = amd_iommu_alias_table[devid];
221 if (list_empty(&iommu_pd_list))
224 spin_lock_irqsave(&iommu_pd_list_lock, flags);
226 list_for_each_entry(entry, &iommu_pd_list, list) {
227 if (entry->target_dev == devid ||
228 entry->target_dev == alias) {
234 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
240 * This function checks if the driver got a valid device from the caller to
241 * avoid dereferencing invalid pointers.
243 static bool check_device(struct device *dev)
247 if (!dev || !dev->dma_mask)
250 /* No device or no PCI device */
251 if (dev->bus != &pci_bus_type)
254 devid = get_device_id(dev);
256 /* Out of our scope? */
257 if (devid > amd_iommu_last_bdf)
260 if (amd_iommu_rlookup_table[devid] == NULL)
266 static void swap_pci_ref(struct pci_dev **from, struct pci_dev *to)
272 static struct pci_bus *find_hosted_bus(struct pci_bus *bus)
275 if (!pci_is_root_bus(bus))
278 return ERR_PTR(-ENODEV);
284 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
286 static struct pci_dev *get_isolation_root(struct pci_dev *pdev)
288 struct pci_dev *dma_pdev = pdev;
290 /* Account for quirked devices */
291 swap_pci_ref(&dma_pdev, pci_get_dma_source(dma_pdev));
294 * If it's a multifunction device that does not support our
295 * required ACS flags, add to the same group as function 0.
297 if (dma_pdev->multifunction &&
298 !pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS))
299 swap_pci_ref(&dma_pdev,
300 pci_get_slot(dma_pdev->bus,
301 PCI_DEVFN(PCI_SLOT(dma_pdev->devfn),
305 * Devices on the root bus go through the iommu. If that's not us,
306 * find the next upstream device and test ACS up to the root bus.
307 * Finding the next device may require skipping virtual buses.
309 while (!pci_is_root_bus(dma_pdev->bus)) {
310 struct pci_bus *bus = find_hosted_bus(dma_pdev->bus);
314 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
317 swap_pci_ref(&dma_pdev, pci_dev_get(bus->self));
323 static int use_pdev_iommu_group(struct pci_dev *pdev, struct device *dev)
325 struct iommu_group *group = iommu_group_get(&pdev->dev);
329 group = iommu_group_alloc();
331 return PTR_ERR(group);
333 WARN_ON(&pdev->dev != dev);
336 ret = iommu_group_add_device(group, dev);
337 iommu_group_put(group);
341 static int use_dev_data_iommu_group(struct iommu_dev_data *dev_data,
344 if (!dev_data->group) {
345 struct iommu_group *group = iommu_group_alloc();
347 return PTR_ERR(group);
349 dev_data->group = group;
352 return iommu_group_add_device(dev_data->group, dev);
355 static int init_iommu_group(struct device *dev)
357 struct iommu_dev_data *dev_data;
358 struct iommu_group *group;
359 struct pci_dev *dma_pdev;
362 group = iommu_group_get(dev);
364 iommu_group_put(group);
368 dev_data = find_dev_data(get_device_id(dev));
372 if (dev_data->alias_data) {
376 if (dev_data->alias_data->group)
380 * If the alias device exists, it's effectively just a first
381 * level quirk for finding the DMA source.
383 alias = amd_iommu_alias_table[dev_data->devid];
384 dma_pdev = pci_get_bus_and_slot(alias >> 8, alias & 0xff);
386 dma_pdev = get_isolation_root(dma_pdev);
391 * If the alias is virtual, try to find a parent device
392 * and test whether the IOMMU group is actualy rooted above
393 * the alias. Be careful to also test the parent device if
394 * we think the alias is the root of the group.
396 bus = pci_find_bus(0, alias >> 8);
400 bus = find_hosted_bus(bus);
401 if (IS_ERR(bus) || !bus->self)
404 dma_pdev = get_isolation_root(pci_dev_get(bus->self));
405 if (dma_pdev != bus->self || (dma_pdev->multifunction &&
406 !pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS)))
409 pci_dev_put(dma_pdev);
413 dma_pdev = get_isolation_root(pci_dev_get(to_pci_dev(dev)));
415 ret = use_pdev_iommu_group(dma_pdev, dev);
416 pci_dev_put(dma_pdev);
419 return use_dev_data_iommu_group(dev_data->alias_data, dev);
422 static int iommu_init_device(struct device *dev)
424 struct pci_dev *pdev = to_pci_dev(dev);
425 struct iommu_dev_data *dev_data;
429 if (dev->archdata.iommu)
432 dev_data = find_dev_data(get_device_id(dev));
436 alias = amd_iommu_alias_table[dev_data->devid];
437 if (alias != dev_data->devid) {
438 struct iommu_dev_data *alias_data;
440 alias_data = find_dev_data(alias);
441 if (alias_data == NULL) {
442 pr_err("AMD-Vi: Warning: Unhandled device %s\n",
444 free_dev_data(dev_data);
447 dev_data->alias_data = alias_data;
450 ret = init_iommu_group(dev);
454 if (pci_iommuv2_capable(pdev)) {
455 struct amd_iommu *iommu;
457 iommu = amd_iommu_rlookup_table[dev_data->devid];
458 dev_data->iommu_v2 = iommu->is_iommu_v2;
461 dev->archdata.iommu = dev_data;
466 static void iommu_ignore_device(struct device *dev)
470 devid = get_device_id(dev);
471 alias = amd_iommu_alias_table[devid];
473 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
474 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
476 amd_iommu_rlookup_table[devid] = NULL;
477 amd_iommu_rlookup_table[alias] = NULL;
480 static void iommu_uninit_device(struct device *dev)
482 iommu_group_remove_device(dev);
485 * Nothing to do here - we keep dev_data around for unplugged devices
486 * and reuse it when the device is re-plugged - not doing so would
487 * introduce a ton of races.
491 void __init amd_iommu_uninit_devices(void)
493 struct iommu_dev_data *dev_data, *n;
494 struct pci_dev *pdev = NULL;
496 for_each_pci_dev(pdev) {
498 if (!check_device(&pdev->dev))
501 iommu_uninit_device(&pdev->dev);
504 /* Free all of our dev_data structures */
505 list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
506 free_dev_data(dev_data);
509 int __init amd_iommu_init_devices(void)
511 struct pci_dev *pdev = NULL;
514 for_each_pci_dev(pdev) {
516 if (!check_device(&pdev->dev))
519 ret = iommu_init_device(&pdev->dev);
520 if (ret == -ENOTSUPP)
521 iommu_ignore_device(&pdev->dev);
530 amd_iommu_uninit_devices();
534 #ifdef CONFIG_AMD_IOMMU_STATS
537 * Initialization code for statistics collection
540 DECLARE_STATS_COUNTER(compl_wait);
541 DECLARE_STATS_COUNTER(cnt_map_single);
542 DECLARE_STATS_COUNTER(cnt_unmap_single);
543 DECLARE_STATS_COUNTER(cnt_map_sg);
544 DECLARE_STATS_COUNTER(cnt_unmap_sg);
545 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
546 DECLARE_STATS_COUNTER(cnt_free_coherent);
547 DECLARE_STATS_COUNTER(cross_page);
548 DECLARE_STATS_COUNTER(domain_flush_single);
549 DECLARE_STATS_COUNTER(domain_flush_all);
550 DECLARE_STATS_COUNTER(alloced_io_mem);
551 DECLARE_STATS_COUNTER(total_map_requests);
552 DECLARE_STATS_COUNTER(complete_ppr);
553 DECLARE_STATS_COUNTER(invalidate_iotlb);
554 DECLARE_STATS_COUNTER(invalidate_iotlb_all);
555 DECLARE_STATS_COUNTER(pri_requests);
557 static struct dentry *stats_dir;
558 static struct dentry *de_fflush;
560 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
562 if (stats_dir == NULL)
565 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
569 static void amd_iommu_stats_init(void)
571 stats_dir = debugfs_create_dir("amd-iommu", NULL);
572 if (stats_dir == NULL)
575 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
576 &amd_iommu_unmap_flush);
578 amd_iommu_stats_add(&compl_wait);
579 amd_iommu_stats_add(&cnt_map_single);
580 amd_iommu_stats_add(&cnt_unmap_single);
581 amd_iommu_stats_add(&cnt_map_sg);
582 amd_iommu_stats_add(&cnt_unmap_sg);
583 amd_iommu_stats_add(&cnt_alloc_coherent);
584 amd_iommu_stats_add(&cnt_free_coherent);
585 amd_iommu_stats_add(&cross_page);
586 amd_iommu_stats_add(&domain_flush_single);
587 amd_iommu_stats_add(&domain_flush_all);
588 amd_iommu_stats_add(&alloced_io_mem);
589 amd_iommu_stats_add(&total_map_requests);
590 amd_iommu_stats_add(&complete_ppr);
591 amd_iommu_stats_add(&invalidate_iotlb);
592 amd_iommu_stats_add(&invalidate_iotlb_all);
593 amd_iommu_stats_add(&pri_requests);
598 /****************************************************************************
600 * Interrupt handling functions
602 ****************************************************************************/
604 static void dump_dte_entry(u16 devid)
608 for (i = 0; i < 4; ++i)
609 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
610 amd_iommu_dev_table[devid].data[i]);
613 static void dump_command(unsigned long phys_addr)
615 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
618 for (i = 0; i < 4; ++i)
619 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
622 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
624 int type, devid, domid, flags;
625 volatile u32 *event = __evt;
630 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
631 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
632 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
633 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
634 address = (u64)(((u64)event[3]) << 32) | event[2];
637 /* Did we hit the erratum? */
638 if (++count == LOOP_TIMEOUT) {
639 pr_err("AMD-Vi: No event written to event log\n");
646 printk(KERN_ERR "AMD-Vi: Event logged [");
649 case EVENT_TYPE_ILL_DEV:
650 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
651 "address=0x%016llx flags=0x%04x]\n",
652 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
654 dump_dte_entry(devid);
656 case EVENT_TYPE_IO_FAULT:
657 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
658 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
659 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
660 domid, address, flags);
662 case EVENT_TYPE_DEV_TAB_ERR:
663 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
664 "address=0x%016llx flags=0x%04x]\n",
665 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
668 case EVENT_TYPE_PAGE_TAB_ERR:
669 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
670 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
671 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
672 domid, address, flags);
674 case EVENT_TYPE_ILL_CMD:
675 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
676 dump_command(address);
678 case EVENT_TYPE_CMD_HARD_ERR:
679 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
680 "flags=0x%04x]\n", address, flags);
682 case EVENT_TYPE_IOTLB_INV_TO:
683 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
684 "address=0x%016llx]\n",
685 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
688 case EVENT_TYPE_INV_DEV_REQ:
689 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
690 "address=0x%016llx flags=0x%04x]\n",
691 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
695 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
698 memset(__evt, 0, 4 * sizeof(u32));
701 static void iommu_poll_events(struct amd_iommu *iommu)
706 /* enable event interrupts again */
707 writel(MMIO_STATUS_EVT_INT_MASK, iommu->mmio_base + MMIO_STATUS_OFFSET);
709 spin_lock_irqsave(&iommu->lock, flags);
711 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
712 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
714 while (head != tail) {
715 iommu_print_event(iommu, iommu->evt_buf + head);
716 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
719 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
721 spin_unlock_irqrestore(&iommu->lock, flags);
724 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
726 struct amd_iommu_fault fault;
728 INC_STATS_COUNTER(pri_requests);
730 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
731 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
735 fault.address = raw[1];
736 fault.pasid = PPR_PASID(raw[0]);
737 fault.device_id = PPR_DEVID(raw[0]);
738 fault.tag = PPR_TAG(raw[0]);
739 fault.flags = PPR_FLAGS(raw[0]);
741 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
744 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
749 if (iommu->ppr_log == NULL)
752 /* enable ppr interrupts again */
753 writel(MMIO_STATUS_PPR_INT_MASK, iommu->mmio_base + MMIO_STATUS_OFFSET);
755 spin_lock_irqsave(&iommu->lock, flags);
757 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
758 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
760 while (head != tail) {
765 raw = (u64 *)(iommu->ppr_log + head);
768 * Hardware bug: Interrupt may arrive before the entry is
769 * written to memory. If this happens we need to wait for the
772 for (i = 0; i < LOOP_TIMEOUT; ++i) {
773 if (PPR_REQ_TYPE(raw[0]) != 0)
778 /* Avoid memcpy function-call overhead */
783 * To detect the hardware bug we need to clear the entry
786 raw[0] = raw[1] = 0UL;
788 /* Update head pointer of hardware ring-buffer */
789 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
790 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
793 * Release iommu->lock because ppr-handling might need to
796 spin_unlock_irqrestore(&iommu->lock, flags);
798 /* Handle PPR entry */
799 iommu_handle_ppr_entry(iommu, entry);
801 spin_lock_irqsave(&iommu->lock, flags);
803 /* Refresh ring-buffer information */
804 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
805 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
808 spin_unlock_irqrestore(&iommu->lock, flags);
811 irqreturn_t amd_iommu_int_thread(int irq, void *data)
813 struct amd_iommu *iommu;
815 for_each_iommu(iommu) {
816 iommu_poll_events(iommu);
817 iommu_poll_ppr_log(iommu);
823 irqreturn_t amd_iommu_int_handler(int irq, void *data)
825 return IRQ_WAKE_THREAD;
828 /****************************************************************************
830 * IOMMU command queuing functions
832 ****************************************************************************/
834 static int wait_on_sem(volatile u64 *sem)
838 while (*sem == 0 && i < LOOP_TIMEOUT) {
843 if (i == LOOP_TIMEOUT) {
844 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
851 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
852 struct iommu_cmd *cmd,
857 target = iommu->cmd_buf + tail;
858 tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
860 /* Copy command to buffer */
861 memcpy(target, cmd, sizeof(*cmd));
863 /* Tell the IOMMU about it */
864 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
867 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
869 WARN_ON(address & 0x7ULL);
871 memset(cmd, 0, sizeof(*cmd));
872 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
873 cmd->data[1] = upper_32_bits(__pa(address));
875 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
878 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
880 memset(cmd, 0, sizeof(*cmd));
881 cmd->data[0] = devid;
882 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
885 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
886 size_t size, u16 domid, int pde)
891 pages = iommu_num_pages(address, size, PAGE_SIZE);
896 * If we have to flush more than one page, flush all
897 * TLB entries for this domain
899 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
903 address &= PAGE_MASK;
905 memset(cmd, 0, sizeof(*cmd));
906 cmd->data[1] |= domid;
907 cmd->data[2] = lower_32_bits(address);
908 cmd->data[3] = upper_32_bits(address);
909 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
910 if (s) /* size bit - we flush more than one 4kb page */
911 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
912 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
913 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
916 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
917 u64 address, size_t size)
922 pages = iommu_num_pages(address, size, PAGE_SIZE);
927 * If we have to flush more than one page, flush all
928 * TLB entries for this domain
930 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
934 address &= PAGE_MASK;
936 memset(cmd, 0, sizeof(*cmd));
937 cmd->data[0] = devid;
938 cmd->data[0] |= (qdep & 0xff) << 24;
939 cmd->data[1] = devid;
940 cmd->data[2] = lower_32_bits(address);
941 cmd->data[3] = upper_32_bits(address);
942 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
944 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
947 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
948 u64 address, bool size)
950 memset(cmd, 0, sizeof(*cmd));
952 address &= ~(0xfffULL);
954 cmd->data[0] = pasid & PASID_MASK;
955 cmd->data[1] = domid;
956 cmd->data[2] = lower_32_bits(address);
957 cmd->data[3] = upper_32_bits(address);
958 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
959 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
961 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
962 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
965 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
966 int qdep, u64 address, bool size)
968 memset(cmd, 0, sizeof(*cmd));
970 address &= ~(0xfffULL);
972 cmd->data[0] = devid;
973 cmd->data[0] |= (pasid & 0xff) << 16;
974 cmd->data[0] |= (qdep & 0xff) << 24;
975 cmd->data[1] = devid;
976 cmd->data[1] |= ((pasid >> 8) & 0xfff) << 16;
977 cmd->data[2] = lower_32_bits(address);
978 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
979 cmd->data[3] = upper_32_bits(address);
981 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
982 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
985 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
986 int status, int tag, bool gn)
988 memset(cmd, 0, sizeof(*cmd));
990 cmd->data[0] = devid;
992 cmd->data[1] = pasid & PASID_MASK;
993 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
995 cmd->data[3] = tag & 0x1ff;
996 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
998 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
1001 static void build_inv_all(struct iommu_cmd *cmd)
1003 memset(cmd, 0, sizeof(*cmd));
1004 CMD_SET_TYPE(cmd, CMD_INV_ALL);
1007 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
1009 memset(cmd, 0, sizeof(*cmd));
1010 cmd->data[0] = devid;
1011 CMD_SET_TYPE(cmd, CMD_INV_IRT);
1015 * Writes the command to the IOMMUs command buffer and informs the
1016 * hardware about the new command.
1018 static int iommu_queue_command_sync(struct amd_iommu *iommu,
1019 struct iommu_cmd *cmd,
1022 u32 left, tail, head, next_tail;
1023 unsigned long flags;
1025 WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
1028 spin_lock_irqsave(&iommu->lock, flags);
1030 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
1031 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
1032 next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
1033 left = (head - next_tail) % iommu->cmd_buf_size;
1036 struct iommu_cmd sync_cmd;
1037 volatile u64 sem = 0;
1040 build_completion_wait(&sync_cmd, (u64)&sem);
1041 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
1043 spin_unlock_irqrestore(&iommu->lock, flags);
1045 if ((ret = wait_on_sem(&sem)) != 0)
1051 copy_cmd_to_buffer(iommu, cmd, tail);
1053 /* We need to sync now to make sure all commands are processed */
1054 iommu->need_sync = sync;
1056 spin_unlock_irqrestore(&iommu->lock, flags);
1061 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
1063 return iommu_queue_command_sync(iommu, cmd, true);
1067 * This function queues a completion wait command into the command
1068 * buffer of an IOMMU
1070 static int iommu_completion_wait(struct amd_iommu *iommu)
1072 struct iommu_cmd cmd;
1073 volatile u64 sem = 0;
1076 if (!iommu->need_sync)
1079 build_completion_wait(&cmd, (u64)&sem);
1081 ret = iommu_queue_command_sync(iommu, &cmd, false);
1085 return wait_on_sem(&sem);
1088 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1090 struct iommu_cmd cmd;
1092 build_inv_dte(&cmd, devid);
1094 return iommu_queue_command(iommu, &cmd);
1097 static void iommu_flush_dte_all(struct amd_iommu *iommu)
1101 for (devid = 0; devid <= 0xffff; ++devid)
1102 iommu_flush_dte(iommu, devid);
1104 iommu_completion_wait(iommu);
1108 * This function uses heavy locking and may disable irqs for some time. But
1109 * this is no issue because it is only called during resume.
1111 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1115 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1116 struct iommu_cmd cmd;
1117 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1119 iommu_queue_command(iommu, &cmd);
1122 iommu_completion_wait(iommu);
1125 static void iommu_flush_all(struct amd_iommu *iommu)
1127 struct iommu_cmd cmd;
1129 build_inv_all(&cmd);
1131 iommu_queue_command(iommu, &cmd);
1132 iommu_completion_wait(iommu);
1135 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1137 struct iommu_cmd cmd;
1139 build_inv_irt(&cmd, devid);
1141 iommu_queue_command(iommu, &cmd);
1144 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1148 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1149 iommu_flush_irt(iommu, devid);
1151 iommu_completion_wait(iommu);
1154 void iommu_flush_all_caches(struct amd_iommu *iommu)
1156 if (iommu_feature(iommu, FEATURE_IA)) {
1157 iommu_flush_all(iommu);
1159 iommu_flush_dte_all(iommu);
1160 iommu_flush_irt_all(iommu);
1161 iommu_flush_tlb_all(iommu);
1166 * Command send function for flushing on-device TLB
1168 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1169 u64 address, size_t size)
1171 struct amd_iommu *iommu;
1172 struct iommu_cmd cmd;
1175 qdep = dev_data->ats.qdep;
1176 iommu = amd_iommu_rlookup_table[dev_data->devid];
1178 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1180 return iommu_queue_command(iommu, &cmd);
1184 * Command send function for invalidating a device table entry
1186 static int device_flush_dte(struct iommu_dev_data *dev_data)
1188 struct amd_iommu *iommu;
1191 iommu = amd_iommu_rlookup_table[dev_data->devid];
1193 ret = iommu_flush_dte(iommu, dev_data->devid);
1197 if (dev_data->ats.enabled)
1198 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1204 * TLB invalidation function which is called from the mapping functions.
1205 * It invalidates a single PTE if the range to flush is within a single
1206 * page. Otherwise it flushes the whole TLB of the IOMMU.
1208 static void __domain_flush_pages(struct protection_domain *domain,
1209 u64 address, size_t size, int pde)
1211 struct iommu_dev_data *dev_data;
1212 struct iommu_cmd cmd;
1215 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1217 for (i = 0; i < amd_iommus_present; ++i) {
1218 if (!domain->dev_iommu[i])
1222 * Devices of this domain are behind this IOMMU
1223 * We need a TLB flush
1225 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1228 list_for_each_entry(dev_data, &domain->dev_list, list) {
1230 if (!dev_data->ats.enabled)
1233 ret |= device_flush_iotlb(dev_data, address, size);
1239 static void domain_flush_pages(struct protection_domain *domain,
1240 u64 address, size_t size)
1242 __domain_flush_pages(domain, address, size, 0);
1245 /* Flush the whole IO/TLB for a given protection domain */
1246 static void domain_flush_tlb(struct protection_domain *domain)
1248 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1251 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1252 static void domain_flush_tlb_pde(struct protection_domain *domain)
1254 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1257 static void domain_flush_complete(struct protection_domain *domain)
1261 for (i = 0; i < amd_iommus_present; ++i) {
1262 if (!domain->dev_iommu[i])
1266 * Devices of this domain are behind this IOMMU
1267 * We need to wait for completion of all commands.
1269 iommu_completion_wait(amd_iommus[i]);
1275 * This function flushes the DTEs for all devices in domain
1277 static void domain_flush_devices(struct protection_domain *domain)
1279 struct iommu_dev_data *dev_data;
1281 list_for_each_entry(dev_data, &domain->dev_list, list)
1282 device_flush_dte(dev_data);
1285 /****************************************************************************
1287 * The functions below are used the create the page table mappings for
1288 * unity mapped regions.
1290 ****************************************************************************/
1293 * This function is used to add another level to an IO page table. Adding
1294 * another level increases the size of the address space by 9 bits to a size up
1297 static bool increase_address_space(struct protection_domain *domain,
1302 if (domain->mode == PAGE_MODE_6_LEVEL)
1303 /* address space already 64 bit large */
1306 pte = (void *)get_zeroed_page(gfp);
1310 *pte = PM_LEVEL_PDE(domain->mode,
1311 virt_to_phys(domain->pt_root));
1312 domain->pt_root = pte;
1314 domain->updated = true;
1319 static u64 *alloc_pte(struct protection_domain *domain,
1320 unsigned long address,
1321 unsigned long page_size,
1328 BUG_ON(!is_power_of_2(page_size));
1330 while (address > PM_LEVEL_SIZE(domain->mode))
1331 increase_address_space(domain, gfp);
1333 level = domain->mode - 1;
1334 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1335 address = PAGE_SIZE_ALIGN(address, page_size);
1336 end_lvl = PAGE_SIZE_LEVEL(page_size);
1338 while (level > end_lvl) {
1339 if (!IOMMU_PTE_PRESENT(*pte)) {
1340 page = (u64 *)get_zeroed_page(gfp);
1343 *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1346 /* No level skipping support yet */
1347 if (PM_PTE_LEVEL(*pte) != level)
1352 pte = IOMMU_PTE_PAGE(*pte);
1354 if (pte_page && level == end_lvl)
1357 pte = &pte[PM_LEVEL_INDEX(level, address)];
1364 * This function checks if there is a PTE for a given dma address. If
1365 * there is one, it returns the pointer to it.
1367 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
1372 if (address > PM_LEVEL_SIZE(domain->mode))
1375 level = domain->mode - 1;
1376 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1381 if (!IOMMU_PTE_PRESENT(*pte))
1385 if (PM_PTE_LEVEL(*pte) == 0x07) {
1386 unsigned long pte_mask, __pte;
1389 * If we have a series of large PTEs, make
1390 * sure to return a pointer to the first one.
1392 pte_mask = PTE_PAGE_SIZE(*pte);
1393 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1394 __pte = ((unsigned long)pte) & pte_mask;
1396 return (u64 *)__pte;
1399 /* No level skipping support yet */
1400 if (PM_PTE_LEVEL(*pte) != level)
1405 /* Walk to the next level */
1406 pte = IOMMU_PTE_PAGE(*pte);
1407 pte = &pte[PM_LEVEL_INDEX(level, address)];
1414 * Generic mapping functions. It maps a physical address into a DMA
1415 * address space. It allocates the page table pages if necessary.
1416 * In the future it can be extended to a generic mapping function
1417 * supporting all features of AMD IOMMU page tables like level skipping
1418 * and full 64 bit address spaces.
1420 static int iommu_map_page(struct protection_domain *dom,
1421 unsigned long bus_addr,
1422 unsigned long phys_addr,
1424 unsigned long page_size)
1429 if (!(prot & IOMMU_PROT_MASK))
1432 bus_addr = PAGE_ALIGN(bus_addr);
1433 phys_addr = PAGE_ALIGN(phys_addr);
1434 count = PAGE_SIZE_PTE_COUNT(page_size);
1435 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1437 for (i = 0; i < count; ++i)
1438 if (IOMMU_PTE_PRESENT(pte[i]))
1441 if (page_size > PAGE_SIZE) {
1442 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1443 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1445 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1447 if (prot & IOMMU_PROT_IR)
1448 __pte |= IOMMU_PTE_IR;
1449 if (prot & IOMMU_PROT_IW)
1450 __pte |= IOMMU_PTE_IW;
1452 for (i = 0; i < count; ++i)
1460 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1461 unsigned long bus_addr,
1462 unsigned long page_size)
1464 unsigned long long unmap_size, unmapped;
1467 BUG_ON(!is_power_of_2(page_size));
1471 while (unmapped < page_size) {
1473 pte = fetch_pte(dom, bus_addr);
1477 * No PTE for this address
1478 * move forward in 4kb steps
1480 unmap_size = PAGE_SIZE;
1481 } else if (PM_PTE_LEVEL(*pte) == 0) {
1482 /* 4kb PTE found for this address */
1483 unmap_size = PAGE_SIZE;
1488 /* Large PTE found which maps this address */
1489 unmap_size = PTE_PAGE_SIZE(*pte);
1490 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1491 for (i = 0; i < count; i++)
1495 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1496 unmapped += unmap_size;
1499 BUG_ON(!is_power_of_2(unmapped));
1505 * This function checks if a specific unity mapping entry is needed for
1506 * this specific IOMMU.
1508 static int iommu_for_unity_map(struct amd_iommu *iommu,
1509 struct unity_map_entry *entry)
1513 for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1514 bdf = amd_iommu_alias_table[i];
1515 if (amd_iommu_rlookup_table[bdf] == iommu)
1523 * This function actually applies the mapping to the page table of the
1526 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1527 struct unity_map_entry *e)
1532 for (addr = e->address_start; addr < e->address_end;
1533 addr += PAGE_SIZE) {
1534 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1539 * if unity mapping is in aperture range mark the page
1540 * as allocated in the aperture
1542 if (addr < dma_dom->aperture_size)
1543 __set_bit(addr >> PAGE_SHIFT,
1544 dma_dom->aperture[0]->bitmap);
1551 * Init the unity mappings for a specific IOMMU in the system
1553 * Basically iterates over all unity mapping entries and applies them to
1554 * the default domain DMA of that IOMMU if necessary.
1556 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1558 struct unity_map_entry *entry;
1561 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1562 if (!iommu_for_unity_map(iommu, entry))
1564 ret = dma_ops_unity_map(iommu->default_dom, entry);
1573 * Inits the unity mappings required for a specific device
1575 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1578 struct unity_map_entry *e;
1581 list_for_each_entry(e, &amd_iommu_unity_map, list) {
1582 if (!(devid >= e->devid_start && devid <= e->devid_end))
1584 ret = dma_ops_unity_map(dma_dom, e);
1592 /****************************************************************************
1594 * The next functions belong to the address allocator for the dma_ops
1595 * interface functions. They work like the allocators in the other IOMMU
1596 * drivers. Its basically a bitmap which marks the allocated pages in
1597 * the aperture. Maybe it could be enhanced in the future to a more
1598 * efficient allocator.
1600 ****************************************************************************/
1603 * The address allocator core functions.
1605 * called with domain->lock held
1609 * Used to reserve address ranges in the aperture (e.g. for exclusion
1612 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1613 unsigned long start_page,
1616 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1618 if (start_page + pages > last_page)
1619 pages = last_page - start_page;
1621 for (i = start_page; i < start_page + pages; ++i) {
1622 int index = i / APERTURE_RANGE_PAGES;
1623 int page = i % APERTURE_RANGE_PAGES;
1624 __set_bit(page, dom->aperture[index]->bitmap);
1629 * This function is used to add a new aperture range to an existing
1630 * aperture in case of dma_ops domain allocation or address allocation
1633 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1634 bool populate, gfp_t gfp)
1636 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1637 struct amd_iommu *iommu;
1638 unsigned long i, old_size;
1640 #ifdef CONFIG_IOMMU_STRESS
1644 if (index >= APERTURE_MAX_RANGES)
1647 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1648 if (!dma_dom->aperture[index])
1651 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1652 if (!dma_dom->aperture[index]->bitmap)
1655 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1658 unsigned long address = dma_dom->aperture_size;
1659 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1660 u64 *pte, *pte_page;
1662 for (i = 0; i < num_ptes; ++i) {
1663 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1668 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1670 address += APERTURE_RANGE_SIZE / 64;
1674 old_size = dma_dom->aperture_size;
1675 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1677 /* Reserve address range used for MSI messages */
1678 if (old_size < MSI_ADDR_BASE_LO &&
1679 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1680 unsigned long spage;
1683 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1684 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1686 dma_ops_reserve_addresses(dma_dom, spage, pages);
1689 /* Initialize the exclusion range if necessary */
1690 for_each_iommu(iommu) {
1691 if (iommu->exclusion_start &&
1692 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1693 && iommu->exclusion_start < dma_dom->aperture_size) {
1694 unsigned long startpage;
1695 int pages = iommu_num_pages(iommu->exclusion_start,
1696 iommu->exclusion_length,
1698 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1699 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1704 * Check for areas already mapped as present in the new aperture
1705 * range and mark those pages as reserved in the allocator. Such
1706 * mappings may already exist as a result of requested unity
1707 * mappings for devices.
1709 for (i = dma_dom->aperture[index]->offset;
1710 i < dma_dom->aperture_size;
1712 u64 *pte = fetch_pte(&dma_dom->domain, i);
1713 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1716 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1719 update_domain(&dma_dom->domain);
1724 update_domain(&dma_dom->domain);
1726 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1728 kfree(dma_dom->aperture[index]);
1729 dma_dom->aperture[index] = NULL;
1734 static unsigned long dma_ops_area_alloc(struct device *dev,
1735 struct dma_ops_domain *dom,
1737 unsigned long align_mask,
1739 unsigned long start)
1741 unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1742 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1743 int i = start >> APERTURE_RANGE_SHIFT;
1744 unsigned long boundary_size;
1745 unsigned long address = -1;
1746 unsigned long limit;
1748 next_bit >>= PAGE_SHIFT;
1750 boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1751 PAGE_SIZE) >> PAGE_SHIFT;
1753 for (;i < max_index; ++i) {
1754 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1756 if (dom->aperture[i]->offset >= dma_mask)
1759 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1760 dma_mask >> PAGE_SHIFT);
1762 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1763 limit, next_bit, pages, 0,
1764 boundary_size, align_mask);
1765 if (address != -1) {
1766 address = dom->aperture[i]->offset +
1767 (address << PAGE_SHIFT);
1768 dom->next_address = address + (pages << PAGE_SHIFT);
1778 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1779 struct dma_ops_domain *dom,
1781 unsigned long align_mask,
1784 unsigned long address;
1786 #ifdef CONFIG_IOMMU_STRESS
1787 dom->next_address = 0;
1788 dom->need_flush = true;
1791 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1792 dma_mask, dom->next_address);
1794 if (address == -1) {
1795 dom->next_address = 0;
1796 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1798 dom->need_flush = true;
1801 if (unlikely(address == -1))
1802 address = DMA_ERROR_CODE;
1804 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1810 * The address free function.
1812 * called with domain->lock held
1814 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1815 unsigned long address,
1818 unsigned i = address >> APERTURE_RANGE_SHIFT;
1819 struct aperture_range *range = dom->aperture[i];
1821 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1823 #ifdef CONFIG_IOMMU_STRESS
1828 if (address >= dom->next_address)
1829 dom->need_flush = true;
1831 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1833 bitmap_clear(range->bitmap, address, pages);
1837 /****************************************************************************
1839 * The next functions belong to the domain allocation. A domain is
1840 * allocated for every IOMMU as the default domain. If device isolation
1841 * is enabled, every device get its own domain. The most important thing
1842 * about domains is the page table mapping the DMA address space they
1845 ****************************************************************************/
1848 * This function adds a protection domain to the global protection domain list
1850 static void add_domain_to_list(struct protection_domain *domain)
1852 unsigned long flags;
1854 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1855 list_add(&domain->list, &amd_iommu_pd_list);
1856 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1860 * This function removes a protection domain to the global
1861 * protection domain list
1863 static void del_domain_from_list(struct protection_domain *domain)
1865 unsigned long flags;
1867 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1868 list_del(&domain->list);
1869 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1872 static u16 domain_id_alloc(void)
1874 unsigned long flags;
1877 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1878 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1880 if (id > 0 && id < MAX_DOMAIN_ID)
1881 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1884 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1889 static void domain_id_free(int id)
1891 unsigned long flags;
1893 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1894 if (id > 0 && id < MAX_DOMAIN_ID)
1895 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1896 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1899 static void free_pagetable(struct protection_domain *domain)
1904 p1 = domain->pt_root;
1909 for (i = 0; i < 512; ++i) {
1910 if (!IOMMU_PTE_PRESENT(p1[i]))
1913 p2 = IOMMU_PTE_PAGE(p1[i]);
1914 for (j = 0; j < 512; ++j) {
1915 if (!IOMMU_PTE_PRESENT(p2[j]))
1917 p3 = IOMMU_PTE_PAGE(p2[j]);
1918 free_page((unsigned long)p3);
1921 free_page((unsigned long)p2);
1924 free_page((unsigned long)p1);
1926 domain->pt_root = NULL;
1929 static void free_gcr3_tbl_level1(u64 *tbl)
1934 for (i = 0; i < 512; ++i) {
1935 if (!(tbl[i] & GCR3_VALID))
1938 ptr = __va(tbl[i] & PAGE_MASK);
1940 free_page((unsigned long)ptr);
1944 static void free_gcr3_tbl_level2(u64 *tbl)
1949 for (i = 0; i < 512; ++i) {
1950 if (!(tbl[i] & GCR3_VALID))
1953 ptr = __va(tbl[i] & PAGE_MASK);
1955 free_gcr3_tbl_level1(ptr);
1959 static void free_gcr3_table(struct protection_domain *domain)
1961 if (domain->glx == 2)
1962 free_gcr3_tbl_level2(domain->gcr3_tbl);
1963 else if (domain->glx == 1)
1964 free_gcr3_tbl_level1(domain->gcr3_tbl);
1965 else if (domain->glx != 0)
1968 free_page((unsigned long)domain->gcr3_tbl);
1972 * Free a domain, only used if something went wrong in the
1973 * allocation path and we need to free an already allocated page table
1975 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1982 del_domain_from_list(&dom->domain);
1984 free_pagetable(&dom->domain);
1986 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1987 if (!dom->aperture[i])
1989 free_page((unsigned long)dom->aperture[i]->bitmap);
1990 kfree(dom->aperture[i]);
1997 * Allocates a new protection domain usable for the dma_ops functions.
1998 * It also initializes the page table and the address allocator data
1999 * structures required for the dma_ops interface
2001 static struct dma_ops_domain *dma_ops_domain_alloc(void)
2003 struct dma_ops_domain *dma_dom;
2005 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
2009 spin_lock_init(&dma_dom->domain.lock);
2011 dma_dom->domain.id = domain_id_alloc();
2012 if (dma_dom->domain.id == 0)
2014 INIT_LIST_HEAD(&dma_dom->domain.dev_list);
2015 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
2016 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2017 dma_dom->domain.flags = PD_DMA_OPS_MASK;
2018 dma_dom->domain.priv = dma_dom;
2019 if (!dma_dom->domain.pt_root)
2022 dma_dom->need_flush = false;
2023 dma_dom->target_dev = 0xffff;
2025 add_domain_to_list(&dma_dom->domain);
2027 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
2031 * mark the first page as allocated so we never return 0 as
2032 * a valid dma-address. So we can use 0 as error value
2034 dma_dom->aperture[0]->bitmap[0] = 1;
2035 dma_dom->next_address = 0;
2041 dma_ops_domain_free(dma_dom);
2047 * little helper function to check whether a given protection domain is a
2050 static bool dma_ops_domain(struct protection_domain *domain)
2052 return domain->flags & PD_DMA_OPS_MASK;
2055 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
2060 if (domain->mode != PAGE_MODE_NONE)
2061 pte_root = virt_to_phys(domain->pt_root);
2063 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
2064 << DEV_ENTRY_MODE_SHIFT;
2065 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
2067 flags = amd_iommu_dev_table[devid].data[1];
2070 flags |= DTE_FLAG_IOTLB;
2072 if (domain->flags & PD_IOMMUV2_MASK) {
2073 u64 gcr3 = __pa(domain->gcr3_tbl);
2074 u64 glx = domain->glx;
2077 pte_root |= DTE_FLAG_GV;
2078 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
2080 /* First mask out possible old values for GCR3 table */
2081 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
2084 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
2087 /* Encode GCR3 table into DTE */
2088 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
2091 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
2094 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
2098 flags &= ~(0xffffUL);
2099 flags |= domain->id;
2101 amd_iommu_dev_table[devid].data[1] = flags;
2102 amd_iommu_dev_table[devid].data[0] = pte_root;
2105 static void clear_dte_entry(u16 devid)
2107 /* remove entry from the device table seen by the hardware */
2108 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
2109 amd_iommu_dev_table[devid].data[1] = 0;
2111 amd_iommu_apply_erratum_63(devid);
2114 static void do_attach(struct iommu_dev_data *dev_data,
2115 struct protection_domain *domain)
2117 struct amd_iommu *iommu;
2120 iommu = amd_iommu_rlookup_table[dev_data->devid];
2121 ats = dev_data->ats.enabled;
2123 /* Update data structures */
2124 dev_data->domain = domain;
2125 list_add(&dev_data->list, &domain->dev_list);
2126 set_dte_entry(dev_data->devid, domain, ats);
2128 /* Do reference counting */
2129 domain->dev_iommu[iommu->index] += 1;
2130 domain->dev_cnt += 1;
2132 /* Flush the DTE entry */
2133 device_flush_dte(dev_data);
2136 static void do_detach(struct iommu_dev_data *dev_data)
2138 struct amd_iommu *iommu;
2140 iommu = amd_iommu_rlookup_table[dev_data->devid];
2142 /* decrease reference counters */
2143 dev_data->domain->dev_iommu[iommu->index] -= 1;
2144 dev_data->domain->dev_cnt -= 1;
2146 /* Update data structures */
2147 dev_data->domain = NULL;
2148 list_del(&dev_data->list);
2149 clear_dte_entry(dev_data->devid);
2151 /* Flush the DTE entry */
2152 device_flush_dte(dev_data);
2156 * If a device is not yet associated with a domain, this function does
2157 * assigns it visible for the hardware
2159 static int __attach_device(struct iommu_dev_data *dev_data,
2160 struct protection_domain *domain)
2165 spin_lock(&domain->lock);
2167 if (dev_data->alias_data != NULL) {
2168 struct iommu_dev_data *alias_data = dev_data->alias_data;
2170 /* Some sanity checks */
2172 if (alias_data->domain != NULL &&
2173 alias_data->domain != domain)
2176 if (dev_data->domain != NULL &&
2177 dev_data->domain != domain)
2180 /* Do real assignment */
2181 if (alias_data->domain == NULL)
2182 do_attach(alias_data, domain);
2184 atomic_inc(&alias_data->bind);
2187 if (dev_data->domain == NULL)
2188 do_attach(dev_data, domain);
2190 atomic_inc(&dev_data->bind);
2197 spin_unlock(&domain->lock);
2203 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2205 pci_disable_ats(pdev);
2206 pci_disable_pri(pdev);
2207 pci_disable_pasid(pdev);
2210 /* FIXME: Change generic reset-function to do the same */
2211 static int pri_reset_while_enabled(struct pci_dev *pdev)
2216 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2220 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2221 control |= PCI_PRI_CTRL_RESET;
2222 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2227 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2232 /* FIXME: Hardcode number of outstanding requests for now */
2234 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2236 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2238 /* Only allow access to user-accessible pages */
2239 ret = pci_enable_pasid(pdev, 0);
2243 /* First reset the PRI state of the device */
2244 ret = pci_reset_pri(pdev);
2249 ret = pci_enable_pri(pdev, reqs);
2254 ret = pri_reset_while_enabled(pdev);
2259 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2266 pci_disable_pri(pdev);
2267 pci_disable_pasid(pdev);
2272 /* FIXME: Move this to PCI code */
2273 #define PCI_PRI_TLP_OFF (1 << 15)
2275 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2280 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2284 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2286 return (status & PCI_PRI_TLP_OFF) ? true : false;
2290 * If a device is not yet associated with a domain, this function
2291 * assigns it visible for the hardware
2293 static int attach_device(struct device *dev,
2294 struct protection_domain *domain)
2296 struct pci_dev *pdev = to_pci_dev(dev);
2297 struct iommu_dev_data *dev_data;
2298 unsigned long flags;
2301 dev_data = get_dev_data(dev);
2303 if (domain->flags & PD_IOMMUV2_MASK) {
2304 if (!dev_data->iommu_v2 || !dev_data->passthrough)
2307 if (pdev_iommuv2_enable(pdev) != 0)
2310 dev_data->ats.enabled = true;
2311 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2312 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2313 } else if (amd_iommu_iotlb_sup &&
2314 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2315 dev_data->ats.enabled = true;
2316 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2319 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2320 ret = __attach_device(dev_data, domain);
2321 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2324 * We might boot into a crash-kernel here. The crashed kernel
2325 * left the caches in the IOMMU dirty. So we have to flush
2326 * here to evict all dirty stuff.
2328 domain_flush_tlb_pde(domain);
2334 * Removes a device from a protection domain (unlocked)
2336 static void __detach_device(struct iommu_dev_data *dev_data)
2338 struct protection_domain *domain;
2339 unsigned long flags;
2341 BUG_ON(!dev_data->domain);
2343 domain = dev_data->domain;
2345 spin_lock_irqsave(&domain->lock, flags);
2347 if (dev_data->alias_data != NULL) {
2348 struct iommu_dev_data *alias_data = dev_data->alias_data;
2350 if (atomic_dec_and_test(&alias_data->bind))
2351 do_detach(alias_data);
2354 if (atomic_dec_and_test(&dev_data->bind))
2355 do_detach(dev_data);
2357 spin_unlock_irqrestore(&domain->lock, flags);
2360 * If we run in passthrough mode the device must be assigned to the
2361 * passthrough domain if it is detached from any other domain.
2362 * Make sure we can deassign from the pt_domain itself.
2364 if (dev_data->passthrough &&
2365 (dev_data->domain == NULL && domain != pt_domain))
2366 __attach_device(dev_data, pt_domain);
2370 * Removes a device from a protection domain (with devtable_lock held)
2372 static void detach_device(struct device *dev)
2374 struct protection_domain *domain;
2375 struct iommu_dev_data *dev_data;
2376 unsigned long flags;
2378 dev_data = get_dev_data(dev);
2379 domain = dev_data->domain;
2381 /* lock device table */
2382 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2383 __detach_device(dev_data);
2384 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2386 if (domain->flags & PD_IOMMUV2_MASK)
2387 pdev_iommuv2_disable(to_pci_dev(dev));
2388 else if (dev_data->ats.enabled)
2389 pci_disable_ats(to_pci_dev(dev));
2391 dev_data->ats.enabled = false;
2395 * Find out the protection domain structure for a given PCI device. This
2396 * will give us the pointer to the page table root for example.
2398 static struct protection_domain *domain_for_device(struct device *dev)
2400 struct iommu_dev_data *dev_data;
2401 struct protection_domain *dom = NULL;
2402 unsigned long flags;
2404 dev_data = get_dev_data(dev);
2406 if (dev_data->domain)
2407 return dev_data->domain;
2409 if (dev_data->alias_data != NULL) {
2410 struct iommu_dev_data *alias_data = dev_data->alias_data;
2412 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
2413 if (alias_data->domain != NULL) {
2414 __attach_device(dev_data, alias_data->domain);
2415 dom = alias_data->domain;
2417 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2423 static int device_change_notifier(struct notifier_block *nb,
2424 unsigned long action, void *data)
2426 struct dma_ops_domain *dma_domain;
2427 struct protection_domain *domain;
2428 struct iommu_dev_data *dev_data;
2429 struct device *dev = data;
2430 struct amd_iommu *iommu;
2431 unsigned long flags;
2434 if (!check_device(dev))
2437 devid = get_device_id(dev);
2438 iommu = amd_iommu_rlookup_table[devid];
2439 dev_data = get_dev_data(dev);
2442 case BUS_NOTIFY_UNBOUND_DRIVER:
2444 domain = domain_for_device(dev);
2448 if (dev_data->passthrough)
2452 case BUS_NOTIFY_ADD_DEVICE:
2454 iommu_init_device(dev);
2457 * dev_data is still NULL and
2458 * got initialized in iommu_init_device
2460 dev_data = get_dev_data(dev);
2462 if (iommu_pass_through || dev_data->iommu_v2) {
2463 dev_data->passthrough = true;
2464 attach_device(dev, pt_domain);
2468 domain = domain_for_device(dev);
2470 /* allocate a protection domain if a device is added */
2471 dma_domain = find_protection_domain(devid);
2473 dma_domain = dma_ops_domain_alloc();
2476 dma_domain->target_dev = devid;
2478 spin_lock_irqsave(&iommu_pd_list_lock, flags);
2479 list_add_tail(&dma_domain->list, &iommu_pd_list);
2480 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
2483 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2486 case BUS_NOTIFY_DEL_DEVICE:
2488 iommu_uninit_device(dev);
2494 iommu_completion_wait(iommu);
2500 static struct notifier_block device_nb = {
2501 .notifier_call = device_change_notifier,
2504 void amd_iommu_init_notifier(void)
2506 bus_register_notifier(&pci_bus_type, &device_nb);
2509 /*****************************************************************************
2511 * The next functions belong to the dma_ops mapping/unmapping code.
2513 *****************************************************************************/
2516 * In the dma_ops path we only have the struct device. This function
2517 * finds the corresponding IOMMU, the protection domain and the
2518 * requestor id for a given device.
2519 * If the device is not yet associated with a domain this is also done
2522 static struct protection_domain *get_domain(struct device *dev)
2524 struct protection_domain *domain;
2525 struct dma_ops_domain *dma_dom;
2526 u16 devid = get_device_id(dev);
2528 if (!check_device(dev))
2529 return ERR_PTR(-EINVAL);
2531 domain = domain_for_device(dev);
2532 if (domain != NULL && !dma_ops_domain(domain))
2533 return ERR_PTR(-EBUSY);
2538 /* Device not bound yet - bind it */
2539 dma_dom = find_protection_domain(devid);
2541 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
2542 attach_device(dev, &dma_dom->domain);
2543 DUMP_printk("Using protection domain %d for device %s\n",
2544 dma_dom->domain.id, dev_name(dev));
2546 return &dma_dom->domain;
2549 static void update_device_table(struct protection_domain *domain)
2551 struct iommu_dev_data *dev_data;
2553 list_for_each_entry(dev_data, &domain->dev_list, list)
2554 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2557 static void update_domain(struct protection_domain *domain)
2559 if (!domain->updated)
2562 update_device_table(domain);
2564 domain_flush_devices(domain);
2565 domain_flush_tlb_pde(domain);
2567 domain->updated = false;
2571 * This function fetches the PTE for a given address in the aperture
2573 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2574 unsigned long address)
2576 struct aperture_range *aperture;
2577 u64 *pte, *pte_page;
2579 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2583 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2585 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2587 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2589 pte += PM_LEVEL_INDEX(0, address);
2591 update_domain(&dom->domain);
2597 * This is the generic map function. It maps one 4kb page at paddr to
2598 * the given address in the DMA address space for the domain.
2600 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2601 unsigned long address,
2607 WARN_ON(address > dom->aperture_size);
2611 pte = dma_ops_get_pte(dom, address);
2613 return DMA_ERROR_CODE;
2615 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2617 if (direction == DMA_TO_DEVICE)
2618 __pte |= IOMMU_PTE_IR;
2619 else if (direction == DMA_FROM_DEVICE)
2620 __pte |= IOMMU_PTE_IW;
2621 else if (direction == DMA_BIDIRECTIONAL)
2622 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2628 return (dma_addr_t)address;
2632 * The generic unmapping function for on page in the DMA address space.
2634 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2635 unsigned long address)
2637 struct aperture_range *aperture;
2640 if (address >= dom->aperture_size)
2643 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2647 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2651 pte += PM_LEVEL_INDEX(0, address);
2659 * This function contains common code for mapping of a physically
2660 * contiguous memory region into DMA address space. It is used by all
2661 * mapping functions provided with this IOMMU driver.
2662 * Must be called with the domain lock held.
2664 static dma_addr_t __map_single(struct device *dev,
2665 struct dma_ops_domain *dma_dom,
2672 dma_addr_t offset = paddr & ~PAGE_MASK;
2673 dma_addr_t address, start, ret;
2675 unsigned long align_mask = 0;
2678 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2681 INC_STATS_COUNTER(total_map_requests);
2684 INC_STATS_COUNTER(cross_page);
2687 align_mask = (1UL << get_order(size)) - 1;
2690 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2692 if (unlikely(address == DMA_ERROR_CODE)) {
2694 * setting next_address here will let the address
2695 * allocator only scan the new allocated range in the
2696 * first run. This is a small optimization.
2698 dma_dom->next_address = dma_dom->aperture_size;
2700 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2704 * aperture was successfully enlarged by 128 MB, try
2711 for (i = 0; i < pages; ++i) {
2712 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2713 if (ret == DMA_ERROR_CODE)
2721 ADD_STATS_COUNTER(alloced_io_mem, size);
2723 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2724 domain_flush_tlb(&dma_dom->domain);
2725 dma_dom->need_flush = false;
2726 } else if (unlikely(amd_iommu_np_cache))
2727 domain_flush_pages(&dma_dom->domain, address, size);
2734 for (--i; i >= 0; --i) {
2736 dma_ops_domain_unmap(dma_dom, start);
2739 dma_ops_free_addresses(dma_dom, address, pages);
2741 return DMA_ERROR_CODE;
2745 * Does the reverse of the __map_single function. Must be called with
2746 * the domain lock held too
2748 static void __unmap_single(struct dma_ops_domain *dma_dom,
2749 dma_addr_t dma_addr,
2753 dma_addr_t flush_addr;
2754 dma_addr_t i, start;
2757 if ((dma_addr == DMA_ERROR_CODE) ||
2758 (dma_addr + size > dma_dom->aperture_size))
2761 flush_addr = dma_addr;
2762 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2763 dma_addr &= PAGE_MASK;
2766 for (i = 0; i < pages; ++i) {
2767 dma_ops_domain_unmap(dma_dom, start);
2771 SUB_STATS_COUNTER(alloced_io_mem, size);
2773 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2775 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2776 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2777 dma_dom->need_flush = false;
2782 * The exported map_single function for dma_ops.
2784 static dma_addr_t map_page(struct device *dev, struct page *page,
2785 unsigned long offset, size_t size,
2786 enum dma_data_direction dir,
2787 struct dma_attrs *attrs)
2789 unsigned long flags;
2790 struct protection_domain *domain;
2793 phys_addr_t paddr = page_to_phys(page) + offset;
2795 INC_STATS_COUNTER(cnt_map_single);
2797 domain = get_domain(dev);
2798 if (PTR_ERR(domain) == -EINVAL)
2799 return (dma_addr_t)paddr;
2800 else if (IS_ERR(domain))
2801 return DMA_ERROR_CODE;
2803 dma_mask = *dev->dma_mask;
2805 spin_lock_irqsave(&domain->lock, flags);
2807 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2809 if (addr == DMA_ERROR_CODE)
2812 domain_flush_complete(domain);
2815 spin_unlock_irqrestore(&domain->lock, flags);
2821 * The exported unmap_single function for dma_ops.
2823 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2824 enum dma_data_direction dir, struct dma_attrs *attrs)
2826 unsigned long flags;
2827 struct protection_domain *domain;
2829 INC_STATS_COUNTER(cnt_unmap_single);
2831 domain = get_domain(dev);
2835 spin_lock_irqsave(&domain->lock, flags);
2837 __unmap_single(domain->priv, dma_addr, size, dir);
2839 domain_flush_complete(domain);
2841 spin_unlock_irqrestore(&domain->lock, flags);
2845 * The exported map_sg function for dma_ops (handles scatter-gather
2848 static int map_sg(struct device *dev, struct scatterlist *sglist,
2849 int nelems, enum dma_data_direction dir,
2850 struct dma_attrs *attrs)
2852 unsigned long flags;
2853 struct protection_domain *domain;
2855 struct scatterlist *s;
2857 int mapped_elems = 0;
2860 INC_STATS_COUNTER(cnt_map_sg);
2862 domain = get_domain(dev);
2866 dma_mask = *dev->dma_mask;
2868 spin_lock_irqsave(&domain->lock, flags);
2870 for_each_sg(sglist, s, nelems, i) {
2873 s->dma_address = __map_single(dev, domain->priv,
2874 paddr, s->length, dir, false,
2877 if (s->dma_address) {
2878 s->dma_length = s->length;
2884 domain_flush_complete(domain);
2887 spin_unlock_irqrestore(&domain->lock, flags);
2889 return mapped_elems;
2891 for_each_sg(sglist, s, mapped_elems, i) {
2893 __unmap_single(domain->priv, s->dma_address,
2894 s->dma_length, dir);
2895 s->dma_address = s->dma_length = 0;
2904 * The exported map_sg function for dma_ops (handles scatter-gather
2907 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2908 int nelems, enum dma_data_direction dir,
2909 struct dma_attrs *attrs)
2911 unsigned long flags;
2912 struct protection_domain *domain;
2913 struct scatterlist *s;
2916 INC_STATS_COUNTER(cnt_unmap_sg);
2918 domain = get_domain(dev);
2922 spin_lock_irqsave(&domain->lock, flags);
2924 for_each_sg(sglist, s, nelems, i) {
2925 __unmap_single(domain->priv, s->dma_address,
2926 s->dma_length, dir);
2927 s->dma_address = s->dma_length = 0;
2930 domain_flush_complete(domain);
2932 spin_unlock_irqrestore(&domain->lock, flags);
2936 * The exported alloc_coherent function for dma_ops.
2938 static void *alloc_coherent(struct device *dev, size_t size,
2939 dma_addr_t *dma_addr, gfp_t flag,
2940 struct dma_attrs *attrs)
2942 unsigned long flags;
2944 struct protection_domain *domain;
2946 u64 dma_mask = dev->coherent_dma_mask;
2948 INC_STATS_COUNTER(cnt_alloc_coherent);
2950 domain = get_domain(dev);
2951 if (PTR_ERR(domain) == -EINVAL) {
2952 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2953 *dma_addr = __pa(virt_addr);
2955 } else if (IS_ERR(domain))
2958 dma_mask = dev->coherent_dma_mask;
2959 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2962 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2966 paddr = virt_to_phys(virt_addr);
2969 dma_mask = *dev->dma_mask;
2971 spin_lock_irqsave(&domain->lock, flags);
2973 *dma_addr = __map_single(dev, domain->priv, paddr,
2974 size, DMA_BIDIRECTIONAL, true, dma_mask);
2976 if (*dma_addr == DMA_ERROR_CODE) {
2977 spin_unlock_irqrestore(&domain->lock, flags);
2981 domain_flush_complete(domain);
2983 spin_unlock_irqrestore(&domain->lock, flags);
2989 free_pages((unsigned long)virt_addr, get_order(size));
2995 * The exported free_coherent function for dma_ops.
2997 static void free_coherent(struct device *dev, size_t size,
2998 void *virt_addr, dma_addr_t dma_addr,
2999 struct dma_attrs *attrs)
3001 unsigned long flags;
3002 struct protection_domain *domain;
3004 INC_STATS_COUNTER(cnt_free_coherent);
3006 domain = get_domain(dev);
3010 spin_lock_irqsave(&domain->lock, flags);
3012 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
3014 domain_flush_complete(domain);
3016 spin_unlock_irqrestore(&domain->lock, flags);
3019 free_pages((unsigned long)virt_addr, get_order(size));
3023 * This function is called by the DMA layer to find out if we can handle a
3024 * particular device. It is part of the dma_ops.
3026 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
3028 return check_device(dev);
3032 * The function for pre-allocating protection domains.
3034 * If the driver core informs the DMA layer if a driver grabs a device
3035 * we don't need to preallocate the protection domains anymore.
3036 * For now we have to.
3038 static void __init prealloc_protection_domains(void)
3040 struct iommu_dev_data *dev_data;
3041 struct dma_ops_domain *dma_dom;
3042 struct pci_dev *dev = NULL;
3045 for_each_pci_dev(dev) {
3047 /* Do we handle this device? */
3048 if (!check_device(&dev->dev))
3051 dev_data = get_dev_data(&dev->dev);
3052 if (!amd_iommu_force_isolation && dev_data->iommu_v2) {
3053 /* Make sure passthrough domain is allocated */
3054 alloc_passthrough_domain();
3055 dev_data->passthrough = true;
3056 attach_device(&dev->dev, pt_domain);
3057 pr_info("AMD-Vi: Using passthrough domain for device %s\n",
3058 dev_name(&dev->dev));
3061 /* Is there already any domain for it? */
3062 if (domain_for_device(&dev->dev))
3065 devid = get_device_id(&dev->dev);
3067 dma_dom = dma_ops_domain_alloc();
3070 init_unity_mappings_for_device(dma_dom, devid);
3071 dma_dom->target_dev = devid;
3073 attach_device(&dev->dev, &dma_dom->domain);
3075 list_add_tail(&dma_dom->list, &iommu_pd_list);
3079 static struct dma_map_ops amd_iommu_dma_ops = {
3080 .alloc = alloc_coherent,
3081 .free = free_coherent,
3082 .map_page = map_page,
3083 .unmap_page = unmap_page,
3085 .unmap_sg = unmap_sg,
3086 .dma_supported = amd_iommu_dma_supported,
3089 static unsigned device_dma_ops_init(void)
3091 struct iommu_dev_data *dev_data;
3092 struct pci_dev *pdev = NULL;
3093 unsigned unhandled = 0;
3095 for_each_pci_dev(pdev) {
3096 if (!check_device(&pdev->dev)) {
3098 iommu_ignore_device(&pdev->dev);
3104 dev_data = get_dev_data(&pdev->dev);
3106 if (!dev_data->passthrough)
3107 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
3109 pdev->dev.archdata.dma_ops = &nommu_dma_ops;
3116 * The function which clues the AMD IOMMU driver into dma_ops.
3119 void __init amd_iommu_init_api(void)
3121 bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
3124 int __init amd_iommu_init_dma_ops(void)
3126 struct amd_iommu *iommu;
3130 * first allocate a default protection domain for every IOMMU we
3131 * found in the system. Devices not assigned to any other
3132 * protection domain will be assigned to the default one.
3134 for_each_iommu(iommu) {
3135 iommu->default_dom = dma_ops_domain_alloc();
3136 if (iommu->default_dom == NULL)
3138 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
3139 ret = iommu_init_unity_mappings(iommu);
3145 * Pre-allocate the protection domains for each device.
3147 prealloc_protection_domains();
3152 /* Make the driver finally visible to the drivers */
3153 unhandled = device_dma_ops_init();
3154 if (unhandled && max_pfn > MAX_DMA32_PFN) {
3155 /* There are unhandled devices - initialize swiotlb for them */
3159 amd_iommu_stats_init();
3161 if (amd_iommu_unmap_flush)
3162 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
3164 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
3170 for_each_iommu(iommu) {
3171 dma_ops_domain_free(iommu->default_dom);
3177 /*****************************************************************************
3179 * The following functions belong to the exported interface of AMD IOMMU
3181 * This interface allows access to lower level functions of the IOMMU
3182 * like protection domain handling and assignement of devices to domains
3183 * which is not possible with the dma_ops interface.
3185 *****************************************************************************/
3187 static void cleanup_domain(struct protection_domain *domain)
3189 struct iommu_dev_data *dev_data, *next;
3190 unsigned long flags;
3192 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3194 list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
3195 __detach_device(dev_data);
3196 atomic_set(&dev_data->bind, 0);
3199 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3202 static void protection_domain_free(struct protection_domain *domain)
3207 del_domain_from_list(domain);
3210 domain_id_free(domain->id);
3215 static struct protection_domain *protection_domain_alloc(void)
3217 struct protection_domain *domain;
3219 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
3223 spin_lock_init(&domain->lock);
3224 mutex_init(&domain->api_lock);
3225 domain->id = domain_id_alloc();
3228 INIT_LIST_HEAD(&domain->dev_list);
3230 add_domain_to_list(domain);
3240 static int __init alloc_passthrough_domain(void)
3242 if (pt_domain != NULL)
3245 /* allocate passthrough domain */
3246 pt_domain = protection_domain_alloc();
3250 pt_domain->mode = PAGE_MODE_NONE;
3254 static int amd_iommu_domain_init(struct iommu_domain *dom)
3256 struct protection_domain *domain;
3258 domain = protection_domain_alloc();
3262 domain->mode = PAGE_MODE_3_LEVEL;
3263 domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
3264 if (!domain->pt_root)
3267 domain->iommu_domain = dom;
3271 dom->geometry.aperture_start = 0;
3272 dom->geometry.aperture_end = ~0ULL;
3273 dom->geometry.force_aperture = true;
3278 protection_domain_free(domain);
3283 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
3285 struct protection_domain *domain = dom->priv;
3290 if (domain->dev_cnt > 0)
3291 cleanup_domain(domain);
3293 BUG_ON(domain->dev_cnt != 0);
3295 if (domain->mode != PAGE_MODE_NONE)
3296 free_pagetable(domain);
3298 if (domain->flags & PD_IOMMUV2_MASK)
3299 free_gcr3_table(domain);
3301 protection_domain_free(domain);
3306 static void amd_iommu_detach_device(struct iommu_domain *dom,
3309 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3310 struct amd_iommu *iommu;
3313 if (!check_device(dev))
3316 devid = get_device_id(dev);
3318 if (dev_data->domain != NULL)
3321 iommu = amd_iommu_rlookup_table[devid];
3325 iommu_completion_wait(iommu);
3328 static int amd_iommu_attach_device(struct iommu_domain *dom,
3331 struct protection_domain *domain = dom->priv;
3332 struct iommu_dev_data *dev_data;
3333 struct amd_iommu *iommu;
3336 if (!check_device(dev))
3339 dev_data = dev->archdata.iommu;
3341 iommu = amd_iommu_rlookup_table[dev_data->devid];
3345 if (dev_data->domain)
3348 ret = attach_device(dev, domain);
3350 iommu_completion_wait(iommu);
3355 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3356 phys_addr_t paddr, size_t page_size, int iommu_prot)
3358 struct protection_domain *domain = dom->priv;
3362 if (domain->mode == PAGE_MODE_NONE)
3365 if (iommu_prot & IOMMU_READ)
3366 prot |= IOMMU_PROT_IR;
3367 if (iommu_prot & IOMMU_WRITE)
3368 prot |= IOMMU_PROT_IW;
3370 mutex_lock(&domain->api_lock);
3371 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3372 mutex_unlock(&domain->api_lock);
3377 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3380 struct protection_domain *domain = dom->priv;
3383 if (domain->mode == PAGE_MODE_NONE)
3386 mutex_lock(&domain->api_lock);
3387 unmap_size = iommu_unmap_page(domain, iova, page_size);
3388 mutex_unlock(&domain->api_lock);
3390 domain_flush_tlb_pde(domain);
3395 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3398 struct protection_domain *domain = dom->priv;
3399 unsigned long offset_mask;
3403 if (domain->mode == PAGE_MODE_NONE)
3406 pte = fetch_pte(domain, iova);
3408 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3411 if (PM_PTE_LEVEL(*pte) == 0)
3412 offset_mask = PAGE_SIZE - 1;
3414 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
3416 __pte = *pte & PM_ADDR_MASK;
3417 paddr = (__pte & ~offset_mask) | (iova & offset_mask);
3422 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
3426 case IOMMU_CAP_CACHE_COHERENCY:
3428 case IOMMU_CAP_INTR_REMAP:
3429 return irq_remapping_enabled;
3435 static struct iommu_ops amd_iommu_ops = {
3436 .domain_init = amd_iommu_domain_init,
3437 .domain_destroy = amd_iommu_domain_destroy,
3438 .attach_dev = amd_iommu_attach_device,
3439 .detach_dev = amd_iommu_detach_device,
3440 .map = amd_iommu_map,
3441 .unmap = amd_iommu_unmap,
3442 .iova_to_phys = amd_iommu_iova_to_phys,
3443 .domain_has_cap = amd_iommu_domain_has_cap,
3444 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3447 /*****************************************************************************
3449 * The next functions do a basic initialization of IOMMU for pass through
3452 * In passthrough mode the IOMMU is initialized and enabled but not used for
3453 * DMA-API translation.
3455 *****************************************************************************/
3457 int __init amd_iommu_init_passthrough(void)
3459 struct iommu_dev_data *dev_data;
3460 struct pci_dev *dev = NULL;
3461 struct amd_iommu *iommu;
3465 ret = alloc_passthrough_domain();
3469 for_each_pci_dev(dev) {
3470 if (!check_device(&dev->dev))
3473 dev_data = get_dev_data(&dev->dev);
3474 dev_data->passthrough = true;
3476 devid = get_device_id(&dev->dev);
3478 iommu = amd_iommu_rlookup_table[devid];
3482 attach_device(&dev->dev, pt_domain);
3485 amd_iommu_stats_init();
3487 pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
3492 /* IOMMUv2 specific functions */
3493 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3495 return atomic_notifier_chain_register(&ppr_notifier, nb);
3497 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3499 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3501 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3503 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3505 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3507 struct protection_domain *domain = dom->priv;
3508 unsigned long flags;
3510 spin_lock_irqsave(&domain->lock, flags);
3512 /* Update data structure */
3513 domain->mode = PAGE_MODE_NONE;
3514 domain->updated = true;
3516 /* Make changes visible to IOMMUs */
3517 update_domain(domain);
3519 /* Page-table is not visible to IOMMU anymore, so free it */
3520 free_pagetable(domain);
3522 spin_unlock_irqrestore(&domain->lock, flags);
3524 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3526 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3528 struct protection_domain *domain = dom->priv;
3529 unsigned long flags;
3532 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3535 /* Number of GCR3 table levels required */
3536 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3539 if (levels > amd_iommu_max_glx_val)
3542 spin_lock_irqsave(&domain->lock, flags);
3545 * Save us all sanity checks whether devices already in the
3546 * domain support IOMMUv2. Just force that the domain has no
3547 * devices attached when it is switched into IOMMUv2 mode.
3550 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3554 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3555 if (domain->gcr3_tbl == NULL)
3558 domain->glx = levels;
3559 domain->flags |= PD_IOMMUV2_MASK;
3560 domain->updated = true;
3562 update_domain(domain);
3567 spin_unlock_irqrestore(&domain->lock, flags);
3571 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3573 static int __flush_pasid(struct protection_domain *domain, int pasid,
3574 u64 address, bool size)
3576 struct iommu_dev_data *dev_data;
3577 struct iommu_cmd cmd;
3580 if (!(domain->flags & PD_IOMMUV2_MASK))
3583 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3586 * IOMMU TLB needs to be flushed before Device TLB to
3587 * prevent device TLB refill from IOMMU TLB
3589 for (i = 0; i < amd_iommus_present; ++i) {
3590 if (domain->dev_iommu[i] == 0)
3593 ret = iommu_queue_command(amd_iommus[i], &cmd);
3598 /* Wait until IOMMU TLB flushes are complete */
3599 domain_flush_complete(domain);
3601 /* Now flush device TLBs */
3602 list_for_each_entry(dev_data, &domain->dev_list, list) {
3603 struct amd_iommu *iommu;
3606 BUG_ON(!dev_data->ats.enabled);
3608 qdep = dev_data->ats.qdep;
3609 iommu = amd_iommu_rlookup_table[dev_data->devid];
3611 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3612 qdep, address, size);
3614 ret = iommu_queue_command(iommu, &cmd);
3619 /* Wait until all device TLBs are flushed */
3620 domain_flush_complete(domain);
3629 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3632 INC_STATS_COUNTER(invalidate_iotlb);
3634 return __flush_pasid(domain, pasid, address, false);
3637 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3640 struct protection_domain *domain = dom->priv;
3641 unsigned long flags;
3644 spin_lock_irqsave(&domain->lock, flags);
3645 ret = __amd_iommu_flush_page(domain, pasid, address);
3646 spin_unlock_irqrestore(&domain->lock, flags);
3650 EXPORT_SYMBOL(amd_iommu_flush_page);
3652 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3654 INC_STATS_COUNTER(invalidate_iotlb_all);
3656 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3660 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3662 struct protection_domain *domain = dom->priv;
3663 unsigned long flags;
3666 spin_lock_irqsave(&domain->lock, flags);
3667 ret = __amd_iommu_flush_tlb(domain, pasid);
3668 spin_unlock_irqrestore(&domain->lock, flags);
3672 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3674 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3681 index = (pasid >> (9 * level)) & 0x1ff;
3687 if (!(*pte & GCR3_VALID)) {
3691 root = (void *)get_zeroed_page(GFP_ATOMIC);
3695 *pte = __pa(root) | GCR3_VALID;
3698 root = __va(*pte & PAGE_MASK);
3706 static int __set_gcr3(struct protection_domain *domain, int pasid,
3711 if (domain->mode != PAGE_MODE_NONE)
3714 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3718 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3720 return __amd_iommu_flush_tlb(domain, pasid);
3723 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3727 if (domain->mode != PAGE_MODE_NONE)
3730 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3736 return __amd_iommu_flush_tlb(domain, pasid);
3739 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3742 struct protection_domain *domain = dom->priv;
3743 unsigned long flags;
3746 spin_lock_irqsave(&domain->lock, flags);
3747 ret = __set_gcr3(domain, pasid, cr3);
3748 spin_unlock_irqrestore(&domain->lock, flags);
3752 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3754 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3756 struct protection_domain *domain = dom->priv;
3757 unsigned long flags;
3760 spin_lock_irqsave(&domain->lock, flags);
3761 ret = __clear_gcr3(domain, pasid);
3762 spin_unlock_irqrestore(&domain->lock, flags);
3766 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3768 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3769 int status, int tag)
3771 struct iommu_dev_data *dev_data;
3772 struct amd_iommu *iommu;
3773 struct iommu_cmd cmd;
3775 INC_STATS_COUNTER(complete_ppr);
3777 dev_data = get_dev_data(&pdev->dev);
3778 iommu = amd_iommu_rlookup_table[dev_data->devid];
3780 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3781 tag, dev_data->pri_tlp);
3783 return iommu_queue_command(iommu, &cmd);
3785 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3787 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3789 struct protection_domain *domain;
3791 domain = get_domain(&pdev->dev);
3795 /* Only return IOMMUv2 domains */
3796 if (!(domain->flags & PD_IOMMUV2_MASK))
3799 return domain->iommu_domain;
3801 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3803 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3805 struct iommu_dev_data *dev_data;
3807 if (!amd_iommu_v2_supported())
3810 dev_data = get_dev_data(&pdev->dev);
3811 dev_data->errata |= (1 << erratum);
3813 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3815 int amd_iommu_device_info(struct pci_dev *pdev,
3816 struct amd_iommu_device_info *info)
3821 if (pdev == NULL || info == NULL)
3824 if (!amd_iommu_v2_supported())
3827 memset(info, 0, sizeof(*info));
3829 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3831 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3833 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3835 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3837 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3841 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3842 max_pasids = min(max_pasids, (1 << 20));
3844 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3845 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3847 features = pci_pasid_features(pdev);
3848 if (features & PCI_PASID_CAP_EXEC)
3849 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3850 if (features & PCI_PASID_CAP_PRIV)
3851 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3856 EXPORT_SYMBOL(amd_iommu_device_info);
3858 #ifdef CONFIG_IRQ_REMAP
3860 /*****************************************************************************
3862 * Interrupt Remapping Implementation
3864 *****************************************************************************/
3881 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3882 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3883 #define DTE_IRQ_TABLE_LEN (8ULL << 1)
3884 #define DTE_IRQ_REMAP_ENABLE 1ULL
3886 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3890 dte = amd_iommu_dev_table[devid].data[2];
3891 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3892 dte |= virt_to_phys(table->table);
3893 dte |= DTE_IRQ_REMAP_INTCTL;
3894 dte |= DTE_IRQ_TABLE_LEN;
3895 dte |= DTE_IRQ_REMAP_ENABLE;
3897 amd_iommu_dev_table[devid].data[2] = dte;
3900 #define IRTE_ALLOCATED (~1U)
3902 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3904 struct irq_remap_table *table = NULL;
3905 struct amd_iommu *iommu;
3906 unsigned long flags;
3909 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3911 iommu = amd_iommu_rlookup_table[devid];
3915 table = irq_lookup_table[devid];
3919 alias = amd_iommu_alias_table[devid];
3920 table = irq_lookup_table[alias];
3922 irq_lookup_table[devid] = table;
3923 set_dte_irq_entry(devid, table);
3924 iommu_flush_dte(iommu, devid);
3928 /* Nothing there yet, allocate new irq remapping table */
3929 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3933 /* Initialize table spin-lock */
3934 spin_lock_init(&table->lock);
3937 /* Keep the first 32 indexes free for IOAPIC interrupts */
3938 table->min_index = 32;
3940 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3941 if (!table->table) {
3947 memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3952 for (i = 0; i < 32; ++i)
3953 table->table[i] = IRTE_ALLOCATED;
3956 irq_lookup_table[devid] = table;
3957 set_dte_irq_entry(devid, table);
3958 iommu_flush_dte(iommu, devid);
3959 if (devid != alias) {
3960 irq_lookup_table[alias] = table;
3961 set_dte_irq_entry(devid, table);
3962 iommu_flush_dte(iommu, alias);
3966 iommu_completion_wait(iommu);
3969 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3974 static int alloc_irq_index(struct irq_cfg *cfg, u16 devid, int count)
3976 struct irq_remap_table *table;
3977 unsigned long flags;
3980 table = get_irq_table(devid, false);
3984 spin_lock_irqsave(&table->lock, flags);
3986 /* Scan table for free entries */
3987 for (c = 0, index = table->min_index;
3988 index < MAX_IRQS_PER_TABLE;
3990 if (table->table[index] == 0)
3996 struct irq_2_irte *irte_info;
3999 table->table[index - c + 1] = IRTE_ALLOCATED;
4004 irte_info = &cfg->irq_2_irte;
4005 irte_info->devid = devid;
4006 irte_info->index = index;
4015 spin_unlock_irqrestore(&table->lock, flags);
4020 static int get_irte(u16 devid, int index, union irte *irte)
4022 struct irq_remap_table *table;
4023 unsigned long flags;
4025 table = get_irq_table(devid, false);
4029 spin_lock_irqsave(&table->lock, flags);
4030 irte->val = table->table[index];
4031 spin_unlock_irqrestore(&table->lock, flags);
4036 static int modify_irte(u16 devid, int index, union irte irte)
4038 struct irq_remap_table *table;
4039 struct amd_iommu *iommu;
4040 unsigned long flags;
4042 iommu = amd_iommu_rlookup_table[devid];
4046 table = get_irq_table(devid, false);
4050 spin_lock_irqsave(&table->lock, flags);
4051 table->table[index] = irte.val;
4052 spin_unlock_irqrestore(&table->lock, flags);
4054 iommu_flush_irt(iommu, devid);
4055 iommu_completion_wait(iommu);
4060 static void free_irte(u16 devid, int index)
4062 struct irq_remap_table *table;
4063 struct amd_iommu *iommu;
4064 unsigned long flags;
4066 iommu = amd_iommu_rlookup_table[devid];
4070 table = get_irq_table(devid, false);
4074 spin_lock_irqsave(&table->lock, flags);
4075 table->table[index] = 0;
4076 spin_unlock_irqrestore(&table->lock, flags);
4078 iommu_flush_irt(iommu, devid);
4079 iommu_completion_wait(iommu);
4082 static int setup_ioapic_entry(int irq, struct IO_APIC_route_entry *entry,
4083 unsigned int destination, int vector,
4084 struct io_apic_irq_attr *attr)
4086 struct irq_remap_table *table;
4087 struct irq_2_irte *irte_info;
4088 struct irq_cfg *cfg;
4095 cfg = irq_get_chip_data(irq);
4099 irte_info = &cfg->irq_2_irte;
4100 ioapic_id = mpc_ioapic_id(attr->ioapic);
4101 devid = get_ioapic_devid(ioapic_id);
4106 table = get_irq_table(devid, true);
4110 index = attr->ioapic_pin;
4112 /* Setup IRQ remapping info */
4114 irte_info->devid = devid;
4115 irte_info->index = index;
4117 /* Setup IRTE for IOMMU */
4119 irte.fields.vector = vector;
4120 irte.fields.int_type = apic->irq_delivery_mode;
4121 irte.fields.destination = destination;
4122 irte.fields.dm = apic->irq_dest_mode;
4123 irte.fields.valid = 1;
4125 ret = modify_irte(devid, index, irte);
4129 /* Setup IOAPIC entry */
4130 memset(entry, 0, sizeof(*entry));
4132 entry->vector = index;
4134 entry->trigger = attr->trigger;
4135 entry->polarity = attr->polarity;
4138 * Mask level triggered irqs.
4146 static int set_affinity(struct irq_data *data, const struct cpumask *mask,
4149 struct irq_2_irte *irte_info;
4150 unsigned int dest, irq;
4151 struct irq_cfg *cfg;
4155 if (!config_enabled(CONFIG_SMP))
4158 cfg = data->chip_data;
4160 irte_info = &cfg->irq_2_irte;
4162 if (!cpumask_intersects(mask, cpu_online_mask))
4165 if (get_irte(irte_info->devid, irte_info->index, &irte))
4168 if (assign_irq_vector(irq, cfg, mask))
4171 err = apic->cpu_mask_to_apicid_and(cfg->domain, mask, &dest);
4173 if (assign_irq_vector(irq, cfg, data->affinity))
4174 pr_err("AMD-Vi: Failed to recover vector for irq %d\n", irq);
4178 irte.fields.vector = cfg->vector;
4179 irte.fields.destination = dest;
4181 modify_irte(irte_info->devid, irte_info->index, irte);
4183 if (cfg->move_in_progress)
4184 send_cleanup_vector(cfg);
4186 cpumask_copy(data->affinity, mask);
4191 static int free_irq(int irq)
4193 struct irq_2_irte *irte_info;
4194 struct irq_cfg *cfg;
4196 cfg = irq_get_chip_data(irq);
4200 irte_info = &cfg->irq_2_irte;
4202 free_irte(irte_info->devid, irte_info->index);
4207 static void compose_msi_msg(struct pci_dev *pdev,
4208 unsigned int irq, unsigned int dest,
4209 struct msi_msg *msg, u8 hpet_id)
4211 struct irq_2_irte *irte_info;
4212 struct irq_cfg *cfg;
4215 cfg = irq_get_chip_data(irq);
4219 irte_info = &cfg->irq_2_irte;
4222 irte.fields.vector = cfg->vector;
4223 irte.fields.int_type = apic->irq_delivery_mode;
4224 irte.fields.destination = dest;
4225 irte.fields.dm = apic->irq_dest_mode;
4226 irte.fields.valid = 1;
4228 modify_irte(irte_info->devid, irte_info->index, irte);
4230 msg->address_hi = MSI_ADDR_BASE_HI;
4231 msg->address_lo = MSI_ADDR_BASE_LO;
4232 msg->data = irte_info->index;
4235 static int msi_alloc_irq(struct pci_dev *pdev, int irq, int nvec)
4237 struct irq_cfg *cfg;
4244 cfg = irq_get_chip_data(irq);
4248 devid = get_device_id(&pdev->dev);
4249 index = alloc_irq_index(cfg, devid, nvec);
4251 return index < 0 ? MAX_IRQS_PER_TABLE : index;
4254 static int msi_setup_irq(struct pci_dev *pdev, unsigned int irq,
4255 int index, int offset)
4257 struct irq_2_irte *irte_info;
4258 struct irq_cfg *cfg;
4264 cfg = irq_get_chip_data(irq);
4268 if (index >= MAX_IRQS_PER_TABLE)
4271 devid = get_device_id(&pdev->dev);
4272 irte_info = &cfg->irq_2_irte;
4275 irte_info->devid = devid;
4276 irte_info->index = index + offset;
4281 static int setup_hpet_msi(unsigned int irq, unsigned int id)
4283 struct irq_2_irte *irte_info;
4284 struct irq_cfg *cfg;
4287 cfg = irq_get_chip_data(irq);
4291 irte_info = &cfg->irq_2_irte;
4292 devid = get_hpet_devid(id);
4296 index = alloc_irq_index(cfg, devid, 1);
4301 irte_info->devid = devid;
4302 irte_info->index = index;
4307 struct irq_remap_ops amd_iommu_irq_ops = {
4308 .supported = amd_iommu_supported,
4309 .prepare = amd_iommu_prepare,
4310 .enable = amd_iommu_enable,
4311 .disable = amd_iommu_disable,
4312 .reenable = amd_iommu_reenable,
4313 .enable_faulting = amd_iommu_enable_faulting,
4314 .setup_ioapic_entry = setup_ioapic_entry,
4315 .set_affinity = set_affinity,
4316 .free_irq = free_irq,
4317 .compose_msi_msg = compose_msi_msg,
4318 .msi_alloc_irq = msi_alloc_irq,
4319 .msi_setup_irq = msi_setup_irq,
4320 .setup_hpet_msi = setup_hpet_msi,