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 * 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.
64 * To retain this behavior, we currently advertise that we support
65 * all page sizes that are an order of 4KiB.
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.
70 #define AMD_IOMMU_PGSIZES (~0xFFFUL)
72 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
74 /* A list of preallocated protection domains */
75 static LIST_HEAD(iommu_pd_list);
76 static DEFINE_SPINLOCK(iommu_pd_list_lock);
78 /* List of all available dev_data structures */
79 static LIST_HEAD(dev_data_list);
80 static DEFINE_SPINLOCK(dev_data_list_lock);
82 LIST_HEAD(ioapic_map);
86 * Domain for untranslated devices - only allocated
87 * if iommu=pt passed on kernel cmd line.
89 static struct protection_domain *pt_domain;
91 static struct iommu_ops amd_iommu_ops;
93 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
94 int amd_iommu_max_glx_val = -1;
96 static struct dma_map_ops amd_iommu_dma_ops;
99 * general struct to manage commands send to an IOMMU
105 struct kmem_cache *amd_iommu_irq_cache;
107 static void update_domain(struct protection_domain *domain);
108 static int __init alloc_passthrough_domain(void);
110 /****************************************************************************
114 ****************************************************************************/
116 static struct iommu_dev_data *alloc_dev_data(u16 devid)
118 struct iommu_dev_data *dev_data;
121 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
125 dev_data->devid = devid;
126 atomic_set(&dev_data->bind, 0);
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);
135 static void free_dev_data(struct iommu_dev_data *dev_data)
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);
144 iommu_group_put(dev_data->group);
149 static struct iommu_dev_data *search_dev_data(u16 devid)
151 struct iommu_dev_data *dev_data;
154 spin_lock_irqsave(&dev_data_list_lock, flags);
155 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
156 if (dev_data->devid == devid)
163 spin_unlock_irqrestore(&dev_data_list_lock, flags);
168 static struct iommu_dev_data *find_dev_data(u16 devid)
170 struct iommu_dev_data *dev_data;
172 dev_data = search_dev_data(devid);
174 if (dev_data == NULL)
175 dev_data = alloc_dev_data(devid);
180 static inline u16 get_device_id(struct device *dev)
182 struct pci_dev *pdev = to_pci_dev(dev);
184 return calc_devid(pdev->bus->number, pdev->devfn);
187 static struct iommu_dev_data *get_dev_data(struct device *dev)
189 return dev->archdata.iommu;
192 static bool pci_iommuv2_capable(struct pci_dev *pdev)
194 static const int caps[] = {
197 PCI_EXT_CAP_ID_PASID,
201 for (i = 0; i < 3; ++i) {
202 pos = pci_find_ext_capability(pdev, caps[i]);
210 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
212 struct iommu_dev_data *dev_data;
214 dev_data = get_dev_data(&pdev->dev);
216 return dev_data->errata & (1 << erratum) ? true : false;
220 * In this function the list of preallocated protection domains is traversed to
221 * find the domain for a specific device
223 static struct dma_ops_domain *find_protection_domain(u16 devid)
225 struct dma_ops_domain *entry, *ret = NULL;
227 u16 alias = amd_iommu_alias_table[devid];
229 if (list_empty(&iommu_pd_list))
232 spin_lock_irqsave(&iommu_pd_list_lock, flags);
234 list_for_each_entry(entry, &iommu_pd_list, list) {
235 if (entry->target_dev == devid ||
236 entry->target_dev == alias) {
242 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
248 * This function checks if the driver got a valid device from the caller to
249 * avoid dereferencing invalid pointers.
251 static bool check_device(struct device *dev)
255 if (!dev || !dev->dma_mask)
258 /* No device or no PCI device */
259 if (dev->bus != &pci_bus_type)
262 devid = get_device_id(dev);
264 /* Out of our scope? */
265 if (devid > amd_iommu_last_bdf)
268 if (amd_iommu_rlookup_table[devid] == NULL)
274 static void swap_pci_ref(struct pci_dev **from, struct pci_dev *to)
280 static struct pci_bus *find_hosted_bus(struct pci_bus *bus)
283 if (!pci_is_root_bus(bus))
286 return ERR_PTR(-ENODEV);
292 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
294 static struct pci_dev *get_isolation_root(struct pci_dev *pdev)
296 struct pci_dev *dma_pdev = pdev;
298 /* Account for quirked devices */
299 swap_pci_ref(&dma_pdev, pci_get_dma_source(dma_pdev));
302 * If it's a multifunction device that does not support our
303 * required ACS flags, add to the same group as function 0.
305 if (dma_pdev->multifunction &&
306 !pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS))
307 swap_pci_ref(&dma_pdev,
308 pci_get_slot(dma_pdev->bus,
309 PCI_DEVFN(PCI_SLOT(dma_pdev->devfn),
313 * Devices on the root bus go through the iommu. If that's not us,
314 * find the next upstream device and test ACS up to the root bus.
315 * Finding the next device may require skipping virtual buses.
317 while (!pci_is_root_bus(dma_pdev->bus)) {
318 struct pci_bus *bus = find_hosted_bus(dma_pdev->bus);
322 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
325 swap_pci_ref(&dma_pdev, pci_dev_get(bus->self));
331 static int use_pdev_iommu_group(struct pci_dev *pdev, struct device *dev)
333 struct iommu_group *group = iommu_group_get(&pdev->dev);
337 group = iommu_group_alloc();
339 return PTR_ERR(group);
341 WARN_ON(&pdev->dev != dev);
344 ret = iommu_group_add_device(group, dev);
345 iommu_group_put(group);
349 static int use_dev_data_iommu_group(struct iommu_dev_data *dev_data,
352 if (!dev_data->group) {
353 struct iommu_group *group = iommu_group_alloc();
355 return PTR_ERR(group);
357 dev_data->group = group;
360 return iommu_group_add_device(dev_data->group, dev);
363 static int init_iommu_group(struct device *dev)
365 struct iommu_dev_data *dev_data;
366 struct iommu_group *group;
367 struct pci_dev *dma_pdev;
370 group = iommu_group_get(dev);
372 iommu_group_put(group);
376 dev_data = find_dev_data(get_device_id(dev));
380 if (dev_data->alias_data) {
384 if (dev_data->alias_data->group)
388 * If the alias device exists, it's effectively just a first
389 * level quirk for finding the DMA source.
391 alias = amd_iommu_alias_table[dev_data->devid];
392 dma_pdev = pci_get_bus_and_slot(alias >> 8, alias & 0xff);
394 dma_pdev = get_isolation_root(dma_pdev);
399 * If the alias is virtual, try to find a parent device
400 * and test whether the IOMMU group is actualy rooted above
401 * the alias. Be careful to also test the parent device if
402 * we think the alias is the root of the group.
404 bus = pci_find_bus(0, alias >> 8);
408 bus = find_hosted_bus(bus);
409 if (IS_ERR(bus) || !bus->self)
412 dma_pdev = get_isolation_root(pci_dev_get(bus->self));
413 if (dma_pdev != bus->self || (dma_pdev->multifunction &&
414 !pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS)))
417 pci_dev_put(dma_pdev);
421 dma_pdev = get_isolation_root(pci_dev_get(to_pci_dev(dev)));
423 ret = use_pdev_iommu_group(dma_pdev, dev);
424 pci_dev_put(dma_pdev);
427 return use_dev_data_iommu_group(dev_data->alias_data, dev);
430 static int iommu_init_device(struct device *dev)
432 struct pci_dev *pdev = to_pci_dev(dev);
433 struct iommu_dev_data *dev_data;
437 if (dev->archdata.iommu)
440 dev_data = find_dev_data(get_device_id(dev));
444 alias = amd_iommu_alias_table[dev_data->devid];
445 if (alias != dev_data->devid) {
446 struct iommu_dev_data *alias_data;
448 alias_data = find_dev_data(alias);
449 if (alias_data == NULL) {
450 pr_err("AMD-Vi: Warning: Unhandled device %s\n",
452 free_dev_data(dev_data);
455 dev_data->alias_data = alias_data;
458 ret = init_iommu_group(dev);
462 if (pci_iommuv2_capable(pdev)) {
463 struct amd_iommu *iommu;
465 iommu = amd_iommu_rlookup_table[dev_data->devid];
466 dev_data->iommu_v2 = iommu->is_iommu_v2;
469 dev->archdata.iommu = dev_data;
474 static void iommu_ignore_device(struct device *dev)
478 devid = get_device_id(dev);
479 alias = amd_iommu_alias_table[devid];
481 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
482 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
484 amd_iommu_rlookup_table[devid] = NULL;
485 amd_iommu_rlookup_table[alias] = NULL;
488 static void iommu_uninit_device(struct device *dev)
490 iommu_group_remove_device(dev);
493 * Nothing to do here - we keep dev_data around for unplugged devices
494 * and reuse it when the device is re-plugged - not doing so would
495 * introduce a ton of races.
499 void __init amd_iommu_uninit_devices(void)
501 struct iommu_dev_data *dev_data, *n;
502 struct pci_dev *pdev = NULL;
504 for_each_pci_dev(pdev) {
506 if (!check_device(&pdev->dev))
509 iommu_uninit_device(&pdev->dev);
512 /* Free all of our dev_data structures */
513 list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
514 free_dev_data(dev_data);
517 int __init amd_iommu_init_devices(void)
519 struct pci_dev *pdev = NULL;
522 for_each_pci_dev(pdev) {
524 if (!check_device(&pdev->dev))
527 ret = iommu_init_device(&pdev->dev);
528 if (ret == -ENOTSUPP)
529 iommu_ignore_device(&pdev->dev);
538 amd_iommu_uninit_devices();
542 #ifdef CONFIG_AMD_IOMMU_STATS
545 * Initialization code for statistics collection
548 DECLARE_STATS_COUNTER(compl_wait);
549 DECLARE_STATS_COUNTER(cnt_map_single);
550 DECLARE_STATS_COUNTER(cnt_unmap_single);
551 DECLARE_STATS_COUNTER(cnt_map_sg);
552 DECLARE_STATS_COUNTER(cnt_unmap_sg);
553 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
554 DECLARE_STATS_COUNTER(cnt_free_coherent);
555 DECLARE_STATS_COUNTER(cross_page);
556 DECLARE_STATS_COUNTER(domain_flush_single);
557 DECLARE_STATS_COUNTER(domain_flush_all);
558 DECLARE_STATS_COUNTER(alloced_io_mem);
559 DECLARE_STATS_COUNTER(total_map_requests);
560 DECLARE_STATS_COUNTER(complete_ppr);
561 DECLARE_STATS_COUNTER(invalidate_iotlb);
562 DECLARE_STATS_COUNTER(invalidate_iotlb_all);
563 DECLARE_STATS_COUNTER(pri_requests);
565 static struct dentry *stats_dir;
566 static struct dentry *de_fflush;
568 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
570 if (stats_dir == NULL)
573 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
577 static void amd_iommu_stats_init(void)
579 stats_dir = debugfs_create_dir("amd-iommu", NULL);
580 if (stats_dir == NULL)
583 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
584 &amd_iommu_unmap_flush);
586 amd_iommu_stats_add(&compl_wait);
587 amd_iommu_stats_add(&cnt_map_single);
588 amd_iommu_stats_add(&cnt_unmap_single);
589 amd_iommu_stats_add(&cnt_map_sg);
590 amd_iommu_stats_add(&cnt_unmap_sg);
591 amd_iommu_stats_add(&cnt_alloc_coherent);
592 amd_iommu_stats_add(&cnt_free_coherent);
593 amd_iommu_stats_add(&cross_page);
594 amd_iommu_stats_add(&domain_flush_single);
595 amd_iommu_stats_add(&domain_flush_all);
596 amd_iommu_stats_add(&alloced_io_mem);
597 amd_iommu_stats_add(&total_map_requests);
598 amd_iommu_stats_add(&complete_ppr);
599 amd_iommu_stats_add(&invalidate_iotlb);
600 amd_iommu_stats_add(&invalidate_iotlb_all);
601 amd_iommu_stats_add(&pri_requests);
606 /****************************************************************************
608 * Interrupt handling functions
610 ****************************************************************************/
612 static void dump_dte_entry(u16 devid)
616 for (i = 0; i < 4; ++i)
617 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
618 amd_iommu_dev_table[devid].data[i]);
621 static void dump_command(unsigned long phys_addr)
623 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
626 for (i = 0; i < 4; ++i)
627 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
630 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
632 int type, devid, domid, flags;
633 volatile u32 *event = __evt;
638 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
639 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
640 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
641 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
642 address = (u64)(((u64)event[3]) << 32) | event[2];
645 /* Did we hit the erratum? */
646 if (++count == LOOP_TIMEOUT) {
647 pr_err("AMD-Vi: No event written to event log\n");
654 printk(KERN_ERR "AMD-Vi: Event logged [");
657 case EVENT_TYPE_ILL_DEV:
658 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
659 "address=0x%016llx flags=0x%04x]\n",
660 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
662 dump_dte_entry(devid);
664 case EVENT_TYPE_IO_FAULT:
665 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
666 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
667 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
668 domid, address, flags);
670 case EVENT_TYPE_DEV_TAB_ERR:
671 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
672 "address=0x%016llx flags=0x%04x]\n",
673 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
676 case EVENT_TYPE_PAGE_TAB_ERR:
677 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
678 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
679 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
680 domid, address, flags);
682 case EVENT_TYPE_ILL_CMD:
683 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
684 dump_command(address);
686 case EVENT_TYPE_CMD_HARD_ERR:
687 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
688 "flags=0x%04x]\n", address, flags);
690 case EVENT_TYPE_IOTLB_INV_TO:
691 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
692 "address=0x%016llx]\n",
693 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
696 case EVENT_TYPE_INV_DEV_REQ:
697 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
698 "address=0x%016llx flags=0x%04x]\n",
699 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
703 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
706 memset(__evt, 0, 4 * sizeof(u32));
709 static void iommu_poll_events(struct amd_iommu *iommu)
714 spin_lock_irqsave(&iommu->lock, flags);
716 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
717 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
719 while (head != tail) {
720 iommu_print_event(iommu, iommu->evt_buf + head);
721 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
724 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
726 spin_unlock_irqrestore(&iommu->lock, flags);
729 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
731 struct amd_iommu_fault fault;
733 INC_STATS_COUNTER(pri_requests);
735 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
736 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
740 fault.address = raw[1];
741 fault.pasid = PPR_PASID(raw[0]);
742 fault.device_id = PPR_DEVID(raw[0]);
743 fault.tag = PPR_TAG(raw[0]);
744 fault.flags = PPR_FLAGS(raw[0]);
746 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
749 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
754 if (iommu->ppr_log == NULL)
757 /* enable ppr interrupts again */
758 writel(MMIO_STATUS_PPR_INT_MASK, iommu->mmio_base + MMIO_STATUS_OFFSET);
760 spin_lock_irqsave(&iommu->lock, flags);
762 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
763 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
765 while (head != tail) {
770 raw = (u64 *)(iommu->ppr_log + head);
773 * Hardware bug: Interrupt may arrive before the entry is
774 * written to memory. If this happens we need to wait for the
777 for (i = 0; i < LOOP_TIMEOUT; ++i) {
778 if (PPR_REQ_TYPE(raw[0]) != 0)
783 /* Avoid memcpy function-call overhead */
788 * To detect the hardware bug we need to clear the entry
791 raw[0] = raw[1] = 0UL;
793 /* Update head pointer of hardware ring-buffer */
794 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
795 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
798 * Release iommu->lock because ppr-handling might need to
801 spin_unlock_irqrestore(&iommu->lock, flags);
803 /* Handle PPR entry */
804 iommu_handle_ppr_entry(iommu, entry);
806 spin_lock_irqsave(&iommu->lock, flags);
808 /* Refresh ring-buffer information */
809 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
810 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
813 spin_unlock_irqrestore(&iommu->lock, flags);
816 irqreturn_t amd_iommu_int_thread(int irq, void *data)
818 struct amd_iommu *iommu;
820 for_each_iommu(iommu) {
821 iommu_poll_events(iommu);
822 iommu_poll_ppr_log(iommu);
828 irqreturn_t amd_iommu_int_handler(int irq, void *data)
830 return IRQ_WAKE_THREAD;
833 /****************************************************************************
835 * IOMMU command queuing functions
837 ****************************************************************************/
839 static int wait_on_sem(volatile u64 *sem)
843 while (*sem == 0 && i < LOOP_TIMEOUT) {
848 if (i == LOOP_TIMEOUT) {
849 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
856 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
857 struct iommu_cmd *cmd,
862 target = iommu->cmd_buf + tail;
863 tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
865 /* Copy command to buffer */
866 memcpy(target, cmd, sizeof(*cmd));
868 /* Tell the IOMMU about it */
869 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
872 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
874 WARN_ON(address & 0x7ULL);
876 memset(cmd, 0, sizeof(*cmd));
877 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
878 cmd->data[1] = upper_32_bits(__pa(address));
880 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
883 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
885 memset(cmd, 0, sizeof(*cmd));
886 cmd->data[0] = devid;
887 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
890 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
891 size_t size, u16 domid, int pde)
896 pages = iommu_num_pages(address, size, PAGE_SIZE);
901 * If we have to flush more than one page, flush all
902 * TLB entries for this domain
904 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
908 address &= PAGE_MASK;
910 memset(cmd, 0, sizeof(*cmd));
911 cmd->data[1] |= domid;
912 cmd->data[2] = lower_32_bits(address);
913 cmd->data[3] = upper_32_bits(address);
914 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
915 if (s) /* size bit - we flush more than one 4kb page */
916 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
917 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
918 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
921 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
922 u64 address, size_t size)
927 pages = iommu_num_pages(address, size, PAGE_SIZE);
932 * If we have to flush more than one page, flush all
933 * TLB entries for this domain
935 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
939 address &= PAGE_MASK;
941 memset(cmd, 0, sizeof(*cmd));
942 cmd->data[0] = devid;
943 cmd->data[0] |= (qdep & 0xff) << 24;
944 cmd->data[1] = devid;
945 cmd->data[2] = lower_32_bits(address);
946 cmd->data[3] = upper_32_bits(address);
947 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
949 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
952 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
953 u64 address, bool size)
955 memset(cmd, 0, sizeof(*cmd));
957 address &= ~(0xfffULL);
959 cmd->data[0] = pasid & PASID_MASK;
960 cmd->data[1] = domid;
961 cmd->data[2] = lower_32_bits(address);
962 cmd->data[3] = upper_32_bits(address);
963 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
964 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
966 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
967 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
970 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
971 int qdep, u64 address, bool size)
973 memset(cmd, 0, sizeof(*cmd));
975 address &= ~(0xfffULL);
977 cmd->data[0] = devid;
978 cmd->data[0] |= (pasid & 0xff) << 16;
979 cmd->data[0] |= (qdep & 0xff) << 24;
980 cmd->data[1] = devid;
981 cmd->data[1] |= ((pasid >> 8) & 0xfff) << 16;
982 cmd->data[2] = lower_32_bits(address);
983 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
984 cmd->data[3] = upper_32_bits(address);
986 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
987 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
990 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
991 int status, int tag, bool gn)
993 memset(cmd, 0, sizeof(*cmd));
995 cmd->data[0] = devid;
997 cmd->data[1] = pasid & PASID_MASK;
998 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
1000 cmd->data[3] = tag & 0x1ff;
1001 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
1003 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
1006 static void build_inv_all(struct iommu_cmd *cmd)
1008 memset(cmd, 0, sizeof(*cmd));
1009 CMD_SET_TYPE(cmd, CMD_INV_ALL);
1012 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
1014 memset(cmd, 0, sizeof(*cmd));
1015 cmd->data[0] = devid;
1016 CMD_SET_TYPE(cmd, CMD_INV_IRT);
1020 * Writes the command to the IOMMUs command buffer and informs the
1021 * hardware about the new command.
1023 static int iommu_queue_command_sync(struct amd_iommu *iommu,
1024 struct iommu_cmd *cmd,
1027 u32 left, tail, head, next_tail;
1028 unsigned long flags;
1030 WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
1033 spin_lock_irqsave(&iommu->lock, flags);
1035 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
1036 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
1037 next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
1038 left = (head - next_tail) % iommu->cmd_buf_size;
1041 struct iommu_cmd sync_cmd;
1042 volatile u64 sem = 0;
1045 build_completion_wait(&sync_cmd, (u64)&sem);
1046 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
1048 spin_unlock_irqrestore(&iommu->lock, flags);
1050 if ((ret = wait_on_sem(&sem)) != 0)
1056 copy_cmd_to_buffer(iommu, cmd, tail);
1058 /* We need to sync now to make sure all commands are processed */
1059 iommu->need_sync = sync;
1061 spin_unlock_irqrestore(&iommu->lock, flags);
1066 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
1068 return iommu_queue_command_sync(iommu, cmd, true);
1072 * This function queues a completion wait command into the command
1073 * buffer of an IOMMU
1075 static int iommu_completion_wait(struct amd_iommu *iommu)
1077 struct iommu_cmd cmd;
1078 volatile u64 sem = 0;
1081 if (!iommu->need_sync)
1084 build_completion_wait(&cmd, (u64)&sem);
1086 ret = iommu_queue_command_sync(iommu, &cmd, false);
1090 return wait_on_sem(&sem);
1093 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1095 struct iommu_cmd cmd;
1097 build_inv_dte(&cmd, devid);
1099 return iommu_queue_command(iommu, &cmd);
1102 static void iommu_flush_dte_all(struct amd_iommu *iommu)
1106 for (devid = 0; devid <= 0xffff; ++devid)
1107 iommu_flush_dte(iommu, devid);
1109 iommu_completion_wait(iommu);
1113 * This function uses heavy locking and may disable irqs for some time. But
1114 * this is no issue because it is only called during resume.
1116 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1120 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1121 struct iommu_cmd cmd;
1122 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1124 iommu_queue_command(iommu, &cmd);
1127 iommu_completion_wait(iommu);
1130 static void iommu_flush_all(struct amd_iommu *iommu)
1132 struct iommu_cmd cmd;
1134 build_inv_all(&cmd);
1136 iommu_queue_command(iommu, &cmd);
1137 iommu_completion_wait(iommu);
1140 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1142 struct iommu_cmd cmd;
1144 build_inv_irt(&cmd, devid);
1146 iommu_queue_command(iommu, &cmd);
1149 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1153 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1154 iommu_flush_irt(iommu, devid);
1156 iommu_completion_wait(iommu);
1159 void iommu_flush_all_caches(struct amd_iommu *iommu)
1161 if (iommu_feature(iommu, FEATURE_IA)) {
1162 iommu_flush_all(iommu);
1164 iommu_flush_dte_all(iommu);
1165 iommu_flush_irt_all(iommu);
1166 iommu_flush_tlb_all(iommu);
1171 * Command send function for flushing on-device TLB
1173 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1174 u64 address, size_t size)
1176 struct amd_iommu *iommu;
1177 struct iommu_cmd cmd;
1180 qdep = dev_data->ats.qdep;
1181 iommu = amd_iommu_rlookup_table[dev_data->devid];
1183 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1185 return iommu_queue_command(iommu, &cmd);
1189 * Command send function for invalidating a device table entry
1191 static int device_flush_dte(struct iommu_dev_data *dev_data)
1193 struct amd_iommu *iommu;
1196 iommu = amd_iommu_rlookup_table[dev_data->devid];
1198 ret = iommu_flush_dte(iommu, dev_data->devid);
1202 if (dev_data->ats.enabled)
1203 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1209 * TLB invalidation function which is called from the mapping functions.
1210 * It invalidates a single PTE if the range to flush is within a single
1211 * page. Otherwise it flushes the whole TLB of the IOMMU.
1213 static void __domain_flush_pages(struct protection_domain *domain,
1214 u64 address, size_t size, int pde)
1216 struct iommu_dev_data *dev_data;
1217 struct iommu_cmd cmd;
1220 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1222 for (i = 0; i < amd_iommus_present; ++i) {
1223 if (!domain->dev_iommu[i])
1227 * Devices of this domain are behind this IOMMU
1228 * We need a TLB flush
1230 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1233 list_for_each_entry(dev_data, &domain->dev_list, list) {
1235 if (!dev_data->ats.enabled)
1238 ret |= device_flush_iotlb(dev_data, address, size);
1244 static void domain_flush_pages(struct protection_domain *domain,
1245 u64 address, size_t size)
1247 __domain_flush_pages(domain, address, size, 0);
1250 /* Flush the whole IO/TLB for a given protection domain */
1251 static void domain_flush_tlb(struct protection_domain *domain)
1253 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1256 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1257 static void domain_flush_tlb_pde(struct protection_domain *domain)
1259 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1262 static void domain_flush_complete(struct protection_domain *domain)
1266 for (i = 0; i < amd_iommus_present; ++i) {
1267 if (!domain->dev_iommu[i])
1271 * Devices of this domain are behind this IOMMU
1272 * We need to wait for completion of all commands.
1274 iommu_completion_wait(amd_iommus[i]);
1280 * This function flushes the DTEs for all devices in domain
1282 static void domain_flush_devices(struct protection_domain *domain)
1284 struct iommu_dev_data *dev_data;
1286 list_for_each_entry(dev_data, &domain->dev_list, list)
1287 device_flush_dte(dev_data);
1290 /****************************************************************************
1292 * The functions below are used the create the page table mappings for
1293 * unity mapped regions.
1295 ****************************************************************************/
1298 * This function is used to add another level to an IO page table. Adding
1299 * another level increases the size of the address space by 9 bits to a size up
1302 static bool increase_address_space(struct protection_domain *domain,
1307 if (domain->mode == PAGE_MODE_6_LEVEL)
1308 /* address space already 64 bit large */
1311 pte = (void *)get_zeroed_page(gfp);
1315 *pte = PM_LEVEL_PDE(domain->mode,
1316 virt_to_phys(domain->pt_root));
1317 domain->pt_root = pte;
1319 domain->updated = true;
1324 static u64 *alloc_pte(struct protection_domain *domain,
1325 unsigned long address,
1326 unsigned long page_size,
1333 BUG_ON(!is_power_of_2(page_size));
1335 while (address > PM_LEVEL_SIZE(domain->mode))
1336 increase_address_space(domain, gfp);
1338 level = domain->mode - 1;
1339 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1340 address = PAGE_SIZE_ALIGN(address, page_size);
1341 end_lvl = PAGE_SIZE_LEVEL(page_size);
1343 while (level > end_lvl) {
1344 if (!IOMMU_PTE_PRESENT(*pte)) {
1345 page = (u64 *)get_zeroed_page(gfp);
1348 *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1351 /* No level skipping support yet */
1352 if (PM_PTE_LEVEL(*pte) != level)
1357 pte = IOMMU_PTE_PAGE(*pte);
1359 if (pte_page && level == end_lvl)
1362 pte = &pte[PM_LEVEL_INDEX(level, address)];
1369 * This function checks if there is a PTE for a given dma address. If
1370 * there is one, it returns the pointer to it.
1372 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
1377 if (address > PM_LEVEL_SIZE(domain->mode))
1380 level = domain->mode - 1;
1381 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1386 if (!IOMMU_PTE_PRESENT(*pte))
1390 if (PM_PTE_LEVEL(*pte) == 0x07) {
1391 unsigned long pte_mask, __pte;
1394 * If we have a series of large PTEs, make
1395 * sure to return a pointer to the first one.
1397 pte_mask = PTE_PAGE_SIZE(*pte);
1398 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1399 __pte = ((unsigned long)pte) & pte_mask;
1401 return (u64 *)__pte;
1404 /* No level skipping support yet */
1405 if (PM_PTE_LEVEL(*pte) != level)
1410 /* Walk to the next level */
1411 pte = IOMMU_PTE_PAGE(*pte);
1412 pte = &pte[PM_LEVEL_INDEX(level, address)];
1419 * Generic mapping functions. It maps a physical address into a DMA
1420 * address space. It allocates the page table pages if necessary.
1421 * In the future it can be extended to a generic mapping function
1422 * supporting all features of AMD IOMMU page tables like level skipping
1423 * and full 64 bit address spaces.
1425 static int iommu_map_page(struct protection_domain *dom,
1426 unsigned long bus_addr,
1427 unsigned long phys_addr,
1429 unsigned long page_size)
1434 if (!(prot & IOMMU_PROT_MASK))
1437 bus_addr = PAGE_ALIGN(bus_addr);
1438 phys_addr = PAGE_ALIGN(phys_addr);
1439 count = PAGE_SIZE_PTE_COUNT(page_size);
1440 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1442 for (i = 0; i < count; ++i)
1443 if (IOMMU_PTE_PRESENT(pte[i]))
1446 if (page_size > PAGE_SIZE) {
1447 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1448 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1450 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1452 if (prot & IOMMU_PROT_IR)
1453 __pte |= IOMMU_PTE_IR;
1454 if (prot & IOMMU_PROT_IW)
1455 __pte |= IOMMU_PTE_IW;
1457 for (i = 0; i < count; ++i)
1465 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1466 unsigned long bus_addr,
1467 unsigned long page_size)
1469 unsigned long long unmap_size, unmapped;
1472 BUG_ON(!is_power_of_2(page_size));
1476 while (unmapped < page_size) {
1478 pte = fetch_pte(dom, bus_addr);
1482 * No PTE for this address
1483 * move forward in 4kb steps
1485 unmap_size = PAGE_SIZE;
1486 } else if (PM_PTE_LEVEL(*pte) == 0) {
1487 /* 4kb PTE found for this address */
1488 unmap_size = PAGE_SIZE;
1493 /* Large PTE found which maps this address */
1494 unmap_size = PTE_PAGE_SIZE(*pte);
1495 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1496 for (i = 0; i < count; i++)
1500 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1501 unmapped += unmap_size;
1504 BUG_ON(!is_power_of_2(unmapped));
1510 * This function checks if a specific unity mapping entry is needed for
1511 * this specific IOMMU.
1513 static int iommu_for_unity_map(struct amd_iommu *iommu,
1514 struct unity_map_entry *entry)
1518 for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1519 bdf = amd_iommu_alias_table[i];
1520 if (amd_iommu_rlookup_table[bdf] == iommu)
1528 * This function actually applies the mapping to the page table of the
1531 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1532 struct unity_map_entry *e)
1537 for (addr = e->address_start; addr < e->address_end;
1538 addr += PAGE_SIZE) {
1539 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1544 * if unity mapping is in aperture range mark the page
1545 * as allocated in the aperture
1547 if (addr < dma_dom->aperture_size)
1548 __set_bit(addr >> PAGE_SHIFT,
1549 dma_dom->aperture[0]->bitmap);
1556 * Init the unity mappings for a specific IOMMU in the system
1558 * Basically iterates over all unity mapping entries and applies them to
1559 * the default domain DMA of that IOMMU if necessary.
1561 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1563 struct unity_map_entry *entry;
1566 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1567 if (!iommu_for_unity_map(iommu, entry))
1569 ret = dma_ops_unity_map(iommu->default_dom, entry);
1578 * Inits the unity mappings required for a specific device
1580 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1583 struct unity_map_entry *e;
1586 list_for_each_entry(e, &amd_iommu_unity_map, list) {
1587 if (!(devid >= e->devid_start && devid <= e->devid_end))
1589 ret = dma_ops_unity_map(dma_dom, e);
1597 /****************************************************************************
1599 * The next functions belong to the address allocator for the dma_ops
1600 * interface functions. They work like the allocators in the other IOMMU
1601 * drivers. Its basically a bitmap which marks the allocated pages in
1602 * the aperture. Maybe it could be enhanced in the future to a more
1603 * efficient allocator.
1605 ****************************************************************************/
1608 * The address allocator core functions.
1610 * called with domain->lock held
1614 * Used to reserve address ranges in the aperture (e.g. for exclusion
1617 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1618 unsigned long start_page,
1621 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1623 if (start_page + pages > last_page)
1624 pages = last_page - start_page;
1626 for (i = start_page; i < start_page + pages; ++i) {
1627 int index = i / APERTURE_RANGE_PAGES;
1628 int page = i % APERTURE_RANGE_PAGES;
1629 __set_bit(page, dom->aperture[index]->bitmap);
1634 * This function is used to add a new aperture range to an existing
1635 * aperture in case of dma_ops domain allocation or address allocation
1638 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1639 bool populate, gfp_t gfp)
1641 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1642 struct amd_iommu *iommu;
1643 unsigned long i, old_size;
1645 #ifdef CONFIG_IOMMU_STRESS
1649 if (index >= APERTURE_MAX_RANGES)
1652 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1653 if (!dma_dom->aperture[index])
1656 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1657 if (!dma_dom->aperture[index]->bitmap)
1660 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1663 unsigned long address = dma_dom->aperture_size;
1664 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1665 u64 *pte, *pte_page;
1667 for (i = 0; i < num_ptes; ++i) {
1668 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1673 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1675 address += APERTURE_RANGE_SIZE / 64;
1679 old_size = dma_dom->aperture_size;
1680 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1682 /* Reserve address range used for MSI messages */
1683 if (old_size < MSI_ADDR_BASE_LO &&
1684 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1685 unsigned long spage;
1688 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1689 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1691 dma_ops_reserve_addresses(dma_dom, spage, pages);
1694 /* Initialize the exclusion range if necessary */
1695 for_each_iommu(iommu) {
1696 if (iommu->exclusion_start &&
1697 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1698 && iommu->exclusion_start < dma_dom->aperture_size) {
1699 unsigned long startpage;
1700 int pages = iommu_num_pages(iommu->exclusion_start,
1701 iommu->exclusion_length,
1703 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1704 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1709 * Check for areas already mapped as present in the new aperture
1710 * range and mark those pages as reserved in the allocator. Such
1711 * mappings may already exist as a result of requested unity
1712 * mappings for devices.
1714 for (i = dma_dom->aperture[index]->offset;
1715 i < dma_dom->aperture_size;
1717 u64 *pte = fetch_pte(&dma_dom->domain, i);
1718 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1721 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1724 update_domain(&dma_dom->domain);
1729 update_domain(&dma_dom->domain);
1731 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1733 kfree(dma_dom->aperture[index]);
1734 dma_dom->aperture[index] = NULL;
1739 static unsigned long dma_ops_area_alloc(struct device *dev,
1740 struct dma_ops_domain *dom,
1742 unsigned long align_mask,
1744 unsigned long start)
1746 unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1747 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1748 int i = start >> APERTURE_RANGE_SHIFT;
1749 unsigned long boundary_size;
1750 unsigned long address = -1;
1751 unsigned long limit;
1753 next_bit >>= PAGE_SHIFT;
1755 boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1756 PAGE_SIZE) >> PAGE_SHIFT;
1758 for (;i < max_index; ++i) {
1759 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1761 if (dom->aperture[i]->offset >= dma_mask)
1764 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1765 dma_mask >> PAGE_SHIFT);
1767 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1768 limit, next_bit, pages, 0,
1769 boundary_size, align_mask);
1770 if (address != -1) {
1771 address = dom->aperture[i]->offset +
1772 (address << PAGE_SHIFT);
1773 dom->next_address = address + (pages << PAGE_SHIFT);
1783 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1784 struct dma_ops_domain *dom,
1786 unsigned long align_mask,
1789 unsigned long address;
1791 #ifdef CONFIG_IOMMU_STRESS
1792 dom->next_address = 0;
1793 dom->need_flush = true;
1796 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1797 dma_mask, dom->next_address);
1799 if (address == -1) {
1800 dom->next_address = 0;
1801 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1803 dom->need_flush = true;
1806 if (unlikely(address == -1))
1807 address = DMA_ERROR_CODE;
1809 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1815 * The address free function.
1817 * called with domain->lock held
1819 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1820 unsigned long address,
1823 unsigned i = address >> APERTURE_RANGE_SHIFT;
1824 struct aperture_range *range = dom->aperture[i];
1826 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1828 #ifdef CONFIG_IOMMU_STRESS
1833 if (address >= dom->next_address)
1834 dom->need_flush = true;
1836 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1838 bitmap_clear(range->bitmap, address, pages);
1842 /****************************************************************************
1844 * The next functions belong to the domain allocation. A domain is
1845 * allocated for every IOMMU as the default domain. If device isolation
1846 * is enabled, every device get its own domain. The most important thing
1847 * about domains is the page table mapping the DMA address space they
1850 ****************************************************************************/
1853 * This function adds a protection domain to the global protection domain list
1855 static void add_domain_to_list(struct protection_domain *domain)
1857 unsigned long flags;
1859 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1860 list_add(&domain->list, &amd_iommu_pd_list);
1861 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1865 * This function removes a protection domain to the global
1866 * protection domain list
1868 static void del_domain_from_list(struct protection_domain *domain)
1870 unsigned long flags;
1872 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1873 list_del(&domain->list);
1874 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1877 static u16 domain_id_alloc(void)
1879 unsigned long flags;
1882 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1883 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1885 if (id > 0 && id < MAX_DOMAIN_ID)
1886 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1889 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1894 static void domain_id_free(int id)
1896 unsigned long flags;
1898 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1899 if (id > 0 && id < MAX_DOMAIN_ID)
1900 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1901 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1904 static void free_pagetable(struct protection_domain *domain)
1909 p1 = domain->pt_root;
1914 for (i = 0; i < 512; ++i) {
1915 if (!IOMMU_PTE_PRESENT(p1[i]))
1918 p2 = IOMMU_PTE_PAGE(p1[i]);
1919 for (j = 0; j < 512; ++j) {
1920 if (!IOMMU_PTE_PRESENT(p2[j]))
1922 p3 = IOMMU_PTE_PAGE(p2[j]);
1923 free_page((unsigned long)p3);
1926 free_page((unsigned long)p2);
1929 free_page((unsigned long)p1);
1931 domain->pt_root = NULL;
1934 static void free_gcr3_tbl_level1(u64 *tbl)
1939 for (i = 0; i < 512; ++i) {
1940 if (!(tbl[i] & GCR3_VALID))
1943 ptr = __va(tbl[i] & PAGE_MASK);
1945 free_page((unsigned long)ptr);
1949 static void free_gcr3_tbl_level2(u64 *tbl)
1954 for (i = 0; i < 512; ++i) {
1955 if (!(tbl[i] & GCR3_VALID))
1958 ptr = __va(tbl[i] & PAGE_MASK);
1960 free_gcr3_tbl_level1(ptr);
1964 static void free_gcr3_table(struct protection_domain *domain)
1966 if (domain->glx == 2)
1967 free_gcr3_tbl_level2(domain->gcr3_tbl);
1968 else if (domain->glx == 1)
1969 free_gcr3_tbl_level1(domain->gcr3_tbl);
1970 else if (domain->glx != 0)
1973 free_page((unsigned long)domain->gcr3_tbl);
1977 * Free a domain, only used if something went wrong in the
1978 * allocation path and we need to free an already allocated page table
1980 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1987 del_domain_from_list(&dom->domain);
1989 free_pagetable(&dom->domain);
1991 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1992 if (!dom->aperture[i])
1994 free_page((unsigned long)dom->aperture[i]->bitmap);
1995 kfree(dom->aperture[i]);
2002 * Allocates a new protection domain usable for the dma_ops functions.
2003 * It also initializes the page table and the address allocator data
2004 * structures required for the dma_ops interface
2006 static struct dma_ops_domain *dma_ops_domain_alloc(void)
2008 struct dma_ops_domain *dma_dom;
2010 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
2014 spin_lock_init(&dma_dom->domain.lock);
2016 dma_dom->domain.id = domain_id_alloc();
2017 if (dma_dom->domain.id == 0)
2019 INIT_LIST_HEAD(&dma_dom->domain.dev_list);
2020 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
2021 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2022 dma_dom->domain.flags = PD_DMA_OPS_MASK;
2023 dma_dom->domain.priv = dma_dom;
2024 if (!dma_dom->domain.pt_root)
2027 dma_dom->need_flush = false;
2028 dma_dom->target_dev = 0xffff;
2030 add_domain_to_list(&dma_dom->domain);
2032 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
2036 * mark the first page as allocated so we never return 0 as
2037 * a valid dma-address. So we can use 0 as error value
2039 dma_dom->aperture[0]->bitmap[0] = 1;
2040 dma_dom->next_address = 0;
2046 dma_ops_domain_free(dma_dom);
2052 * little helper function to check whether a given protection domain is a
2055 static bool dma_ops_domain(struct protection_domain *domain)
2057 return domain->flags & PD_DMA_OPS_MASK;
2060 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
2065 if (domain->mode != PAGE_MODE_NONE)
2066 pte_root = virt_to_phys(domain->pt_root);
2068 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
2069 << DEV_ENTRY_MODE_SHIFT;
2070 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
2072 flags = amd_iommu_dev_table[devid].data[1];
2075 flags |= DTE_FLAG_IOTLB;
2077 if (domain->flags & PD_IOMMUV2_MASK) {
2078 u64 gcr3 = __pa(domain->gcr3_tbl);
2079 u64 glx = domain->glx;
2082 pte_root |= DTE_FLAG_GV;
2083 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
2085 /* First mask out possible old values for GCR3 table */
2086 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
2089 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
2092 /* Encode GCR3 table into DTE */
2093 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
2096 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
2099 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
2103 flags &= ~(0xffffUL);
2104 flags |= domain->id;
2106 amd_iommu_dev_table[devid].data[1] = flags;
2107 amd_iommu_dev_table[devid].data[0] = pte_root;
2110 static void clear_dte_entry(u16 devid)
2112 /* remove entry from the device table seen by the hardware */
2113 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
2114 amd_iommu_dev_table[devid].data[1] = 0;
2116 amd_iommu_apply_erratum_63(devid);
2119 static void do_attach(struct iommu_dev_data *dev_data,
2120 struct protection_domain *domain)
2122 struct amd_iommu *iommu;
2125 iommu = amd_iommu_rlookup_table[dev_data->devid];
2126 ats = dev_data->ats.enabled;
2128 /* Update data structures */
2129 dev_data->domain = domain;
2130 list_add(&dev_data->list, &domain->dev_list);
2131 set_dte_entry(dev_data->devid, domain, ats);
2133 /* Do reference counting */
2134 domain->dev_iommu[iommu->index] += 1;
2135 domain->dev_cnt += 1;
2137 /* Flush the DTE entry */
2138 device_flush_dte(dev_data);
2141 static void do_detach(struct iommu_dev_data *dev_data)
2143 struct amd_iommu *iommu;
2145 iommu = amd_iommu_rlookup_table[dev_data->devid];
2147 /* decrease reference counters */
2148 dev_data->domain->dev_iommu[iommu->index] -= 1;
2149 dev_data->domain->dev_cnt -= 1;
2151 /* Update data structures */
2152 dev_data->domain = NULL;
2153 list_del(&dev_data->list);
2154 clear_dte_entry(dev_data->devid);
2156 /* Flush the DTE entry */
2157 device_flush_dte(dev_data);
2161 * If a device is not yet associated with a domain, this function does
2162 * assigns it visible for the hardware
2164 static int __attach_device(struct iommu_dev_data *dev_data,
2165 struct protection_domain *domain)
2170 spin_lock(&domain->lock);
2172 if (dev_data->alias_data != NULL) {
2173 struct iommu_dev_data *alias_data = dev_data->alias_data;
2175 /* Some sanity checks */
2177 if (alias_data->domain != NULL &&
2178 alias_data->domain != domain)
2181 if (dev_data->domain != NULL &&
2182 dev_data->domain != domain)
2185 /* Do real assignment */
2186 if (alias_data->domain == NULL)
2187 do_attach(alias_data, domain);
2189 atomic_inc(&alias_data->bind);
2192 if (dev_data->domain == NULL)
2193 do_attach(dev_data, domain);
2195 atomic_inc(&dev_data->bind);
2202 spin_unlock(&domain->lock);
2208 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2210 pci_disable_ats(pdev);
2211 pci_disable_pri(pdev);
2212 pci_disable_pasid(pdev);
2215 /* FIXME: Change generic reset-function to do the same */
2216 static int pri_reset_while_enabled(struct pci_dev *pdev)
2221 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2225 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2226 control |= PCI_PRI_CTRL_RESET;
2227 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2232 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2237 /* FIXME: Hardcode number of outstanding requests for now */
2239 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2241 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2243 /* Only allow access to user-accessible pages */
2244 ret = pci_enable_pasid(pdev, 0);
2248 /* First reset the PRI state of the device */
2249 ret = pci_reset_pri(pdev);
2254 ret = pci_enable_pri(pdev, reqs);
2259 ret = pri_reset_while_enabled(pdev);
2264 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2271 pci_disable_pri(pdev);
2272 pci_disable_pasid(pdev);
2277 /* FIXME: Move this to PCI code */
2278 #define PCI_PRI_TLP_OFF (1 << 15)
2280 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2285 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2289 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2291 return (status & PCI_PRI_TLP_OFF) ? true : false;
2295 * If a device is not yet associated with a domain, this function
2296 * assigns it visible for the hardware
2298 static int attach_device(struct device *dev,
2299 struct protection_domain *domain)
2301 struct pci_dev *pdev = to_pci_dev(dev);
2302 struct iommu_dev_data *dev_data;
2303 unsigned long flags;
2306 dev_data = get_dev_data(dev);
2308 if (domain->flags & PD_IOMMUV2_MASK) {
2309 if (!dev_data->iommu_v2 || !dev_data->passthrough)
2312 if (pdev_iommuv2_enable(pdev) != 0)
2315 dev_data->ats.enabled = true;
2316 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2317 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2318 } else if (amd_iommu_iotlb_sup &&
2319 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2320 dev_data->ats.enabled = true;
2321 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2324 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2325 ret = __attach_device(dev_data, domain);
2326 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2329 * We might boot into a crash-kernel here. The crashed kernel
2330 * left the caches in the IOMMU dirty. So we have to flush
2331 * here to evict all dirty stuff.
2333 domain_flush_tlb_pde(domain);
2339 * Removes a device from a protection domain (unlocked)
2341 static void __detach_device(struct iommu_dev_data *dev_data)
2343 struct protection_domain *domain;
2344 unsigned long flags;
2346 BUG_ON(!dev_data->domain);
2348 domain = dev_data->domain;
2350 spin_lock_irqsave(&domain->lock, flags);
2352 if (dev_data->alias_data != NULL) {
2353 struct iommu_dev_data *alias_data = dev_data->alias_data;
2355 if (atomic_dec_and_test(&alias_data->bind))
2356 do_detach(alias_data);
2359 if (atomic_dec_and_test(&dev_data->bind))
2360 do_detach(dev_data);
2362 spin_unlock_irqrestore(&domain->lock, flags);
2365 * If we run in passthrough mode the device must be assigned to the
2366 * passthrough domain if it is detached from any other domain.
2367 * Make sure we can deassign from the pt_domain itself.
2369 if (dev_data->passthrough &&
2370 (dev_data->domain == NULL && domain != pt_domain))
2371 __attach_device(dev_data, pt_domain);
2375 * Removes a device from a protection domain (with devtable_lock held)
2377 static void detach_device(struct device *dev)
2379 struct protection_domain *domain;
2380 struct iommu_dev_data *dev_data;
2381 unsigned long flags;
2383 dev_data = get_dev_data(dev);
2384 domain = dev_data->domain;
2386 /* lock device table */
2387 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2388 __detach_device(dev_data);
2389 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2391 if (domain->flags & PD_IOMMUV2_MASK)
2392 pdev_iommuv2_disable(to_pci_dev(dev));
2393 else if (dev_data->ats.enabled)
2394 pci_disable_ats(to_pci_dev(dev));
2396 dev_data->ats.enabled = false;
2400 * Find out the protection domain structure for a given PCI device. This
2401 * will give us the pointer to the page table root for example.
2403 static struct protection_domain *domain_for_device(struct device *dev)
2405 struct iommu_dev_data *dev_data;
2406 struct protection_domain *dom = NULL;
2407 unsigned long flags;
2409 dev_data = get_dev_data(dev);
2411 if (dev_data->domain)
2412 return dev_data->domain;
2414 if (dev_data->alias_data != NULL) {
2415 struct iommu_dev_data *alias_data = dev_data->alias_data;
2417 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
2418 if (alias_data->domain != NULL) {
2419 __attach_device(dev_data, alias_data->domain);
2420 dom = alias_data->domain;
2422 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2428 static int device_change_notifier(struct notifier_block *nb,
2429 unsigned long action, void *data)
2431 struct dma_ops_domain *dma_domain;
2432 struct protection_domain *domain;
2433 struct iommu_dev_data *dev_data;
2434 struct device *dev = data;
2435 struct amd_iommu *iommu;
2436 unsigned long flags;
2439 if (!check_device(dev))
2442 devid = get_device_id(dev);
2443 iommu = amd_iommu_rlookup_table[devid];
2444 dev_data = get_dev_data(dev);
2447 case BUS_NOTIFY_UNBOUND_DRIVER:
2449 domain = domain_for_device(dev);
2453 if (dev_data->passthrough)
2457 case BUS_NOTIFY_ADD_DEVICE:
2459 iommu_init_device(dev);
2462 * dev_data is still NULL and
2463 * got initialized in iommu_init_device
2465 dev_data = get_dev_data(dev);
2467 if (iommu_pass_through || dev_data->iommu_v2) {
2468 dev_data->passthrough = true;
2469 attach_device(dev, pt_domain);
2473 domain = domain_for_device(dev);
2475 /* allocate a protection domain if a device is added */
2476 dma_domain = find_protection_domain(devid);
2479 dma_domain = dma_ops_domain_alloc();
2482 dma_domain->target_dev = devid;
2484 spin_lock_irqsave(&iommu_pd_list_lock, flags);
2485 list_add_tail(&dma_domain->list, &iommu_pd_list);
2486 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
2488 dev_data = get_dev_data(dev);
2490 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2493 case BUS_NOTIFY_DEL_DEVICE:
2495 iommu_uninit_device(dev);
2501 iommu_completion_wait(iommu);
2507 static struct notifier_block device_nb = {
2508 .notifier_call = device_change_notifier,
2511 void amd_iommu_init_notifier(void)
2513 bus_register_notifier(&pci_bus_type, &device_nb);
2516 /*****************************************************************************
2518 * The next functions belong to the dma_ops mapping/unmapping code.
2520 *****************************************************************************/
2523 * In the dma_ops path we only have the struct device. This function
2524 * finds the corresponding IOMMU, the protection domain and the
2525 * requestor id for a given device.
2526 * If the device is not yet associated with a domain this is also done
2529 static struct protection_domain *get_domain(struct device *dev)
2531 struct protection_domain *domain;
2532 struct dma_ops_domain *dma_dom;
2533 u16 devid = get_device_id(dev);
2535 if (!check_device(dev))
2536 return ERR_PTR(-EINVAL);
2538 domain = domain_for_device(dev);
2539 if (domain != NULL && !dma_ops_domain(domain))
2540 return ERR_PTR(-EBUSY);
2545 /* Device not bound yet - bind it */
2546 dma_dom = find_protection_domain(devid);
2548 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
2549 attach_device(dev, &dma_dom->domain);
2550 DUMP_printk("Using protection domain %d for device %s\n",
2551 dma_dom->domain.id, dev_name(dev));
2553 return &dma_dom->domain;
2556 static void update_device_table(struct protection_domain *domain)
2558 struct iommu_dev_data *dev_data;
2560 list_for_each_entry(dev_data, &domain->dev_list, list)
2561 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2564 static void update_domain(struct protection_domain *domain)
2566 if (!domain->updated)
2569 update_device_table(domain);
2571 domain_flush_devices(domain);
2572 domain_flush_tlb_pde(domain);
2574 domain->updated = false;
2578 * This function fetches the PTE for a given address in the aperture
2580 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2581 unsigned long address)
2583 struct aperture_range *aperture;
2584 u64 *pte, *pte_page;
2586 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2590 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2592 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2594 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2596 pte += PM_LEVEL_INDEX(0, address);
2598 update_domain(&dom->domain);
2604 * This is the generic map function. It maps one 4kb page at paddr to
2605 * the given address in the DMA address space for the domain.
2607 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2608 unsigned long address,
2614 WARN_ON(address > dom->aperture_size);
2618 pte = dma_ops_get_pte(dom, address);
2620 return DMA_ERROR_CODE;
2622 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2624 if (direction == DMA_TO_DEVICE)
2625 __pte |= IOMMU_PTE_IR;
2626 else if (direction == DMA_FROM_DEVICE)
2627 __pte |= IOMMU_PTE_IW;
2628 else if (direction == DMA_BIDIRECTIONAL)
2629 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2635 return (dma_addr_t)address;
2639 * The generic unmapping function for on page in the DMA address space.
2641 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2642 unsigned long address)
2644 struct aperture_range *aperture;
2647 if (address >= dom->aperture_size)
2650 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2654 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2658 pte += PM_LEVEL_INDEX(0, address);
2666 * This function contains common code for mapping of a physically
2667 * contiguous memory region into DMA address space. It is used by all
2668 * mapping functions provided with this IOMMU driver.
2669 * Must be called with the domain lock held.
2671 static dma_addr_t __map_single(struct device *dev,
2672 struct dma_ops_domain *dma_dom,
2679 dma_addr_t offset = paddr & ~PAGE_MASK;
2680 dma_addr_t address, start, ret;
2682 unsigned long align_mask = 0;
2685 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2688 INC_STATS_COUNTER(total_map_requests);
2691 INC_STATS_COUNTER(cross_page);
2694 align_mask = (1UL << get_order(size)) - 1;
2697 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2699 if (unlikely(address == DMA_ERROR_CODE)) {
2701 * setting next_address here will let the address
2702 * allocator only scan the new allocated range in the
2703 * first run. This is a small optimization.
2705 dma_dom->next_address = dma_dom->aperture_size;
2707 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2711 * aperture was successfully enlarged by 128 MB, try
2718 for (i = 0; i < pages; ++i) {
2719 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2720 if (ret == DMA_ERROR_CODE)
2728 ADD_STATS_COUNTER(alloced_io_mem, size);
2730 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2731 domain_flush_tlb(&dma_dom->domain);
2732 dma_dom->need_flush = false;
2733 } else if (unlikely(amd_iommu_np_cache))
2734 domain_flush_pages(&dma_dom->domain, address, size);
2741 for (--i; i >= 0; --i) {
2743 dma_ops_domain_unmap(dma_dom, start);
2746 dma_ops_free_addresses(dma_dom, address, pages);
2748 return DMA_ERROR_CODE;
2752 * Does the reverse of the __map_single function. Must be called with
2753 * the domain lock held too
2755 static void __unmap_single(struct dma_ops_domain *dma_dom,
2756 dma_addr_t dma_addr,
2760 dma_addr_t flush_addr;
2761 dma_addr_t i, start;
2764 if ((dma_addr == DMA_ERROR_CODE) ||
2765 (dma_addr + size > dma_dom->aperture_size))
2768 flush_addr = dma_addr;
2769 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2770 dma_addr &= PAGE_MASK;
2773 for (i = 0; i < pages; ++i) {
2774 dma_ops_domain_unmap(dma_dom, start);
2778 SUB_STATS_COUNTER(alloced_io_mem, size);
2780 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2782 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2783 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2784 dma_dom->need_flush = false;
2789 * The exported map_single function for dma_ops.
2791 static dma_addr_t map_page(struct device *dev, struct page *page,
2792 unsigned long offset, size_t size,
2793 enum dma_data_direction dir,
2794 struct dma_attrs *attrs)
2796 unsigned long flags;
2797 struct protection_domain *domain;
2800 phys_addr_t paddr = page_to_phys(page) + offset;
2802 INC_STATS_COUNTER(cnt_map_single);
2804 domain = get_domain(dev);
2805 if (PTR_ERR(domain) == -EINVAL)
2806 return (dma_addr_t)paddr;
2807 else if (IS_ERR(domain))
2808 return DMA_ERROR_CODE;
2810 dma_mask = *dev->dma_mask;
2812 spin_lock_irqsave(&domain->lock, flags);
2814 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2816 if (addr == DMA_ERROR_CODE)
2819 domain_flush_complete(domain);
2822 spin_unlock_irqrestore(&domain->lock, flags);
2828 * The exported unmap_single function for dma_ops.
2830 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2831 enum dma_data_direction dir, struct dma_attrs *attrs)
2833 unsigned long flags;
2834 struct protection_domain *domain;
2836 INC_STATS_COUNTER(cnt_unmap_single);
2838 domain = get_domain(dev);
2842 spin_lock_irqsave(&domain->lock, flags);
2844 __unmap_single(domain->priv, dma_addr, size, dir);
2846 domain_flush_complete(domain);
2848 spin_unlock_irqrestore(&domain->lock, flags);
2852 * This is a special map_sg function which is used if we should map a
2853 * device which is not handled by an AMD IOMMU in the system.
2855 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2856 int nelems, int dir)
2858 struct scatterlist *s;
2861 for_each_sg(sglist, s, nelems, i) {
2862 s->dma_address = (dma_addr_t)sg_phys(s);
2863 s->dma_length = s->length;
2870 * The exported map_sg function for dma_ops (handles scatter-gather
2873 static int map_sg(struct device *dev, struct scatterlist *sglist,
2874 int nelems, enum dma_data_direction dir,
2875 struct dma_attrs *attrs)
2877 unsigned long flags;
2878 struct protection_domain *domain;
2880 struct scatterlist *s;
2882 int mapped_elems = 0;
2885 INC_STATS_COUNTER(cnt_map_sg);
2887 domain = get_domain(dev);
2888 if (PTR_ERR(domain) == -EINVAL)
2889 return map_sg_no_iommu(dev, sglist, nelems, dir);
2890 else if (IS_ERR(domain))
2893 dma_mask = *dev->dma_mask;
2895 spin_lock_irqsave(&domain->lock, flags);
2897 for_each_sg(sglist, s, nelems, i) {
2900 s->dma_address = __map_single(dev, domain->priv,
2901 paddr, s->length, dir, false,
2904 if (s->dma_address) {
2905 s->dma_length = s->length;
2911 domain_flush_complete(domain);
2914 spin_unlock_irqrestore(&domain->lock, flags);
2916 return mapped_elems;
2918 for_each_sg(sglist, s, mapped_elems, i) {
2920 __unmap_single(domain->priv, s->dma_address,
2921 s->dma_length, dir);
2922 s->dma_address = s->dma_length = 0;
2931 * The exported map_sg function for dma_ops (handles scatter-gather
2934 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2935 int nelems, enum dma_data_direction dir,
2936 struct dma_attrs *attrs)
2938 unsigned long flags;
2939 struct protection_domain *domain;
2940 struct scatterlist *s;
2943 INC_STATS_COUNTER(cnt_unmap_sg);
2945 domain = get_domain(dev);
2949 spin_lock_irqsave(&domain->lock, flags);
2951 for_each_sg(sglist, s, nelems, i) {
2952 __unmap_single(domain->priv, s->dma_address,
2953 s->dma_length, dir);
2954 s->dma_address = s->dma_length = 0;
2957 domain_flush_complete(domain);
2959 spin_unlock_irqrestore(&domain->lock, flags);
2963 * The exported alloc_coherent function for dma_ops.
2965 static void *alloc_coherent(struct device *dev, size_t size,
2966 dma_addr_t *dma_addr, gfp_t flag,
2967 struct dma_attrs *attrs)
2969 unsigned long flags;
2971 struct protection_domain *domain;
2973 u64 dma_mask = dev->coherent_dma_mask;
2975 INC_STATS_COUNTER(cnt_alloc_coherent);
2977 domain = get_domain(dev);
2978 if (PTR_ERR(domain) == -EINVAL) {
2979 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2980 *dma_addr = __pa(virt_addr);
2982 } else if (IS_ERR(domain))
2985 dma_mask = dev->coherent_dma_mask;
2986 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2989 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2993 paddr = virt_to_phys(virt_addr);
2996 dma_mask = *dev->dma_mask;
2998 spin_lock_irqsave(&domain->lock, flags);
3000 *dma_addr = __map_single(dev, domain->priv, paddr,
3001 size, DMA_BIDIRECTIONAL, true, dma_mask);
3003 if (*dma_addr == DMA_ERROR_CODE) {
3004 spin_unlock_irqrestore(&domain->lock, flags);
3008 domain_flush_complete(domain);
3010 spin_unlock_irqrestore(&domain->lock, flags);
3016 free_pages((unsigned long)virt_addr, get_order(size));
3022 * The exported free_coherent function for dma_ops.
3024 static void free_coherent(struct device *dev, size_t size,
3025 void *virt_addr, dma_addr_t dma_addr,
3026 struct dma_attrs *attrs)
3028 unsigned long flags;
3029 struct protection_domain *domain;
3031 INC_STATS_COUNTER(cnt_free_coherent);
3033 domain = get_domain(dev);
3037 spin_lock_irqsave(&domain->lock, flags);
3039 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
3041 domain_flush_complete(domain);
3043 spin_unlock_irqrestore(&domain->lock, flags);
3046 free_pages((unsigned long)virt_addr, get_order(size));
3050 * This function is called by the DMA layer to find out if we can handle a
3051 * particular device. It is part of the dma_ops.
3053 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
3055 return check_device(dev);
3059 * The function for pre-allocating protection domains.
3061 * If the driver core informs the DMA layer if a driver grabs a device
3062 * we don't need to preallocate the protection domains anymore.
3063 * For now we have to.
3065 static void __init prealloc_protection_domains(void)
3067 struct iommu_dev_data *dev_data;
3068 struct dma_ops_domain *dma_dom;
3069 struct pci_dev *dev = NULL;
3072 for_each_pci_dev(dev) {
3074 /* Do we handle this device? */
3075 if (!check_device(&dev->dev))
3078 dev_data = get_dev_data(&dev->dev);
3079 if (!amd_iommu_force_isolation && dev_data->iommu_v2) {
3080 /* Make sure passthrough domain is allocated */
3081 alloc_passthrough_domain();
3082 dev_data->passthrough = true;
3083 attach_device(&dev->dev, pt_domain);
3084 pr_info("AMD-Vi: Using passthrough domain for device %s\n",
3085 dev_name(&dev->dev));
3088 /* Is there already any domain for it? */
3089 if (domain_for_device(&dev->dev))
3092 devid = get_device_id(&dev->dev);
3094 dma_dom = dma_ops_domain_alloc();
3097 init_unity_mappings_for_device(dma_dom, devid);
3098 dma_dom->target_dev = devid;
3100 attach_device(&dev->dev, &dma_dom->domain);
3102 list_add_tail(&dma_dom->list, &iommu_pd_list);
3106 static struct dma_map_ops amd_iommu_dma_ops = {
3107 .alloc = alloc_coherent,
3108 .free = free_coherent,
3109 .map_page = map_page,
3110 .unmap_page = unmap_page,
3112 .unmap_sg = unmap_sg,
3113 .dma_supported = amd_iommu_dma_supported,
3116 static unsigned device_dma_ops_init(void)
3118 struct iommu_dev_data *dev_data;
3119 struct pci_dev *pdev = NULL;
3120 unsigned unhandled = 0;
3122 for_each_pci_dev(pdev) {
3123 if (!check_device(&pdev->dev)) {
3125 iommu_ignore_device(&pdev->dev);
3131 dev_data = get_dev_data(&pdev->dev);
3133 if (!dev_data->passthrough)
3134 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
3136 pdev->dev.archdata.dma_ops = &nommu_dma_ops;
3143 * The function which clues the AMD IOMMU driver into dma_ops.
3146 void __init amd_iommu_init_api(void)
3148 bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
3151 int __init amd_iommu_init_dma_ops(void)
3153 struct amd_iommu *iommu;
3157 * first allocate a default protection domain for every IOMMU we
3158 * found in the system. Devices not assigned to any other
3159 * protection domain will be assigned to the default one.
3161 for_each_iommu(iommu) {
3162 iommu->default_dom = dma_ops_domain_alloc();
3163 if (iommu->default_dom == NULL)
3165 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
3166 ret = iommu_init_unity_mappings(iommu);
3172 * Pre-allocate the protection domains for each device.
3174 prealloc_protection_domains();
3179 /* Make the driver finally visible to the drivers */
3180 unhandled = device_dma_ops_init();
3181 if (unhandled && max_pfn > MAX_DMA32_PFN) {
3182 /* There are unhandled devices - initialize swiotlb for them */
3186 amd_iommu_stats_init();
3188 if (amd_iommu_unmap_flush)
3189 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
3191 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
3197 for_each_iommu(iommu) {
3198 if (iommu->default_dom)
3199 dma_ops_domain_free(iommu->default_dom);
3205 /*****************************************************************************
3207 * The following functions belong to the exported interface of AMD IOMMU
3209 * This interface allows access to lower level functions of the IOMMU
3210 * like protection domain handling and assignement of devices to domains
3211 * which is not possible with the dma_ops interface.
3213 *****************************************************************************/
3215 static void cleanup_domain(struct protection_domain *domain)
3217 struct iommu_dev_data *dev_data, *next;
3218 unsigned long flags;
3220 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3222 list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
3223 __detach_device(dev_data);
3224 atomic_set(&dev_data->bind, 0);
3227 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3230 static void protection_domain_free(struct protection_domain *domain)
3235 del_domain_from_list(domain);
3238 domain_id_free(domain->id);
3243 static struct protection_domain *protection_domain_alloc(void)
3245 struct protection_domain *domain;
3247 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
3251 spin_lock_init(&domain->lock);
3252 mutex_init(&domain->api_lock);
3253 domain->id = domain_id_alloc();
3256 INIT_LIST_HEAD(&domain->dev_list);
3258 add_domain_to_list(domain);
3268 static int __init alloc_passthrough_domain(void)
3270 if (pt_domain != NULL)
3273 /* allocate passthrough domain */
3274 pt_domain = protection_domain_alloc();
3278 pt_domain->mode = PAGE_MODE_NONE;
3282 static int amd_iommu_domain_init(struct iommu_domain *dom)
3284 struct protection_domain *domain;
3286 domain = protection_domain_alloc();
3290 domain->mode = PAGE_MODE_3_LEVEL;
3291 domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
3292 if (!domain->pt_root)
3295 domain->iommu_domain = dom;
3299 dom->geometry.aperture_start = 0;
3300 dom->geometry.aperture_end = ~0ULL;
3301 dom->geometry.force_aperture = true;
3306 protection_domain_free(domain);
3311 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
3313 struct protection_domain *domain = dom->priv;
3318 if (domain->dev_cnt > 0)
3319 cleanup_domain(domain);
3321 BUG_ON(domain->dev_cnt != 0);
3323 if (domain->mode != PAGE_MODE_NONE)
3324 free_pagetable(domain);
3326 if (domain->flags & PD_IOMMUV2_MASK)
3327 free_gcr3_table(domain);
3329 protection_domain_free(domain);
3334 static void amd_iommu_detach_device(struct iommu_domain *dom,
3337 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3338 struct amd_iommu *iommu;
3341 if (!check_device(dev))
3344 devid = get_device_id(dev);
3346 if (dev_data->domain != NULL)
3349 iommu = amd_iommu_rlookup_table[devid];
3353 iommu_completion_wait(iommu);
3356 static int amd_iommu_attach_device(struct iommu_domain *dom,
3359 struct protection_domain *domain = dom->priv;
3360 struct iommu_dev_data *dev_data;
3361 struct amd_iommu *iommu;
3364 if (!check_device(dev))
3367 dev_data = dev->archdata.iommu;
3369 iommu = amd_iommu_rlookup_table[dev_data->devid];
3373 if (dev_data->domain)
3376 ret = attach_device(dev, domain);
3378 iommu_completion_wait(iommu);
3383 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3384 phys_addr_t paddr, size_t page_size, int iommu_prot)
3386 struct protection_domain *domain = dom->priv;
3390 if (domain->mode == PAGE_MODE_NONE)
3393 if (iommu_prot & IOMMU_READ)
3394 prot |= IOMMU_PROT_IR;
3395 if (iommu_prot & IOMMU_WRITE)
3396 prot |= IOMMU_PROT_IW;
3398 mutex_lock(&domain->api_lock);
3399 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3400 mutex_unlock(&domain->api_lock);
3405 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3408 struct protection_domain *domain = dom->priv;
3411 if (domain->mode == PAGE_MODE_NONE)
3414 mutex_lock(&domain->api_lock);
3415 unmap_size = iommu_unmap_page(domain, iova, page_size);
3416 mutex_unlock(&domain->api_lock);
3418 domain_flush_tlb_pde(domain);
3423 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3426 struct protection_domain *domain = dom->priv;
3427 unsigned long offset_mask;
3431 if (domain->mode == PAGE_MODE_NONE)
3434 pte = fetch_pte(domain, iova);
3436 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3439 if (PM_PTE_LEVEL(*pte) == 0)
3440 offset_mask = PAGE_SIZE - 1;
3442 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
3444 __pte = *pte & PM_ADDR_MASK;
3445 paddr = (__pte & ~offset_mask) | (iova & offset_mask);
3450 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
3454 case IOMMU_CAP_CACHE_COHERENCY:
3456 case IOMMU_CAP_INTR_REMAP:
3457 return irq_remapping_enabled;
3463 static struct iommu_ops amd_iommu_ops = {
3464 .domain_init = amd_iommu_domain_init,
3465 .domain_destroy = amd_iommu_domain_destroy,
3466 .attach_dev = amd_iommu_attach_device,
3467 .detach_dev = amd_iommu_detach_device,
3468 .map = amd_iommu_map,
3469 .unmap = amd_iommu_unmap,
3470 .iova_to_phys = amd_iommu_iova_to_phys,
3471 .domain_has_cap = amd_iommu_domain_has_cap,
3472 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3475 /*****************************************************************************
3477 * The next functions do a basic initialization of IOMMU for pass through
3480 * In passthrough mode the IOMMU is initialized and enabled but not used for
3481 * DMA-API translation.
3483 *****************************************************************************/
3485 int __init amd_iommu_init_passthrough(void)
3487 struct iommu_dev_data *dev_data;
3488 struct pci_dev *dev = NULL;
3489 struct amd_iommu *iommu;
3493 ret = alloc_passthrough_domain();
3497 for_each_pci_dev(dev) {
3498 if (!check_device(&dev->dev))
3501 dev_data = get_dev_data(&dev->dev);
3502 dev_data->passthrough = true;
3504 devid = get_device_id(&dev->dev);
3506 iommu = amd_iommu_rlookup_table[devid];
3510 attach_device(&dev->dev, pt_domain);
3513 amd_iommu_stats_init();
3515 pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
3520 /* IOMMUv2 specific functions */
3521 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3523 return atomic_notifier_chain_register(&ppr_notifier, nb);
3525 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3527 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3529 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3531 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3533 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3535 struct protection_domain *domain = dom->priv;
3536 unsigned long flags;
3538 spin_lock_irqsave(&domain->lock, flags);
3540 /* Update data structure */
3541 domain->mode = PAGE_MODE_NONE;
3542 domain->updated = true;
3544 /* Make changes visible to IOMMUs */
3545 update_domain(domain);
3547 /* Page-table is not visible to IOMMU anymore, so free it */
3548 free_pagetable(domain);
3550 spin_unlock_irqrestore(&domain->lock, flags);
3552 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3554 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3556 struct protection_domain *domain = dom->priv;
3557 unsigned long flags;
3560 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3563 /* Number of GCR3 table levels required */
3564 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3567 if (levels > amd_iommu_max_glx_val)
3570 spin_lock_irqsave(&domain->lock, flags);
3573 * Save us all sanity checks whether devices already in the
3574 * domain support IOMMUv2. Just force that the domain has no
3575 * devices attached when it is switched into IOMMUv2 mode.
3578 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3582 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3583 if (domain->gcr3_tbl == NULL)
3586 domain->glx = levels;
3587 domain->flags |= PD_IOMMUV2_MASK;
3588 domain->updated = true;
3590 update_domain(domain);
3595 spin_unlock_irqrestore(&domain->lock, flags);
3599 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3601 static int __flush_pasid(struct protection_domain *domain, int pasid,
3602 u64 address, bool size)
3604 struct iommu_dev_data *dev_data;
3605 struct iommu_cmd cmd;
3608 if (!(domain->flags & PD_IOMMUV2_MASK))
3611 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3614 * IOMMU TLB needs to be flushed before Device TLB to
3615 * prevent device TLB refill from IOMMU TLB
3617 for (i = 0; i < amd_iommus_present; ++i) {
3618 if (domain->dev_iommu[i] == 0)
3621 ret = iommu_queue_command(amd_iommus[i], &cmd);
3626 /* Wait until IOMMU TLB flushes are complete */
3627 domain_flush_complete(domain);
3629 /* Now flush device TLBs */
3630 list_for_each_entry(dev_data, &domain->dev_list, list) {
3631 struct amd_iommu *iommu;
3634 BUG_ON(!dev_data->ats.enabled);
3636 qdep = dev_data->ats.qdep;
3637 iommu = amd_iommu_rlookup_table[dev_data->devid];
3639 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3640 qdep, address, size);
3642 ret = iommu_queue_command(iommu, &cmd);
3647 /* Wait until all device TLBs are flushed */
3648 domain_flush_complete(domain);
3657 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3660 INC_STATS_COUNTER(invalidate_iotlb);
3662 return __flush_pasid(domain, pasid, address, false);
3665 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3668 struct protection_domain *domain = dom->priv;
3669 unsigned long flags;
3672 spin_lock_irqsave(&domain->lock, flags);
3673 ret = __amd_iommu_flush_page(domain, pasid, address);
3674 spin_unlock_irqrestore(&domain->lock, flags);
3678 EXPORT_SYMBOL(amd_iommu_flush_page);
3680 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3682 INC_STATS_COUNTER(invalidate_iotlb_all);
3684 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3688 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3690 struct protection_domain *domain = dom->priv;
3691 unsigned long flags;
3694 spin_lock_irqsave(&domain->lock, flags);
3695 ret = __amd_iommu_flush_tlb(domain, pasid);
3696 spin_unlock_irqrestore(&domain->lock, flags);
3700 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3702 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3709 index = (pasid >> (9 * level)) & 0x1ff;
3715 if (!(*pte & GCR3_VALID)) {
3719 root = (void *)get_zeroed_page(GFP_ATOMIC);
3723 *pte = __pa(root) | GCR3_VALID;
3726 root = __va(*pte & PAGE_MASK);
3734 static int __set_gcr3(struct protection_domain *domain, int pasid,
3739 if (domain->mode != PAGE_MODE_NONE)
3742 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3746 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3748 return __amd_iommu_flush_tlb(domain, pasid);
3751 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3755 if (domain->mode != PAGE_MODE_NONE)
3758 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3764 return __amd_iommu_flush_tlb(domain, pasid);
3767 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3770 struct protection_domain *domain = dom->priv;
3771 unsigned long flags;
3774 spin_lock_irqsave(&domain->lock, flags);
3775 ret = __set_gcr3(domain, pasid, cr3);
3776 spin_unlock_irqrestore(&domain->lock, flags);
3780 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3782 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3784 struct protection_domain *domain = dom->priv;
3785 unsigned long flags;
3788 spin_lock_irqsave(&domain->lock, flags);
3789 ret = __clear_gcr3(domain, pasid);
3790 spin_unlock_irqrestore(&domain->lock, flags);
3794 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3796 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3797 int status, int tag)
3799 struct iommu_dev_data *dev_data;
3800 struct amd_iommu *iommu;
3801 struct iommu_cmd cmd;
3803 INC_STATS_COUNTER(complete_ppr);
3805 dev_data = get_dev_data(&pdev->dev);
3806 iommu = amd_iommu_rlookup_table[dev_data->devid];
3808 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3809 tag, dev_data->pri_tlp);
3811 return iommu_queue_command(iommu, &cmd);
3813 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3815 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3817 struct protection_domain *domain;
3819 domain = get_domain(&pdev->dev);
3823 /* Only return IOMMUv2 domains */
3824 if (!(domain->flags & PD_IOMMUV2_MASK))
3827 return domain->iommu_domain;
3829 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3831 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3833 struct iommu_dev_data *dev_data;
3835 if (!amd_iommu_v2_supported())
3838 dev_data = get_dev_data(&pdev->dev);
3839 dev_data->errata |= (1 << erratum);
3841 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3843 int amd_iommu_device_info(struct pci_dev *pdev,
3844 struct amd_iommu_device_info *info)
3849 if (pdev == NULL || info == NULL)
3852 if (!amd_iommu_v2_supported())
3855 memset(info, 0, sizeof(*info));
3857 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3859 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3861 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3863 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3865 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3869 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3870 max_pasids = min(max_pasids, (1 << 20));
3872 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3873 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3875 features = pci_pasid_features(pdev);
3876 if (features & PCI_PASID_CAP_EXEC)
3877 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3878 if (features & PCI_PASID_CAP_PRIV)
3879 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3884 EXPORT_SYMBOL(amd_iommu_device_info);
3886 #ifdef CONFIG_IRQ_REMAP
3888 /*****************************************************************************
3890 * Interrupt Remapping Implementation
3892 *****************************************************************************/
3909 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3910 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3911 #define DTE_IRQ_TABLE_LEN (8ULL << 1)
3912 #define DTE_IRQ_REMAP_ENABLE 1ULL
3914 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3918 dte = amd_iommu_dev_table[devid].data[2];
3919 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3920 dte |= virt_to_phys(table->table);
3921 dte |= DTE_IRQ_REMAP_INTCTL;
3922 dte |= DTE_IRQ_TABLE_LEN;
3923 dte |= DTE_IRQ_REMAP_ENABLE;
3925 amd_iommu_dev_table[devid].data[2] = dte;
3928 #define IRTE_ALLOCATED (~1U)
3930 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3932 struct irq_remap_table *table = NULL;
3933 struct amd_iommu *iommu;
3934 unsigned long flags;
3937 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3939 iommu = amd_iommu_rlookup_table[devid];
3943 table = irq_lookup_table[devid];
3947 alias = amd_iommu_alias_table[devid];
3948 table = irq_lookup_table[alias];
3950 irq_lookup_table[devid] = table;
3951 set_dte_irq_entry(devid, table);
3952 iommu_flush_dte(iommu, devid);
3956 /* Nothing there yet, allocate new irq remapping table */
3957 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3962 /* Keep the first 32 indexes free for IOAPIC interrupts */
3963 table->min_index = 32;
3965 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3966 if (!table->table) {
3972 memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3977 for (i = 0; i < 32; ++i)
3978 table->table[i] = IRTE_ALLOCATED;
3981 irq_lookup_table[devid] = table;
3982 set_dte_irq_entry(devid, table);
3983 iommu_flush_dte(iommu, devid);
3984 if (devid != alias) {
3985 irq_lookup_table[alias] = table;
3986 set_dte_irq_entry(devid, table);
3987 iommu_flush_dte(iommu, alias);
3991 iommu_completion_wait(iommu);
3994 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3999 static int alloc_irq_index(struct irq_cfg *cfg, u16 devid, int count)
4001 struct irq_remap_table *table;
4002 unsigned long flags;
4005 table = get_irq_table(devid, false);
4009 spin_lock_irqsave(&table->lock, flags);
4011 /* Scan table for free entries */
4012 for (c = 0, index = table->min_index;
4013 index < MAX_IRQS_PER_TABLE;
4015 if (table->table[index] == 0)
4021 struct irq_2_iommu *irte_info;
4024 table->table[index - c + 1] = IRTE_ALLOCATED;
4028 irte_info = &cfg->irq_2_iommu;
4029 irte_info->sub_handle = devid;
4030 irte_info->irte_index = index;
4031 irte_info->iommu = (void *)cfg;
4040 spin_unlock_irqrestore(&table->lock, flags);
4045 static int get_irte(u16 devid, int index, union irte *irte)
4047 struct irq_remap_table *table;
4048 unsigned long flags;
4050 table = get_irq_table(devid, false);
4054 spin_lock_irqsave(&table->lock, flags);
4055 irte->val = table->table[index];
4056 spin_unlock_irqrestore(&table->lock, flags);
4061 static int modify_irte(u16 devid, int index, union irte irte)
4063 struct irq_remap_table *table;
4064 struct amd_iommu *iommu;
4065 unsigned long flags;
4067 iommu = amd_iommu_rlookup_table[devid];
4071 table = get_irq_table(devid, false);
4075 spin_lock_irqsave(&table->lock, flags);
4076 table->table[index] = irte.val;
4077 spin_unlock_irqrestore(&table->lock, flags);
4079 iommu_flush_irt(iommu, devid);
4080 iommu_completion_wait(iommu);
4085 static void free_irte(u16 devid, int index)
4087 struct irq_remap_table *table;
4088 struct amd_iommu *iommu;
4089 unsigned long flags;
4091 iommu = amd_iommu_rlookup_table[devid];
4095 table = get_irq_table(devid, false);
4099 spin_lock_irqsave(&table->lock, flags);
4100 table->table[index] = 0;
4101 spin_unlock_irqrestore(&table->lock, flags);
4103 iommu_flush_irt(iommu, devid);
4104 iommu_completion_wait(iommu);
4107 static int setup_ioapic_entry(int irq, struct IO_APIC_route_entry *entry,
4108 unsigned int destination, int vector,
4109 struct io_apic_irq_attr *attr)
4111 struct irq_remap_table *table;
4112 struct irq_2_iommu *irte_info;
4113 struct irq_cfg *cfg;
4120 cfg = irq_get_chip_data(irq);
4124 irte_info = &cfg->irq_2_iommu;
4125 ioapic_id = mpc_ioapic_id(attr->ioapic);
4126 devid = get_ioapic_devid(ioapic_id);
4131 table = get_irq_table(devid, true);
4135 index = attr->ioapic_pin;
4137 /* Setup IRQ remapping info */
4138 irte_info->sub_handle = devid;
4139 irte_info->irte_index = index;
4140 irte_info->iommu = (void *)cfg;
4142 /* Setup IRTE for IOMMU */
4144 irte.fields.vector = vector;
4145 irte.fields.int_type = apic->irq_delivery_mode;
4146 irte.fields.destination = destination;
4147 irte.fields.dm = apic->irq_dest_mode;
4148 irte.fields.valid = 1;
4150 ret = modify_irte(devid, index, irte);
4154 /* Setup IOAPIC entry */
4155 memset(entry, 0, sizeof(*entry));
4157 entry->vector = index;
4159 entry->trigger = attr->trigger;
4160 entry->polarity = attr->polarity;
4163 * Mask level triggered irqs.
4171 static int set_affinity(struct irq_data *data, const struct cpumask *mask,
4174 struct irq_2_iommu *irte_info;
4175 unsigned int dest, irq;
4176 struct irq_cfg *cfg;
4180 if (!config_enabled(CONFIG_SMP))
4183 cfg = data->chip_data;
4185 irte_info = &cfg->irq_2_iommu;
4187 if (!cpumask_intersects(mask, cpu_online_mask))
4190 if (get_irte(irte_info->sub_handle, irte_info->irte_index, &irte))
4193 if (assign_irq_vector(irq, cfg, mask))
4196 err = apic->cpu_mask_to_apicid_and(cfg->domain, mask, &dest);
4198 if (assign_irq_vector(irq, cfg, data->affinity))
4199 pr_err("AMD-Vi: Failed to recover vector for irq %d\n", irq);
4203 irte.fields.vector = cfg->vector;
4204 irte.fields.destination = dest;
4206 modify_irte(irte_info->sub_handle, irte_info->irte_index, irte);
4208 if (cfg->move_in_progress)
4209 send_cleanup_vector(cfg);
4211 cpumask_copy(data->affinity, mask);
4216 static int free_irq(int irq)
4218 struct irq_2_iommu *irte_info;
4219 struct irq_cfg *cfg;
4221 cfg = irq_get_chip_data(irq);
4225 irte_info = &cfg->irq_2_iommu;
4227 free_irte(irte_info->sub_handle, irte_info->irte_index);
4232 static void compose_msi_msg(struct pci_dev *pdev,
4233 unsigned int irq, unsigned int dest,
4234 struct msi_msg *msg, u8 hpet_id)
4236 struct irq_2_iommu *irte_info;
4237 struct irq_cfg *cfg;
4240 cfg = irq_get_chip_data(irq);
4244 irte_info = &cfg->irq_2_iommu;
4247 irte.fields.vector = cfg->vector;
4248 irte.fields.int_type = apic->irq_delivery_mode;
4249 irte.fields.destination = dest;
4250 irte.fields.dm = apic->irq_dest_mode;
4251 irte.fields.valid = 1;
4253 modify_irte(irte_info->sub_handle, irte_info->irte_index, irte);
4255 msg->address_hi = MSI_ADDR_BASE_HI;
4256 msg->address_lo = MSI_ADDR_BASE_LO;
4257 msg->data = irte_info->irte_index;
4260 static int msi_alloc_irq(struct pci_dev *pdev, int irq, int nvec)
4262 struct irq_cfg *cfg;
4269 cfg = irq_get_chip_data(irq);
4273 devid = get_device_id(&pdev->dev);
4274 index = alloc_irq_index(cfg, devid, nvec);
4276 return index < 0 ? MAX_IRQS_PER_TABLE : index;
4279 static int msi_setup_irq(struct pci_dev *pdev, unsigned int irq,
4280 int index, int offset)
4282 struct irq_2_iommu *irte_info;
4283 struct irq_cfg *cfg;
4289 cfg = irq_get_chip_data(irq);
4293 if (index >= MAX_IRQS_PER_TABLE)
4296 devid = get_device_id(&pdev->dev);
4297 irte_info = &cfg->irq_2_iommu;
4299 irte_info->sub_handle = devid;
4300 irte_info->irte_index = index + offset;
4301 irte_info->iommu = (void *)cfg;
4306 static int setup_hpet_msi(unsigned int irq, unsigned int id)
4308 struct irq_2_iommu *irte_info;
4309 struct irq_cfg *cfg;
4312 cfg = irq_get_chip_data(irq);
4316 irte_info = &cfg->irq_2_iommu;
4317 devid = get_hpet_devid(id);
4321 index = alloc_irq_index(cfg, devid, 1);
4325 irte_info->sub_handle = devid;
4326 irte_info->irte_index = index;
4327 irte_info->iommu = (void *)cfg;
4332 struct irq_remap_ops amd_iommu_irq_ops = {
4333 .supported = amd_iommu_supported,
4334 .prepare = amd_iommu_prepare,
4335 .enable = amd_iommu_enable,
4336 .disable = amd_iommu_disable,
4337 .reenable = amd_iommu_reenable,
4338 .enable_faulting = amd_iommu_enable_faulting,
4339 .setup_ioapic_entry = setup_ioapic_entry,
4340 .set_affinity = set_affinity,
4341 .free_irq = free_irq,
4342 .compose_msi_msg = compose_msi_msg,
4343 .msi_alloc_irq = msi_alloc_irq,
4344 .msi_setup_irq = msi_setup_irq,
4345 .setup_hpet_msi = setup_hpet_msi,