2 * Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
3 * Author: Joerg Roedel <jroedel@suse.de>
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/acpi.h>
23 #include <linux/amba/bus.h>
24 #include <linux/platform_device.h>
25 #include <linux/pci-ats.h>
26 #include <linux/bitmap.h>
27 #include <linux/slab.h>
28 #include <linux/debugfs.h>
29 #include <linux/scatterlist.h>
30 #include <linux/dma-mapping.h>
31 #include <linux/iommu-helper.h>
32 #include <linux/iommu.h>
33 #include <linux/delay.h>
34 #include <linux/amd-iommu.h>
35 #include <linux/notifier.h>
36 #include <linux/export.h>
37 #include <linux/irq.h>
38 #include <linux/msi.h>
39 #include <linux/dma-contiguous.h>
40 #include <linux/irqdomain.h>
41 #include <linux/percpu.h>
42 #include <linux/iova.h>
43 #include <asm/irq_remapping.h>
44 #include <asm/io_apic.h>
46 #include <asm/hw_irq.h>
47 #include <asm/msidef.h>
48 #include <asm/proto.h>
49 #include <asm/iommu.h>
53 #include "amd_iommu_proto.h"
54 #include "amd_iommu_types.h"
55 #include "irq_remapping.h"
57 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
59 #define LOOP_TIMEOUT 100000
61 /* IO virtual address start page frame number */
62 #define IOVA_START_PFN (1)
63 #define IOVA_PFN(addr) ((addr) >> PAGE_SHIFT)
64 #define DMA_32BIT_PFN IOVA_PFN(DMA_BIT_MASK(32))
66 /* Reserved IOVA ranges */
67 #define MSI_RANGE_START (0xfee00000)
68 #define MSI_RANGE_END (0xfeefffff)
69 #define HT_RANGE_START (0xfd00000000ULL)
70 #define HT_RANGE_END (0xffffffffffULL)
73 * This bitmap is used to advertise the page sizes our hardware support
74 * to the IOMMU core, which will then use this information to split
75 * physically contiguous memory regions it is mapping into page sizes
78 * 512GB Pages are not supported due to a hardware bug
80 #define AMD_IOMMU_PGSIZES ((~0xFFFUL) & ~(2ULL << 38))
82 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
84 /* List of all available dev_data structures */
85 static LIST_HEAD(dev_data_list);
86 static DEFINE_SPINLOCK(dev_data_list_lock);
88 LIST_HEAD(ioapic_map);
90 LIST_HEAD(acpihid_map);
92 #define FLUSH_QUEUE_SIZE 256
94 struct flush_queue_entry {
95 unsigned long iova_pfn;
97 struct dma_ops_domain *dma_dom;
103 struct flush_queue_entry *entries;
106 static DEFINE_PER_CPU(struct flush_queue, flush_queue);
108 static atomic_t queue_timer_on;
109 static struct timer_list queue_timer;
112 * Domain for untranslated devices - only allocated
113 * if iommu=pt passed on kernel cmd line.
115 static const struct iommu_ops amd_iommu_ops;
117 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
118 int amd_iommu_max_glx_val = -1;
120 static struct dma_map_ops amd_iommu_dma_ops;
123 * This struct contains device specific data for the IOMMU
125 struct iommu_dev_data {
126 struct list_head list; /* For domain->dev_list */
127 struct list_head dev_data_list; /* For global dev_data_list */
128 struct protection_domain *domain; /* Domain the device is bound to */
129 u16 devid; /* PCI Device ID */
130 u16 alias; /* Alias Device ID */
131 bool iommu_v2; /* Device can make use of IOMMUv2 */
132 bool passthrough; /* Device is identity mapped */
136 } ats; /* ATS state */
137 bool pri_tlp; /* PASID TLB required for
139 u32 errata; /* Bitmap for errata to apply */
140 bool use_vapic; /* Enable device to use vapic mode */
144 * general struct to manage commands send to an IOMMU
150 struct kmem_cache *amd_iommu_irq_cache;
152 static void update_domain(struct protection_domain *domain);
153 static int protection_domain_init(struct protection_domain *domain);
154 static void detach_device(struct device *dev);
157 * Data container for a dma_ops specific protection domain
159 struct dma_ops_domain {
160 /* generic protection domain information */
161 struct protection_domain domain;
164 struct iova_domain iovad;
167 static struct iova_domain reserved_iova_ranges;
168 static struct lock_class_key reserved_rbtree_key;
170 /****************************************************************************
174 ****************************************************************************/
176 static inline int match_hid_uid(struct device *dev,
177 struct acpihid_map_entry *entry)
179 struct acpi_device *adev = ACPI_COMPANION(dev);
180 const char *hid, *uid;
185 hid = acpi_device_hid(adev);
186 uid = acpi_device_uid(adev);
192 return strcmp(hid, entry->hid);
195 return strcmp(hid, entry->hid);
197 return (strcmp(hid, entry->hid) || strcmp(uid, entry->uid));
200 static inline u16 get_pci_device_id(struct device *dev)
202 struct pci_dev *pdev = to_pci_dev(dev);
204 return PCI_DEVID(pdev->bus->number, pdev->devfn);
207 static inline int get_acpihid_device_id(struct device *dev,
208 struct acpihid_map_entry **entry)
210 struct acpihid_map_entry *p;
212 list_for_each_entry(p, &acpihid_map, list) {
213 if (!match_hid_uid(dev, p)) {
222 static inline int get_device_id(struct device *dev)
227 devid = get_pci_device_id(dev);
229 devid = get_acpihid_device_id(dev, NULL);
234 static struct protection_domain *to_pdomain(struct iommu_domain *dom)
236 return container_of(dom, struct protection_domain, domain);
239 static struct dma_ops_domain* to_dma_ops_domain(struct protection_domain *domain)
241 BUG_ON(domain->flags != PD_DMA_OPS_MASK);
242 return container_of(domain, struct dma_ops_domain, domain);
245 static struct iommu_dev_data *alloc_dev_data(u16 devid)
247 struct iommu_dev_data *dev_data;
250 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
254 dev_data->devid = devid;
256 spin_lock_irqsave(&dev_data_list_lock, flags);
257 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
258 spin_unlock_irqrestore(&dev_data_list_lock, flags);
263 static struct iommu_dev_data *search_dev_data(u16 devid)
265 struct iommu_dev_data *dev_data;
268 spin_lock_irqsave(&dev_data_list_lock, flags);
269 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
270 if (dev_data->devid == devid)
277 spin_unlock_irqrestore(&dev_data_list_lock, flags);
282 static int __last_alias(struct pci_dev *pdev, u16 alias, void *data)
284 *(u16 *)data = alias;
288 static u16 get_alias(struct device *dev)
290 struct pci_dev *pdev = to_pci_dev(dev);
291 u16 devid, ivrs_alias, pci_alias;
293 /* The callers make sure that get_device_id() does not fail here */
294 devid = get_device_id(dev);
296 /* For ACPI HID devices, we simply return the devid as such */
297 if (!dev_is_pci(dev))
300 ivrs_alias = amd_iommu_alias_table[devid];
302 pci_for_each_dma_alias(pdev, __last_alias, &pci_alias);
304 if (ivrs_alias == pci_alias)
310 * The IVRS is fairly reliable in telling us about aliases, but it
311 * can't know about every screwy device. If we don't have an IVRS
312 * reported alias, use the PCI reported alias. In that case we may
313 * still need to initialize the rlookup and dev_table entries if the
314 * alias is to a non-existent device.
316 if (ivrs_alias == devid) {
317 if (!amd_iommu_rlookup_table[pci_alias]) {
318 amd_iommu_rlookup_table[pci_alias] =
319 amd_iommu_rlookup_table[devid];
320 memcpy(amd_iommu_dev_table[pci_alias].data,
321 amd_iommu_dev_table[devid].data,
322 sizeof(amd_iommu_dev_table[pci_alias].data));
328 pr_info("AMD-Vi: Using IVRS reported alias %02x:%02x.%d "
329 "for device %s[%04x:%04x], kernel reported alias "
330 "%02x:%02x.%d\n", PCI_BUS_NUM(ivrs_alias), PCI_SLOT(ivrs_alias),
331 PCI_FUNC(ivrs_alias), dev_name(dev), pdev->vendor, pdev->device,
332 PCI_BUS_NUM(pci_alias), PCI_SLOT(pci_alias),
333 PCI_FUNC(pci_alias));
336 * If we don't have a PCI DMA alias and the IVRS alias is on the same
337 * bus, then the IVRS table may know about a quirk that we don't.
339 if (pci_alias == devid &&
340 PCI_BUS_NUM(ivrs_alias) == pdev->bus->number) {
341 pci_add_dma_alias(pdev, ivrs_alias & 0xff);
342 pr_info("AMD-Vi: Added PCI DMA alias %02x.%d for %s\n",
343 PCI_SLOT(ivrs_alias), PCI_FUNC(ivrs_alias),
350 static struct iommu_dev_data *find_dev_data(u16 devid)
352 struct iommu_dev_data *dev_data;
354 dev_data = search_dev_data(devid);
356 if (dev_data == NULL)
357 dev_data = alloc_dev_data(devid);
362 static struct iommu_dev_data *get_dev_data(struct device *dev)
364 return dev->archdata.iommu;
368 * Find or create an IOMMU group for a acpihid device.
370 static struct iommu_group *acpihid_device_group(struct device *dev)
372 struct acpihid_map_entry *p, *entry = NULL;
375 devid = get_acpihid_device_id(dev, &entry);
377 return ERR_PTR(devid);
379 list_for_each_entry(p, &acpihid_map, list) {
380 if ((devid == p->devid) && p->group)
381 entry->group = p->group;
385 entry->group = generic_device_group(dev);
390 static bool pci_iommuv2_capable(struct pci_dev *pdev)
392 static const int caps[] = {
395 PCI_EXT_CAP_ID_PASID,
399 for (i = 0; i < 3; ++i) {
400 pos = pci_find_ext_capability(pdev, caps[i]);
408 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
410 struct iommu_dev_data *dev_data;
412 dev_data = get_dev_data(&pdev->dev);
414 return dev_data->errata & (1 << erratum) ? true : false;
418 * This function checks if the driver got a valid device from the caller to
419 * avoid dereferencing invalid pointers.
421 static bool check_device(struct device *dev)
425 if (!dev || !dev->dma_mask)
428 devid = get_device_id(dev);
432 /* Out of our scope? */
433 if (devid > amd_iommu_last_bdf)
436 if (amd_iommu_rlookup_table[devid] == NULL)
442 static void init_iommu_group(struct device *dev)
444 struct iommu_group *group;
446 group = iommu_group_get_for_dev(dev);
450 iommu_group_put(group);
453 static int iommu_init_device(struct device *dev)
455 struct iommu_dev_data *dev_data;
458 if (dev->archdata.iommu)
461 devid = get_device_id(dev);
465 dev_data = find_dev_data(devid);
469 dev_data->alias = get_alias(dev);
472 * By default we use passthrough mode for IOMMUv2 capable device.
473 * But if amd_iommu=force_isolation is set (e.g. to debug DMA to
474 * invalid address), we ignore the capability for the device so
475 * it'll be forced to go into translation mode.
477 if ((iommu_pass_through || !amd_iommu_force_isolation) &&
478 dev_is_pci(dev) && pci_iommuv2_capable(to_pci_dev(dev))) {
479 struct amd_iommu *iommu;
481 iommu = amd_iommu_rlookup_table[dev_data->devid];
482 dev_data->iommu_v2 = iommu->is_iommu_v2;
485 dev->archdata.iommu = dev_data;
487 iommu_device_link(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
493 static void iommu_ignore_device(struct device *dev)
498 devid = get_device_id(dev);
502 alias = get_alias(dev);
504 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
505 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
507 amd_iommu_rlookup_table[devid] = NULL;
508 amd_iommu_rlookup_table[alias] = NULL;
511 static void iommu_uninit_device(struct device *dev)
514 struct iommu_dev_data *dev_data;
516 devid = get_device_id(dev);
520 dev_data = search_dev_data(devid);
524 if (dev_data->domain)
527 iommu_device_unlink(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
530 iommu_group_remove_device(dev);
533 dev->archdata.dma_ops = NULL;
536 * We keep dev_data around for unplugged devices and reuse it when the
537 * device is re-plugged - not doing so would introduce a ton of races.
541 /****************************************************************************
543 * Interrupt handling functions
545 ****************************************************************************/
547 static void dump_dte_entry(u16 devid)
551 for (i = 0; i < 4; ++i)
552 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
553 amd_iommu_dev_table[devid].data[i]);
556 static void dump_command(unsigned long phys_addr)
558 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
561 for (i = 0; i < 4; ++i)
562 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
565 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
567 int type, devid, domid, flags;
568 volatile u32 *event = __evt;
573 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
574 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
575 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
576 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
577 address = (u64)(((u64)event[3]) << 32) | event[2];
580 /* Did we hit the erratum? */
581 if (++count == LOOP_TIMEOUT) {
582 pr_err("AMD-Vi: No event written to event log\n");
589 printk(KERN_ERR "AMD-Vi: Event logged [");
592 case EVENT_TYPE_ILL_DEV:
593 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
594 "address=0x%016llx flags=0x%04x]\n",
595 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
597 dump_dte_entry(devid);
599 case EVENT_TYPE_IO_FAULT:
600 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
601 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
602 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
603 domid, address, flags);
605 case EVENT_TYPE_DEV_TAB_ERR:
606 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
607 "address=0x%016llx flags=0x%04x]\n",
608 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
611 case EVENT_TYPE_PAGE_TAB_ERR:
612 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
613 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
614 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
615 domid, address, flags);
617 case EVENT_TYPE_ILL_CMD:
618 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
619 dump_command(address);
621 case EVENT_TYPE_CMD_HARD_ERR:
622 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
623 "flags=0x%04x]\n", address, flags);
625 case EVENT_TYPE_IOTLB_INV_TO:
626 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
627 "address=0x%016llx]\n",
628 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
631 case EVENT_TYPE_INV_DEV_REQ:
632 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
633 "address=0x%016llx flags=0x%04x]\n",
634 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
638 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
641 memset(__evt, 0, 4 * sizeof(u32));
644 static void iommu_poll_events(struct amd_iommu *iommu)
648 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
649 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
651 while (head != tail) {
652 iommu_print_event(iommu, iommu->evt_buf + head);
653 head = (head + EVENT_ENTRY_SIZE) % EVT_BUFFER_SIZE;
656 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
659 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
661 struct amd_iommu_fault fault;
663 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
664 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
668 fault.address = raw[1];
669 fault.pasid = PPR_PASID(raw[0]);
670 fault.device_id = PPR_DEVID(raw[0]);
671 fault.tag = PPR_TAG(raw[0]);
672 fault.flags = PPR_FLAGS(raw[0]);
674 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
677 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
681 if (iommu->ppr_log == NULL)
684 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
685 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
687 while (head != tail) {
692 raw = (u64 *)(iommu->ppr_log + head);
695 * Hardware bug: Interrupt may arrive before the entry is
696 * written to memory. If this happens we need to wait for the
699 for (i = 0; i < LOOP_TIMEOUT; ++i) {
700 if (PPR_REQ_TYPE(raw[0]) != 0)
705 /* Avoid memcpy function-call overhead */
710 * To detect the hardware bug we need to clear the entry
713 raw[0] = raw[1] = 0UL;
715 /* Update head pointer of hardware ring-buffer */
716 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
717 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
719 /* Handle PPR entry */
720 iommu_handle_ppr_entry(iommu, entry);
722 /* Refresh ring-buffer information */
723 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
724 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
728 #ifdef CONFIG_IRQ_REMAP
729 static int (*iommu_ga_log_notifier)(u32);
731 int amd_iommu_register_ga_log_notifier(int (*notifier)(u32))
733 iommu_ga_log_notifier = notifier;
737 EXPORT_SYMBOL(amd_iommu_register_ga_log_notifier);
739 static void iommu_poll_ga_log(struct amd_iommu *iommu)
741 u32 head, tail, cnt = 0;
743 if (iommu->ga_log == NULL)
746 head = readl(iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
747 tail = readl(iommu->mmio_base + MMIO_GA_TAIL_OFFSET);
749 while (head != tail) {
753 raw = (u64 *)(iommu->ga_log + head);
756 /* Avoid memcpy function-call overhead */
759 /* Update head pointer of hardware ring-buffer */
760 head = (head + GA_ENTRY_SIZE) % GA_LOG_SIZE;
761 writel(head, iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
763 /* Handle GA entry */
764 switch (GA_REQ_TYPE(log_entry)) {
766 if (!iommu_ga_log_notifier)
769 pr_debug("AMD-Vi: %s: devid=%#x, ga_tag=%#x\n",
770 __func__, GA_DEVID(log_entry),
773 if (iommu_ga_log_notifier(GA_TAG(log_entry)) != 0)
774 pr_err("AMD-Vi: GA log notifier failed.\n");
781 #endif /* CONFIG_IRQ_REMAP */
783 #define AMD_IOMMU_INT_MASK \
784 (MMIO_STATUS_EVT_INT_MASK | \
785 MMIO_STATUS_PPR_INT_MASK | \
786 MMIO_STATUS_GALOG_INT_MASK)
788 irqreturn_t amd_iommu_int_thread(int irq, void *data)
790 struct amd_iommu *iommu = (struct amd_iommu *) data;
791 u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
793 while (status & AMD_IOMMU_INT_MASK) {
794 /* Enable EVT and PPR and GA interrupts again */
795 writel(AMD_IOMMU_INT_MASK,
796 iommu->mmio_base + MMIO_STATUS_OFFSET);
798 if (status & MMIO_STATUS_EVT_INT_MASK) {
799 pr_devel("AMD-Vi: Processing IOMMU Event Log\n");
800 iommu_poll_events(iommu);
803 if (status & MMIO_STATUS_PPR_INT_MASK) {
804 pr_devel("AMD-Vi: Processing IOMMU PPR Log\n");
805 iommu_poll_ppr_log(iommu);
808 #ifdef CONFIG_IRQ_REMAP
809 if (status & MMIO_STATUS_GALOG_INT_MASK) {
810 pr_devel("AMD-Vi: Processing IOMMU GA Log\n");
811 iommu_poll_ga_log(iommu);
816 * Hardware bug: ERBT1312
817 * When re-enabling interrupt (by writing 1
818 * to clear the bit), the hardware might also try to set
819 * the interrupt bit in the event status register.
820 * In this scenario, the bit will be set, and disable
821 * subsequent interrupts.
823 * Workaround: The IOMMU driver should read back the
824 * status register and check if the interrupt bits are cleared.
825 * If not, driver will need to go through the interrupt handler
826 * again and re-clear the bits
828 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
833 irqreturn_t amd_iommu_int_handler(int irq, void *data)
835 return IRQ_WAKE_THREAD;
838 /****************************************************************************
840 * IOMMU command queuing functions
842 ****************************************************************************/
844 static int wait_on_sem(volatile u64 *sem)
848 while (*sem == 0 && i < LOOP_TIMEOUT) {
853 if (i == LOOP_TIMEOUT) {
854 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
861 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
862 struct iommu_cmd *cmd,
867 target = iommu->cmd_buf + tail;
868 tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
870 /* Copy command to buffer */
871 memcpy(target, cmd, sizeof(*cmd));
873 /* Tell the IOMMU about it */
874 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
877 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
879 WARN_ON(address & 0x7ULL);
881 memset(cmd, 0, sizeof(*cmd));
882 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
883 cmd->data[1] = upper_32_bits(__pa(address));
885 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
888 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
890 memset(cmd, 0, sizeof(*cmd));
891 cmd->data[0] = devid;
892 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
895 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
896 size_t size, u16 domid, int pde)
901 pages = iommu_num_pages(address, size, PAGE_SIZE);
906 * If we have to flush more than one page, flush all
907 * TLB entries for this domain
909 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
913 address &= PAGE_MASK;
915 memset(cmd, 0, sizeof(*cmd));
916 cmd->data[1] |= domid;
917 cmd->data[2] = lower_32_bits(address);
918 cmd->data[3] = upper_32_bits(address);
919 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
920 if (s) /* size bit - we flush more than one 4kb page */
921 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
922 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
923 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
926 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
927 u64 address, size_t size)
932 pages = iommu_num_pages(address, size, PAGE_SIZE);
937 * If we have to flush more than one page, flush all
938 * TLB entries for this domain
940 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
944 address &= PAGE_MASK;
946 memset(cmd, 0, sizeof(*cmd));
947 cmd->data[0] = devid;
948 cmd->data[0] |= (qdep & 0xff) << 24;
949 cmd->data[1] = devid;
950 cmd->data[2] = lower_32_bits(address);
951 cmd->data[3] = upper_32_bits(address);
952 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
954 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
957 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
958 u64 address, bool size)
960 memset(cmd, 0, sizeof(*cmd));
962 address &= ~(0xfffULL);
964 cmd->data[0] = pasid;
965 cmd->data[1] = domid;
966 cmd->data[2] = lower_32_bits(address);
967 cmd->data[3] = upper_32_bits(address);
968 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
969 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
971 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
972 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
975 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
976 int qdep, u64 address, bool size)
978 memset(cmd, 0, sizeof(*cmd));
980 address &= ~(0xfffULL);
982 cmd->data[0] = devid;
983 cmd->data[0] |= ((pasid >> 8) & 0xff) << 16;
984 cmd->data[0] |= (qdep & 0xff) << 24;
985 cmd->data[1] = devid;
986 cmd->data[1] |= (pasid & 0xff) << 16;
987 cmd->data[2] = lower_32_bits(address);
988 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
989 cmd->data[3] = upper_32_bits(address);
991 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
992 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
995 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
996 int status, int tag, bool gn)
998 memset(cmd, 0, sizeof(*cmd));
1000 cmd->data[0] = devid;
1002 cmd->data[1] = pasid;
1003 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
1005 cmd->data[3] = tag & 0x1ff;
1006 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
1008 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
1011 static void build_inv_all(struct iommu_cmd *cmd)
1013 memset(cmd, 0, sizeof(*cmd));
1014 CMD_SET_TYPE(cmd, CMD_INV_ALL);
1017 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
1019 memset(cmd, 0, sizeof(*cmd));
1020 cmd->data[0] = devid;
1021 CMD_SET_TYPE(cmd, CMD_INV_IRT);
1025 * Writes the command to the IOMMUs command buffer and informs the
1026 * hardware about the new command.
1028 static int __iommu_queue_command_sync(struct amd_iommu *iommu,
1029 struct iommu_cmd *cmd,
1032 u32 left, tail, head, next_tail;
1036 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
1037 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
1038 next_tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
1039 left = (head - next_tail) % CMD_BUFFER_SIZE;
1042 struct iommu_cmd sync_cmd;
1047 build_completion_wait(&sync_cmd, (u64)&iommu->cmd_sem);
1048 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
1050 if ((ret = wait_on_sem(&iommu->cmd_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;
1064 static int iommu_queue_command_sync(struct amd_iommu *iommu,
1065 struct iommu_cmd *cmd,
1068 unsigned long flags;
1071 spin_lock_irqsave(&iommu->lock, flags);
1072 ret = __iommu_queue_command_sync(iommu, cmd, sync);
1073 spin_unlock_irqrestore(&iommu->lock, flags);
1078 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
1080 return iommu_queue_command_sync(iommu, cmd, true);
1084 * This function queues a completion wait command into the command
1085 * buffer of an IOMMU
1087 static int iommu_completion_wait(struct amd_iommu *iommu)
1089 struct iommu_cmd cmd;
1090 unsigned long flags;
1093 if (!iommu->need_sync)
1097 build_completion_wait(&cmd, (u64)&iommu->cmd_sem);
1099 spin_lock_irqsave(&iommu->lock, flags);
1103 ret = __iommu_queue_command_sync(iommu, &cmd, false);
1107 ret = wait_on_sem(&iommu->cmd_sem);
1110 spin_unlock_irqrestore(&iommu->lock, flags);
1115 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1117 struct iommu_cmd cmd;
1119 build_inv_dte(&cmd, devid);
1121 return iommu_queue_command(iommu, &cmd);
1124 static void iommu_flush_dte_all(struct amd_iommu *iommu)
1128 for (devid = 0; devid <= 0xffff; ++devid)
1129 iommu_flush_dte(iommu, devid);
1131 iommu_completion_wait(iommu);
1135 * This function uses heavy locking and may disable irqs for some time. But
1136 * this is no issue because it is only called during resume.
1138 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1142 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1143 struct iommu_cmd cmd;
1144 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1146 iommu_queue_command(iommu, &cmd);
1149 iommu_completion_wait(iommu);
1152 static void iommu_flush_all(struct amd_iommu *iommu)
1154 struct iommu_cmd cmd;
1156 build_inv_all(&cmd);
1158 iommu_queue_command(iommu, &cmd);
1159 iommu_completion_wait(iommu);
1162 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1164 struct iommu_cmd cmd;
1166 build_inv_irt(&cmd, devid);
1168 iommu_queue_command(iommu, &cmd);
1171 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1175 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1176 iommu_flush_irt(iommu, devid);
1178 iommu_completion_wait(iommu);
1181 void iommu_flush_all_caches(struct amd_iommu *iommu)
1183 if (iommu_feature(iommu, FEATURE_IA)) {
1184 iommu_flush_all(iommu);
1186 iommu_flush_dte_all(iommu);
1187 iommu_flush_irt_all(iommu);
1188 iommu_flush_tlb_all(iommu);
1193 * Command send function for flushing on-device TLB
1195 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1196 u64 address, size_t size)
1198 struct amd_iommu *iommu;
1199 struct iommu_cmd cmd;
1202 qdep = dev_data->ats.qdep;
1203 iommu = amd_iommu_rlookup_table[dev_data->devid];
1205 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1207 return iommu_queue_command(iommu, &cmd);
1211 * Command send function for invalidating a device table entry
1213 static int device_flush_dte(struct iommu_dev_data *dev_data)
1215 struct amd_iommu *iommu;
1219 iommu = amd_iommu_rlookup_table[dev_data->devid];
1220 alias = dev_data->alias;
1222 ret = iommu_flush_dte(iommu, dev_data->devid);
1223 if (!ret && alias != dev_data->devid)
1224 ret = iommu_flush_dte(iommu, alias);
1228 if (dev_data->ats.enabled)
1229 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1235 * TLB invalidation function which is called from the mapping functions.
1236 * It invalidates a single PTE if the range to flush is within a single
1237 * page. Otherwise it flushes the whole TLB of the IOMMU.
1239 static void __domain_flush_pages(struct protection_domain *domain,
1240 u64 address, size_t size, int pde)
1242 struct iommu_dev_data *dev_data;
1243 struct iommu_cmd cmd;
1246 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1248 for (i = 0; i < amd_iommus_present; ++i) {
1249 if (!domain->dev_iommu[i])
1253 * Devices of this domain are behind this IOMMU
1254 * We need a TLB flush
1256 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1259 list_for_each_entry(dev_data, &domain->dev_list, list) {
1261 if (!dev_data->ats.enabled)
1264 ret |= device_flush_iotlb(dev_data, address, size);
1270 static void domain_flush_pages(struct protection_domain *domain,
1271 u64 address, size_t size)
1273 __domain_flush_pages(domain, address, size, 0);
1276 /* Flush the whole IO/TLB for a given protection domain */
1277 static void domain_flush_tlb(struct protection_domain *domain)
1279 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1282 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1283 static void domain_flush_tlb_pde(struct protection_domain *domain)
1285 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1288 static void domain_flush_complete(struct protection_domain *domain)
1292 for (i = 0; i < amd_iommus_present; ++i) {
1293 if (domain && !domain->dev_iommu[i])
1297 * Devices of this domain are behind this IOMMU
1298 * We need to wait for completion of all commands.
1300 iommu_completion_wait(amd_iommus[i]);
1306 * This function flushes the DTEs for all devices in domain
1308 static void domain_flush_devices(struct protection_domain *domain)
1310 struct iommu_dev_data *dev_data;
1312 list_for_each_entry(dev_data, &domain->dev_list, list)
1313 device_flush_dte(dev_data);
1316 /****************************************************************************
1318 * The functions below are used the create the page table mappings for
1319 * unity mapped regions.
1321 ****************************************************************************/
1324 * This function is used to add another level to an IO page table. Adding
1325 * another level increases the size of the address space by 9 bits to a size up
1328 static void increase_address_space(struct protection_domain *domain,
1331 unsigned long flags;
1334 pte = (void *)get_zeroed_page(gfp);
1338 spin_lock_irqsave(&domain->lock, flags);
1340 if (WARN_ON_ONCE(domain->mode == PAGE_MODE_6_LEVEL))
1341 /* address space already 64 bit large */
1344 *pte = PM_LEVEL_PDE(domain->mode,
1345 virt_to_phys(domain->pt_root));
1346 domain->pt_root = pte;
1348 domain->updated = true;
1352 spin_unlock_irqrestore(&domain->lock, flags);
1353 free_page((unsigned long)pte);
1358 static u64 *alloc_pte(struct protection_domain *domain,
1359 unsigned long address,
1360 unsigned long page_size,
1367 BUG_ON(!is_power_of_2(page_size));
1369 while (address > PM_LEVEL_SIZE(domain->mode))
1370 increase_address_space(domain, gfp);
1372 level = domain->mode - 1;
1373 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1374 address = PAGE_SIZE_ALIGN(address, page_size);
1375 end_lvl = PAGE_SIZE_LEVEL(page_size);
1377 while (level > end_lvl) {
1382 if (!IOMMU_PTE_PRESENT(__pte)) {
1383 page = (u64 *)get_zeroed_page(gfp);
1387 __npte = PM_LEVEL_PDE(level, virt_to_phys(page));
1389 /* pte could have been changed somewhere. */
1390 if (cmpxchg64(pte, __pte, __npte) != __pte) {
1391 free_page((unsigned long)page);
1396 /* No level skipping support yet */
1397 if (PM_PTE_LEVEL(*pte) != level)
1402 pte = IOMMU_PTE_PAGE(*pte);
1404 if (pte_page && level == end_lvl)
1407 pte = &pte[PM_LEVEL_INDEX(level, address)];
1414 * This function checks if there is a PTE for a given dma address. If
1415 * there is one, it returns the pointer to it.
1417 static u64 *fetch_pte(struct protection_domain *domain,
1418 unsigned long address,
1419 unsigned long *page_size)
1424 if (address > PM_LEVEL_SIZE(domain->mode))
1427 level = domain->mode - 1;
1428 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1429 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1434 if (!IOMMU_PTE_PRESENT(*pte))
1438 if (PM_PTE_LEVEL(*pte) == 7 ||
1439 PM_PTE_LEVEL(*pte) == 0)
1442 /* No level skipping support yet */
1443 if (PM_PTE_LEVEL(*pte) != level)
1448 /* Walk to the next level */
1449 pte = IOMMU_PTE_PAGE(*pte);
1450 pte = &pte[PM_LEVEL_INDEX(level, address)];
1451 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1454 if (PM_PTE_LEVEL(*pte) == 0x07) {
1455 unsigned long pte_mask;
1458 * If we have a series of large PTEs, make
1459 * sure to return a pointer to the first one.
1461 *page_size = pte_mask = PTE_PAGE_SIZE(*pte);
1462 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1463 pte = (u64 *)(((unsigned long)pte) & pte_mask);
1470 * Generic mapping functions. It maps a physical address into a DMA
1471 * address space. It allocates the page table pages if necessary.
1472 * In the future it can be extended to a generic mapping function
1473 * supporting all features of AMD IOMMU page tables like level skipping
1474 * and full 64 bit address spaces.
1476 static int iommu_map_page(struct protection_domain *dom,
1477 unsigned long bus_addr,
1478 unsigned long phys_addr,
1479 unsigned long page_size,
1486 BUG_ON(!IS_ALIGNED(bus_addr, page_size));
1487 BUG_ON(!IS_ALIGNED(phys_addr, page_size));
1489 if (!(prot & IOMMU_PROT_MASK))
1492 count = PAGE_SIZE_PTE_COUNT(page_size);
1493 pte = alloc_pte(dom, bus_addr, page_size, NULL, gfp);
1498 for (i = 0; i < count; ++i)
1499 if (IOMMU_PTE_PRESENT(pte[i]))
1503 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1504 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1506 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1508 if (prot & IOMMU_PROT_IR)
1509 __pte |= IOMMU_PTE_IR;
1510 if (prot & IOMMU_PROT_IW)
1511 __pte |= IOMMU_PTE_IW;
1513 for (i = 0; i < count; ++i)
1521 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1522 unsigned long bus_addr,
1523 unsigned long page_size)
1525 unsigned long long unmapped;
1526 unsigned long unmap_size;
1529 BUG_ON(!is_power_of_2(page_size));
1533 while (unmapped < page_size) {
1535 pte = fetch_pte(dom, bus_addr, &unmap_size);
1540 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1541 for (i = 0; i < count; i++)
1545 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1546 unmapped += unmap_size;
1549 BUG_ON(unmapped && !is_power_of_2(unmapped));
1554 /****************************************************************************
1556 * The next functions belong to the address allocator for the dma_ops
1557 * interface functions.
1559 ****************************************************************************/
1562 static unsigned long dma_ops_alloc_iova(struct device *dev,
1563 struct dma_ops_domain *dma_dom,
1564 unsigned int pages, u64 dma_mask)
1566 unsigned long pfn = 0;
1568 pages = __roundup_pow_of_two(pages);
1570 if (dma_mask > DMA_BIT_MASK(32))
1571 pfn = alloc_iova_fast(&dma_dom->iovad, pages,
1572 IOVA_PFN(DMA_BIT_MASK(32)));
1575 pfn = alloc_iova_fast(&dma_dom->iovad, pages, IOVA_PFN(dma_mask));
1577 return (pfn << PAGE_SHIFT);
1580 static void dma_ops_free_iova(struct dma_ops_domain *dma_dom,
1581 unsigned long address,
1584 pages = __roundup_pow_of_two(pages);
1585 address >>= PAGE_SHIFT;
1587 free_iova_fast(&dma_dom->iovad, address, pages);
1590 /****************************************************************************
1592 * The next functions belong to the domain allocation. A domain is
1593 * allocated for every IOMMU as the default domain. If device isolation
1594 * is enabled, every device get its own domain. The most important thing
1595 * about domains is the page table mapping the DMA address space they
1598 ****************************************************************************/
1601 * This function adds a protection domain to the global protection domain list
1603 static void add_domain_to_list(struct protection_domain *domain)
1605 unsigned long flags;
1607 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1608 list_add(&domain->list, &amd_iommu_pd_list);
1609 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1613 * This function removes a protection domain to the global
1614 * protection domain list
1616 static void del_domain_from_list(struct protection_domain *domain)
1618 unsigned long flags;
1620 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1621 list_del(&domain->list);
1622 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1625 static u16 domain_id_alloc(void)
1627 unsigned long flags;
1630 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1631 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1633 if (id > 0 && id < MAX_DOMAIN_ID)
1634 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1637 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1642 static void domain_id_free(int id)
1644 unsigned long flags;
1646 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1647 if (id > 0 && id < MAX_DOMAIN_ID)
1648 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1649 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1652 #define DEFINE_FREE_PT_FN(LVL, FN) \
1653 static void free_pt_##LVL (unsigned long __pt) \
1661 for (i = 0; i < 512; ++i) { \
1662 /* PTE present? */ \
1663 if (!IOMMU_PTE_PRESENT(pt[i])) \
1667 if (PM_PTE_LEVEL(pt[i]) == 0 || \
1668 PM_PTE_LEVEL(pt[i]) == 7) \
1671 p = (unsigned long)IOMMU_PTE_PAGE(pt[i]); \
1674 free_page((unsigned long)pt); \
1677 DEFINE_FREE_PT_FN(l2, free_page)
1678 DEFINE_FREE_PT_FN(l3, free_pt_l2)
1679 DEFINE_FREE_PT_FN(l4, free_pt_l3)
1680 DEFINE_FREE_PT_FN(l5, free_pt_l4)
1681 DEFINE_FREE_PT_FN(l6, free_pt_l5)
1683 static void free_pagetable(struct protection_domain *domain)
1685 unsigned long root = (unsigned long)domain->pt_root;
1687 switch (domain->mode) {
1688 case PAGE_MODE_NONE:
1690 case PAGE_MODE_1_LEVEL:
1693 case PAGE_MODE_2_LEVEL:
1696 case PAGE_MODE_3_LEVEL:
1699 case PAGE_MODE_4_LEVEL:
1702 case PAGE_MODE_5_LEVEL:
1705 case PAGE_MODE_6_LEVEL:
1713 static void free_gcr3_tbl_level1(u64 *tbl)
1718 for (i = 0; i < 512; ++i) {
1719 if (!(tbl[i] & GCR3_VALID))
1722 ptr = __va(tbl[i] & PAGE_MASK);
1724 free_page((unsigned long)ptr);
1728 static void free_gcr3_tbl_level2(u64 *tbl)
1733 for (i = 0; i < 512; ++i) {
1734 if (!(tbl[i] & GCR3_VALID))
1737 ptr = __va(tbl[i] & PAGE_MASK);
1739 free_gcr3_tbl_level1(ptr);
1743 static void free_gcr3_table(struct protection_domain *domain)
1745 if (domain->glx == 2)
1746 free_gcr3_tbl_level2(domain->gcr3_tbl);
1747 else if (domain->glx == 1)
1748 free_gcr3_tbl_level1(domain->gcr3_tbl);
1750 BUG_ON(domain->glx != 0);
1752 free_page((unsigned long)domain->gcr3_tbl);
1756 * Free a domain, only used if something went wrong in the
1757 * allocation path and we need to free an already allocated page table
1759 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1764 del_domain_from_list(&dom->domain);
1766 put_iova_domain(&dom->iovad);
1768 free_pagetable(&dom->domain);
1771 domain_id_free(dom->domain.id);
1777 * Allocates a new protection domain usable for the dma_ops functions.
1778 * It also initializes the page table and the address allocator data
1779 * structures required for the dma_ops interface
1781 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1783 struct dma_ops_domain *dma_dom;
1785 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1789 if (protection_domain_init(&dma_dom->domain))
1792 dma_dom->domain.mode = PAGE_MODE_3_LEVEL;
1793 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1794 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1795 if (!dma_dom->domain.pt_root)
1798 init_iova_domain(&dma_dom->iovad, PAGE_SIZE,
1799 IOVA_START_PFN, DMA_32BIT_PFN);
1801 /* Initialize reserved ranges */
1802 copy_reserved_iova(&reserved_iova_ranges, &dma_dom->iovad);
1804 add_domain_to_list(&dma_dom->domain);
1809 dma_ops_domain_free(dma_dom);
1815 * little helper function to check whether a given protection domain is a
1818 static bool dma_ops_domain(struct protection_domain *domain)
1820 return domain->flags & PD_DMA_OPS_MASK;
1823 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1828 if (domain->mode != PAGE_MODE_NONE)
1829 pte_root = virt_to_phys(domain->pt_root);
1831 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1832 << DEV_ENTRY_MODE_SHIFT;
1833 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1835 flags = amd_iommu_dev_table[devid].data[1];
1838 flags |= DTE_FLAG_IOTLB;
1840 if (domain->flags & PD_IOMMUV2_MASK) {
1841 u64 gcr3 = __pa(domain->gcr3_tbl);
1842 u64 glx = domain->glx;
1845 pte_root |= DTE_FLAG_GV;
1846 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1848 /* First mask out possible old values for GCR3 table */
1849 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1852 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1855 /* Encode GCR3 table into DTE */
1856 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1859 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1862 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
1866 flags &= ~(0xffffUL);
1867 flags |= domain->id;
1869 amd_iommu_dev_table[devid].data[1] = flags;
1870 amd_iommu_dev_table[devid].data[0] = pte_root;
1873 static void clear_dte_entry(u16 devid)
1875 /* remove entry from the device table seen by the hardware */
1876 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1877 amd_iommu_dev_table[devid].data[1] &= DTE_FLAG_MASK;
1879 amd_iommu_apply_erratum_63(devid);
1882 static void do_attach(struct iommu_dev_data *dev_data,
1883 struct protection_domain *domain)
1885 struct amd_iommu *iommu;
1889 iommu = amd_iommu_rlookup_table[dev_data->devid];
1890 alias = dev_data->alias;
1891 ats = dev_data->ats.enabled;
1893 /* Update data structures */
1894 dev_data->domain = domain;
1895 list_add(&dev_data->list, &domain->dev_list);
1897 /* Do reference counting */
1898 domain->dev_iommu[iommu->index] += 1;
1899 domain->dev_cnt += 1;
1901 /* Update device table */
1902 set_dte_entry(dev_data->devid, domain, ats);
1903 if (alias != dev_data->devid)
1904 set_dte_entry(alias, domain, ats);
1906 device_flush_dte(dev_data);
1909 static void do_detach(struct iommu_dev_data *dev_data)
1911 struct protection_domain *domain = dev_data->domain;
1912 struct amd_iommu *iommu;
1916 * First check if the device is still attached. It might already
1917 * be detached from its domain because the generic
1918 * iommu_detach_group code detached it and we try again here in
1919 * our alias handling.
1921 if (!dev_data->domain)
1924 iommu = amd_iommu_rlookup_table[dev_data->devid];
1925 alias = dev_data->alias;
1927 /* Update data structures */
1928 dev_data->domain = NULL;
1929 list_del(&dev_data->list);
1930 clear_dte_entry(dev_data->devid);
1931 if (alias != dev_data->devid)
1932 clear_dte_entry(alias);
1934 /* Flush the DTE entry */
1935 device_flush_dte(dev_data);
1938 domain_flush_tlb_pde(domain);
1940 /* Wait for the flushes to finish */
1941 domain_flush_complete(domain);
1943 /* decrease reference counters - needs to happen after the flushes */
1944 domain->dev_iommu[iommu->index] -= 1;
1945 domain->dev_cnt -= 1;
1949 * If a device is not yet associated with a domain, this function does
1950 * assigns it visible for the hardware
1952 static int __attach_device(struct iommu_dev_data *dev_data,
1953 struct protection_domain *domain)
1958 * Must be called with IRQs disabled. Warn here to detect early
1961 WARN_ON(!irqs_disabled());
1964 spin_lock(&domain->lock);
1967 if (dev_data->domain != NULL)
1970 /* Attach alias group root */
1971 do_attach(dev_data, domain);
1978 spin_unlock(&domain->lock);
1984 static void pdev_iommuv2_disable(struct pci_dev *pdev)
1986 pci_disable_ats(pdev);
1987 pci_disable_pri(pdev);
1988 pci_disable_pasid(pdev);
1991 /* FIXME: Change generic reset-function to do the same */
1992 static int pri_reset_while_enabled(struct pci_dev *pdev)
1997 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2001 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2002 control |= PCI_PRI_CTRL_RESET;
2003 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2008 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2013 /* FIXME: Hardcode number of outstanding requests for now */
2015 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2017 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2019 /* Only allow access to user-accessible pages */
2020 ret = pci_enable_pasid(pdev, 0);
2024 /* First reset the PRI state of the device */
2025 ret = pci_reset_pri(pdev);
2030 ret = pci_enable_pri(pdev, reqs);
2035 ret = pri_reset_while_enabled(pdev);
2040 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2047 pci_disable_pri(pdev);
2048 pci_disable_pasid(pdev);
2053 /* FIXME: Move this to PCI code */
2054 #define PCI_PRI_TLP_OFF (1 << 15)
2056 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2061 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2065 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2067 return (status & PCI_PRI_TLP_OFF) ? true : false;
2071 * If a device is not yet associated with a domain, this function
2072 * assigns it visible for the hardware
2074 static int attach_device(struct device *dev,
2075 struct protection_domain *domain)
2077 struct pci_dev *pdev;
2078 struct iommu_dev_data *dev_data;
2079 unsigned long flags;
2082 dev_data = get_dev_data(dev);
2084 if (!dev_is_pci(dev))
2085 goto skip_ats_check;
2087 pdev = to_pci_dev(dev);
2088 if (domain->flags & PD_IOMMUV2_MASK) {
2089 if (!dev_data->passthrough)
2092 if (dev_data->iommu_v2) {
2093 if (pdev_iommuv2_enable(pdev) != 0)
2096 dev_data->ats.enabled = true;
2097 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2098 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2100 } else if (amd_iommu_iotlb_sup &&
2101 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2102 dev_data->ats.enabled = true;
2103 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2107 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2108 ret = __attach_device(dev_data, domain);
2109 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2112 * We might boot into a crash-kernel here. The crashed kernel
2113 * left the caches in the IOMMU dirty. So we have to flush
2114 * here to evict all dirty stuff.
2116 domain_flush_tlb_pde(domain);
2118 domain_flush_complete(domain);
2124 * Removes a device from a protection domain (unlocked)
2126 static void __detach_device(struct iommu_dev_data *dev_data)
2128 struct protection_domain *domain;
2131 * Must be called with IRQs disabled. Warn here to detect early
2134 WARN_ON(!irqs_disabled());
2136 if (WARN_ON(!dev_data->domain))
2139 domain = dev_data->domain;
2141 spin_lock(&domain->lock);
2143 do_detach(dev_data);
2145 spin_unlock(&domain->lock);
2149 * Removes a device from a protection domain (with devtable_lock held)
2151 static void detach_device(struct device *dev)
2153 struct protection_domain *domain;
2154 struct iommu_dev_data *dev_data;
2155 unsigned long flags;
2157 dev_data = get_dev_data(dev);
2158 domain = dev_data->domain;
2160 /* lock device table */
2161 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2162 __detach_device(dev_data);
2163 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2165 if (!dev_is_pci(dev))
2168 if (domain->flags & PD_IOMMUV2_MASK && dev_data->iommu_v2)
2169 pdev_iommuv2_disable(to_pci_dev(dev));
2170 else if (dev_data->ats.enabled)
2171 pci_disable_ats(to_pci_dev(dev));
2173 dev_data->ats.enabled = false;
2176 static int amd_iommu_add_device(struct device *dev)
2178 struct iommu_dev_data *dev_data;
2179 struct iommu_domain *domain;
2180 struct amd_iommu *iommu;
2183 if (!check_device(dev) || get_dev_data(dev))
2186 devid = get_device_id(dev);
2190 iommu = amd_iommu_rlookup_table[devid];
2192 ret = iommu_init_device(dev);
2194 if (ret != -ENOTSUPP)
2195 pr_err("Failed to initialize device %s - trying to proceed anyway\n",
2198 iommu_ignore_device(dev);
2199 dev->archdata.dma_ops = &nommu_dma_ops;
2202 init_iommu_group(dev);
2204 dev_data = get_dev_data(dev);
2208 if (iommu_pass_through || dev_data->iommu_v2)
2209 iommu_request_dm_for_dev(dev);
2211 /* Domains are initialized for this device - have a look what we ended up with */
2212 domain = iommu_get_domain_for_dev(dev);
2213 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2214 dev_data->passthrough = true;
2216 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2219 iommu_completion_wait(iommu);
2224 static void amd_iommu_remove_device(struct device *dev)
2226 struct amd_iommu *iommu;
2229 if (!check_device(dev))
2232 devid = get_device_id(dev);
2236 iommu = amd_iommu_rlookup_table[devid];
2238 iommu_uninit_device(dev);
2239 iommu_completion_wait(iommu);
2242 static struct iommu_group *amd_iommu_device_group(struct device *dev)
2244 if (dev_is_pci(dev))
2245 return pci_device_group(dev);
2247 return acpihid_device_group(dev);
2250 /*****************************************************************************
2252 * The next functions belong to the dma_ops mapping/unmapping code.
2254 *****************************************************************************/
2256 static void __queue_flush(struct flush_queue *queue)
2258 struct protection_domain *domain;
2259 unsigned long flags;
2262 /* First flush TLB of all known domains */
2263 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
2264 list_for_each_entry(domain, &amd_iommu_pd_list, list)
2265 domain_flush_tlb(domain);
2266 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
2268 /* Wait until flushes have completed */
2269 domain_flush_complete(NULL);
2271 for (idx = 0; idx < queue->next; ++idx) {
2272 struct flush_queue_entry *entry;
2274 entry = queue->entries + idx;
2276 free_iova_fast(&entry->dma_dom->iovad,
2280 /* Not really necessary, just to make sure we catch any bugs */
2281 entry->dma_dom = NULL;
2287 static void queue_flush_all(void)
2291 for_each_possible_cpu(cpu) {
2292 struct flush_queue *queue;
2293 unsigned long flags;
2295 queue = per_cpu_ptr(&flush_queue, cpu);
2296 spin_lock_irqsave(&queue->lock, flags);
2297 if (queue->next > 0)
2298 __queue_flush(queue);
2299 spin_unlock_irqrestore(&queue->lock, flags);
2303 static void queue_flush_timeout(unsigned long unsused)
2305 atomic_set(&queue_timer_on, 0);
2309 static void queue_add(struct dma_ops_domain *dma_dom,
2310 unsigned long address, unsigned long pages)
2312 struct flush_queue_entry *entry;
2313 struct flush_queue *queue;
2314 unsigned long flags;
2317 pages = __roundup_pow_of_two(pages);
2318 address >>= PAGE_SHIFT;
2320 queue = get_cpu_ptr(&flush_queue);
2321 spin_lock_irqsave(&queue->lock, flags);
2323 if (queue->next == FLUSH_QUEUE_SIZE)
2324 __queue_flush(queue);
2326 idx = queue->next++;
2327 entry = queue->entries + idx;
2329 entry->iova_pfn = address;
2330 entry->pages = pages;
2331 entry->dma_dom = dma_dom;
2333 spin_unlock_irqrestore(&queue->lock, flags);
2335 if (atomic_cmpxchg(&queue_timer_on, 0, 1) == 0)
2336 mod_timer(&queue_timer, jiffies + msecs_to_jiffies(10));
2338 put_cpu_ptr(&flush_queue);
2343 * In the dma_ops path we only have the struct device. This function
2344 * finds the corresponding IOMMU, the protection domain and the
2345 * requestor id for a given device.
2346 * If the device is not yet associated with a domain this is also done
2349 static struct protection_domain *get_domain(struct device *dev)
2351 struct protection_domain *domain;
2353 if (!check_device(dev))
2354 return ERR_PTR(-EINVAL);
2356 domain = get_dev_data(dev)->domain;
2357 if (!dma_ops_domain(domain))
2358 return ERR_PTR(-EBUSY);
2363 static void update_device_table(struct protection_domain *domain)
2365 struct iommu_dev_data *dev_data;
2367 list_for_each_entry(dev_data, &domain->dev_list, list) {
2368 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2370 if (dev_data->devid == dev_data->alias)
2373 /* There is an alias, update device table entry for it */
2374 set_dte_entry(dev_data->alias, domain, dev_data->ats.enabled);
2378 static void update_domain(struct protection_domain *domain)
2380 if (!domain->updated)
2383 update_device_table(domain);
2385 domain_flush_devices(domain);
2386 domain_flush_tlb_pde(domain);
2388 domain->updated = false;
2391 static int dir2prot(enum dma_data_direction direction)
2393 if (direction == DMA_TO_DEVICE)
2394 return IOMMU_PROT_IR;
2395 else if (direction == DMA_FROM_DEVICE)
2396 return IOMMU_PROT_IW;
2397 else if (direction == DMA_BIDIRECTIONAL)
2398 return IOMMU_PROT_IW | IOMMU_PROT_IR;
2403 * This function contains common code for mapping of a physically
2404 * contiguous memory region into DMA address space. It is used by all
2405 * mapping functions provided with this IOMMU driver.
2406 * Must be called with the domain lock held.
2408 static dma_addr_t __map_single(struct device *dev,
2409 struct dma_ops_domain *dma_dom,
2412 enum dma_data_direction direction,
2415 dma_addr_t offset = paddr & ~PAGE_MASK;
2416 dma_addr_t address, start, ret;
2421 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2424 address = dma_ops_alloc_iova(dev, dma_dom, pages, dma_mask);
2425 if (address == DMA_ERROR_CODE)
2428 prot = dir2prot(direction);
2431 for (i = 0; i < pages; ++i) {
2432 ret = iommu_map_page(&dma_dom->domain, start, paddr,
2433 PAGE_SIZE, prot, GFP_ATOMIC);
2442 if (unlikely(amd_iommu_np_cache)) {
2443 domain_flush_pages(&dma_dom->domain, address, size);
2444 domain_flush_complete(&dma_dom->domain);
2452 for (--i; i >= 0; --i) {
2454 iommu_unmap_page(&dma_dom->domain, start, PAGE_SIZE);
2457 domain_flush_tlb(&dma_dom->domain);
2458 domain_flush_complete(&dma_dom->domain);
2460 dma_ops_free_iova(dma_dom, address, pages);
2462 return DMA_ERROR_CODE;
2466 * Does the reverse of the __map_single function. Must be called with
2467 * the domain lock held too
2469 static void __unmap_single(struct dma_ops_domain *dma_dom,
2470 dma_addr_t dma_addr,
2474 dma_addr_t flush_addr;
2475 dma_addr_t i, start;
2478 flush_addr = dma_addr;
2479 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2480 dma_addr &= PAGE_MASK;
2483 for (i = 0; i < pages; ++i) {
2484 iommu_unmap_page(&dma_dom->domain, start, PAGE_SIZE);
2488 if (amd_iommu_unmap_flush) {
2489 domain_flush_tlb(&dma_dom->domain);
2490 domain_flush_complete(&dma_dom->domain);
2491 dma_ops_free_iova(dma_dom, dma_addr, pages);
2493 queue_add(dma_dom, dma_addr, pages);
2498 * The exported map_single function for dma_ops.
2500 static dma_addr_t map_page(struct device *dev, struct page *page,
2501 unsigned long offset, size_t size,
2502 enum dma_data_direction dir,
2503 unsigned long attrs)
2505 phys_addr_t paddr = page_to_phys(page) + offset;
2506 struct protection_domain *domain;
2507 struct dma_ops_domain *dma_dom;
2510 domain = get_domain(dev);
2511 if (PTR_ERR(domain) == -EINVAL)
2512 return (dma_addr_t)paddr;
2513 else if (IS_ERR(domain))
2514 return DMA_ERROR_CODE;
2516 dma_mask = *dev->dma_mask;
2517 dma_dom = to_dma_ops_domain(domain);
2519 return __map_single(dev, dma_dom, paddr, size, dir, dma_mask);
2523 * The exported unmap_single function for dma_ops.
2525 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2526 enum dma_data_direction dir, unsigned long attrs)
2528 struct protection_domain *domain;
2529 struct dma_ops_domain *dma_dom;
2531 domain = get_domain(dev);
2535 dma_dom = to_dma_ops_domain(domain);
2537 __unmap_single(dma_dom, dma_addr, size, dir);
2540 static int sg_num_pages(struct device *dev,
2541 struct scatterlist *sglist,
2544 unsigned long mask, boundary_size;
2545 struct scatterlist *s;
2548 mask = dma_get_seg_boundary(dev);
2549 boundary_size = mask + 1 ? ALIGN(mask + 1, PAGE_SIZE) >> PAGE_SHIFT :
2550 1UL << (BITS_PER_LONG - PAGE_SHIFT);
2552 for_each_sg(sglist, s, nelems, i) {
2555 s->dma_address = npages << PAGE_SHIFT;
2556 p = npages % boundary_size;
2557 n = iommu_num_pages(sg_phys(s), s->length, PAGE_SIZE);
2558 if (p + n > boundary_size)
2559 npages += boundary_size - p;
2567 * The exported map_sg function for dma_ops (handles scatter-gather
2570 static int map_sg(struct device *dev, struct scatterlist *sglist,
2571 int nelems, enum dma_data_direction direction,
2572 unsigned long attrs)
2574 int mapped_pages = 0, npages = 0, prot = 0, i;
2575 struct protection_domain *domain;
2576 struct dma_ops_domain *dma_dom;
2577 struct scatterlist *s;
2578 unsigned long address;
2581 domain = get_domain(dev);
2585 dma_dom = to_dma_ops_domain(domain);
2586 dma_mask = *dev->dma_mask;
2588 npages = sg_num_pages(dev, sglist, nelems);
2590 address = dma_ops_alloc_iova(dev, dma_dom, npages, dma_mask);
2591 if (address == DMA_ERROR_CODE)
2594 prot = dir2prot(direction);
2596 /* Map all sg entries */
2597 for_each_sg(sglist, s, nelems, i) {
2598 int j, pages = iommu_num_pages(sg_phys(s), s->length, PAGE_SIZE);
2600 for (j = 0; j < pages; ++j) {
2601 unsigned long bus_addr, phys_addr;
2604 bus_addr = address + s->dma_address + (j << PAGE_SHIFT);
2605 phys_addr = (sg_phys(s) & PAGE_MASK) + (j << PAGE_SHIFT);
2606 ret = iommu_map_page(domain, bus_addr, phys_addr,
2608 GFP_ATOMIC | __GFP_NOWARN);
2616 /* Everything is mapped - write the right values into s->dma_address */
2617 for_each_sg(sglist, s, nelems, i) {
2619 * Add in the remaining piece of the scatter-gather offset that
2620 * was masked out when we were determining the physical address
2621 * via (sg_phys(s) & PAGE_MASK) earlier.
2623 s->dma_address += address + (s->offset & ~PAGE_MASK);
2624 s->dma_length = s->length;
2630 pr_err("%s: IOMMU mapping error in map_sg (io-pages: %d)\n",
2631 dev_name(dev), npages);
2633 for_each_sg(sglist, s, nelems, i) {
2634 int j, pages = iommu_num_pages(sg_phys(s), s->length, PAGE_SIZE);
2636 for (j = 0; j < pages; ++j) {
2637 unsigned long bus_addr;
2639 bus_addr = address + s->dma_address + (j << PAGE_SHIFT);
2640 iommu_unmap_page(domain, bus_addr, PAGE_SIZE);
2642 if (--mapped_pages == 0)
2648 free_iova_fast(&dma_dom->iovad, address >> PAGE_SHIFT, npages);
2655 * The exported map_sg function for dma_ops (handles scatter-gather
2658 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2659 int nelems, enum dma_data_direction dir,
2660 unsigned long attrs)
2662 struct protection_domain *domain;
2663 struct dma_ops_domain *dma_dom;
2664 unsigned long startaddr;
2667 domain = get_domain(dev);
2671 startaddr = sg_dma_address(sglist) & PAGE_MASK;
2672 dma_dom = to_dma_ops_domain(domain);
2673 npages = sg_num_pages(dev, sglist, nelems);
2675 __unmap_single(dma_dom, startaddr, npages << PAGE_SHIFT, dir);
2679 * The exported alloc_coherent function for dma_ops.
2681 static void *alloc_coherent(struct device *dev, size_t size,
2682 dma_addr_t *dma_addr, gfp_t flag,
2683 unsigned long attrs)
2685 u64 dma_mask = dev->coherent_dma_mask;
2686 struct protection_domain *domain;
2687 struct dma_ops_domain *dma_dom;
2690 domain = get_domain(dev);
2691 if (PTR_ERR(domain) == -EINVAL) {
2692 page = alloc_pages(flag, get_order(size));
2693 *dma_addr = page_to_phys(page);
2694 return page_address(page);
2695 } else if (IS_ERR(domain))
2698 dma_dom = to_dma_ops_domain(domain);
2699 size = PAGE_ALIGN(size);
2700 dma_mask = dev->coherent_dma_mask;
2701 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2704 page = alloc_pages(flag | __GFP_NOWARN, get_order(size));
2706 if (!gfpflags_allow_blocking(flag))
2709 page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
2716 dma_mask = *dev->dma_mask;
2718 *dma_addr = __map_single(dev, dma_dom, page_to_phys(page),
2719 size, DMA_BIDIRECTIONAL, dma_mask);
2721 if (*dma_addr == DMA_ERROR_CODE)
2724 return page_address(page);
2728 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2729 __free_pages(page, get_order(size));
2735 * The exported free_coherent function for dma_ops.
2737 static void free_coherent(struct device *dev, size_t size,
2738 void *virt_addr, dma_addr_t dma_addr,
2739 unsigned long attrs)
2741 struct protection_domain *domain;
2742 struct dma_ops_domain *dma_dom;
2745 page = virt_to_page(virt_addr);
2746 size = PAGE_ALIGN(size);
2748 domain = get_domain(dev);
2752 dma_dom = to_dma_ops_domain(domain);
2754 __unmap_single(dma_dom, dma_addr, size, DMA_BIDIRECTIONAL);
2757 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2758 __free_pages(page, get_order(size));
2762 * This function is called by the DMA layer to find out if we can handle a
2763 * particular device. It is part of the dma_ops.
2765 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2767 return check_device(dev);
2770 static struct dma_map_ops amd_iommu_dma_ops = {
2771 .alloc = alloc_coherent,
2772 .free = free_coherent,
2773 .map_page = map_page,
2774 .unmap_page = unmap_page,
2776 .unmap_sg = unmap_sg,
2777 .dma_supported = amd_iommu_dma_supported,
2780 static int init_reserved_iova_ranges(void)
2782 struct pci_dev *pdev = NULL;
2785 init_iova_domain(&reserved_iova_ranges, PAGE_SIZE,
2786 IOVA_START_PFN, DMA_32BIT_PFN);
2788 lockdep_set_class(&reserved_iova_ranges.iova_rbtree_lock,
2789 &reserved_rbtree_key);
2791 /* MSI memory range */
2792 val = reserve_iova(&reserved_iova_ranges,
2793 IOVA_PFN(MSI_RANGE_START), IOVA_PFN(MSI_RANGE_END));
2795 pr_err("Reserving MSI range failed\n");
2799 /* HT memory range */
2800 val = reserve_iova(&reserved_iova_ranges,
2801 IOVA_PFN(HT_RANGE_START), IOVA_PFN(HT_RANGE_END));
2803 pr_err("Reserving HT range failed\n");
2808 * Memory used for PCI resources
2809 * FIXME: Check whether we can reserve the PCI-hole completly
2811 for_each_pci_dev(pdev) {
2814 for (i = 0; i < PCI_NUM_RESOURCES; ++i) {
2815 struct resource *r = &pdev->resource[i];
2817 if (!(r->flags & IORESOURCE_MEM))
2820 val = reserve_iova(&reserved_iova_ranges,
2824 pr_err("Reserve pci-resource range failed\n");
2833 int __init amd_iommu_init_api(void)
2835 int ret, cpu, err = 0;
2837 ret = iova_cache_get();
2841 ret = init_reserved_iova_ranges();
2845 for_each_possible_cpu(cpu) {
2846 struct flush_queue *queue = per_cpu_ptr(&flush_queue, cpu);
2848 queue->entries = kzalloc(FLUSH_QUEUE_SIZE *
2849 sizeof(*queue->entries),
2851 if (!queue->entries)
2854 spin_lock_init(&queue->lock);
2857 err = bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2860 #ifdef CONFIG_ARM_AMBA
2861 err = bus_set_iommu(&amba_bustype, &amd_iommu_ops);
2865 err = bus_set_iommu(&platform_bus_type, &amd_iommu_ops);
2871 for_each_possible_cpu(cpu) {
2872 struct flush_queue *queue = per_cpu_ptr(&flush_queue, cpu);
2874 kfree(queue->entries);
2880 int __init amd_iommu_init_dma_ops(void)
2882 setup_timer(&queue_timer, queue_flush_timeout, 0);
2883 atomic_set(&queue_timer_on, 0);
2885 swiotlb = iommu_pass_through ? 1 : 0;
2889 * In case we don't initialize SWIOTLB (actually the common case
2890 * when AMD IOMMU is enabled), make sure there are global
2891 * dma_ops set as a fall-back for devices not handled by this
2892 * driver (for example non-PCI devices).
2895 dma_ops = &nommu_dma_ops;
2897 if (amd_iommu_unmap_flush)
2898 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
2900 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
2906 /*****************************************************************************
2908 * The following functions belong to the exported interface of AMD IOMMU
2910 * This interface allows access to lower level functions of the IOMMU
2911 * like protection domain handling and assignement of devices to domains
2912 * which is not possible with the dma_ops interface.
2914 *****************************************************************************/
2916 static void cleanup_domain(struct protection_domain *domain)
2918 struct iommu_dev_data *entry;
2919 unsigned long flags;
2921 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2923 while (!list_empty(&domain->dev_list)) {
2924 entry = list_first_entry(&domain->dev_list,
2925 struct iommu_dev_data, list);
2926 __detach_device(entry);
2929 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2932 static void protection_domain_free(struct protection_domain *domain)
2937 del_domain_from_list(domain);
2940 domain_id_free(domain->id);
2945 static int protection_domain_init(struct protection_domain *domain)
2947 spin_lock_init(&domain->lock);
2948 mutex_init(&domain->api_lock);
2949 domain->id = domain_id_alloc();
2952 INIT_LIST_HEAD(&domain->dev_list);
2957 static struct protection_domain *protection_domain_alloc(void)
2959 struct protection_domain *domain;
2961 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2965 if (protection_domain_init(domain))
2968 add_domain_to_list(domain);
2978 static struct iommu_domain *amd_iommu_domain_alloc(unsigned type)
2980 struct protection_domain *pdomain;
2981 struct dma_ops_domain *dma_domain;
2984 case IOMMU_DOMAIN_UNMANAGED:
2985 pdomain = protection_domain_alloc();
2989 pdomain->mode = PAGE_MODE_3_LEVEL;
2990 pdomain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2991 if (!pdomain->pt_root) {
2992 protection_domain_free(pdomain);
2996 pdomain->domain.geometry.aperture_start = 0;
2997 pdomain->domain.geometry.aperture_end = ~0ULL;
2998 pdomain->domain.geometry.force_aperture = true;
3001 case IOMMU_DOMAIN_DMA:
3002 dma_domain = dma_ops_domain_alloc();
3004 pr_err("AMD-Vi: Failed to allocate\n");
3007 pdomain = &dma_domain->domain;
3009 case IOMMU_DOMAIN_IDENTITY:
3010 pdomain = protection_domain_alloc();
3014 pdomain->mode = PAGE_MODE_NONE;
3020 return &pdomain->domain;
3023 static void amd_iommu_domain_free(struct iommu_domain *dom)
3025 struct protection_domain *domain;
3026 struct dma_ops_domain *dma_dom;
3028 domain = to_pdomain(dom);
3030 if (domain->dev_cnt > 0)
3031 cleanup_domain(domain);
3033 BUG_ON(domain->dev_cnt != 0);
3038 switch (dom->type) {
3039 case IOMMU_DOMAIN_DMA:
3041 * First make sure the domain is no longer referenced from the
3046 /* Now release the domain */
3047 dma_dom = to_dma_ops_domain(domain);
3048 dma_ops_domain_free(dma_dom);
3051 if (domain->mode != PAGE_MODE_NONE)
3052 free_pagetable(domain);
3054 if (domain->flags & PD_IOMMUV2_MASK)
3055 free_gcr3_table(domain);
3057 protection_domain_free(domain);
3062 static void amd_iommu_detach_device(struct iommu_domain *dom,
3065 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3066 struct amd_iommu *iommu;
3069 if (!check_device(dev))
3072 devid = get_device_id(dev);
3076 if (dev_data->domain != NULL)
3079 iommu = amd_iommu_rlookup_table[devid];
3083 #ifdef CONFIG_IRQ_REMAP
3084 if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) &&
3085 (dom->type == IOMMU_DOMAIN_UNMANAGED))
3086 dev_data->use_vapic = 0;
3089 iommu_completion_wait(iommu);
3092 static int amd_iommu_attach_device(struct iommu_domain *dom,
3095 struct protection_domain *domain = to_pdomain(dom);
3096 struct iommu_dev_data *dev_data;
3097 struct amd_iommu *iommu;
3100 if (!check_device(dev))
3103 dev_data = dev->archdata.iommu;
3105 iommu = amd_iommu_rlookup_table[dev_data->devid];
3109 if (dev_data->domain)
3112 ret = attach_device(dev, domain);
3114 #ifdef CONFIG_IRQ_REMAP
3115 if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
3116 if (dom->type == IOMMU_DOMAIN_UNMANAGED)
3117 dev_data->use_vapic = 1;
3119 dev_data->use_vapic = 0;
3123 iommu_completion_wait(iommu);
3128 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3129 phys_addr_t paddr, size_t page_size, int iommu_prot)
3131 struct protection_domain *domain = to_pdomain(dom);
3135 if (domain->mode == PAGE_MODE_NONE)
3138 if (iommu_prot & IOMMU_READ)
3139 prot |= IOMMU_PROT_IR;
3140 if (iommu_prot & IOMMU_WRITE)
3141 prot |= IOMMU_PROT_IW;
3143 mutex_lock(&domain->api_lock);
3144 ret = iommu_map_page(domain, iova, paddr, page_size, prot, GFP_KERNEL);
3145 mutex_unlock(&domain->api_lock);
3150 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3153 struct protection_domain *domain = to_pdomain(dom);
3156 if (domain->mode == PAGE_MODE_NONE)
3159 mutex_lock(&domain->api_lock);
3160 unmap_size = iommu_unmap_page(domain, iova, page_size);
3161 mutex_unlock(&domain->api_lock);
3163 domain_flush_tlb_pde(domain);
3164 domain_flush_complete(domain);
3169 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3172 struct protection_domain *domain = to_pdomain(dom);
3173 unsigned long offset_mask, pte_pgsize;
3176 if (domain->mode == PAGE_MODE_NONE)
3179 pte = fetch_pte(domain, iova, &pte_pgsize);
3181 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3184 offset_mask = pte_pgsize - 1;
3185 __pte = *pte & PM_ADDR_MASK;
3187 return (__pte & ~offset_mask) | (iova & offset_mask);
3190 static bool amd_iommu_capable(enum iommu_cap cap)
3193 case IOMMU_CAP_CACHE_COHERENCY:
3195 case IOMMU_CAP_INTR_REMAP:
3196 return (irq_remapping_enabled == 1);
3197 case IOMMU_CAP_NOEXEC:
3204 static void amd_iommu_get_dm_regions(struct device *dev,
3205 struct list_head *head)
3207 struct unity_map_entry *entry;
3210 devid = get_device_id(dev);
3214 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
3215 struct iommu_dm_region *region;
3217 if (devid < entry->devid_start || devid > entry->devid_end)
3220 region = kzalloc(sizeof(*region), GFP_KERNEL);
3222 pr_err("Out of memory allocating dm-regions for %s\n",
3227 region->start = entry->address_start;
3228 region->length = entry->address_end - entry->address_start;
3229 if (entry->prot & IOMMU_PROT_IR)
3230 region->prot |= IOMMU_READ;
3231 if (entry->prot & IOMMU_PROT_IW)
3232 region->prot |= IOMMU_WRITE;
3234 list_add_tail(®ion->list, head);
3238 static void amd_iommu_put_dm_regions(struct device *dev,
3239 struct list_head *head)
3241 struct iommu_dm_region *entry, *next;
3243 list_for_each_entry_safe(entry, next, head, list)
3247 static void amd_iommu_apply_dm_region(struct device *dev,
3248 struct iommu_domain *domain,
3249 struct iommu_dm_region *region)
3251 struct dma_ops_domain *dma_dom = to_dma_ops_domain(to_pdomain(domain));
3252 unsigned long start, end;
3254 start = IOVA_PFN(region->start);
3255 end = IOVA_PFN(region->start + region->length - 1);
3257 WARN_ON_ONCE(reserve_iova(&dma_dom->iovad, start, end) == NULL);
3260 static const struct iommu_ops amd_iommu_ops = {
3261 .capable = amd_iommu_capable,
3262 .domain_alloc = amd_iommu_domain_alloc,
3263 .domain_free = amd_iommu_domain_free,
3264 .attach_dev = amd_iommu_attach_device,
3265 .detach_dev = amd_iommu_detach_device,
3266 .map = amd_iommu_map,
3267 .unmap = amd_iommu_unmap,
3268 .map_sg = default_iommu_map_sg,
3269 .iova_to_phys = amd_iommu_iova_to_phys,
3270 .add_device = amd_iommu_add_device,
3271 .remove_device = amd_iommu_remove_device,
3272 .device_group = amd_iommu_device_group,
3273 .get_dm_regions = amd_iommu_get_dm_regions,
3274 .put_dm_regions = amd_iommu_put_dm_regions,
3275 .apply_dm_region = amd_iommu_apply_dm_region,
3276 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3279 /*****************************************************************************
3281 * The next functions do a basic initialization of IOMMU for pass through
3284 * In passthrough mode the IOMMU is initialized and enabled but not used for
3285 * DMA-API translation.
3287 *****************************************************************************/
3289 /* IOMMUv2 specific functions */
3290 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3292 return atomic_notifier_chain_register(&ppr_notifier, nb);
3294 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3296 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3298 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3300 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3302 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3304 struct protection_domain *domain = to_pdomain(dom);
3305 unsigned long flags;
3307 spin_lock_irqsave(&domain->lock, flags);
3309 /* Update data structure */
3310 domain->mode = PAGE_MODE_NONE;
3311 domain->updated = true;
3313 /* Make changes visible to IOMMUs */
3314 update_domain(domain);
3316 /* Page-table is not visible to IOMMU anymore, so free it */
3317 free_pagetable(domain);
3319 spin_unlock_irqrestore(&domain->lock, flags);
3321 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3323 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3325 struct protection_domain *domain = to_pdomain(dom);
3326 unsigned long flags;
3329 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3332 /* Number of GCR3 table levels required */
3333 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3336 if (levels > amd_iommu_max_glx_val)
3339 spin_lock_irqsave(&domain->lock, flags);
3342 * Save us all sanity checks whether devices already in the
3343 * domain support IOMMUv2. Just force that the domain has no
3344 * devices attached when it is switched into IOMMUv2 mode.
3347 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3351 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3352 if (domain->gcr3_tbl == NULL)
3355 domain->glx = levels;
3356 domain->flags |= PD_IOMMUV2_MASK;
3357 domain->updated = true;
3359 update_domain(domain);
3364 spin_unlock_irqrestore(&domain->lock, flags);
3368 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3370 static int __flush_pasid(struct protection_domain *domain, int pasid,
3371 u64 address, bool size)
3373 struct iommu_dev_data *dev_data;
3374 struct iommu_cmd cmd;
3377 if (!(domain->flags & PD_IOMMUV2_MASK))
3380 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3383 * IOMMU TLB needs to be flushed before Device TLB to
3384 * prevent device TLB refill from IOMMU TLB
3386 for (i = 0; i < amd_iommus_present; ++i) {
3387 if (domain->dev_iommu[i] == 0)
3390 ret = iommu_queue_command(amd_iommus[i], &cmd);
3395 /* Wait until IOMMU TLB flushes are complete */
3396 domain_flush_complete(domain);
3398 /* Now flush device TLBs */
3399 list_for_each_entry(dev_data, &domain->dev_list, list) {
3400 struct amd_iommu *iommu;
3404 There might be non-IOMMUv2 capable devices in an IOMMUv2
3407 if (!dev_data->ats.enabled)
3410 qdep = dev_data->ats.qdep;
3411 iommu = amd_iommu_rlookup_table[dev_data->devid];
3413 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3414 qdep, address, size);
3416 ret = iommu_queue_command(iommu, &cmd);
3421 /* Wait until all device TLBs are flushed */
3422 domain_flush_complete(domain);
3431 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3434 return __flush_pasid(domain, pasid, address, false);
3437 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3440 struct protection_domain *domain = to_pdomain(dom);
3441 unsigned long flags;
3444 spin_lock_irqsave(&domain->lock, flags);
3445 ret = __amd_iommu_flush_page(domain, pasid, address);
3446 spin_unlock_irqrestore(&domain->lock, flags);
3450 EXPORT_SYMBOL(amd_iommu_flush_page);
3452 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3454 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3458 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3460 struct protection_domain *domain = to_pdomain(dom);
3461 unsigned long flags;
3464 spin_lock_irqsave(&domain->lock, flags);
3465 ret = __amd_iommu_flush_tlb(domain, pasid);
3466 spin_unlock_irqrestore(&domain->lock, flags);
3470 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3472 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3479 index = (pasid >> (9 * level)) & 0x1ff;
3485 if (!(*pte & GCR3_VALID)) {
3489 root = (void *)get_zeroed_page(GFP_ATOMIC);
3493 *pte = __pa(root) | GCR3_VALID;
3496 root = __va(*pte & PAGE_MASK);
3504 static int __set_gcr3(struct protection_domain *domain, int pasid,
3509 if (domain->mode != PAGE_MODE_NONE)
3512 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3516 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3518 return __amd_iommu_flush_tlb(domain, pasid);
3521 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3525 if (domain->mode != PAGE_MODE_NONE)
3528 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3534 return __amd_iommu_flush_tlb(domain, pasid);
3537 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3540 struct protection_domain *domain = to_pdomain(dom);
3541 unsigned long flags;
3544 spin_lock_irqsave(&domain->lock, flags);
3545 ret = __set_gcr3(domain, pasid, cr3);
3546 spin_unlock_irqrestore(&domain->lock, flags);
3550 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3552 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3554 struct protection_domain *domain = to_pdomain(dom);
3555 unsigned long flags;
3558 spin_lock_irqsave(&domain->lock, flags);
3559 ret = __clear_gcr3(domain, pasid);
3560 spin_unlock_irqrestore(&domain->lock, flags);
3564 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3566 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3567 int status, int tag)
3569 struct iommu_dev_data *dev_data;
3570 struct amd_iommu *iommu;
3571 struct iommu_cmd cmd;
3573 dev_data = get_dev_data(&pdev->dev);
3574 iommu = amd_iommu_rlookup_table[dev_data->devid];
3576 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3577 tag, dev_data->pri_tlp);
3579 return iommu_queue_command(iommu, &cmd);
3581 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3583 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3585 struct protection_domain *pdomain;
3587 pdomain = get_domain(&pdev->dev);
3588 if (IS_ERR(pdomain))
3591 /* Only return IOMMUv2 domains */
3592 if (!(pdomain->flags & PD_IOMMUV2_MASK))
3595 return &pdomain->domain;
3597 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3599 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3601 struct iommu_dev_data *dev_data;
3603 if (!amd_iommu_v2_supported())
3606 dev_data = get_dev_data(&pdev->dev);
3607 dev_data->errata |= (1 << erratum);
3609 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3611 int amd_iommu_device_info(struct pci_dev *pdev,
3612 struct amd_iommu_device_info *info)
3617 if (pdev == NULL || info == NULL)
3620 if (!amd_iommu_v2_supported())
3623 memset(info, 0, sizeof(*info));
3625 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3627 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3629 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3631 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3633 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3637 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3638 max_pasids = min(max_pasids, (1 << 20));
3640 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3641 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3643 features = pci_pasid_features(pdev);
3644 if (features & PCI_PASID_CAP_EXEC)
3645 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3646 if (features & PCI_PASID_CAP_PRIV)
3647 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3652 EXPORT_SYMBOL(amd_iommu_device_info);
3654 #ifdef CONFIG_IRQ_REMAP
3656 /*****************************************************************************
3658 * Interrupt Remapping Implementation
3660 *****************************************************************************/
3662 static struct irq_chip amd_ir_chip;
3664 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3665 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3666 #define DTE_IRQ_TABLE_LEN (9ULL << 1)
3667 #define DTE_IRQ_REMAP_ENABLE 1ULL
3669 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3673 dte = amd_iommu_dev_table[devid].data[2];
3674 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3675 dte |= virt_to_phys(table->table);
3676 dte |= DTE_IRQ_REMAP_INTCTL;
3677 dte |= DTE_IRQ_TABLE_LEN;
3678 dte |= DTE_IRQ_REMAP_ENABLE;
3680 amd_iommu_dev_table[devid].data[2] = dte;
3683 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3685 struct irq_remap_table *table = NULL;
3686 struct amd_iommu *iommu;
3687 unsigned long flags;
3690 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3692 iommu = amd_iommu_rlookup_table[devid];
3696 table = irq_lookup_table[devid];
3700 alias = amd_iommu_alias_table[devid];
3701 table = irq_lookup_table[alias];
3703 irq_lookup_table[devid] = table;
3704 set_dte_irq_entry(devid, table);
3705 iommu_flush_dte(iommu, devid);
3709 /* Nothing there yet, allocate new irq remapping table */
3710 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3714 /* Initialize table spin-lock */
3715 spin_lock_init(&table->lock);
3718 /* Keep the first 32 indexes free for IOAPIC interrupts */
3719 table->min_index = 32;
3721 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3722 if (!table->table) {
3728 if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
3729 memset(table->table, 0,
3730 MAX_IRQS_PER_TABLE * sizeof(u32));
3732 memset(table->table, 0,
3733 (MAX_IRQS_PER_TABLE * (sizeof(u64) * 2)));
3738 for (i = 0; i < 32; ++i)
3739 iommu->irte_ops->set_allocated(table, i);
3742 irq_lookup_table[devid] = table;
3743 set_dte_irq_entry(devid, table);
3744 iommu_flush_dte(iommu, devid);
3745 if (devid != alias) {
3746 irq_lookup_table[alias] = table;
3747 set_dte_irq_entry(alias, table);
3748 iommu_flush_dte(iommu, alias);
3752 iommu_completion_wait(iommu);
3755 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3760 static int alloc_irq_index(u16 devid, int count)
3762 struct irq_remap_table *table;
3763 unsigned long flags;
3765 struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
3770 table = get_irq_table(devid, false);
3774 spin_lock_irqsave(&table->lock, flags);
3776 /* Scan table for free entries */
3777 for (c = 0, index = table->min_index;
3778 index < MAX_IRQS_PER_TABLE;
3780 if (!iommu->irte_ops->is_allocated(table, index))
3787 iommu->irte_ops->set_allocated(table, index - c + 1);
3797 spin_unlock_irqrestore(&table->lock, flags);
3802 static int modify_irte_ga(u16 devid, int index, struct irte_ga *irte,
3803 struct amd_ir_data *data)
3805 struct irq_remap_table *table;
3806 struct amd_iommu *iommu;
3807 unsigned long flags;
3808 struct irte_ga *entry;
3810 iommu = amd_iommu_rlookup_table[devid];
3814 table = get_irq_table(devid, false);
3818 spin_lock_irqsave(&table->lock, flags);
3820 entry = (struct irte_ga *)table->table;
3821 entry = &entry[index];
3822 entry->lo.fields_remap.valid = 0;
3823 entry->hi.val = irte->hi.val;
3824 entry->lo.val = irte->lo.val;
3825 entry->lo.fields_remap.valid = 1;
3829 spin_unlock_irqrestore(&table->lock, flags);
3831 iommu_flush_irt(iommu, devid);
3832 iommu_completion_wait(iommu);
3837 static int modify_irte(u16 devid, int index, union irte *irte)
3839 struct irq_remap_table *table;
3840 struct amd_iommu *iommu;
3841 unsigned long flags;
3843 iommu = amd_iommu_rlookup_table[devid];
3847 table = get_irq_table(devid, false);
3851 spin_lock_irqsave(&table->lock, flags);
3852 table->table[index] = irte->val;
3853 spin_unlock_irqrestore(&table->lock, flags);
3855 iommu_flush_irt(iommu, devid);
3856 iommu_completion_wait(iommu);
3861 static void free_irte(u16 devid, int index)
3863 struct irq_remap_table *table;
3864 struct amd_iommu *iommu;
3865 unsigned long flags;
3867 iommu = amd_iommu_rlookup_table[devid];
3871 table = get_irq_table(devid, false);
3875 spin_lock_irqsave(&table->lock, flags);
3876 iommu->irte_ops->clear_allocated(table, index);
3877 spin_unlock_irqrestore(&table->lock, flags);
3879 iommu_flush_irt(iommu, devid);
3880 iommu_completion_wait(iommu);
3883 static void irte_prepare(void *entry,
3884 u32 delivery_mode, u32 dest_mode,
3885 u8 vector, u32 dest_apicid, int devid)
3887 union irte *irte = (union irte *) entry;
3890 irte->fields.vector = vector;
3891 irte->fields.int_type = delivery_mode;
3892 irte->fields.destination = dest_apicid;
3893 irte->fields.dm = dest_mode;
3894 irte->fields.valid = 1;
3897 static void irte_ga_prepare(void *entry,
3898 u32 delivery_mode, u32 dest_mode,
3899 u8 vector, u32 dest_apicid, int devid)
3901 struct irte_ga *irte = (struct irte_ga *) entry;
3905 irte->lo.fields_remap.int_type = delivery_mode;
3906 irte->lo.fields_remap.dm = dest_mode;
3907 irte->hi.fields.vector = vector;
3908 irte->lo.fields_remap.destination = dest_apicid;
3909 irte->lo.fields_remap.valid = 1;
3912 static void irte_activate(void *entry, u16 devid, u16 index)
3914 union irte *irte = (union irte *) entry;
3916 irte->fields.valid = 1;
3917 modify_irte(devid, index, irte);
3920 static void irte_ga_activate(void *entry, u16 devid, u16 index)
3922 struct irte_ga *irte = (struct irte_ga *) entry;
3924 irte->lo.fields_remap.valid = 1;
3925 modify_irte_ga(devid, index, irte, NULL);
3928 static void irte_deactivate(void *entry, u16 devid, u16 index)
3930 union irte *irte = (union irte *) entry;
3932 irte->fields.valid = 0;
3933 modify_irte(devid, index, irte);
3936 static void irte_ga_deactivate(void *entry, u16 devid, u16 index)
3938 struct irte_ga *irte = (struct irte_ga *) entry;
3940 irte->lo.fields_remap.valid = 0;
3941 modify_irte_ga(devid, index, irte, NULL);
3944 static void irte_set_affinity(void *entry, u16 devid, u16 index,
3945 u8 vector, u32 dest_apicid)
3947 union irte *irte = (union irte *) entry;
3949 irte->fields.vector = vector;
3950 irte->fields.destination = dest_apicid;
3951 modify_irte(devid, index, irte);
3954 static void irte_ga_set_affinity(void *entry, u16 devid, u16 index,
3955 u8 vector, u32 dest_apicid)
3957 struct irte_ga *irte = (struct irte_ga *) entry;
3958 struct iommu_dev_data *dev_data = search_dev_data(devid);
3960 if (!dev_data || !dev_data->use_vapic ||
3961 !irte->lo.fields_remap.guest_mode) {
3962 irte->hi.fields.vector = vector;
3963 irte->lo.fields_remap.destination = dest_apicid;
3964 modify_irte_ga(devid, index, irte, NULL);
3968 #define IRTE_ALLOCATED (~1U)
3969 static void irte_set_allocated(struct irq_remap_table *table, int index)
3971 table->table[index] = IRTE_ALLOCATED;
3974 static void irte_ga_set_allocated(struct irq_remap_table *table, int index)
3976 struct irte_ga *ptr = (struct irte_ga *)table->table;
3977 struct irte_ga *irte = &ptr[index];
3979 memset(&irte->lo.val, 0, sizeof(u64));
3980 memset(&irte->hi.val, 0, sizeof(u64));
3981 irte->hi.fields.vector = 0xff;
3984 static bool irte_is_allocated(struct irq_remap_table *table, int index)
3986 union irte *ptr = (union irte *)table->table;
3987 union irte *irte = &ptr[index];
3989 return irte->val != 0;
3992 static bool irte_ga_is_allocated(struct irq_remap_table *table, int index)
3994 struct irte_ga *ptr = (struct irte_ga *)table->table;
3995 struct irte_ga *irte = &ptr[index];
3997 return irte->hi.fields.vector != 0;
4000 static void irte_clear_allocated(struct irq_remap_table *table, int index)
4002 table->table[index] = 0;
4005 static void irte_ga_clear_allocated(struct irq_remap_table *table, int index)
4007 struct irte_ga *ptr = (struct irte_ga *)table->table;
4008 struct irte_ga *irte = &ptr[index];
4010 memset(&irte->lo.val, 0, sizeof(u64));
4011 memset(&irte->hi.val, 0, sizeof(u64));
4014 static int get_devid(struct irq_alloc_info *info)
4018 switch (info->type) {
4019 case X86_IRQ_ALLOC_TYPE_IOAPIC:
4020 devid = get_ioapic_devid(info->ioapic_id);
4022 case X86_IRQ_ALLOC_TYPE_HPET:
4023 devid = get_hpet_devid(info->hpet_id);
4025 case X86_IRQ_ALLOC_TYPE_MSI:
4026 case X86_IRQ_ALLOC_TYPE_MSIX:
4027 devid = get_device_id(&info->msi_dev->dev);
4037 static struct irq_domain *get_ir_irq_domain(struct irq_alloc_info *info)
4039 struct amd_iommu *iommu;
4045 devid = get_devid(info);
4047 iommu = amd_iommu_rlookup_table[devid];
4049 return iommu->ir_domain;
4055 static struct irq_domain *get_irq_domain(struct irq_alloc_info *info)
4057 struct amd_iommu *iommu;
4063 switch (info->type) {
4064 case X86_IRQ_ALLOC_TYPE_MSI:
4065 case X86_IRQ_ALLOC_TYPE_MSIX:
4066 devid = get_device_id(&info->msi_dev->dev);
4070 iommu = amd_iommu_rlookup_table[devid];
4072 return iommu->msi_domain;
4081 struct irq_remap_ops amd_iommu_irq_ops = {
4082 .prepare = amd_iommu_prepare,
4083 .enable = amd_iommu_enable,
4084 .disable = amd_iommu_disable,
4085 .reenable = amd_iommu_reenable,
4086 .enable_faulting = amd_iommu_enable_faulting,
4087 .get_ir_irq_domain = get_ir_irq_domain,
4088 .get_irq_domain = get_irq_domain,
4091 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
4092 struct irq_cfg *irq_cfg,
4093 struct irq_alloc_info *info,
4094 int devid, int index, int sub_handle)
4096 struct irq_2_irte *irte_info = &data->irq_2_irte;
4097 struct msi_msg *msg = &data->msi_entry;
4098 struct IO_APIC_route_entry *entry;
4099 struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
4104 data->irq_2_irte.devid = devid;
4105 data->irq_2_irte.index = index + sub_handle;
4106 iommu->irte_ops->prepare(data->entry, apic->irq_delivery_mode,
4107 apic->irq_dest_mode, irq_cfg->vector,
4108 irq_cfg->dest_apicid, devid);
4110 switch (info->type) {
4111 case X86_IRQ_ALLOC_TYPE_IOAPIC:
4112 /* Setup IOAPIC entry */
4113 entry = info->ioapic_entry;
4114 info->ioapic_entry = NULL;
4115 memset(entry, 0, sizeof(*entry));
4116 entry->vector = index;
4118 entry->trigger = info->ioapic_trigger;
4119 entry->polarity = info->ioapic_polarity;
4120 /* Mask level triggered irqs. */
4121 if (info->ioapic_trigger)
4125 case X86_IRQ_ALLOC_TYPE_HPET:
4126 case X86_IRQ_ALLOC_TYPE_MSI:
4127 case X86_IRQ_ALLOC_TYPE_MSIX:
4128 msg->address_hi = MSI_ADDR_BASE_HI;
4129 msg->address_lo = MSI_ADDR_BASE_LO;
4130 msg->data = irte_info->index;
4139 struct amd_irte_ops irte_32_ops = {
4140 .prepare = irte_prepare,
4141 .activate = irte_activate,
4142 .deactivate = irte_deactivate,
4143 .set_affinity = irte_set_affinity,
4144 .set_allocated = irte_set_allocated,
4145 .is_allocated = irte_is_allocated,
4146 .clear_allocated = irte_clear_allocated,
4149 struct amd_irte_ops irte_128_ops = {
4150 .prepare = irte_ga_prepare,
4151 .activate = irte_ga_activate,
4152 .deactivate = irte_ga_deactivate,
4153 .set_affinity = irte_ga_set_affinity,
4154 .set_allocated = irte_ga_set_allocated,
4155 .is_allocated = irte_ga_is_allocated,
4156 .clear_allocated = irte_ga_clear_allocated,
4159 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
4160 unsigned int nr_irqs, void *arg)
4162 struct irq_alloc_info *info = arg;
4163 struct irq_data *irq_data;
4164 struct amd_ir_data *data = NULL;
4165 struct irq_cfg *cfg;
4171 if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_MSI &&
4172 info->type != X86_IRQ_ALLOC_TYPE_MSIX)
4176 * With IRQ remapping enabled, don't need contiguous CPU vectors
4177 * to support multiple MSI interrupts.
4179 if (info->type == X86_IRQ_ALLOC_TYPE_MSI)
4180 info->flags &= ~X86_IRQ_ALLOC_CONTIGUOUS_VECTORS;
4182 devid = get_devid(info);
4186 ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
4190 if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
4191 if (get_irq_table(devid, true))
4192 index = info->ioapic_pin;
4196 index = alloc_irq_index(devid, nr_irqs);
4199 pr_warn("Failed to allocate IRTE\n");
4201 goto out_free_parent;
4204 for (i = 0; i < nr_irqs; i++) {
4205 irq_data = irq_domain_get_irq_data(domain, virq + i);
4206 cfg = irqd_cfg(irq_data);
4207 if (!irq_data || !cfg) {
4213 data = kzalloc(sizeof(*data), GFP_KERNEL);
4217 if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
4218 data->entry = kzalloc(sizeof(union irte), GFP_KERNEL);
4220 data->entry = kzalloc(sizeof(struct irte_ga),
4227 irq_data->hwirq = (devid << 16) + i;
4228 irq_data->chip_data = data;
4229 irq_data->chip = &amd_ir_chip;
4230 irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
4231 irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
4237 for (i--; i >= 0; i--) {
4238 irq_data = irq_domain_get_irq_data(domain, virq + i);
4240 kfree(irq_data->chip_data);
4242 for (i = 0; i < nr_irqs; i++)
4243 free_irte(devid, index + i);
4245 irq_domain_free_irqs_common(domain, virq, nr_irqs);
4249 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
4250 unsigned int nr_irqs)
4252 struct irq_2_irte *irte_info;
4253 struct irq_data *irq_data;
4254 struct amd_ir_data *data;
4257 for (i = 0; i < nr_irqs; i++) {
4258 irq_data = irq_domain_get_irq_data(domain, virq + i);
4259 if (irq_data && irq_data->chip_data) {
4260 data = irq_data->chip_data;
4261 irte_info = &data->irq_2_irte;
4262 free_irte(irte_info->devid, irte_info->index);
4267 irq_domain_free_irqs_common(domain, virq, nr_irqs);
4270 static void irq_remapping_activate(struct irq_domain *domain,
4271 struct irq_data *irq_data)
4273 struct amd_ir_data *data = irq_data->chip_data;
4274 struct irq_2_irte *irte_info = &data->irq_2_irte;
4275 struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
4278 iommu->irte_ops->activate(data->entry, irte_info->devid,
4282 static void irq_remapping_deactivate(struct irq_domain *domain,
4283 struct irq_data *irq_data)
4285 struct amd_ir_data *data = irq_data->chip_data;
4286 struct irq_2_irte *irte_info = &data->irq_2_irte;
4287 struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
4290 iommu->irte_ops->deactivate(data->entry, irte_info->devid,
4294 static struct irq_domain_ops amd_ir_domain_ops = {
4295 .alloc = irq_remapping_alloc,
4296 .free = irq_remapping_free,
4297 .activate = irq_remapping_activate,
4298 .deactivate = irq_remapping_deactivate,
4301 static int amd_ir_set_vcpu_affinity(struct irq_data *data, void *vcpu_info)
4303 struct amd_iommu *iommu;
4304 struct amd_iommu_pi_data *pi_data = vcpu_info;
4305 struct vcpu_data *vcpu_pi_info = pi_data->vcpu_data;
4306 struct amd_ir_data *ir_data = data->chip_data;
4307 struct irte_ga *irte = (struct irte_ga *) ir_data->entry;
4308 struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4309 struct iommu_dev_data *dev_data = search_dev_data(irte_info->devid);
4312 * This device has never been set up for guest mode.
4313 * we should not modify the IRTE
4315 if (!dev_data || !dev_data->use_vapic)
4318 pi_data->ir_data = ir_data;
4321 * SVM tries to set up for VAPIC mode, but we are in
4322 * legacy mode. So, we force legacy mode instead.
4324 if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
4325 pr_debug("AMD-Vi: %s: Fall back to using intr legacy remap\n",
4327 pi_data->is_guest_mode = false;
4330 iommu = amd_iommu_rlookup_table[irte_info->devid];
4334 pi_data->prev_ga_tag = ir_data->cached_ga_tag;
4335 if (pi_data->is_guest_mode) {
4337 irte->hi.fields.ga_root_ptr = (pi_data->base >> 12);
4338 irte->hi.fields.vector = vcpu_pi_info->vector;
4339 irte->lo.fields_vapic.ga_log_intr = 1;
4340 irte->lo.fields_vapic.guest_mode = 1;
4341 irte->lo.fields_vapic.ga_tag = pi_data->ga_tag;
4343 ir_data->cached_ga_tag = pi_data->ga_tag;
4346 struct irq_cfg *cfg = irqd_cfg(data);
4350 irte->hi.fields.vector = cfg->vector;
4351 irte->lo.fields_remap.guest_mode = 0;
4352 irte->lo.fields_remap.destination = cfg->dest_apicid;
4353 irte->lo.fields_remap.int_type = apic->irq_delivery_mode;
4354 irte->lo.fields_remap.dm = apic->irq_dest_mode;
4357 * This communicates the ga_tag back to the caller
4358 * so that it can do all the necessary clean up.
4360 ir_data->cached_ga_tag = 0;
4363 return modify_irte_ga(irte_info->devid, irte_info->index, irte, ir_data);
4366 static int amd_ir_set_affinity(struct irq_data *data,
4367 const struct cpumask *mask, bool force)
4369 struct amd_ir_data *ir_data = data->chip_data;
4370 struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4371 struct irq_cfg *cfg = irqd_cfg(data);
4372 struct irq_data *parent = data->parent_data;
4373 struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
4379 ret = parent->chip->irq_set_affinity(parent, mask, force);
4380 if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
4384 * Atomically updates the IRTE with the new destination, vector
4385 * and flushes the interrupt entry cache.
4387 iommu->irte_ops->set_affinity(ir_data->entry, irte_info->devid,
4388 irte_info->index, cfg->vector, cfg->dest_apicid);
4391 * After this point, all the interrupts will start arriving
4392 * at the new destination. So, time to cleanup the previous
4393 * vector allocation.
4395 send_cleanup_vector(cfg);
4397 return IRQ_SET_MASK_OK_DONE;
4400 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
4402 struct amd_ir_data *ir_data = irq_data->chip_data;
4404 *msg = ir_data->msi_entry;
4407 static struct irq_chip amd_ir_chip = {
4408 .irq_ack = ir_ack_apic_edge,
4409 .irq_set_affinity = amd_ir_set_affinity,
4410 .irq_set_vcpu_affinity = amd_ir_set_vcpu_affinity,
4411 .irq_compose_msi_msg = ir_compose_msi_msg,
4414 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
4416 iommu->ir_domain = irq_domain_add_tree(NULL, &amd_ir_domain_ops, iommu);
4417 if (!iommu->ir_domain)
4420 iommu->ir_domain->parent = arch_get_ir_parent_domain();
4421 iommu->msi_domain = arch_create_msi_irq_domain(iommu->ir_domain);
4426 int amd_iommu_update_ga(int cpu, bool is_run, void *data)
4428 unsigned long flags;
4429 struct amd_iommu *iommu;
4430 struct irq_remap_table *irt;
4431 struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
4432 int devid = ir_data->irq_2_irte.devid;
4433 struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
4434 struct irte_ga *ref = (struct irte_ga *) ir_data->ref;
4436 if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) ||
4437 !ref || !entry || !entry->lo.fields_vapic.guest_mode)
4440 iommu = amd_iommu_rlookup_table[devid];
4444 irt = get_irq_table(devid, false);
4448 spin_lock_irqsave(&irt->lock, flags);
4450 if (ref->lo.fields_vapic.guest_mode) {
4452 ref->lo.fields_vapic.destination = cpu;
4453 ref->lo.fields_vapic.is_run = is_run;
4457 spin_unlock_irqrestore(&irt->lock, flags);
4459 iommu_flush_irt(iommu, devid);
4460 iommu_completion_wait(iommu);
4463 EXPORT_SYMBOL(amd_iommu_update_ga);