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 const struct iommu_ops amd_iommu_ops;
117 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
118 int amd_iommu_max_glx_val = -1;
120 static const 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 */
142 struct ratelimit_state rs; /* Ratelimit IOPF messages */
146 * general struct to manage commands send to an IOMMU
152 struct kmem_cache *amd_iommu_irq_cache;
154 static void update_domain(struct protection_domain *domain);
155 static int protection_domain_init(struct protection_domain *domain);
156 static void detach_device(struct device *dev);
159 * Data container for a dma_ops specific protection domain
161 struct dma_ops_domain {
162 /* generic protection domain information */
163 struct protection_domain domain;
166 struct iova_domain iovad;
169 static struct iova_domain reserved_iova_ranges;
170 static struct lock_class_key reserved_rbtree_key;
172 /****************************************************************************
176 ****************************************************************************/
178 static inline int match_hid_uid(struct device *dev,
179 struct acpihid_map_entry *entry)
181 const char *hid, *uid;
183 hid = acpi_device_hid(ACPI_COMPANION(dev));
184 uid = acpi_device_uid(ACPI_COMPANION(dev));
190 return strcmp(hid, entry->hid);
193 return strcmp(hid, entry->hid);
195 return (strcmp(hid, entry->hid) || strcmp(uid, entry->uid));
198 static inline u16 get_pci_device_id(struct device *dev)
200 struct pci_dev *pdev = to_pci_dev(dev);
202 return PCI_DEVID(pdev->bus->number, pdev->devfn);
205 static inline int get_acpihid_device_id(struct device *dev,
206 struct acpihid_map_entry **entry)
208 struct acpihid_map_entry *p;
210 list_for_each_entry(p, &acpihid_map, list) {
211 if (!match_hid_uid(dev, p)) {
220 static inline int get_device_id(struct device *dev)
225 devid = get_pci_device_id(dev);
227 devid = get_acpihid_device_id(dev, NULL);
232 static struct protection_domain *to_pdomain(struct iommu_domain *dom)
234 return container_of(dom, struct protection_domain, domain);
237 static struct dma_ops_domain* to_dma_ops_domain(struct protection_domain *domain)
239 BUG_ON(domain->flags != PD_DMA_OPS_MASK);
240 return container_of(domain, struct dma_ops_domain, domain);
243 static struct iommu_dev_data *alloc_dev_data(u16 devid)
245 struct iommu_dev_data *dev_data;
248 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
252 dev_data->devid = devid;
254 spin_lock_irqsave(&dev_data_list_lock, flags);
255 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
256 spin_unlock_irqrestore(&dev_data_list_lock, flags);
258 ratelimit_default_init(&dev_data->rs);
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);
295 ivrs_alias = amd_iommu_alias_table[devid];
296 pci_for_each_dma_alias(pdev, __last_alias, &pci_alias);
298 if (ivrs_alias == pci_alias)
304 * The IVRS is fairly reliable in telling us about aliases, but it
305 * can't know about every screwy device. If we don't have an IVRS
306 * reported alias, use the PCI reported alias. In that case we may
307 * still need to initialize the rlookup and dev_table entries if the
308 * alias is to a non-existent device.
310 if (ivrs_alias == devid) {
311 if (!amd_iommu_rlookup_table[pci_alias]) {
312 amd_iommu_rlookup_table[pci_alias] =
313 amd_iommu_rlookup_table[devid];
314 memcpy(amd_iommu_dev_table[pci_alias].data,
315 amd_iommu_dev_table[devid].data,
316 sizeof(amd_iommu_dev_table[pci_alias].data));
322 pr_info("AMD-Vi: Using IVRS reported alias %02x:%02x.%d "
323 "for device %s[%04x:%04x], kernel reported alias "
324 "%02x:%02x.%d\n", PCI_BUS_NUM(ivrs_alias), PCI_SLOT(ivrs_alias),
325 PCI_FUNC(ivrs_alias), dev_name(dev), pdev->vendor, pdev->device,
326 PCI_BUS_NUM(pci_alias), PCI_SLOT(pci_alias),
327 PCI_FUNC(pci_alias));
330 * If we don't have a PCI DMA alias and the IVRS alias is on the same
331 * bus, then the IVRS table may know about a quirk that we don't.
333 if (pci_alias == devid &&
334 PCI_BUS_NUM(ivrs_alias) == pdev->bus->number) {
335 pci_add_dma_alias(pdev, ivrs_alias & 0xff);
336 pr_info("AMD-Vi: Added PCI DMA alias %02x.%d for %s\n",
337 PCI_SLOT(ivrs_alias), PCI_FUNC(ivrs_alias),
344 static struct iommu_dev_data *find_dev_data(u16 devid)
346 struct iommu_dev_data *dev_data;
348 dev_data = search_dev_data(devid);
350 if (dev_data == NULL)
351 dev_data = alloc_dev_data(devid);
356 static struct iommu_dev_data *get_dev_data(struct device *dev)
358 return dev->archdata.iommu;
362 * Find or create an IOMMU group for a acpihid device.
364 static struct iommu_group *acpihid_device_group(struct device *dev)
366 struct acpihid_map_entry *p, *entry = NULL;
369 devid = get_acpihid_device_id(dev, &entry);
371 return ERR_PTR(devid);
373 list_for_each_entry(p, &acpihid_map, list) {
374 if ((devid == p->devid) && p->group)
375 entry->group = p->group;
379 entry->group = generic_device_group(dev);
381 iommu_group_ref_get(entry->group);
386 static bool pci_iommuv2_capable(struct pci_dev *pdev)
388 static const int caps[] = {
391 PCI_EXT_CAP_ID_PASID,
395 for (i = 0; i < 3; ++i) {
396 pos = pci_find_ext_capability(pdev, caps[i]);
404 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
406 struct iommu_dev_data *dev_data;
408 dev_data = get_dev_data(&pdev->dev);
410 return dev_data->errata & (1 << erratum) ? true : false;
414 * This function checks if the driver got a valid device from the caller to
415 * avoid dereferencing invalid pointers.
417 static bool check_device(struct device *dev)
421 if (!dev || !dev->dma_mask)
424 devid = get_device_id(dev);
428 /* Out of our scope? */
429 if (devid > amd_iommu_last_bdf)
432 if (amd_iommu_rlookup_table[devid] == NULL)
438 static void init_iommu_group(struct device *dev)
440 struct iommu_group *group;
442 group = iommu_group_get_for_dev(dev);
446 iommu_group_put(group);
449 static int iommu_init_device(struct device *dev)
451 struct iommu_dev_data *dev_data;
452 struct amd_iommu *iommu;
455 if (dev->archdata.iommu)
458 devid = get_device_id(dev);
462 iommu = amd_iommu_rlookup_table[devid];
464 dev_data = find_dev_data(devid);
468 dev_data->alias = get_alias(dev);
470 if (dev_is_pci(dev) && pci_iommuv2_capable(to_pci_dev(dev))) {
471 struct amd_iommu *iommu;
473 iommu = amd_iommu_rlookup_table[dev_data->devid];
474 dev_data->iommu_v2 = iommu->is_iommu_v2;
477 dev->archdata.iommu = dev_data;
479 iommu_device_link(&iommu->iommu, dev);
484 static void iommu_ignore_device(struct device *dev)
489 devid = get_device_id(dev);
493 alias = get_alias(dev);
495 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
496 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
498 amd_iommu_rlookup_table[devid] = NULL;
499 amd_iommu_rlookup_table[alias] = NULL;
502 static void iommu_uninit_device(struct device *dev)
504 struct iommu_dev_data *dev_data;
505 struct amd_iommu *iommu;
508 devid = get_device_id(dev);
512 iommu = amd_iommu_rlookup_table[devid];
514 dev_data = search_dev_data(devid);
518 if (dev_data->domain)
521 iommu_device_unlink(&iommu->iommu, dev);
523 iommu_group_remove_device(dev);
529 * We keep dev_data around for unplugged devices and reuse it when the
530 * device is re-plugged - not doing so would introduce a ton of races.
534 /****************************************************************************
536 * Interrupt handling functions
538 ****************************************************************************/
540 static void dump_dte_entry(u16 devid)
544 for (i = 0; i < 4; ++i)
545 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
546 amd_iommu_dev_table[devid].data[i]);
549 static void dump_command(unsigned long phys_addr)
551 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
554 for (i = 0; i < 4; ++i)
555 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
558 static void amd_iommu_report_page_fault(u16 devid, u16 domain_id,
559 u64 address, int flags)
561 struct iommu_dev_data *dev_data = NULL;
562 struct pci_dev *pdev;
564 pdev = pci_get_bus_and_slot(PCI_BUS_NUM(devid), devid & 0xff);
566 dev_data = get_dev_data(&pdev->dev);
568 if (dev_data && __ratelimit(&dev_data->rs)) {
569 dev_err(&pdev->dev, "AMD-Vi: Event logged [IO_PAGE_FAULT domain=0x%04x address=0x%016llx flags=0x%04x]\n",
570 domain_id, address, flags);
571 } else if (printk_ratelimit()) {
572 pr_err("AMD-Vi: Event logged [IO_PAGE_FAULT device=%02x:%02x.%x domain=0x%04x address=0x%016llx flags=0x%04x]\n",
573 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
574 domain_id, address, flags);
581 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
583 int type, devid, domid, flags;
584 volatile u32 *event = __evt;
589 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
590 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
591 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
592 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
593 address = (u64)(((u64)event[3]) << 32) | event[2];
596 /* Did we hit the erratum? */
597 if (++count == LOOP_TIMEOUT) {
598 pr_err("AMD-Vi: No event written to event log\n");
605 if (type == EVENT_TYPE_IO_FAULT) {
606 amd_iommu_report_page_fault(devid, domid, address, flags);
609 printk(KERN_ERR "AMD-Vi: Event logged [");
613 case EVENT_TYPE_ILL_DEV:
614 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
615 "address=0x%016llx flags=0x%04x]\n",
616 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
618 dump_dte_entry(devid);
620 case EVENT_TYPE_DEV_TAB_ERR:
621 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
622 "address=0x%016llx flags=0x%04x]\n",
623 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
626 case EVENT_TYPE_PAGE_TAB_ERR:
627 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
628 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
629 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
630 domid, address, flags);
632 case EVENT_TYPE_ILL_CMD:
633 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
634 dump_command(address);
636 case EVENT_TYPE_CMD_HARD_ERR:
637 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
638 "flags=0x%04x]\n", address, flags);
640 case EVENT_TYPE_IOTLB_INV_TO:
641 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
642 "address=0x%016llx]\n",
643 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
646 case EVENT_TYPE_INV_DEV_REQ:
647 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
648 "address=0x%016llx flags=0x%04x]\n",
649 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
653 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
656 memset(__evt, 0, 4 * sizeof(u32));
659 static void iommu_poll_events(struct amd_iommu *iommu)
663 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
664 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
666 while (head != tail) {
667 iommu_print_event(iommu, iommu->evt_buf + head);
668 head = (head + EVENT_ENTRY_SIZE) % EVT_BUFFER_SIZE;
671 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
674 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
676 struct amd_iommu_fault fault;
678 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
679 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
683 fault.address = raw[1];
684 fault.pasid = PPR_PASID(raw[0]);
685 fault.device_id = PPR_DEVID(raw[0]);
686 fault.tag = PPR_TAG(raw[0]);
687 fault.flags = PPR_FLAGS(raw[0]);
689 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
692 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
696 if (iommu->ppr_log == NULL)
699 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
700 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
702 while (head != tail) {
707 raw = (u64 *)(iommu->ppr_log + head);
710 * Hardware bug: Interrupt may arrive before the entry is
711 * written to memory. If this happens we need to wait for the
714 for (i = 0; i < LOOP_TIMEOUT; ++i) {
715 if (PPR_REQ_TYPE(raw[0]) != 0)
720 /* Avoid memcpy function-call overhead */
725 * To detect the hardware bug we need to clear the entry
728 raw[0] = raw[1] = 0UL;
730 /* Update head pointer of hardware ring-buffer */
731 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
732 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
734 /* Handle PPR entry */
735 iommu_handle_ppr_entry(iommu, entry);
737 /* Refresh ring-buffer information */
738 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
739 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
743 #ifdef CONFIG_IRQ_REMAP
744 static int (*iommu_ga_log_notifier)(u32);
746 int amd_iommu_register_ga_log_notifier(int (*notifier)(u32))
748 iommu_ga_log_notifier = notifier;
752 EXPORT_SYMBOL(amd_iommu_register_ga_log_notifier);
754 static void iommu_poll_ga_log(struct amd_iommu *iommu)
756 u32 head, tail, cnt = 0;
758 if (iommu->ga_log == NULL)
761 head = readl(iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
762 tail = readl(iommu->mmio_base + MMIO_GA_TAIL_OFFSET);
764 while (head != tail) {
768 raw = (u64 *)(iommu->ga_log + head);
771 /* Avoid memcpy function-call overhead */
774 /* Update head pointer of hardware ring-buffer */
775 head = (head + GA_ENTRY_SIZE) % GA_LOG_SIZE;
776 writel(head, iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
778 /* Handle GA entry */
779 switch (GA_REQ_TYPE(log_entry)) {
781 if (!iommu_ga_log_notifier)
784 pr_debug("AMD-Vi: %s: devid=%#x, ga_tag=%#x\n",
785 __func__, GA_DEVID(log_entry),
788 if (iommu_ga_log_notifier(GA_TAG(log_entry)) != 0)
789 pr_err("AMD-Vi: GA log notifier failed.\n");
796 #endif /* CONFIG_IRQ_REMAP */
798 #define AMD_IOMMU_INT_MASK \
799 (MMIO_STATUS_EVT_INT_MASK | \
800 MMIO_STATUS_PPR_INT_MASK | \
801 MMIO_STATUS_GALOG_INT_MASK)
803 irqreturn_t amd_iommu_int_thread(int irq, void *data)
805 struct amd_iommu *iommu = (struct amd_iommu *) data;
806 u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
808 while (status & AMD_IOMMU_INT_MASK) {
809 /* Enable EVT and PPR and GA interrupts again */
810 writel(AMD_IOMMU_INT_MASK,
811 iommu->mmio_base + MMIO_STATUS_OFFSET);
813 if (status & MMIO_STATUS_EVT_INT_MASK) {
814 pr_devel("AMD-Vi: Processing IOMMU Event Log\n");
815 iommu_poll_events(iommu);
818 if (status & MMIO_STATUS_PPR_INT_MASK) {
819 pr_devel("AMD-Vi: Processing IOMMU PPR Log\n");
820 iommu_poll_ppr_log(iommu);
823 #ifdef CONFIG_IRQ_REMAP
824 if (status & MMIO_STATUS_GALOG_INT_MASK) {
825 pr_devel("AMD-Vi: Processing IOMMU GA Log\n");
826 iommu_poll_ga_log(iommu);
831 * Hardware bug: ERBT1312
832 * When re-enabling interrupt (by writing 1
833 * to clear the bit), the hardware might also try to set
834 * the interrupt bit in the event status register.
835 * In this scenario, the bit will be set, and disable
836 * subsequent interrupts.
838 * Workaround: The IOMMU driver should read back the
839 * status register and check if the interrupt bits are cleared.
840 * If not, driver will need to go through the interrupt handler
841 * again and re-clear the bits
843 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
848 irqreturn_t amd_iommu_int_handler(int irq, void *data)
850 return IRQ_WAKE_THREAD;
853 /****************************************************************************
855 * IOMMU command queuing functions
857 ****************************************************************************/
859 static int wait_on_sem(volatile u64 *sem)
863 while (*sem == 0 && i < LOOP_TIMEOUT) {
868 if (i == LOOP_TIMEOUT) {
869 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
876 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
877 struct iommu_cmd *cmd,
882 target = iommu->cmd_buf + tail;
883 tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
885 /* Copy command to buffer */
886 memcpy(target, cmd, sizeof(*cmd));
888 /* Tell the IOMMU about it */
889 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
892 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
894 WARN_ON(address & 0x7ULL);
896 memset(cmd, 0, sizeof(*cmd));
897 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
898 cmd->data[1] = upper_32_bits(__pa(address));
900 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
903 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
905 memset(cmd, 0, sizeof(*cmd));
906 cmd->data[0] = devid;
907 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
910 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
911 size_t size, u16 domid, int pde)
916 pages = iommu_num_pages(address, size, PAGE_SIZE);
921 * If we have to flush more than one page, flush all
922 * TLB entries for this domain
924 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
928 address &= PAGE_MASK;
930 memset(cmd, 0, sizeof(*cmd));
931 cmd->data[1] |= domid;
932 cmd->data[2] = lower_32_bits(address);
933 cmd->data[3] = upper_32_bits(address);
934 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
935 if (s) /* size bit - we flush more than one 4kb page */
936 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
937 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
938 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
941 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
942 u64 address, size_t size)
947 pages = iommu_num_pages(address, size, PAGE_SIZE);
952 * If we have to flush more than one page, flush all
953 * TLB entries for this domain
955 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
959 address &= PAGE_MASK;
961 memset(cmd, 0, sizeof(*cmd));
962 cmd->data[0] = devid;
963 cmd->data[0] |= (qdep & 0xff) << 24;
964 cmd->data[1] = devid;
965 cmd->data[2] = lower_32_bits(address);
966 cmd->data[3] = upper_32_bits(address);
967 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
969 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
972 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
973 u64 address, bool size)
975 memset(cmd, 0, sizeof(*cmd));
977 address &= ~(0xfffULL);
979 cmd->data[0] = pasid;
980 cmd->data[1] = domid;
981 cmd->data[2] = lower_32_bits(address);
982 cmd->data[3] = upper_32_bits(address);
983 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
984 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
986 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
987 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
990 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
991 int qdep, u64 address, bool size)
993 memset(cmd, 0, sizeof(*cmd));
995 address &= ~(0xfffULL);
997 cmd->data[0] = devid;
998 cmd->data[0] |= ((pasid >> 8) & 0xff) << 16;
999 cmd->data[0] |= (qdep & 0xff) << 24;
1000 cmd->data[1] = devid;
1001 cmd->data[1] |= (pasid & 0xff) << 16;
1002 cmd->data[2] = lower_32_bits(address);
1003 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
1004 cmd->data[3] = upper_32_bits(address);
1006 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
1007 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
1010 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
1011 int status, int tag, bool gn)
1013 memset(cmd, 0, sizeof(*cmd));
1015 cmd->data[0] = devid;
1017 cmd->data[1] = pasid;
1018 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
1020 cmd->data[3] = tag & 0x1ff;
1021 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
1023 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
1026 static void build_inv_all(struct iommu_cmd *cmd)
1028 memset(cmd, 0, sizeof(*cmd));
1029 CMD_SET_TYPE(cmd, CMD_INV_ALL);
1032 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
1034 memset(cmd, 0, sizeof(*cmd));
1035 cmd->data[0] = devid;
1036 CMD_SET_TYPE(cmd, CMD_INV_IRT);
1040 * Writes the command to the IOMMUs command buffer and informs the
1041 * hardware about the new command.
1043 static int __iommu_queue_command_sync(struct amd_iommu *iommu,
1044 struct iommu_cmd *cmd,
1047 u32 left, tail, head, next_tail;
1051 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
1052 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
1053 next_tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
1054 left = (head - next_tail) % CMD_BUFFER_SIZE;
1057 struct iommu_cmd sync_cmd;
1062 build_completion_wait(&sync_cmd, (u64)&iommu->cmd_sem);
1063 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
1065 if ((ret = wait_on_sem(&iommu->cmd_sem)) != 0)
1071 copy_cmd_to_buffer(iommu, cmd, tail);
1073 /* We need to sync now to make sure all commands are processed */
1074 iommu->need_sync = sync;
1079 static int iommu_queue_command_sync(struct amd_iommu *iommu,
1080 struct iommu_cmd *cmd,
1083 unsigned long flags;
1086 spin_lock_irqsave(&iommu->lock, flags);
1087 ret = __iommu_queue_command_sync(iommu, cmd, sync);
1088 spin_unlock_irqrestore(&iommu->lock, flags);
1093 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
1095 return iommu_queue_command_sync(iommu, cmd, true);
1099 * This function queues a completion wait command into the command
1100 * buffer of an IOMMU
1102 static int iommu_completion_wait(struct amd_iommu *iommu)
1104 struct iommu_cmd cmd;
1105 unsigned long flags;
1108 if (!iommu->need_sync)
1112 build_completion_wait(&cmd, (u64)&iommu->cmd_sem);
1114 spin_lock_irqsave(&iommu->lock, flags);
1118 ret = __iommu_queue_command_sync(iommu, &cmd, false);
1122 ret = wait_on_sem(&iommu->cmd_sem);
1125 spin_unlock_irqrestore(&iommu->lock, flags);
1130 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1132 struct iommu_cmd cmd;
1134 build_inv_dte(&cmd, devid);
1136 return iommu_queue_command(iommu, &cmd);
1139 static void iommu_flush_dte_all(struct amd_iommu *iommu)
1143 for (devid = 0; devid <= 0xffff; ++devid)
1144 iommu_flush_dte(iommu, devid);
1146 iommu_completion_wait(iommu);
1150 * This function uses heavy locking and may disable irqs for some time. But
1151 * this is no issue because it is only called during resume.
1153 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1157 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1158 struct iommu_cmd cmd;
1159 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1161 iommu_queue_command(iommu, &cmd);
1164 iommu_completion_wait(iommu);
1167 static void iommu_flush_all(struct amd_iommu *iommu)
1169 struct iommu_cmd cmd;
1171 build_inv_all(&cmd);
1173 iommu_queue_command(iommu, &cmd);
1174 iommu_completion_wait(iommu);
1177 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1179 struct iommu_cmd cmd;
1181 build_inv_irt(&cmd, devid);
1183 iommu_queue_command(iommu, &cmd);
1186 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1190 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1191 iommu_flush_irt(iommu, devid);
1193 iommu_completion_wait(iommu);
1196 void iommu_flush_all_caches(struct amd_iommu *iommu)
1198 if (iommu_feature(iommu, FEATURE_IA)) {
1199 iommu_flush_all(iommu);
1201 iommu_flush_dte_all(iommu);
1202 iommu_flush_irt_all(iommu);
1203 iommu_flush_tlb_all(iommu);
1208 * Command send function for flushing on-device TLB
1210 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1211 u64 address, size_t size)
1213 struct amd_iommu *iommu;
1214 struct iommu_cmd cmd;
1217 qdep = dev_data->ats.qdep;
1218 iommu = amd_iommu_rlookup_table[dev_data->devid];
1220 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1222 return iommu_queue_command(iommu, &cmd);
1226 * Command send function for invalidating a device table entry
1228 static int device_flush_dte(struct iommu_dev_data *dev_data)
1230 struct amd_iommu *iommu;
1234 iommu = amd_iommu_rlookup_table[dev_data->devid];
1235 alias = dev_data->alias;
1237 ret = iommu_flush_dte(iommu, dev_data->devid);
1238 if (!ret && alias != dev_data->devid)
1239 ret = iommu_flush_dte(iommu, alias);
1243 if (dev_data->ats.enabled)
1244 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1250 * TLB invalidation function which is called from the mapping functions.
1251 * It invalidates a single PTE if the range to flush is within a single
1252 * page. Otherwise it flushes the whole TLB of the IOMMU.
1254 static void __domain_flush_pages(struct protection_domain *domain,
1255 u64 address, size_t size, int pde)
1257 struct iommu_dev_data *dev_data;
1258 struct iommu_cmd cmd;
1261 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1263 for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
1264 if (!domain->dev_iommu[i])
1268 * Devices of this domain are behind this IOMMU
1269 * We need a TLB flush
1271 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1274 list_for_each_entry(dev_data, &domain->dev_list, list) {
1276 if (!dev_data->ats.enabled)
1279 ret |= device_flush_iotlb(dev_data, address, size);
1285 static void domain_flush_pages(struct protection_domain *domain,
1286 u64 address, size_t size)
1288 __domain_flush_pages(domain, address, size, 0);
1291 /* Flush the whole IO/TLB for a given protection domain */
1292 static void domain_flush_tlb(struct protection_domain *domain)
1294 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1297 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1298 static void domain_flush_tlb_pde(struct protection_domain *domain)
1300 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1303 static void domain_flush_complete(struct protection_domain *domain)
1307 for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
1308 if (domain && !domain->dev_iommu[i])
1312 * Devices of this domain are behind this IOMMU
1313 * We need to wait for completion of all commands.
1315 iommu_completion_wait(amd_iommus[i]);
1321 * This function flushes the DTEs for all devices in domain
1323 static void domain_flush_devices(struct protection_domain *domain)
1325 struct iommu_dev_data *dev_data;
1327 list_for_each_entry(dev_data, &domain->dev_list, list)
1328 device_flush_dte(dev_data);
1331 /****************************************************************************
1333 * The functions below are used the create the page table mappings for
1334 * unity mapped regions.
1336 ****************************************************************************/
1339 * This function is used to add another level to an IO page table. Adding
1340 * another level increases the size of the address space by 9 bits to a size up
1343 static bool increase_address_space(struct protection_domain *domain,
1348 if (domain->mode == PAGE_MODE_6_LEVEL)
1349 /* address space already 64 bit large */
1352 pte = (void *)get_zeroed_page(gfp);
1356 *pte = PM_LEVEL_PDE(domain->mode,
1357 virt_to_phys(domain->pt_root));
1358 domain->pt_root = pte;
1360 domain->updated = true;
1365 static u64 *alloc_pte(struct protection_domain *domain,
1366 unsigned long address,
1367 unsigned long page_size,
1374 BUG_ON(!is_power_of_2(page_size));
1376 while (address > PM_LEVEL_SIZE(domain->mode))
1377 increase_address_space(domain, gfp);
1379 level = domain->mode - 1;
1380 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1381 address = PAGE_SIZE_ALIGN(address, page_size);
1382 end_lvl = PAGE_SIZE_LEVEL(page_size);
1384 while (level > end_lvl) {
1389 if (!IOMMU_PTE_PRESENT(__pte)) {
1390 page = (u64 *)get_zeroed_page(gfp);
1394 __npte = PM_LEVEL_PDE(level, virt_to_phys(page));
1396 /* pte could have been changed somewhere. */
1397 if (cmpxchg64(pte, __pte, __npte) != __pte) {
1398 free_page((unsigned long)page);
1403 /* No level skipping support yet */
1404 if (PM_PTE_LEVEL(*pte) != level)
1409 pte = IOMMU_PTE_PAGE(*pte);
1411 if (pte_page && level == end_lvl)
1414 pte = &pte[PM_LEVEL_INDEX(level, address)];
1421 * This function checks if there is a PTE for a given dma address. If
1422 * there is one, it returns the pointer to it.
1424 static u64 *fetch_pte(struct protection_domain *domain,
1425 unsigned long address,
1426 unsigned long *page_size)
1431 if (address > PM_LEVEL_SIZE(domain->mode))
1434 level = domain->mode - 1;
1435 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1436 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1441 if (!IOMMU_PTE_PRESENT(*pte))
1445 if (PM_PTE_LEVEL(*pte) == 7 ||
1446 PM_PTE_LEVEL(*pte) == 0)
1449 /* No level skipping support yet */
1450 if (PM_PTE_LEVEL(*pte) != level)
1455 /* Walk to the next level */
1456 pte = IOMMU_PTE_PAGE(*pte);
1457 pte = &pte[PM_LEVEL_INDEX(level, address)];
1458 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1461 if (PM_PTE_LEVEL(*pte) == 0x07) {
1462 unsigned long pte_mask;
1465 * If we have a series of large PTEs, make
1466 * sure to return a pointer to the first one.
1468 *page_size = pte_mask = PTE_PAGE_SIZE(*pte);
1469 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1470 pte = (u64 *)(((unsigned long)pte) & pte_mask);
1477 * Generic mapping functions. It maps a physical address into a DMA
1478 * address space. It allocates the page table pages if necessary.
1479 * In the future it can be extended to a generic mapping function
1480 * supporting all features of AMD IOMMU page tables like level skipping
1481 * and full 64 bit address spaces.
1483 static int iommu_map_page(struct protection_domain *dom,
1484 unsigned long bus_addr,
1485 unsigned long phys_addr,
1486 unsigned long page_size,
1493 BUG_ON(!IS_ALIGNED(bus_addr, page_size));
1494 BUG_ON(!IS_ALIGNED(phys_addr, page_size));
1496 if (!(prot & IOMMU_PROT_MASK))
1499 count = PAGE_SIZE_PTE_COUNT(page_size);
1500 pte = alloc_pte(dom, bus_addr, page_size, NULL, gfp);
1505 for (i = 0; i < count; ++i)
1506 if (IOMMU_PTE_PRESENT(pte[i]))
1510 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1511 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1513 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1515 if (prot & IOMMU_PROT_IR)
1516 __pte |= IOMMU_PTE_IR;
1517 if (prot & IOMMU_PROT_IW)
1518 __pte |= IOMMU_PTE_IW;
1520 for (i = 0; i < count; ++i)
1528 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1529 unsigned long bus_addr,
1530 unsigned long page_size)
1532 unsigned long long unmapped;
1533 unsigned long unmap_size;
1536 BUG_ON(!is_power_of_2(page_size));
1540 while (unmapped < page_size) {
1542 pte = fetch_pte(dom, bus_addr, &unmap_size);
1547 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1548 for (i = 0; i < count; i++)
1552 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1553 unmapped += unmap_size;
1556 BUG_ON(unmapped && !is_power_of_2(unmapped));
1561 /****************************************************************************
1563 * The next functions belong to the address allocator for the dma_ops
1564 * interface functions.
1566 ****************************************************************************/
1569 static unsigned long dma_ops_alloc_iova(struct device *dev,
1570 struct dma_ops_domain *dma_dom,
1571 unsigned int pages, u64 dma_mask)
1573 unsigned long pfn = 0;
1575 pages = __roundup_pow_of_two(pages);
1577 if (dma_mask > DMA_BIT_MASK(32))
1578 pfn = alloc_iova_fast(&dma_dom->iovad, pages,
1579 IOVA_PFN(DMA_BIT_MASK(32)));
1582 pfn = alloc_iova_fast(&dma_dom->iovad, pages, IOVA_PFN(dma_mask));
1584 return (pfn << PAGE_SHIFT);
1587 static void dma_ops_free_iova(struct dma_ops_domain *dma_dom,
1588 unsigned long address,
1591 pages = __roundup_pow_of_two(pages);
1592 address >>= PAGE_SHIFT;
1594 free_iova_fast(&dma_dom->iovad, address, pages);
1597 /****************************************************************************
1599 * The next functions belong to the domain allocation. A domain is
1600 * allocated for every IOMMU as the default domain. If device isolation
1601 * is enabled, every device get its own domain. The most important thing
1602 * about domains is the page table mapping the DMA address space they
1605 ****************************************************************************/
1608 * This function adds a protection domain to the global protection domain list
1610 static void add_domain_to_list(struct protection_domain *domain)
1612 unsigned long flags;
1614 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1615 list_add(&domain->list, &amd_iommu_pd_list);
1616 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1620 * This function removes a protection domain to the global
1621 * protection domain list
1623 static void del_domain_from_list(struct protection_domain *domain)
1625 unsigned long flags;
1627 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1628 list_del(&domain->list);
1629 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1632 static u16 domain_id_alloc(void)
1634 unsigned long flags;
1637 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1638 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1640 if (id > 0 && id < MAX_DOMAIN_ID)
1641 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1644 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1649 static void domain_id_free(int id)
1651 unsigned long flags;
1653 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1654 if (id > 0 && id < MAX_DOMAIN_ID)
1655 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1656 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1659 #define DEFINE_FREE_PT_FN(LVL, FN) \
1660 static void free_pt_##LVL (unsigned long __pt) \
1668 for (i = 0; i < 512; ++i) { \
1669 /* PTE present? */ \
1670 if (!IOMMU_PTE_PRESENT(pt[i])) \
1674 if (PM_PTE_LEVEL(pt[i]) == 0 || \
1675 PM_PTE_LEVEL(pt[i]) == 7) \
1678 p = (unsigned long)IOMMU_PTE_PAGE(pt[i]); \
1681 free_page((unsigned long)pt); \
1684 DEFINE_FREE_PT_FN(l2, free_page)
1685 DEFINE_FREE_PT_FN(l3, free_pt_l2)
1686 DEFINE_FREE_PT_FN(l4, free_pt_l3)
1687 DEFINE_FREE_PT_FN(l5, free_pt_l4)
1688 DEFINE_FREE_PT_FN(l6, free_pt_l5)
1690 static void free_pagetable(struct protection_domain *domain)
1692 unsigned long root = (unsigned long)domain->pt_root;
1694 switch (domain->mode) {
1695 case PAGE_MODE_NONE:
1697 case PAGE_MODE_1_LEVEL:
1700 case PAGE_MODE_2_LEVEL:
1703 case PAGE_MODE_3_LEVEL:
1706 case PAGE_MODE_4_LEVEL:
1709 case PAGE_MODE_5_LEVEL:
1712 case PAGE_MODE_6_LEVEL:
1720 static void free_gcr3_tbl_level1(u64 *tbl)
1725 for (i = 0; i < 512; ++i) {
1726 if (!(tbl[i] & GCR3_VALID))
1729 ptr = __va(tbl[i] & PAGE_MASK);
1731 free_page((unsigned long)ptr);
1735 static void free_gcr3_tbl_level2(u64 *tbl)
1740 for (i = 0; i < 512; ++i) {
1741 if (!(tbl[i] & GCR3_VALID))
1744 ptr = __va(tbl[i] & PAGE_MASK);
1746 free_gcr3_tbl_level1(ptr);
1750 static void free_gcr3_table(struct protection_domain *domain)
1752 if (domain->glx == 2)
1753 free_gcr3_tbl_level2(domain->gcr3_tbl);
1754 else if (domain->glx == 1)
1755 free_gcr3_tbl_level1(domain->gcr3_tbl);
1757 BUG_ON(domain->glx != 0);
1759 free_page((unsigned long)domain->gcr3_tbl);
1763 * Free a domain, only used if something went wrong in the
1764 * allocation path and we need to free an already allocated page table
1766 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1771 del_domain_from_list(&dom->domain);
1773 put_iova_domain(&dom->iovad);
1775 free_pagetable(&dom->domain);
1778 domain_id_free(dom->domain.id);
1784 * Allocates a new protection domain usable for the dma_ops functions.
1785 * It also initializes the page table and the address allocator data
1786 * structures required for the dma_ops interface
1788 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1790 struct dma_ops_domain *dma_dom;
1792 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1796 if (protection_domain_init(&dma_dom->domain))
1799 dma_dom->domain.mode = PAGE_MODE_3_LEVEL;
1800 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1801 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1802 if (!dma_dom->domain.pt_root)
1805 init_iova_domain(&dma_dom->iovad, PAGE_SIZE,
1806 IOVA_START_PFN, DMA_32BIT_PFN);
1808 /* Initialize reserved ranges */
1809 copy_reserved_iova(&reserved_iova_ranges, &dma_dom->iovad);
1811 add_domain_to_list(&dma_dom->domain);
1816 dma_ops_domain_free(dma_dom);
1822 * little helper function to check whether a given protection domain is a
1825 static bool dma_ops_domain(struct protection_domain *domain)
1827 return domain->flags & PD_DMA_OPS_MASK;
1830 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1835 if (domain->mode != PAGE_MODE_NONE)
1836 pte_root = virt_to_phys(domain->pt_root);
1838 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1839 << DEV_ENTRY_MODE_SHIFT;
1840 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1842 flags = amd_iommu_dev_table[devid].data[1];
1845 flags |= DTE_FLAG_IOTLB;
1847 if (domain->flags & PD_IOMMUV2_MASK) {
1848 u64 gcr3 = __pa(domain->gcr3_tbl);
1849 u64 glx = domain->glx;
1852 pte_root |= DTE_FLAG_GV;
1853 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1855 /* First mask out possible old values for GCR3 table */
1856 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1859 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1862 /* Encode GCR3 table into DTE */
1863 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1866 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1869 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
1873 flags &= ~(0xffffUL);
1874 flags |= domain->id;
1876 amd_iommu_dev_table[devid].data[1] = flags;
1877 amd_iommu_dev_table[devid].data[0] = pte_root;
1880 static void clear_dte_entry(u16 devid)
1882 /* remove entry from the device table seen by the hardware */
1883 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1884 amd_iommu_dev_table[devid].data[1] &= DTE_FLAG_MASK;
1886 amd_iommu_apply_erratum_63(devid);
1889 static void do_attach(struct iommu_dev_data *dev_data,
1890 struct protection_domain *domain)
1892 struct amd_iommu *iommu;
1896 iommu = amd_iommu_rlookup_table[dev_data->devid];
1897 alias = dev_data->alias;
1898 ats = dev_data->ats.enabled;
1900 /* Update data structures */
1901 dev_data->domain = domain;
1902 list_add(&dev_data->list, &domain->dev_list);
1904 /* Do reference counting */
1905 domain->dev_iommu[iommu->index] += 1;
1906 domain->dev_cnt += 1;
1908 /* Update device table */
1909 set_dte_entry(dev_data->devid, domain, ats);
1910 if (alias != dev_data->devid)
1911 set_dte_entry(alias, domain, ats);
1913 device_flush_dte(dev_data);
1916 static void do_detach(struct iommu_dev_data *dev_data)
1918 struct amd_iommu *iommu;
1922 * First check if the device is still attached. It might already
1923 * be detached from its domain because the generic
1924 * iommu_detach_group code detached it and we try again here in
1925 * our alias handling.
1927 if (!dev_data->domain)
1930 iommu = amd_iommu_rlookup_table[dev_data->devid];
1931 alias = dev_data->alias;
1933 /* decrease reference counters */
1934 dev_data->domain->dev_iommu[iommu->index] -= 1;
1935 dev_data->domain->dev_cnt -= 1;
1937 /* Update data structures */
1938 dev_data->domain = NULL;
1939 list_del(&dev_data->list);
1940 clear_dte_entry(dev_data->devid);
1941 if (alias != dev_data->devid)
1942 clear_dte_entry(alias);
1944 /* Flush the DTE entry */
1945 device_flush_dte(dev_data);
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);
2122 * Removes a device from a protection domain (unlocked)
2124 static void __detach_device(struct iommu_dev_data *dev_data)
2126 struct protection_domain *domain;
2129 * Must be called with IRQs disabled. Warn here to detect early
2132 WARN_ON(!irqs_disabled());
2134 if (WARN_ON(!dev_data->domain))
2137 domain = dev_data->domain;
2139 spin_lock(&domain->lock);
2141 do_detach(dev_data);
2143 spin_unlock(&domain->lock);
2147 * Removes a device from a protection domain (with devtable_lock held)
2149 static void detach_device(struct device *dev)
2151 struct protection_domain *domain;
2152 struct iommu_dev_data *dev_data;
2153 unsigned long flags;
2155 dev_data = get_dev_data(dev);
2156 domain = dev_data->domain;
2158 /* lock device table */
2159 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2160 __detach_device(dev_data);
2161 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2163 if (!dev_is_pci(dev))
2166 if (domain->flags & PD_IOMMUV2_MASK && dev_data->iommu_v2)
2167 pdev_iommuv2_disable(to_pci_dev(dev));
2168 else if (dev_data->ats.enabled)
2169 pci_disable_ats(to_pci_dev(dev));
2171 dev_data->ats.enabled = false;
2174 static int amd_iommu_add_device(struct device *dev)
2176 struct iommu_dev_data *dev_data;
2177 struct iommu_domain *domain;
2178 struct amd_iommu *iommu;
2181 if (!check_device(dev) || get_dev_data(dev))
2184 devid = get_device_id(dev);
2188 iommu = amd_iommu_rlookup_table[devid];
2190 ret = iommu_init_device(dev);
2192 if (ret != -ENOTSUPP)
2193 pr_err("Failed to initialize device %s - trying to proceed anyway\n",
2196 iommu_ignore_device(dev);
2197 dev->dma_ops = &nommu_dma_ops;
2200 init_iommu_group(dev);
2202 dev_data = get_dev_data(dev);
2206 if (iommu_pass_through || dev_data->iommu_v2)
2207 iommu_request_dm_for_dev(dev);
2209 /* Domains are initialized for this device - have a look what we ended up with */
2210 domain = iommu_get_domain_for_dev(dev);
2211 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2212 dev_data->passthrough = true;
2214 dev->dma_ops = &amd_iommu_dma_ops;
2217 iommu_completion_wait(iommu);
2222 static void amd_iommu_remove_device(struct device *dev)
2224 struct amd_iommu *iommu;
2227 if (!check_device(dev))
2230 devid = get_device_id(dev);
2234 iommu = amd_iommu_rlookup_table[devid];
2236 iommu_uninit_device(dev);
2237 iommu_completion_wait(iommu);
2240 static struct iommu_group *amd_iommu_device_group(struct device *dev)
2242 if (dev_is_pci(dev))
2243 return pci_device_group(dev);
2245 return acpihid_device_group(dev);
2248 /*****************************************************************************
2250 * The next functions belong to the dma_ops mapping/unmapping code.
2252 *****************************************************************************/
2254 static void __queue_flush(struct flush_queue *queue)
2256 struct protection_domain *domain;
2257 unsigned long flags;
2260 /* First flush TLB of all known domains */
2261 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
2262 list_for_each_entry(domain, &amd_iommu_pd_list, list)
2263 domain_flush_tlb(domain);
2264 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
2266 /* Wait until flushes have completed */
2267 domain_flush_complete(NULL);
2269 for (idx = 0; idx < queue->next; ++idx) {
2270 struct flush_queue_entry *entry;
2272 entry = queue->entries + idx;
2274 free_iova_fast(&entry->dma_dom->iovad,
2278 /* Not really necessary, just to make sure we catch any bugs */
2279 entry->dma_dom = NULL;
2285 static void queue_flush_all(void)
2289 for_each_possible_cpu(cpu) {
2290 struct flush_queue *queue;
2291 unsigned long flags;
2293 queue = per_cpu_ptr(&flush_queue, cpu);
2294 spin_lock_irqsave(&queue->lock, flags);
2295 if (queue->next > 0)
2296 __queue_flush(queue);
2297 spin_unlock_irqrestore(&queue->lock, flags);
2301 static void queue_flush_timeout(unsigned long unsused)
2303 atomic_set(&queue_timer_on, 0);
2307 static void queue_add(struct dma_ops_domain *dma_dom,
2308 unsigned long address, unsigned long pages)
2310 struct flush_queue_entry *entry;
2311 struct flush_queue *queue;
2312 unsigned long flags;
2315 pages = __roundup_pow_of_two(pages);
2316 address >>= PAGE_SHIFT;
2318 queue = get_cpu_ptr(&flush_queue);
2319 spin_lock_irqsave(&queue->lock, flags);
2321 if (queue->next == FLUSH_QUEUE_SIZE)
2322 __queue_flush(queue);
2324 idx = queue->next++;
2325 entry = queue->entries + idx;
2327 entry->iova_pfn = address;
2328 entry->pages = pages;
2329 entry->dma_dom = dma_dom;
2331 spin_unlock_irqrestore(&queue->lock, flags);
2333 if (atomic_cmpxchg(&queue_timer_on, 0, 1) == 0)
2334 mod_timer(&queue_timer, jiffies + msecs_to_jiffies(10));
2336 put_cpu_ptr(&flush_queue);
2341 * In the dma_ops path we only have the struct device. This function
2342 * finds the corresponding IOMMU, the protection domain and the
2343 * requestor id for a given device.
2344 * If the device is not yet associated with a domain this is also done
2347 static struct protection_domain *get_domain(struct device *dev)
2349 struct protection_domain *domain;
2351 if (!check_device(dev))
2352 return ERR_PTR(-EINVAL);
2354 domain = get_dev_data(dev)->domain;
2355 if (!dma_ops_domain(domain))
2356 return ERR_PTR(-EBUSY);
2361 static void update_device_table(struct protection_domain *domain)
2363 struct iommu_dev_data *dev_data;
2365 list_for_each_entry(dev_data, &domain->dev_list, list) {
2366 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2368 if (dev_data->devid == dev_data->alias)
2371 /* There is an alias, update device table entry for it */
2372 set_dte_entry(dev_data->alias, domain, dev_data->ats.enabled);
2376 static void update_domain(struct protection_domain *domain)
2378 if (!domain->updated)
2381 update_device_table(domain);
2383 domain_flush_devices(domain);
2384 domain_flush_tlb_pde(domain);
2386 domain->updated = false;
2389 static int dir2prot(enum dma_data_direction direction)
2391 if (direction == DMA_TO_DEVICE)
2392 return IOMMU_PROT_IR;
2393 else if (direction == DMA_FROM_DEVICE)
2394 return IOMMU_PROT_IW;
2395 else if (direction == DMA_BIDIRECTIONAL)
2396 return IOMMU_PROT_IW | IOMMU_PROT_IR;
2401 * This function contains common code for mapping of a physically
2402 * contiguous memory region into DMA address space. It is used by all
2403 * mapping functions provided with this IOMMU driver.
2404 * Must be called with the domain lock held.
2406 static dma_addr_t __map_single(struct device *dev,
2407 struct dma_ops_domain *dma_dom,
2410 enum dma_data_direction direction,
2413 dma_addr_t offset = paddr & ~PAGE_MASK;
2414 dma_addr_t address, start, ret;
2419 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2422 address = dma_ops_alloc_iova(dev, dma_dom, pages, dma_mask);
2423 if (address == DMA_ERROR_CODE)
2426 prot = dir2prot(direction);
2429 for (i = 0; i < pages; ++i) {
2430 ret = iommu_map_page(&dma_dom->domain, start, paddr,
2431 PAGE_SIZE, prot, GFP_ATOMIC);
2440 if (unlikely(amd_iommu_np_cache)) {
2441 domain_flush_pages(&dma_dom->domain, address, size);
2442 domain_flush_complete(&dma_dom->domain);
2450 for (--i; i >= 0; --i) {
2452 iommu_unmap_page(&dma_dom->domain, start, PAGE_SIZE);
2455 domain_flush_tlb(&dma_dom->domain);
2456 domain_flush_complete(&dma_dom->domain);
2458 dma_ops_free_iova(dma_dom, address, pages);
2460 return DMA_ERROR_CODE;
2464 * Does the reverse of the __map_single function. Must be called with
2465 * the domain lock held too
2467 static void __unmap_single(struct dma_ops_domain *dma_dom,
2468 dma_addr_t dma_addr,
2472 dma_addr_t flush_addr;
2473 dma_addr_t i, start;
2476 flush_addr = dma_addr;
2477 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2478 dma_addr &= PAGE_MASK;
2481 for (i = 0; i < pages; ++i) {
2482 iommu_unmap_page(&dma_dom->domain, start, PAGE_SIZE);
2486 if (amd_iommu_unmap_flush) {
2487 dma_ops_free_iova(dma_dom, dma_addr, pages);
2488 domain_flush_tlb(&dma_dom->domain);
2489 domain_flush_complete(&dma_dom->domain);
2491 queue_add(dma_dom, dma_addr, pages);
2496 * The exported map_single function for dma_ops.
2498 static dma_addr_t map_page(struct device *dev, struct page *page,
2499 unsigned long offset, size_t size,
2500 enum dma_data_direction dir,
2501 unsigned long attrs)
2503 phys_addr_t paddr = page_to_phys(page) + offset;
2504 struct protection_domain *domain;
2505 struct dma_ops_domain *dma_dom;
2508 domain = get_domain(dev);
2509 if (PTR_ERR(domain) == -EINVAL)
2510 return (dma_addr_t)paddr;
2511 else if (IS_ERR(domain))
2512 return DMA_ERROR_CODE;
2514 dma_mask = *dev->dma_mask;
2515 dma_dom = to_dma_ops_domain(domain);
2517 return __map_single(dev, dma_dom, paddr, size, dir, dma_mask);
2521 * The exported unmap_single function for dma_ops.
2523 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2524 enum dma_data_direction dir, unsigned long attrs)
2526 struct protection_domain *domain;
2527 struct dma_ops_domain *dma_dom;
2529 domain = get_domain(dev);
2533 dma_dom = to_dma_ops_domain(domain);
2535 __unmap_single(dma_dom, dma_addr, size, dir);
2538 static int sg_num_pages(struct device *dev,
2539 struct scatterlist *sglist,
2542 unsigned long mask, boundary_size;
2543 struct scatterlist *s;
2546 mask = dma_get_seg_boundary(dev);
2547 boundary_size = mask + 1 ? ALIGN(mask + 1, PAGE_SIZE) >> PAGE_SHIFT :
2548 1UL << (BITS_PER_LONG - PAGE_SHIFT);
2550 for_each_sg(sglist, s, nelems, i) {
2553 s->dma_address = npages << PAGE_SHIFT;
2554 p = npages % boundary_size;
2555 n = iommu_num_pages(sg_phys(s), s->length, PAGE_SIZE);
2556 if (p + n > boundary_size)
2557 npages += boundary_size - p;
2565 * The exported map_sg function for dma_ops (handles scatter-gather
2568 static int map_sg(struct device *dev, struct scatterlist *sglist,
2569 int nelems, enum dma_data_direction direction,
2570 unsigned long attrs)
2572 int mapped_pages = 0, npages = 0, prot = 0, i;
2573 struct protection_domain *domain;
2574 struct dma_ops_domain *dma_dom;
2575 struct scatterlist *s;
2576 unsigned long address;
2579 domain = get_domain(dev);
2583 dma_dom = to_dma_ops_domain(domain);
2584 dma_mask = *dev->dma_mask;
2586 npages = sg_num_pages(dev, sglist, nelems);
2588 address = dma_ops_alloc_iova(dev, dma_dom, npages, dma_mask);
2589 if (address == DMA_ERROR_CODE)
2592 prot = dir2prot(direction);
2594 /* Map all sg entries */
2595 for_each_sg(sglist, s, nelems, i) {
2596 int j, pages = iommu_num_pages(sg_phys(s), s->length, PAGE_SIZE);
2598 for (j = 0; j < pages; ++j) {
2599 unsigned long bus_addr, phys_addr;
2602 bus_addr = address + s->dma_address + (j << PAGE_SHIFT);
2603 phys_addr = (sg_phys(s) & PAGE_MASK) + (j << PAGE_SHIFT);
2604 ret = iommu_map_page(domain, bus_addr, phys_addr, PAGE_SIZE, prot, GFP_ATOMIC);
2612 /* Everything is mapped - write the right values into s->dma_address */
2613 for_each_sg(sglist, s, nelems, i) {
2614 s->dma_address += address + s->offset;
2615 s->dma_length = s->length;
2621 pr_err("%s: IOMMU mapping error in map_sg (io-pages: %d)\n",
2622 dev_name(dev), npages);
2624 for_each_sg(sglist, s, nelems, i) {
2625 int j, pages = iommu_num_pages(sg_phys(s), s->length, PAGE_SIZE);
2627 for (j = 0; j < pages; ++j) {
2628 unsigned long bus_addr;
2630 bus_addr = address + s->dma_address + (j << PAGE_SHIFT);
2631 iommu_unmap_page(domain, bus_addr, PAGE_SIZE);
2639 free_iova_fast(&dma_dom->iovad, address, npages);
2646 * The exported map_sg function for dma_ops (handles scatter-gather
2649 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2650 int nelems, enum dma_data_direction dir,
2651 unsigned long attrs)
2653 struct protection_domain *domain;
2654 struct dma_ops_domain *dma_dom;
2655 unsigned long startaddr;
2658 domain = get_domain(dev);
2662 startaddr = sg_dma_address(sglist) & PAGE_MASK;
2663 dma_dom = to_dma_ops_domain(domain);
2664 npages = sg_num_pages(dev, sglist, nelems);
2666 __unmap_single(dma_dom, startaddr, npages << PAGE_SHIFT, dir);
2670 * The exported alloc_coherent function for dma_ops.
2672 static void *alloc_coherent(struct device *dev, size_t size,
2673 dma_addr_t *dma_addr, gfp_t flag,
2674 unsigned long attrs)
2676 u64 dma_mask = dev->coherent_dma_mask;
2677 struct protection_domain *domain;
2678 struct dma_ops_domain *dma_dom;
2681 domain = get_domain(dev);
2682 if (PTR_ERR(domain) == -EINVAL) {
2683 page = alloc_pages(flag, get_order(size));
2684 *dma_addr = page_to_phys(page);
2685 return page_address(page);
2686 } else if (IS_ERR(domain))
2689 dma_dom = to_dma_ops_domain(domain);
2690 size = PAGE_ALIGN(size);
2691 dma_mask = dev->coherent_dma_mask;
2692 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2695 page = alloc_pages(flag | __GFP_NOWARN, get_order(size));
2697 if (!gfpflags_allow_blocking(flag))
2700 page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
2701 get_order(size), flag);
2707 dma_mask = *dev->dma_mask;
2709 *dma_addr = __map_single(dev, dma_dom, page_to_phys(page),
2710 size, DMA_BIDIRECTIONAL, dma_mask);
2712 if (*dma_addr == DMA_ERROR_CODE)
2715 return page_address(page);
2719 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2720 __free_pages(page, get_order(size));
2726 * The exported free_coherent function for dma_ops.
2728 static void free_coherent(struct device *dev, size_t size,
2729 void *virt_addr, dma_addr_t dma_addr,
2730 unsigned long attrs)
2732 struct protection_domain *domain;
2733 struct dma_ops_domain *dma_dom;
2736 page = virt_to_page(virt_addr);
2737 size = PAGE_ALIGN(size);
2739 domain = get_domain(dev);
2743 dma_dom = to_dma_ops_domain(domain);
2745 __unmap_single(dma_dom, dma_addr, size, DMA_BIDIRECTIONAL);
2748 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2749 __free_pages(page, get_order(size));
2753 * This function is called by the DMA layer to find out if we can handle a
2754 * particular device. It is part of the dma_ops.
2756 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2758 return check_device(dev);
2761 static const struct dma_map_ops amd_iommu_dma_ops = {
2762 .alloc = alloc_coherent,
2763 .free = free_coherent,
2764 .map_page = map_page,
2765 .unmap_page = unmap_page,
2767 .unmap_sg = unmap_sg,
2768 .dma_supported = amd_iommu_dma_supported,
2771 static int init_reserved_iova_ranges(void)
2773 struct pci_dev *pdev = NULL;
2776 init_iova_domain(&reserved_iova_ranges, PAGE_SIZE,
2777 IOVA_START_PFN, DMA_32BIT_PFN);
2779 lockdep_set_class(&reserved_iova_ranges.iova_rbtree_lock,
2780 &reserved_rbtree_key);
2782 /* MSI memory range */
2783 val = reserve_iova(&reserved_iova_ranges,
2784 IOVA_PFN(MSI_RANGE_START), IOVA_PFN(MSI_RANGE_END));
2786 pr_err("Reserving MSI range failed\n");
2790 /* HT memory range */
2791 val = reserve_iova(&reserved_iova_ranges,
2792 IOVA_PFN(HT_RANGE_START), IOVA_PFN(HT_RANGE_END));
2794 pr_err("Reserving HT range failed\n");
2799 * Memory used for PCI resources
2800 * FIXME: Check whether we can reserve the PCI-hole completly
2802 for_each_pci_dev(pdev) {
2805 for (i = 0; i < PCI_NUM_RESOURCES; ++i) {
2806 struct resource *r = &pdev->resource[i];
2808 if (!(r->flags & IORESOURCE_MEM))
2811 val = reserve_iova(&reserved_iova_ranges,
2815 pr_err("Reserve pci-resource range failed\n");
2824 int __init amd_iommu_init_api(void)
2826 int ret, cpu, err = 0;
2828 ret = iova_cache_get();
2832 ret = init_reserved_iova_ranges();
2836 for_each_possible_cpu(cpu) {
2837 struct flush_queue *queue = per_cpu_ptr(&flush_queue, cpu);
2839 queue->entries = kzalloc(FLUSH_QUEUE_SIZE *
2840 sizeof(*queue->entries),
2842 if (!queue->entries)
2845 spin_lock_init(&queue->lock);
2848 err = bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2851 #ifdef CONFIG_ARM_AMBA
2852 err = bus_set_iommu(&amba_bustype, &amd_iommu_ops);
2856 err = bus_set_iommu(&platform_bus_type, &amd_iommu_ops);
2862 for_each_possible_cpu(cpu) {
2863 struct flush_queue *queue = per_cpu_ptr(&flush_queue, cpu);
2865 kfree(queue->entries);
2871 int __init amd_iommu_init_dma_ops(void)
2873 setup_timer(&queue_timer, queue_flush_timeout, 0);
2874 atomic_set(&queue_timer_on, 0);
2876 swiotlb = iommu_pass_through ? 1 : 0;
2880 * In case we don't initialize SWIOTLB (actually the common case
2881 * when AMD IOMMU is enabled), make sure there are global
2882 * dma_ops set as a fall-back for devices not handled by this
2883 * driver (for example non-PCI devices).
2886 dma_ops = &nommu_dma_ops;
2888 if (amd_iommu_unmap_flush)
2889 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
2891 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
2897 /*****************************************************************************
2899 * The following functions belong to the exported interface of AMD IOMMU
2901 * This interface allows access to lower level functions of the IOMMU
2902 * like protection domain handling and assignement of devices to domains
2903 * which is not possible with the dma_ops interface.
2905 *****************************************************************************/
2907 static void cleanup_domain(struct protection_domain *domain)
2909 struct iommu_dev_data *entry;
2910 unsigned long flags;
2912 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2914 while (!list_empty(&domain->dev_list)) {
2915 entry = list_first_entry(&domain->dev_list,
2916 struct iommu_dev_data, list);
2917 __detach_device(entry);
2920 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2923 static void protection_domain_free(struct protection_domain *domain)
2928 del_domain_from_list(domain);
2931 domain_id_free(domain->id);
2936 static int protection_domain_init(struct protection_domain *domain)
2938 spin_lock_init(&domain->lock);
2939 mutex_init(&domain->api_lock);
2940 domain->id = domain_id_alloc();
2943 INIT_LIST_HEAD(&domain->dev_list);
2948 static struct protection_domain *protection_domain_alloc(void)
2950 struct protection_domain *domain;
2952 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2956 if (protection_domain_init(domain))
2959 add_domain_to_list(domain);
2969 static struct iommu_domain *amd_iommu_domain_alloc(unsigned type)
2971 struct protection_domain *pdomain;
2972 struct dma_ops_domain *dma_domain;
2975 case IOMMU_DOMAIN_UNMANAGED:
2976 pdomain = protection_domain_alloc();
2980 pdomain->mode = PAGE_MODE_3_LEVEL;
2981 pdomain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2982 if (!pdomain->pt_root) {
2983 protection_domain_free(pdomain);
2987 pdomain->domain.geometry.aperture_start = 0;
2988 pdomain->domain.geometry.aperture_end = ~0ULL;
2989 pdomain->domain.geometry.force_aperture = true;
2992 case IOMMU_DOMAIN_DMA:
2993 dma_domain = dma_ops_domain_alloc();
2995 pr_err("AMD-Vi: Failed to allocate\n");
2998 pdomain = &dma_domain->domain;
3000 case IOMMU_DOMAIN_IDENTITY:
3001 pdomain = protection_domain_alloc();
3005 pdomain->mode = PAGE_MODE_NONE;
3011 return &pdomain->domain;
3014 static void amd_iommu_domain_free(struct iommu_domain *dom)
3016 struct protection_domain *domain;
3017 struct dma_ops_domain *dma_dom;
3019 domain = to_pdomain(dom);
3021 if (domain->dev_cnt > 0)
3022 cleanup_domain(domain);
3024 BUG_ON(domain->dev_cnt != 0);
3029 switch (dom->type) {
3030 case IOMMU_DOMAIN_DMA:
3032 * First make sure the domain is no longer referenced from the
3037 /* Now release the domain */
3038 dma_dom = to_dma_ops_domain(domain);
3039 dma_ops_domain_free(dma_dom);
3042 if (domain->mode != PAGE_MODE_NONE)
3043 free_pagetable(domain);
3045 if (domain->flags & PD_IOMMUV2_MASK)
3046 free_gcr3_table(domain);
3048 protection_domain_free(domain);
3053 static void amd_iommu_detach_device(struct iommu_domain *dom,
3056 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3057 struct amd_iommu *iommu;
3060 if (!check_device(dev))
3063 devid = get_device_id(dev);
3067 if (dev_data->domain != NULL)
3070 iommu = amd_iommu_rlookup_table[devid];
3074 #ifdef CONFIG_IRQ_REMAP
3075 if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) &&
3076 (dom->type == IOMMU_DOMAIN_UNMANAGED))
3077 dev_data->use_vapic = 0;
3080 iommu_completion_wait(iommu);
3083 static int amd_iommu_attach_device(struct iommu_domain *dom,
3086 struct protection_domain *domain = to_pdomain(dom);
3087 struct iommu_dev_data *dev_data;
3088 struct amd_iommu *iommu;
3091 if (!check_device(dev))
3094 dev_data = dev->archdata.iommu;
3096 iommu = amd_iommu_rlookup_table[dev_data->devid];
3100 if (dev_data->domain)
3103 ret = attach_device(dev, domain);
3105 #ifdef CONFIG_IRQ_REMAP
3106 if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
3107 if (dom->type == IOMMU_DOMAIN_UNMANAGED)
3108 dev_data->use_vapic = 1;
3110 dev_data->use_vapic = 0;
3114 iommu_completion_wait(iommu);
3119 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3120 phys_addr_t paddr, size_t page_size, int iommu_prot)
3122 struct protection_domain *domain = to_pdomain(dom);
3126 if (domain->mode == PAGE_MODE_NONE)
3129 if (iommu_prot & IOMMU_READ)
3130 prot |= IOMMU_PROT_IR;
3131 if (iommu_prot & IOMMU_WRITE)
3132 prot |= IOMMU_PROT_IW;
3134 mutex_lock(&domain->api_lock);
3135 ret = iommu_map_page(domain, iova, paddr, page_size, prot, GFP_KERNEL);
3136 mutex_unlock(&domain->api_lock);
3141 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3144 struct protection_domain *domain = to_pdomain(dom);
3147 if (domain->mode == PAGE_MODE_NONE)
3150 mutex_lock(&domain->api_lock);
3151 unmap_size = iommu_unmap_page(domain, iova, page_size);
3152 mutex_unlock(&domain->api_lock);
3154 domain_flush_tlb_pde(domain);
3159 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3162 struct protection_domain *domain = to_pdomain(dom);
3163 unsigned long offset_mask, pte_pgsize;
3166 if (domain->mode == PAGE_MODE_NONE)
3169 pte = fetch_pte(domain, iova, &pte_pgsize);
3171 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3174 offset_mask = pte_pgsize - 1;
3175 __pte = *pte & PM_ADDR_MASK;
3177 return (__pte & ~offset_mask) | (iova & offset_mask);
3180 static bool amd_iommu_capable(enum iommu_cap cap)
3183 case IOMMU_CAP_CACHE_COHERENCY:
3185 case IOMMU_CAP_INTR_REMAP:
3186 return (irq_remapping_enabled == 1);
3187 case IOMMU_CAP_NOEXEC:
3194 static void amd_iommu_get_resv_regions(struct device *dev,
3195 struct list_head *head)
3197 struct iommu_resv_region *region;
3198 struct unity_map_entry *entry;
3201 devid = get_device_id(dev);
3205 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
3209 if (devid < entry->devid_start || devid > entry->devid_end)
3212 length = entry->address_end - entry->address_start;
3213 if (entry->prot & IOMMU_PROT_IR)
3215 if (entry->prot & IOMMU_PROT_IW)
3216 prot |= IOMMU_WRITE;
3218 region = iommu_alloc_resv_region(entry->address_start,
3222 pr_err("Out of memory allocating dm-regions for %s\n",
3226 list_add_tail(®ion->list, head);
3229 region = iommu_alloc_resv_region(MSI_RANGE_START,
3230 MSI_RANGE_END - MSI_RANGE_START + 1,
3234 list_add_tail(®ion->list, head);
3236 region = iommu_alloc_resv_region(HT_RANGE_START,
3237 HT_RANGE_END - HT_RANGE_START + 1,
3238 0, IOMMU_RESV_RESERVED);
3241 list_add_tail(®ion->list, head);
3244 static void amd_iommu_put_resv_regions(struct device *dev,
3245 struct list_head *head)
3247 struct iommu_resv_region *entry, *next;
3249 list_for_each_entry_safe(entry, next, head, list)
3253 static void amd_iommu_apply_resv_region(struct device *dev,
3254 struct iommu_domain *domain,
3255 struct iommu_resv_region *region)
3257 struct dma_ops_domain *dma_dom = to_dma_ops_domain(to_pdomain(domain));
3258 unsigned long start, end;
3260 start = IOVA_PFN(region->start);
3261 end = IOVA_PFN(region->start + region->length);
3263 WARN_ON_ONCE(reserve_iova(&dma_dom->iovad, start, end) == NULL);
3266 const struct iommu_ops amd_iommu_ops = {
3267 .capable = amd_iommu_capable,
3268 .domain_alloc = amd_iommu_domain_alloc,
3269 .domain_free = amd_iommu_domain_free,
3270 .attach_dev = amd_iommu_attach_device,
3271 .detach_dev = amd_iommu_detach_device,
3272 .map = amd_iommu_map,
3273 .unmap = amd_iommu_unmap,
3274 .map_sg = default_iommu_map_sg,
3275 .iova_to_phys = amd_iommu_iova_to_phys,
3276 .add_device = amd_iommu_add_device,
3277 .remove_device = amd_iommu_remove_device,
3278 .device_group = amd_iommu_device_group,
3279 .get_resv_regions = amd_iommu_get_resv_regions,
3280 .put_resv_regions = amd_iommu_put_resv_regions,
3281 .apply_resv_region = amd_iommu_apply_resv_region,
3282 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3285 /*****************************************************************************
3287 * The next functions do a basic initialization of IOMMU for pass through
3290 * In passthrough mode the IOMMU is initialized and enabled but not used for
3291 * DMA-API translation.
3293 *****************************************************************************/
3295 /* IOMMUv2 specific functions */
3296 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3298 return atomic_notifier_chain_register(&ppr_notifier, nb);
3300 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3302 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3304 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3306 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3308 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3310 struct protection_domain *domain = to_pdomain(dom);
3311 unsigned long flags;
3313 spin_lock_irqsave(&domain->lock, flags);
3315 /* Update data structure */
3316 domain->mode = PAGE_MODE_NONE;
3317 domain->updated = true;
3319 /* Make changes visible to IOMMUs */
3320 update_domain(domain);
3322 /* Page-table is not visible to IOMMU anymore, so free it */
3323 free_pagetable(domain);
3325 spin_unlock_irqrestore(&domain->lock, flags);
3327 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3329 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3331 struct protection_domain *domain = to_pdomain(dom);
3332 unsigned long flags;
3335 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3338 /* Number of GCR3 table levels required */
3339 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3342 if (levels > amd_iommu_max_glx_val)
3345 spin_lock_irqsave(&domain->lock, flags);
3348 * Save us all sanity checks whether devices already in the
3349 * domain support IOMMUv2. Just force that the domain has no
3350 * devices attached when it is switched into IOMMUv2 mode.
3353 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3357 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3358 if (domain->gcr3_tbl == NULL)
3361 domain->glx = levels;
3362 domain->flags |= PD_IOMMUV2_MASK;
3363 domain->updated = true;
3365 update_domain(domain);
3370 spin_unlock_irqrestore(&domain->lock, flags);
3374 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3376 static int __flush_pasid(struct protection_domain *domain, int pasid,
3377 u64 address, bool size)
3379 struct iommu_dev_data *dev_data;
3380 struct iommu_cmd cmd;
3383 if (!(domain->flags & PD_IOMMUV2_MASK))
3386 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3389 * IOMMU TLB needs to be flushed before Device TLB to
3390 * prevent device TLB refill from IOMMU TLB
3392 for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
3393 if (domain->dev_iommu[i] == 0)
3396 ret = iommu_queue_command(amd_iommus[i], &cmd);
3401 /* Wait until IOMMU TLB flushes are complete */
3402 domain_flush_complete(domain);
3404 /* Now flush device TLBs */
3405 list_for_each_entry(dev_data, &domain->dev_list, list) {
3406 struct amd_iommu *iommu;
3410 There might be non-IOMMUv2 capable devices in an IOMMUv2
3413 if (!dev_data->ats.enabled)
3416 qdep = dev_data->ats.qdep;
3417 iommu = amd_iommu_rlookup_table[dev_data->devid];
3419 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3420 qdep, address, size);
3422 ret = iommu_queue_command(iommu, &cmd);
3427 /* Wait until all device TLBs are flushed */
3428 domain_flush_complete(domain);
3437 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3440 return __flush_pasid(domain, pasid, address, false);
3443 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3446 struct protection_domain *domain = to_pdomain(dom);
3447 unsigned long flags;
3450 spin_lock_irqsave(&domain->lock, flags);
3451 ret = __amd_iommu_flush_page(domain, pasid, address);
3452 spin_unlock_irqrestore(&domain->lock, flags);
3456 EXPORT_SYMBOL(amd_iommu_flush_page);
3458 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3460 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3464 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3466 struct protection_domain *domain = to_pdomain(dom);
3467 unsigned long flags;
3470 spin_lock_irqsave(&domain->lock, flags);
3471 ret = __amd_iommu_flush_tlb(domain, pasid);
3472 spin_unlock_irqrestore(&domain->lock, flags);
3476 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3478 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3485 index = (pasid >> (9 * level)) & 0x1ff;
3491 if (!(*pte & GCR3_VALID)) {
3495 root = (void *)get_zeroed_page(GFP_ATOMIC);
3499 *pte = __pa(root) | GCR3_VALID;
3502 root = __va(*pte & PAGE_MASK);
3510 static int __set_gcr3(struct protection_domain *domain, int pasid,
3515 if (domain->mode != PAGE_MODE_NONE)
3518 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3522 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3524 return __amd_iommu_flush_tlb(domain, pasid);
3527 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3531 if (domain->mode != PAGE_MODE_NONE)
3534 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3540 return __amd_iommu_flush_tlb(domain, pasid);
3543 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3546 struct protection_domain *domain = to_pdomain(dom);
3547 unsigned long flags;
3550 spin_lock_irqsave(&domain->lock, flags);
3551 ret = __set_gcr3(domain, pasid, cr3);
3552 spin_unlock_irqrestore(&domain->lock, flags);
3556 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3558 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3560 struct protection_domain *domain = to_pdomain(dom);
3561 unsigned long flags;
3564 spin_lock_irqsave(&domain->lock, flags);
3565 ret = __clear_gcr3(domain, pasid);
3566 spin_unlock_irqrestore(&domain->lock, flags);
3570 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3572 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3573 int status, int tag)
3575 struct iommu_dev_data *dev_data;
3576 struct amd_iommu *iommu;
3577 struct iommu_cmd cmd;
3579 dev_data = get_dev_data(&pdev->dev);
3580 iommu = amd_iommu_rlookup_table[dev_data->devid];
3582 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3583 tag, dev_data->pri_tlp);
3585 return iommu_queue_command(iommu, &cmd);
3587 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3589 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3591 struct protection_domain *pdomain;
3593 pdomain = get_domain(&pdev->dev);
3594 if (IS_ERR(pdomain))
3597 /* Only return IOMMUv2 domains */
3598 if (!(pdomain->flags & PD_IOMMUV2_MASK))
3601 return &pdomain->domain;
3603 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3605 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3607 struct iommu_dev_data *dev_data;
3609 if (!amd_iommu_v2_supported())
3612 dev_data = get_dev_data(&pdev->dev);
3613 dev_data->errata |= (1 << erratum);
3615 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3617 int amd_iommu_device_info(struct pci_dev *pdev,
3618 struct amd_iommu_device_info *info)
3623 if (pdev == NULL || info == NULL)
3626 if (!amd_iommu_v2_supported())
3629 memset(info, 0, sizeof(*info));
3631 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3633 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3635 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3637 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3639 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3643 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3644 max_pasids = min(max_pasids, (1 << 20));
3646 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3647 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3649 features = pci_pasid_features(pdev);
3650 if (features & PCI_PASID_CAP_EXEC)
3651 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3652 if (features & PCI_PASID_CAP_PRIV)
3653 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3658 EXPORT_SYMBOL(amd_iommu_device_info);
3660 #ifdef CONFIG_IRQ_REMAP
3662 /*****************************************************************************
3664 * Interrupt Remapping Implementation
3666 *****************************************************************************/
3668 static struct irq_chip amd_ir_chip;
3670 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3671 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3672 #define DTE_IRQ_TABLE_LEN (8ULL << 1)
3673 #define DTE_IRQ_REMAP_ENABLE 1ULL
3675 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3679 dte = amd_iommu_dev_table[devid].data[2];
3680 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3681 dte |= virt_to_phys(table->table);
3682 dte |= DTE_IRQ_REMAP_INTCTL;
3683 dte |= DTE_IRQ_TABLE_LEN;
3684 dte |= DTE_IRQ_REMAP_ENABLE;
3686 amd_iommu_dev_table[devid].data[2] = dte;
3689 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3691 struct irq_remap_table *table = NULL;
3692 struct amd_iommu *iommu;
3693 unsigned long flags;
3696 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3698 iommu = amd_iommu_rlookup_table[devid];
3702 table = irq_lookup_table[devid];
3706 alias = amd_iommu_alias_table[devid];
3707 table = irq_lookup_table[alias];
3709 irq_lookup_table[devid] = table;
3710 set_dte_irq_entry(devid, table);
3711 iommu_flush_dte(iommu, devid);
3715 /* Nothing there yet, allocate new irq remapping table */
3716 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3720 /* Initialize table spin-lock */
3721 spin_lock_init(&table->lock);
3724 /* Keep the first 32 indexes free for IOAPIC interrupts */
3725 table->min_index = 32;
3727 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3728 if (!table->table) {
3734 if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
3735 memset(table->table, 0,
3736 MAX_IRQS_PER_TABLE * sizeof(u32));
3738 memset(table->table, 0,
3739 (MAX_IRQS_PER_TABLE * (sizeof(u64) * 2)));
3744 for (i = 0; i < 32; ++i)
3745 iommu->irte_ops->set_allocated(table, i);
3748 irq_lookup_table[devid] = table;
3749 set_dte_irq_entry(devid, table);
3750 iommu_flush_dte(iommu, devid);
3751 if (devid != alias) {
3752 irq_lookup_table[alias] = table;
3753 set_dte_irq_entry(alias, table);
3754 iommu_flush_dte(iommu, alias);
3758 iommu_completion_wait(iommu);
3761 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3766 static int alloc_irq_index(u16 devid, int count)
3768 struct irq_remap_table *table;
3769 unsigned long flags;
3771 struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
3776 table = get_irq_table(devid, false);
3780 spin_lock_irqsave(&table->lock, flags);
3782 /* Scan table for free entries */
3783 for (c = 0, index = table->min_index;
3784 index < MAX_IRQS_PER_TABLE;
3786 if (!iommu->irte_ops->is_allocated(table, index))
3793 iommu->irte_ops->set_allocated(table, index - c + 1);
3803 spin_unlock_irqrestore(&table->lock, flags);
3808 static int modify_irte_ga(u16 devid, int index, struct irte_ga *irte,
3809 struct amd_ir_data *data)
3811 struct irq_remap_table *table;
3812 struct amd_iommu *iommu;
3813 unsigned long flags;
3814 struct irte_ga *entry;
3816 iommu = amd_iommu_rlookup_table[devid];
3820 table = get_irq_table(devid, false);
3824 spin_lock_irqsave(&table->lock, flags);
3826 entry = (struct irte_ga *)table->table;
3827 entry = &entry[index];
3828 entry->lo.fields_remap.valid = 0;
3829 entry->hi.val = irte->hi.val;
3830 entry->lo.val = irte->lo.val;
3831 entry->lo.fields_remap.valid = 1;
3835 spin_unlock_irqrestore(&table->lock, flags);
3837 iommu_flush_irt(iommu, devid);
3838 iommu_completion_wait(iommu);
3843 static int modify_irte(u16 devid, int index, union irte *irte)
3845 struct irq_remap_table *table;
3846 struct amd_iommu *iommu;
3847 unsigned long flags;
3849 iommu = amd_iommu_rlookup_table[devid];
3853 table = get_irq_table(devid, false);
3857 spin_lock_irqsave(&table->lock, flags);
3858 table->table[index] = irte->val;
3859 spin_unlock_irqrestore(&table->lock, flags);
3861 iommu_flush_irt(iommu, devid);
3862 iommu_completion_wait(iommu);
3867 static void free_irte(u16 devid, int index)
3869 struct irq_remap_table *table;
3870 struct amd_iommu *iommu;
3871 unsigned long flags;
3873 iommu = amd_iommu_rlookup_table[devid];
3877 table = get_irq_table(devid, false);
3881 spin_lock_irqsave(&table->lock, flags);
3882 iommu->irte_ops->clear_allocated(table, index);
3883 spin_unlock_irqrestore(&table->lock, flags);
3885 iommu_flush_irt(iommu, devid);
3886 iommu_completion_wait(iommu);
3889 static void irte_prepare(void *entry,
3890 u32 delivery_mode, u32 dest_mode,
3891 u8 vector, u32 dest_apicid, int devid)
3893 union irte *irte = (union irte *) entry;
3896 irte->fields.vector = vector;
3897 irte->fields.int_type = delivery_mode;
3898 irte->fields.destination = dest_apicid;
3899 irte->fields.dm = dest_mode;
3900 irte->fields.valid = 1;
3903 static void irte_ga_prepare(void *entry,
3904 u32 delivery_mode, u32 dest_mode,
3905 u8 vector, u32 dest_apicid, int devid)
3907 struct irte_ga *irte = (struct irte_ga *) entry;
3908 struct iommu_dev_data *dev_data = search_dev_data(devid);
3912 irte->lo.fields_remap.guest_mode = dev_data ? dev_data->use_vapic : 0;
3913 irte->lo.fields_remap.int_type = delivery_mode;
3914 irte->lo.fields_remap.dm = dest_mode;
3915 irte->hi.fields.vector = vector;
3916 irte->lo.fields_remap.destination = dest_apicid;
3917 irte->lo.fields_remap.valid = 1;
3920 static void irte_activate(void *entry, u16 devid, u16 index)
3922 union irte *irte = (union irte *) entry;
3924 irte->fields.valid = 1;
3925 modify_irte(devid, index, irte);
3928 static void irte_ga_activate(void *entry, u16 devid, u16 index)
3930 struct irte_ga *irte = (struct irte_ga *) entry;
3932 irte->lo.fields_remap.valid = 1;
3933 modify_irte_ga(devid, index, irte, NULL);
3936 static void irte_deactivate(void *entry, u16 devid, u16 index)
3938 union irte *irte = (union irte *) entry;
3940 irte->fields.valid = 0;
3941 modify_irte(devid, index, irte);
3944 static void irte_ga_deactivate(void *entry, u16 devid, u16 index)
3946 struct irte_ga *irte = (struct irte_ga *) entry;
3948 irte->lo.fields_remap.valid = 0;
3949 modify_irte_ga(devid, index, irte, NULL);
3952 static void irte_set_affinity(void *entry, u16 devid, u16 index,
3953 u8 vector, u32 dest_apicid)
3955 union irte *irte = (union irte *) entry;
3957 irte->fields.vector = vector;
3958 irte->fields.destination = dest_apicid;
3959 modify_irte(devid, index, irte);
3962 static void irte_ga_set_affinity(void *entry, u16 devid, u16 index,
3963 u8 vector, u32 dest_apicid)
3965 struct irte_ga *irte = (struct irte_ga *) entry;
3966 struct iommu_dev_data *dev_data = search_dev_data(devid);
3968 if (!dev_data || !dev_data->use_vapic) {
3969 irte->hi.fields.vector = vector;
3970 irte->lo.fields_remap.destination = dest_apicid;
3971 irte->lo.fields_remap.guest_mode = 0;
3972 modify_irte_ga(devid, index, irte, NULL);
3976 #define IRTE_ALLOCATED (~1U)
3977 static void irte_set_allocated(struct irq_remap_table *table, int index)
3979 table->table[index] = IRTE_ALLOCATED;
3982 static void irte_ga_set_allocated(struct irq_remap_table *table, int index)
3984 struct irte_ga *ptr = (struct irte_ga *)table->table;
3985 struct irte_ga *irte = &ptr[index];
3987 memset(&irte->lo.val, 0, sizeof(u64));
3988 memset(&irte->hi.val, 0, sizeof(u64));
3989 irte->hi.fields.vector = 0xff;
3992 static bool irte_is_allocated(struct irq_remap_table *table, int index)
3994 union irte *ptr = (union irte *)table->table;
3995 union irte *irte = &ptr[index];
3997 return irte->val != 0;
4000 static bool irte_ga_is_allocated(struct irq_remap_table *table, int index)
4002 struct irte_ga *ptr = (struct irte_ga *)table->table;
4003 struct irte_ga *irte = &ptr[index];
4005 return irte->hi.fields.vector != 0;
4008 static void irte_clear_allocated(struct irq_remap_table *table, int index)
4010 table->table[index] = 0;
4013 static void irte_ga_clear_allocated(struct irq_remap_table *table, int index)
4015 struct irte_ga *ptr = (struct irte_ga *)table->table;
4016 struct irte_ga *irte = &ptr[index];
4018 memset(&irte->lo.val, 0, sizeof(u64));
4019 memset(&irte->hi.val, 0, sizeof(u64));
4022 static int get_devid(struct irq_alloc_info *info)
4026 switch (info->type) {
4027 case X86_IRQ_ALLOC_TYPE_IOAPIC:
4028 devid = get_ioapic_devid(info->ioapic_id);
4030 case X86_IRQ_ALLOC_TYPE_HPET:
4031 devid = get_hpet_devid(info->hpet_id);
4033 case X86_IRQ_ALLOC_TYPE_MSI:
4034 case X86_IRQ_ALLOC_TYPE_MSIX:
4035 devid = get_device_id(&info->msi_dev->dev);
4045 static struct irq_domain *get_ir_irq_domain(struct irq_alloc_info *info)
4047 struct amd_iommu *iommu;
4053 devid = get_devid(info);
4055 iommu = amd_iommu_rlookup_table[devid];
4057 return iommu->ir_domain;
4063 static struct irq_domain *get_irq_domain(struct irq_alloc_info *info)
4065 struct amd_iommu *iommu;
4071 switch (info->type) {
4072 case X86_IRQ_ALLOC_TYPE_MSI:
4073 case X86_IRQ_ALLOC_TYPE_MSIX:
4074 devid = get_device_id(&info->msi_dev->dev);
4078 iommu = amd_iommu_rlookup_table[devid];
4080 return iommu->msi_domain;
4089 struct irq_remap_ops amd_iommu_irq_ops = {
4090 .prepare = amd_iommu_prepare,
4091 .enable = amd_iommu_enable,
4092 .disable = amd_iommu_disable,
4093 .reenable = amd_iommu_reenable,
4094 .enable_faulting = amd_iommu_enable_faulting,
4095 .get_ir_irq_domain = get_ir_irq_domain,
4096 .get_irq_domain = get_irq_domain,
4099 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
4100 struct irq_cfg *irq_cfg,
4101 struct irq_alloc_info *info,
4102 int devid, int index, int sub_handle)
4104 struct irq_2_irte *irte_info = &data->irq_2_irte;
4105 struct msi_msg *msg = &data->msi_entry;
4106 struct IO_APIC_route_entry *entry;
4107 struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
4112 data->irq_2_irte.devid = devid;
4113 data->irq_2_irte.index = index + sub_handle;
4114 iommu->irte_ops->prepare(data->entry, apic->irq_delivery_mode,
4115 apic->irq_dest_mode, irq_cfg->vector,
4116 irq_cfg->dest_apicid, devid);
4118 switch (info->type) {
4119 case X86_IRQ_ALLOC_TYPE_IOAPIC:
4120 /* Setup IOAPIC entry */
4121 entry = info->ioapic_entry;
4122 info->ioapic_entry = NULL;
4123 memset(entry, 0, sizeof(*entry));
4124 entry->vector = index;
4126 entry->trigger = info->ioapic_trigger;
4127 entry->polarity = info->ioapic_polarity;
4128 /* Mask level triggered irqs. */
4129 if (info->ioapic_trigger)
4133 case X86_IRQ_ALLOC_TYPE_HPET:
4134 case X86_IRQ_ALLOC_TYPE_MSI:
4135 case X86_IRQ_ALLOC_TYPE_MSIX:
4136 msg->address_hi = MSI_ADDR_BASE_HI;
4137 msg->address_lo = MSI_ADDR_BASE_LO;
4138 msg->data = irte_info->index;
4147 struct amd_irte_ops irte_32_ops = {
4148 .prepare = irte_prepare,
4149 .activate = irte_activate,
4150 .deactivate = irte_deactivate,
4151 .set_affinity = irte_set_affinity,
4152 .set_allocated = irte_set_allocated,
4153 .is_allocated = irte_is_allocated,
4154 .clear_allocated = irte_clear_allocated,
4157 struct amd_irte_ops irte_128_ops = {
4158 .prepare = irte_ga_prepare,
4159 .activate = irte_ga_activate,
4160 .deactivate = irte_ga_deactivate,
4161 .set_affinity = irte_ga_set_affinity,
4162 .set_allocated = irte_ga_set_allocated,
4163 .is_allocated = irte_ga_is_allocated,
4164 .clear_allocated = irte_ga_clear_allocated,
4167 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
4168 unsigned int nr_irqs, void *arg)
4170 struct irq_alloc_info *info = arg;
4171 struct irq_data *irq_data;
4172 struct amd_ir_data *data = NULL;
4173 struct irq_cfg *cfg;
4179 if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_MSI &&
4180 info->type != X86_IRQ_ALLOC_TYPE_MSIX)
4184 * With IRQ remapping enabled, don't need contiguous CPU vectors
4185 * to support multiple MSI interrupts.
4187 if (info->type == X86_IRQ_ALLOC_TYPE_MSI)
4188 info->flags &= ~X86_IRQ_ALLOC_CONTIGUOUS_VECTORS;
4190 devid = get_devid(info);
4194 ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
4198 if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
4199 if (get_irq_table(devid, true))
4200 index = info->ioapic_pin;
4204 index = alloc_irq_index(devid, nr_irqs);
4207 pr_warn("Failed to allocate IRTE\n");
4209 goto out_free_parent;
4212 for (i = 0; i < nr_irqs; i++) {
4213 irq_data = irq_domain_get_irq_data(domain, virq + i);
4214 cfg = irqd_cfg(irq_data);
4215 if (!irq_data || !cfg) {
4221 data = kzalloc(sizeof(*data), GFP_KERNEL);
4225 if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
4226 data->entry = kzalloc(sizeof(union irte), GFP_KERNEL);
4228 data->entry = kzalloc(sizeof(struct irte_ga),
4235 irq_data->hwirq = (devid << 16) + i;
4236 irq_data->chip_data = data;
4237 irq_data->chip = &amd_ir_chip;
4238 irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
4239 irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
4245 for (i--; i >= 0; i--) {
4246 irq_data = irq_domain_get_irq_data(domain, virq + i);
4248 kfree(irq_data->chip_data);
4250 for (i = 0; i < nr_irqs; i++)
4251 free_irte(devid, index + i);
4253 irq_domain_free_irqs_common(domain, virq, nr_irqs);
4257 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
4258 unsigned int nr_irqs)
4260 struct irq_2_irte *irte_info;
4261 struct irq_data *irq_data;
4262 struct amd_ir_data *data;
4265 for (i = 0; i < nr_irqs; i++) {
4266 irq_data = irq_domain_get_irq_data(domain, virq + i);
4267 if (irq_data && irq_data->chip_data) {
4268 data = irq_data->chip_data;
4269 irte_info = &data->irq_2_irte;
4270 free_irte(irte_info->devid, irte_info->index);
4275 irq_domain_free_irqs_common(domain, virq, nr_irqs);
4278 static void irq_remapping_activate(struct irq_domain *domain,
4279 struct irq_data *irq_data)
4281 struct amd_ir_data *data = irq_data->chip_data;
4282 struct irq_2_irte *irte_info = &data->irq_2_irte;
4283 struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
4286 iommu->irte_ops->activate(data->entry, irte_info->devid,
4290 static void irq_remapping_deactivate(struct irq_domain *domain,
4291 struct irq_data *irq_data)
4293 struct amd_ir_data *data = irq_data->chip_data;
4294 struct irq_2_irte *irte_info = &data->irq_2_irte;
4295 struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
4298 iommu->irte_ops->deactivate(data->entry, irte_info->devid,
4302 static struct irq_domain_ops amd_ir_domain_ops = {
4303 .alloc = irq_remapping_alloc,
4304 .free = irq_remapping_free,
4305 .activate = irq_remapping_activate,
4306 .deactivate = irq_remapping_deactivate,
4309 static int amd_ir_set_vcpu_affinity(struct irq_data *data, void *vcpu_info)
4311 struct amd_iommu *iommu;
4312 struct amd_iommu_pi_data *pi_data = vcpu_info;
4313 struct vcpu_data *vcpu_pi_info = pi_data->vcpu_data;
4314 struct amd_ir_data *ir_data = data->chip_data;
4315 struct irte_ga *irte = (struct irte_ga *) ir_data->entry;
4316 struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4317 struct iommu_dev_data *dev_data = search_dev_data(irte_info->devid);
4320 * This device has never been set up for guest mode.
4321 * we should not modify the IRTE
4323 if (!dev_data || !dev_data->use_vapic)
4326 pi_data->ir_data = ir_data;
4329 * SVM tries to set up for VAPIC mode, but we are in
4330 * legacy mode. So, we force legacy mode instead.
4332 if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
4333 pr_debug("AMD-Vi: %s: Fall back to using intr legacy remap\n",
4335 pi_data->is_guest_mode = false;
4338 iommu = amd_iommu_rlookup_table[irte_info->devid];
4342 pi_data->prev_ga_tag = ir_data->cached_ga_tag;
4343 if (pi_data->is_guest_mode) {
4345 irte->hi.fields.ga_root_ptr = (pi_data->base >> 12);
4346 irte->hi.fields.vector = vcpu_pi_info->vector;
4347 irte->lo.fields_vapic.guest_mode = 1;
4348 irte->lo.fields_vapic.ga_tag = pi_data->ga_tag;
4350 ir_data->cached_ga_tag = pi_data->ga_tag;
4353 struct irq_cfg *cfg = irqd_cfg(data);
4357 irte->hi.fields.vector = cfg->vector;
4358 irte->lo.fields_remap.guest_mode = 0;
4359 irte->lo.fields_remap.destination = cfg->dest_apicid;
4360 irte->lo.fields_remap.int_type = apic->irq_delivery_mode;
4361 irte->lo.fields_remap.dm = apic->irq_dest_mode;
4364 * This communicates the ga_tag back to the caller
4365 * so that it can do all the necessary clean up.
4367 ir_data->cached_ga_tag = 0;
4370 return modify_irte_ga(irte_info->devid, irte_info->index, irte, ir_data);
4373 static int amd_ir_set_affinity(struct irq_data *data,
4374 const struct cpumask *mask, bool force)
4376 struct amd_ir_data *ir_data = data->chip_data;
4377 struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4378 struct irq_cfg *cfg = irqd_cfg(data);
4379 struct irq_data *parent = data->parent_data;
4380 struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
4386 ret = parent->chip->irq_set_affinity(parent, mask, force);
4387 if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
4391 * Atomically updates the IRTE with the new destination, vector
4392 * and flushes the interrupt entry cache.
4394 iommu->irte_ops->set_affinity(ir_data->entry, irte_info->devid,
4395 irte_info->index, cfg->vector, cfg->dest_apicid);
4398 * After this point, all the interrupts will start arriving
4399 * at the new destination. So, time to cleanup the previous
4400 * vector allocation.
4402 send_cleanup_vector(cfg);
4404 return IRQ_SET_MASK_OK_DONE;
4407 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
4409 struct amd_ir_data *ir_data = irq_data->chip_data;
4411 *msg = ir_data->msi_entry;
4414 static struct irq_chip amd_ir_chip = {
4415 .irq_ack = ir_ack_apic_edge,
4416 .irq_set_affinity = amd_ir_set_affinity,
4417 .irq_set_vcpu_affinity = amd_ir_set_vcpu_affinity,
4418 .irq_compose_msi_msg = ir_compose_msi_msg,
4421 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
4423 iommu->ir_domain = irq_domain_add_tree(NULL, &amd_ir_domain_ops, iommu);
4424 if (!iommu->ir_domain)
4427 iommu->ir_domain->parent = arch_get_ir_parent_domain();
4428 iommu->msi_domain = arch_create_msi_irq_domain(iommu->ir_domain);
4433 int amd_iommu_update_ga(int cpu, bool is_run, void *data)
4435 unsigned long flags;
4436 struct amd_iommu *iommu;
4437 struct irq_remap_table *irt;
4438 struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
4439 int devid = ir_data->irq_2_irte.devid;
4440 struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
4441 struct irte_ga *ref = (struct irte_ga *) ir_data->ref;
4443 if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) ||
4444 !ref || !entry || !entry->lo.fields_vapic.guest_mode)
4447 iommu = amd_iommu_rlookup_table[devid];
4451 irt = get_irq_table(devid, false);
4455 spin_lock_irqsave(&irt->lock, flags);
4457 if (ref->lo.fields_vapic.guest_mode) {
4459 ref->lo.fields_vapic.destination = cpu;
4460 ref->lo.fields_vapic.is_run = is_run;
4464 spin_unlock_irqrestore(&irt->lock, flags);
4466 iommu_flush_irt(iommu, devid);
4467 iommu_completion_wait(iommu);
4470 EXPORT_SYMBOL(amd_iommu_update_ga);