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))
67 * This bitmap is used to advertise the page sizes our hardware support
68 * to the IOMMU core, which will then use this information to split
69 * physically contiguous memory regions it is mapping into page sizes
72 * 512GB Pages are not supported due to a hardware bug
74 #define AMD_IOMMU_PGSIZES ((~0xFFFUL) & ~(2ULL << 38))
76 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
78 /* List of all available dev_data structures */
79 static LIST_HEAD(dev_data_list);
80 static DEFINE_SPINLOCK(dev_data_list_lock);
82 LIST_HEAD(ioapic_map);
84 LIST_HEAD(acpihid_map);
87 * Domain for untranslated devices - only allocated
88 * if iommu=pt passed on kernel cmd line.
90 static const struct iommu_ops amd_iommu_ops;
92 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
93 int amd_iommu_max_glx_val = -1;
95 static struct dma_map_ops amd_iommu_dma_ops;
98 * This struct contains device specific data for the IOMMU
100 struct iommu_dev_data {
101 struct list_head list; /* For domain->dev_list */
102 struct list_head dev_data_list; /* For global dev_data_list */
103 struct protection_domain *domain; /* Domain the device is bound to */
104 u16 devid; /* PCI Device ID */
105 u16 alias; /* Alias Device ID */
106 bool iommu_v2; /* Device can make use of IOMMUv2 */
107 bool passthrough; /* Device is identity mapped */
111 } ats; /* ATS state */
112 bool pri_tlp; /* PASID TLB required for
114 u32 errata; /* Bitmap for errata to apply */
118 * general struct to manage commands send to an IOMMU
124 struct kmem_cache *amd_iommu_irq_cache;
126 static void update_domain(struct protection_domain *domain);
127 static int protection_domain_init(struct protection_domain *domain);
128 static void detach_device(struct device *dev);
131 * For dynamic growth the aperture size is split into ranges of 128MB of
132 * DMA address space each. This struct represents one such range.
134 struct aperture_range {
136 spinlock_t bitmap_lock;
138 /* address allocation bitmap */
139 unsigned long *bitmap;
140 unsigned long offset;
141 unsigned long next_bit;
144 * Array of PTE pages for the aperture. In this array we save all the
145 * leaf pages of the domain page table used for the aperture. This way
146 * we don't need to walk the page table to find a specific PTE. We can
147 * just calculate its address in constant time.
153 * Data container for a dma_ops specific protection domain
155 struct dma_ops_domain {
156 /* generic protection domain information */
157 struct protection_domain domain;
159 /* size of the aperture for the mappings */
160 unsigned long aperture_size;
162 /* aperture index we start searching for free addresses */
163 u32 __percpu *next_index;
165 /* address space relevant data */
166 struct aperture_range *aperture[APERTURE_MAX_RANGES];
169 struct iova_domain iovad;
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 iommu_dev_data *alloc_dev_data(u16 devid)
239 struct iommu_dev_data *dev_data;
242 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
246 dev_data->devid = devid;
248 spin_lock_irqsave(&dev_data_list_lock, flags);
249 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
250 spin_unlock_irqrestore(&dev_data_list_lock, flags);
255 static struct iommu_dev_data *search_dev_data(u16 devid)
257 struct iommu_dev_data *dev_data;
260 spin_lock_irqsave(&dev_data_list_lock, flags);
261 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
262 if (dev_data->devid == devid)
269 spin_unlock_irqrestore(&dev_data_list_lock, flags);
274 static int __last_alias(struct pci_dev *pdev, u16 alias, void *data)
276 *(u16 *)data = alias;
280 static u16 get_alias(struct device *dev)
282 struct pci_dev *pdev = to_pci_dev(dev);
283 u16 devid, ivrs_alias, pci_alias;
285 /* The callers make sure that get_device_id() does not fail here */
286 devid = get_device_id(dev);
287 ivrs_alias = amd_iommu_alias_table[devid];
288 pci_for_each_dma_alias(pdev, __last_alias, &pci_alias);
290 if (ivrs_alias == pci_alias)
296 * The IVRS is fairly reliable in telling us about aliases, but it
297 * can't know about every screwy device. If we don't have an IVRS
298 * reported alias, use the PCI reported alias. In that case we may
299 * still need to initialize the rlookup and dev_table entries if the
300 * alias is to a non-existent device.
302 if (ivrs_alias == devid) {
303 if (!amd_iommu_rlookup_table[pci_alias]) {
304 amd_iommu_rlookup_table[pci_alias] =
305 amd_iommu_rlookup_table[devid];
306 memcpy(amd_iommu_dev_table[pci_alias].data,
307 amd_iommu_dev_table[devid].data,
308 sizeof(amd_iommu_dev_table[pci_alias].data));
314 pr_info("AMD-Vi: Using IVRS reported alias %02x:%02x.%d "
315 "for device %s[%04x:%04x], kernel reported alias "
316 "%02x:%02x.%d\n", PCI_BUS_NUM(ivrs_alias), PCI_SLOT(ivrs_alias),
317 PCI_FUNC(ivrs_alias), dev_name(dev), pdev->vendor, pdev->device,
318 PCI_BUS_NUM(pci_alias), PCI_SLOT(pci_alias),
319 PCI_FUNC(pci_alias));
322 * If we don't have a PCI DMA alias and the IVRS alias is on the same
323 * bus, then the IVRS table may know about a quirk that we don't.
325 if (pci_alias == devid &&
326 PCI_BUS_NUM(ivrs_alias) == pdev->bus->number) {
327 pci_add_dma_alias(pdev, ivrs_alias & 0xff);
328 pr_info("AMD-Vi: Added PCI DMA alias %02x.%d for %s\n",
329 PCI_SLOT(ivrs_alias), PCI_FUNC(ivrs_alias),
336 static struct iommu_dev_data *find_dev_data(u16 devid)
338 struct iommu_dev_data *dev_data;
340 dev_data = search_dev_data(devid);
342 if (dev_data == NULL)
343 dev_data = alloc_dev_data(devid);
348 static struct iommu_dev_data *get_dev_data(struct device *dev)
350 return dev->archdata.iommu;
354 * Find or create an IOMMU group for a acpihid device.
356 static struct iommu_group *acpihid_device_group(struct device *dev)
358 struct acpihid_map_entry *p, *entry = NULL;
361 devid = get_acpihid_device_id(dev, &entry);
363 return ERR_PTR(devid);
365 list_for_each_entry(p, &acpihid_map, list) {
366 if ((devid == p->devid) && p->group)
367 entry->group = p->group;
371 entry->group = generic_device_group(dev);
376 static bool pci_iommuv2_capable(struct pci_dev *pdev)
378 static const int caps[] = {
381 PCI_EXT_CAP_ID_PASID,
385 for (i = 0; i < 3; ++i) {
386 pos = pci_find_ext_capability(pdev, caps[i]);
394 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
396 struct iommu_dev_data *dev_data;
398 dev_data = get_dev_data(&pdev->dev);
400 return dev_data->errata & (1 << erratum) ? true : false;
404 * This function actually applies the mapping to the page table of the
407 static void alloc_unity_mapping(struct dma_ops_domain *dma_dom,
408 struct unity_map_entry *e)
412 for (addr = e->address_start; addr < e->address_end;
414 if (addr < dma_dom->aperture_size)
415 __set_bit(addr >> PAGE_SHIFT,
416 dma_dom->aperture[0]->bitmap);
421 * Inits the unity mappings required for a specific device
423 static void init_unity_mappings_for_device(struct device *dev,
424 struct dma_ops_domain *dma_dom)
426 struct unity_map_entry *e;
429 devid = get_device_id(dev);
433 list_for_each_entry(e, &amd_iommu_unity_map, list) {
434 if (!(devid >= e->devid_start && devid <= e->devid_end))
436 alloc_unity_mapping(dma_dom, e);
441 * This function checks if the driver got a valid device from the caller to
442 * avoid dereferencing invalid pointers.
444 static bool check_device(struct device *dev)
448 if (!dev || !dev->dma_mask)
451 devid = get_device_id(dev);
455 /* Out of our scope? */
456 if (devid > amd_iommu_last_bdf)
459 if (amd_iommu_rlookup_table[devid] == NULL)
465 static void init_iommu_group(struct device *dev)
467 struct dma_ops_domain *dma_domain;
468 struct iommu_domain *domain;
469 struct iommu_group *group;
471 group = iommu_group_get_for_dev(dev);
475 domain = iommu_group_default_domain(group);
479 if (to_pdomain(domain)->flags == PD_DMA_OPS_MASK) {
480 dma_domain = to_pdomain(domain)->priv;
481 init_unity_mappings_for_device(dev, dma_domain);
485 iommu_group_put(group);
488 static int iommu_init_device(struct device *dev)
490 struct iommu_dev_data *dev_data;
493 if (dev->archdata.iommu)
496 devid = get_device_id(dev);
500 dev_data = find_dev_data(devid);
504 dev_data->alias = get_alias(dev);
506 if (dev_is_pci(dev) && pci_iommuv2_capable(to_pci_dev(dev))) {
507 struct amd_iommu *iommu;
509 iommu = amd_iommu_rlookup_table[dev_data->devid];
510 dev_data->iommu_v2 = iommu->is_iommu_v2;
513 dev->archdata.iommu = dev_data;
515 iommu_device_link(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
521 static void iommu_ignore_device(struct device *dev)
526 devid = get_device_id(dev);
530 alias = get_alias(dev);
532 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
533 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
535 amd_iommu_rlookup_table[devid] = NULL;
536 amd_iommu_rlookup_table[alias] = NULL;
539 static void iommu_uninit_device(struct device *dev)
542 struct iommu_dev_data *dev_data;
544 devid = get_device_id(dev);
548 dev_data = search_dev_data(devid);
552 if (dev_data->domain)
555 iommu_device_unlink(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
558 iommu_group_remove_device(dev);
561 dev->archdata.dma_ops = NULL;
564 * We keep dev_data around for unplugged devices and reuse it when the
565 * device is re-plugged - not doing so would introduce a ton of races.
569 /****************************************************************************
571 * Interrupt handling functions
573 ****************************************************************************/
575 static void dump_dte_entry(u16 devid)
579 for (i = 0; i < 4; ++i)
580 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
581 amd_iommu_dev_table[devid].data[i]);
584 static void dump_command(unsigned long phys_addr)
586 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
589 for (i = 0; i < 4; ++i)
590 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
593 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
595 int type, devid, domid, flags;
596 volatile u32 *event = __evt;
601 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
602 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
603 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
604 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
605 address = (u64)(((u64)event[3]) << 32) | event[2];
608 /* Did we hit the erratum? */
609 if (++count == LOOP_TIMEOUT) {
610 pr_err("AMD-Vi: No event written to event log\n");
617 printk(KERN_ERR "AMD-Vi: Event logged [");
620 case EVENT_TYPE_ILL_DEV:
621 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
622 "address=0x%016llx flags=0x%04x]\n",
623 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
625 dump_dte_entry(devid);
627 case EVENT_TYPE_IO_FAULT:
628 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
629 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
630 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
631 domid, address, flags);
633 case EVENT_TYPE_DEV_TAB_ERR:
634 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
635 "address=0x%016llx flags=0x%04x]\n",
636 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
639 case EVENT_TYPE_PAGE_TAB_ERR:
640 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
641 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
642 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
643 domid, address, flags);
645 case EVENT_TYPE_ILL_CMD:
646 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
647 dump_command(address);
649 case EVENT_TYPE_CMD_HARD_ERR:
650 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
651 "flags=0x%04x]\n", address, flags);
653 case EVENT_TYPE_IOTLB_INV_TO:
654 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
655 "address=0x%016llx]\n",
656 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
659 case EVENT_TYPE_INV_DEV_REQ:
660 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
661 "address=0x%016llx flags=0x%04x]\n",
662 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
666 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
669 memset(__evt, 0, 4 * sizeof(u32));
672 static void iommu_poll_events(struct amd_iommu *iommu)
676 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
677 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
679 while (head != tail) {
680 iommu_print_event(iommu, iommu->evt_buf + head);
681 head = (head + EVENT_ENTRY_SIZE) % EVT_BUFFER_SIZE;
684 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
687 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
689 struct amd_iommu_fault fault;
691 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
692 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
696 fault.address = raw[1];
697 fault.pasid = PPR_PASID(raw[0]);
698 fault.device_id = PPR_DEVID(raw[0]);
699 fault.tag = PPR_TAG(raw[0]);
700 fault.flags = PPR_FLAGS(raw[0]);
702 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
705 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
709 if (iommu->ppr_log == NULL)
712 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
713 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
715 while (head != tail) {
720 raw = (u64 *)(iommu->ppr_log + head);
723 * Hardware bug: Interrupt may arrive before the entry is
724 * written to memory. If this happens we need to wait for the
727 for (i = 0; i < LOOP_TIMEOUT; ++i) {
728 if (PPR_REQ_TYPE(raw[0]) != 0)
733 /* Avoid memcpy function-call overhead */
738 * To detect the hardware bug we need to clear the entry
741 raw[0] = raw[1] = 0UL;
743 /* Update head pointer of hardware ring-buffer */
744 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
745 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
747 /* Handle PPR entry */
748 iommu_handle_ppr_entry(iommu, entry);
750 /* Refresh ring-buffer information */
751 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
752 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
756 irqreturn_t amd_iommu_int_thread(int irq, void *data)
758 struct amd_iommu *iommu = (struct amd_iommu *) data;
759 u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
761 while (status & (MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK)) {
762 /* Enable EVT and PPR interrupts again */
763 writel((MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK),
764 iommu->mmio_base + MMIO_STATUS_OFFSET);
766 if (status & MMIO_STATUS_EVT_INT_MASK) {
767 pr_devel("AMD-Vi: Processing IOMMU Event Log\n");
768 iommu_poll_events(iommu);
771 if (status & MMIO_STATUS_PPR_INT_MASK) {
772 pr_devel("AMD-Vi: Processing IOMMU PPR Log\n");
773 iommu_poll_ppr_log(iommu);
777 * Hardware bug: ERBT1312
778 * When re-enabling interrupt (by writing 1
779 * to clear the bit), the hardware might also try to set
780 * the interrupt bit in the event status register.
781 * In this scenario, the bit will be set, and disable
782 * subsequent interrupts.
784 * Workaround: The IOMMU driver should read back the
785 * status register and check if the interrupt bits are cleared.
786 * If not, driver will need to go through the interrupt handler
787 * again and re-clear the bits
789 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
794 irqreturn_t amd_iommu_int_handler(int irq, void *data)
796 return IRQ_WAKE_THREAD;
799 /****************************************************************************
801 * IOMMU command queuing functions
803 ****************************************************************************/
805 static int wait_on_sem(volatile u64 *sem)
809 while (*sem == 0 && i < LOOP_TIMEOUT) {
814 if (i == LOOP_TIMEOUT) {
815 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
822 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
823 struct iommu_cmd *cmd,
828 target = iommu->cmd_buf + tail;
829 tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
831 /* Copy command to buffer */
832 memcpy(target, cmd, sizeof(*cmd));
834 /* Tell the IOMMU about it */
835 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
838 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
840 WARN_ON(address & 0x7ULL);
842 memset(cmd, 0, sizeof(*cmd));
843 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
844 cmd->data[1] = upper_32_bits(__pa(address));
846 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
849 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
851 memset(cmd, 0, sizeof(*cmd));
852 cmd->data[0] = devid;
853 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
856 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
857 size_t size, u16 domid, int pde)
862 pages = iommu_num_pages(address, size, PAGE_SIZE);
867 * If we have to flush more than one page, flush all
868 * TLB entries for this domain
870 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
874 address &= PAGE_MASK;
876 memset(cmd, 0, sizeof(*cmd));
877 cmd->data[1] |= domid;
878 cmd->data[2] = lower_32_bits(address);
879 cmd->data[3] = upper_32_bits(address);
880 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
881 if (s) /* size bit - we flush more than one 4kb page */
882 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
883 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
884 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
887 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
888 u64 address, size_t size)
893 pages = iommu_num_pages(address, size, PAGE_SIZE);
898 * If we have to flush more than one page, flush all
899 * TLB entries for this domain
901 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
905 address &= PAGE_MASK;
907 memset(cmd, 0, sizeof(*cmd));
908 cmd->data[0] = devid;
909 cmd->data[0] |= (qdep & 0xff) << 24;
910 cmd->data[1] = devid;
911 cmd->data[2] = lower_32_bits(address);
912 cmd->data[3] = upper_32_bits(address);
913 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
915 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
918 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
919 u64 address, bool size)
921 memset(cmd, 0, sizeof(*cmd));
923 address &= ~(0xfffULL);
925 cmd->data[0] = pasid;
926 cmd->data[1] = domid;
927 cmd->data[2] = lower_32_bits(address);
928 cmd->data[3] = upper_32_bits(address);
929 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
930 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
932 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
933 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
936 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
937 int qdep, u64 address, bool size)
939 memset(cmd, 0, sizeof(*cmd));
941 address &= ~(0xfffULL);
943 cmd->data[0] = devid;
944 cmd->data[0] |= ((pasid >> 8) & 0xff) << 16;
945 cmd->data[0] |= (qdep & 0xff) << 24;
946 cmd->data[1] = devid;
947 cmd->data[1] |= (pasid & 0xff) << 16;
948 cmd->data[2] = lower_32_bits(address);
949 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
950 cmd->data[3] = upper_32_bits(address);
952 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
953 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
956 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
957 int status, int tag, bool gn)
959 memset(cmd, 0, sizeof(*cmd));
961 cmd->data[0] = devid;
963 cmd->data[1] = pasid;
964 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
966 cmd->data[3] = tag & 0x1ff;
967 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
969 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
972 static void build_inv_all(struct iommu_cmd *cmd)
974 memset(cmd, 0, sizeof(*cmd));
975 CMD_SET_TYPE(cmd, CMD_INV_ALL);
978 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
980 memset(cmd, 0, sizeof(*cmd));
981 cmd->data[0] = devid;
982 CMD_SET_TYPE(cmd, CMD_INV_IRT);
986 * Writes the command to the IOMMUs command buffer and informs the
987 * hardware about the new command.
989 static int iommu_queue_command_sync(struct amd_iommu *iommu,
990 struct iommu_cmd *cmd,
993 u32 left, tail, head, next_tail;
997 spin_lock_irqsave(&iommu->lock, flags);
999 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
1000 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
1001 next_tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
1002 left = (head - next_tail) % CMD_BUFFER_SIZE;
1005 struct iommu_cmd sync_cmd;
1006 volatile u64 sem = 0;
1009 build_completion_wait(&sync_cmd, (u64)&sem);
1010 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
1012 spin_unlock_irqrestore(&iommu->lock, flags);
1014 if ((ret = wait_on_sem(&sem)) != 0)
1020 copy_cmd_to_buffer(iommu, cmd, tail);
1022 /* We need to sync now to make sure all commands are processed */
1023 iommu->need_sync = sync;
1025 spin_unlock_irqrestore(&iommu->lock, flags);
1030 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
1032 return iommu_queue_command_sync(iommu, cmd, true);
1036 * This function queues a completion wait command into the command
1037 * buffer of an IOMMU
1039 static int iommu_completion_wait(struct amd_iommu *iommu)
1041 struct iommu_cmd cmd;
1042 volatile u64 sem = 0;
1045 if (!iommu->need_sync)
1048 build_completion_wait(&cmd, (u64)&sem);
1050 ret = iommu_queue_command_sync(iommu, &cmd, false);
1054 return wait_on_sem(&sem);
1057 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1059 struct iommu_cmd cmd;
1061 build_inv_dte(&cmd, devid);
1063 return iommu_queue_command(iommu, &cmd);
1066 static void iommu_flush_dte_all(struct amd_iommu *iommu)
1070 for (devid = 0; devid <= 0xffff; ++devid)
1071 iommu_flush_dte(iommu, devid);
1073 iommu_completion_wait(iommu);
1077 * This function uses heavy locking and may disable irqs for some time. But
1078 * this is no issue because it is only called during resume.
1080 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1084 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1085 struct iommu_cmd cmd;
1086 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1088 iommu_queue_command(iommu, &cmd);
1091 iommu_completion_wait(iommu);
1094 static void iommu_flush_all(struct amd_iommu *iommu)
1096 struct iommu_cmd cmd;
1098 build_inv_all(&cmd);
1100 iommu_queue_command(iommu, &cmd);
1101 iommu_completion_wait(iommu);
1104 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1106 struct iommu_cmd cmd;
1108 build_inv_irt(&cmd, devid);
1110 iommu_queue_command(iommu, &cmd);
1113 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1117 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1118 iommu_flush_irt(iommu, devid);
1120 iommu_completion_wait(iommu);
1123 void iommu_flush_all_caches(struct amd_iommu *iommu)
1125 if (iommu_feature(iommu, FEATURE_IA)) {
1126 iommu_flush_all(iommu);
1128 iommu_flush_dte_all(iommu);
1129 iommu_flush_irt_all(iommu);
1130 iommu_flush_tlb_all(iommu);
1135 * Command send function for flushing on-device TLB
1137 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1138 u64 address, size_t size)
1140 struct amd_iommu *iommu;
1141 struct iommu_cmd cmd;
1144 qdep = dev_data->ats.qdep;
1145 iommu = amd_iommu_rlookup_table[dev_data->devid];
1147 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1149 return iommu_queue_command(iommu, &cmd);
1153 * Command send function for invalidating a device table entry
1155 static int device_flush_dte(struct iommu_dev_data *dev_data)
1157 struct amd_iommu *iommu;
1161 iommu = amd_iommu_rlookup_table[dev_data->devid];
1162 alias = dev_data->alias;
1164 ret = iommu_flush_dte(iommu, dev_data->devid);
1165 if (!ret && alias != dev_data->devid)
1166 ret = iommu_flush_dte(iommu, alias);
1170 if (dev_data->ats.enabled)
1171 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1177 * TLB invalidation function which is called from the mapping functions.
1178 * It invalidates a single PTE if the range to flush is within a single
1179 * page. Otherwise it flushes the whole TLB of the IOMMU.
1181 static void __domain_flush_pages(struct protection_domain *domain,
1182 u64 address, size_t size, int pde)
1184 struct iommu_dev_data *dev_data;
1185 struct iommu_cmd cmd;
1188 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1190 for (i = 0; i < amd_iommus_present; ++i) {
1191 if (!domain->dev_iommu[i])
1195 * Devices of this domain are behind this IOMMU
1196 * We need a TLB flush
1198 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1201 list_for_each_entry(dev_data, &domain->dev_list, list) {
1203 if (!dev_data->ats.enabled)
1206 ret |= device_flush_iotlb(dev_data, address, size);
1212 static void domain_flush_pages(struct protection_domain *domain,
1213 u64 address, size_t size)
1215 __domain_flush_pages(domain, address, size, 0);
1218 /* Flush the whole IO/TLB for a given protection domain */
1219 static void domain_flush_tlb(struct protection_domain *domain)
1221 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1224 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1225 static void domain_flush_tlb_pde(struct protection_domain *domain)
1227 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1230 static void domain_flush_complete(struct protection_domain *domain)
1234 for (i = 0; i < amd_iommus_present; ++i) {
1235 if (!domain->dev_iommu[i])
1239 * Devices of this domain are behind this IOMMU
1240 * We need to wait for completion of all commands.
1242 iommu_completion_wait(amd_iommus[i]);
1248 * This function flushes the DTEs for all devices in domain
1250 static void domain_flush_devices(struct protection_domain *domain)
1252 struct iommu_dev_data *dev_data;
1254 list_for_each_entry(dev_data, &domain->dev_list, list)
1255 device_flush_dte(dev_data);
1258 /****************************************************************************
1260 * The functions below are used the create the page table mappings for
1261 * unity mapped regions.
1263 ****************************************************************************/
1266 * This function is used to add another level to an IO page table. Adding
1267 * another level increases the size of the address space by 9 bits to a size up
1270 static bool increase_address_space(struct protection_domain *domain,
1275 if (domain->mode == PAGE_MODE_6_LEVEL)
1276 /* address space already 64 bit large */
1279 pte = (void *)get_zeroed_page(gfp);
1283 *pte = PM_LEVEL_PDE(domain->mode,
1284 virt_to_phys(domain->pt_root));
1285 domain->pt_root = pte;
1287 domain->updated = true;
1292 static u64 *alloc_pte(struct protection_domain *domain,
1293 unsigned long address,
1294 unsigned long page_size,
1301 BUG_ON(!is_power_of_2(page_size));
1303 while (address > PM_LEVEL_SIZE(domain->mode))
1304 increase_address_space(domain, gfp);
1306 level = domain->mode - 1;
1307 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1308 address = PAGE_SIZE_ALIGN(address, page_size);
1309 end_lvl = PAGE_SIZE_LEVEL(page_size);
1311 while (level > end_lvl) {
1316 if (!IOMMU_PTE_PRESENT(__pte)) {
1317 page = (u64 *)get_zeroed_page(gfp);
1321 __npte = PM_LEVEL_PDE(level, virt_to_phys(page));
1323 if (cmpxchg64(pte, __pte, __npte)) {
1324 free_page((unsigned long)page);
1329 /* No level skipping support yet */
1330 if (PM_PTE_LEVEL(*pte) != level)
1335 pte = IOMMU_PTE_PAGE(*pte);
1337 if (pte_page && level == end_lvl)
1340 pte = &pte[PM_LEVEL_INDEX(level, address)];
1347 * This function checks if there is a PTE for a given dma address. If
1348 * there is one, it returns the pointer to it.
1350 static u64 *fetch_pte(struct protection_domain *domain,
1351 unsigned long address,
1352 unsigned long *page_size)
1357 if (address > PM_LEVEL_SIZE(domain->mode))
1360 level = domain->mode - 1;
1361 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1362 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1367 if (!IOMMU_PTE_PRESENT(*pte))
1371 if (PM_PTE_LEVEL(*pte) == 7 ||
1372 PM_PTE_LEVEL(*pte) == 0)
1375 /* No level skipping support yet */
1376 if (PM_PTE_LEVEL(*pte) != level)
1381 /* Walk to the next level */
1382 pte = IOMMU_PTE_PAGE(*pte);
1383 pte = &pte[PM_LEVEL_INDEX(level, address)];
1384 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1387 if (PM_PTE_LEVEL(*pte) == 0x07) {
1388 unsigned long pte_mask;
1391 * If we have a series of large PTEs, make
1392 * sure to return a pointer to the first one.
1394 *page_size = pte_mask = PTE_PAGE_SIZE(*pte);
1395 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1396 pte = (u64 *)(((unsigned long)pte) & pte_mask);
1403 * Generic mapping functions. It maps a physical address into a DMA
1404 * address space. It allocates the page table pages if necessary.
1405 * In the future it can be extended to a generic mapping function
1406 * supporting all features of AMD IOMMU page tables like level skipping
1407 * and full 64 bit address spaces.
1409 static int iommu_map_page(struct protection_domain *dom,
1410 unsigned long bus_addr,
1411 unsigned long phys_addr,
1413 unsigned long page_size)
1418 BUG_ON(!IS_ALIGNED(bus_addr, page_size));
1419 BUG_ON(!IS_ALIGNED(phys_addr, page_size));
1421 if (!(prot & IOMMU_PROT_MASK))
1424 count = PAGE_SIZE_PTE_COUNT(page_size);
1425 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1430 for (i = 0; i < count; ++i)
1431 if (IOMMU_PTE_PRESENT(pte[i]))
1435 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1436 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1438 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1440 if (prot & IOMMU_PROT_IR)
1441 __pte |= IOMMU_PTE_IR;
1442 if (prot & IOMMU_PROT_IW)
1443 __pte |= IOMMU_PTE_IW;
1445 for (i = 0; i < count; ++i)
1453 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1454 unsigned long bus_addr,
1455 unsigned long page_size)
1457 unsigned long long unmapped;
1458 unsigned long unmap_size;
1461 BUG_ON(!is_power_of_2(page_size));
1465 while (unmapped < page_size) {
1467 pte = fetch_pte(dom, bus_addr, &unmap_size);
1472 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1473 for (i = 0; i < count; i++)
1477 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1478 unmapped += unmap_size;
1481 BUG_ON(unmapped && !is_power_of_2(unmapped));
1486 /****************************************************************************
1488 * The next functions belong to the address allocator for the dma_ops
1489 * interface functions. They work like the allocators in the other IOMMU
1490 * drivers. Its basically a bitmap which marks the allocated pages in
1491 * the aperture. Maybe it could be enhanced in the future to a more
1492 * efficient allocator.
1494 ****************************************************************************/
1497 * The address allocator core functions.
1499 * called with domain->lock held
1503 * Used to reserve address ranges in the aperture (e.g. for exclusion
1506 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1507 unsigned long start_page,
1510 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1512 if (start_page + pages > last_page)
1513 pages = last_page - start_page;
1515 for (i = start_page; i < start_page + pages; ++i) {
1516 int index = i / APERTURE_RANGE_PAGES;
1517 int page = i % APERTURE_RANGE_PAGES;
1518 __set_bit(page, dom->aperture[index]->bitmap);
1523 * This function is used to add a new aperture range to an existing
1524 * aperture in case of dma_ops domain allocation or address allocation
1527 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1528 bool populate, gfp_t gfp)
1530 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1531 unsigned long i, old_size, pte_pgsize;
1532 struct aperture_range *range;
1533 struct amd_iommu *iommu;
1534 unsigned long flags;
1536 #ifdef CONFIG_IOMMU_STRESS
1540 if (index >= APERTURE_MAX_RANGES)
1543 range = kzalloc(sizeof(struct aperture_range), gfp);
1547 range->bitmap = (void *)get_zeroed_page(gfp);
1551 range->offset = dma_dom->aperture_size;
1553 spin_lock_init(&range->bitmap_lock);
1556 unsigned long address = dma_dom->aperture_size;
1557 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1558 u64 *pte, *pte_page;
1560 for (i = 0; i < num_ptes; ++i) {
1561 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1566 range->pte_pages[i] = pte_page;
1568 address += APERTURE_RANGE_SIZE / 64;
1572 spin_lock_irqsave(&dma_dom->domain.lock, flags);
1574 /* First take the bitmap_lock and then publish the range */
1575 spin_lock(&range->bitmap_lock);
1577 old_size = dma_dom->aperture_size;
1578 dma_dom->aperture[index] = range;
1579 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1581 /* Reserve address range used for MSI messages */
1582 if (old_size < MSI_ADDR_BASE_LO &&
1583 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1584 unsigned long spage;
1587 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1588 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1590 dma_ops_reserve_addresses(dma_dom, spage, pages);
1593 /* Initialize the exclusion range if necessary */
1594 for_each_iommu(iommu) {
1595 if (iommu->exclusion_start &&
1596 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1597 && iommu->exclusion_start < dma_dom->aperture_size) {
1598 unsigned long startpage;
1599 int pages = iommu_num_pages(iommu->exclusion_start,
1600 iommu->exclusion_length,
1602 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1603 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1608 * Check for areas already mapped as present in the new aperture
1609 * range and mark those pages as reserved in the allocator. Such
1610 * mappings may already exist as a result of requested unity
1611 * mappings for devices.
1613 for (i = dma_dom->aperture[index]->offset;
1614 i < dma_dom->aperture_size;
1616 u64 *pte = fetch_pte(&dma_dom->domain, i, &pte_pgsize);
1617 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1620 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT,
1624 update_domain(&dma_dom->domain);
1626 spin_unlock(&range->bitmap_lock);
1628 spin_unlock_irqrestore(&dma_dom->domain.lock, flags);
1633 update_domain(&dma_dom->domain);
1635 free_page((unsigned long)range->bitmap);
1642 static dma_addr_t dma_ops_aperture_alloc(struct dma_ops_domain *dom,
1643 struct aperture_range *range,
1644 unsigned long pages,
1645 unsigned long dma_mask,
1646 unsigned long boundary_size,
1647 unsigned long align_mask,
1650 unsigned long offset, limit, flags;
1654 offset = range->offset >> PAGE_SHIFT;
1655 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1656 dma_mask >> PAGE_SHIFT);
1659 if (!spin_trylock_irqsave(&range->bitmap_lock, flags))
1662 spin_lock_irqsave(&range->bitmap_lock, flags);
1665 address = iommu_area_alloc(range->bitmap, limit, range->next_bit,
1666 pages, offset, boundary_size, align_mask);
1667 if (address == -1) {
1668 /* Nothing found, retry one time */
1669 address = iommu_area_alloc(range->bitmap, limit,
1670 0, pages, offset, boundary_size,
1676 range->next_bit = address + pages;
1678 spin_unlock_irqrestore(&range->bitmap_lock, flags);
1681 domain_flush_tlb(&dom->domain);
1682 domain_flush_complete(&dom->domain);
1688 static unsigned long dma_ops_area_alloc(struct device *dev,
1689 struct dma_ops_domain *dom,
1691 unsigned long align_mask,
1694 unsigned long boundary_size, mask;
1695 unsigned long address = -1;
1701 mask = dma_get_seg_boundary(dev);
1704 start = this_cpu_read(*dom->next_index);
1706 /* Sanity check - is it really necessary? */
1707 if (unlikely(start > APERTURE_MAX_RANGES)) {
1709 this_cpu_write(*dom->next_index, 0);
1712 boundary_size = mask + 1 ? ALIGN(mask + 1, PAGE_SIZE) >> PAGE_SHIFT :
1713 1UL << (BITS_PER_LONG - PAGE_SHIFT);
1715 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1716 struct aperture_range *range;
1719 index = (start + i) % APERTURE_MAX_RANGES;
1721 range = dom->aperture[index];
1723 if (!range || range->offset >= dma_mask)
1726 address = dma_ops_aperture_alloc(dom, range, pages,
1727 dma_mask, boundary_size,
1729 if (address != -1) {
1730 address = range->offset + (address << PAGE_SHIFT);
1731 this_cpu_write(*dom->next_index, index);
1736 if (address == -1 && first) {
1746 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1747 struct dma_ops_domain *dom,
1749 unsigned long align_mask,
1752 unsigned long address = -1;
1754 while (address == -1) {
1755 address = dma_ops_area_alloc(dev, dom, pages,
1756 align_mask, dma_mask);
1758 if (address == -1 && alloc_new_range(dom, false, GFP_ATOMIC))
1762 if (unlikely(address == -1))
1763 address = DMA_ERROR_CODE;
1765 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1771 * The address free function.
1773 * called with domain->lock held
1775 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1776 unsigned long address,
1779 unsigned i = address >> APERTURE_RANGE_SHIFT;
1780 struct aperture_range *range = dom->aperture[i];
1781 unsigned long flags;
1783 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1785 #ifdef CONFIG_IOMMU_STRESS
1790 if (amd_iommu_unmap_flush) {
1791 domain_flush_tlb(&dom->domain);
1792 domain_flush_complete(&dom->domain);
1795 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1797 spin_lock_irqsave(&range->bitmap_lock, flags);
1798 if (address + pages > range->next_bit)
1799 range->next_bit = address + pages;
1800 bitmap_clear(range->bitmap, address, pages);
1801 spin_unlock_irqrestore(&range->bitmap_lock, flags);
1805 /****************************************************************************
1807 * The next functions belong to the domain allocation. A domain is
1808 * allocated for every IOMMU as the default domain. If device isolation
1809 * is enabled, every device get its own domain. The most important thing
1810 * about domains is the page table mapping the DMA address space they
1813 ****************************************************************************/
1816 * This function adds a protection domain to the global protection domain list
1818 static void add_domain_to_list(struct protection_domain *domain)
1820 unsigned long flags;
1822 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1823 list_add(&domain->list, &amd_iommu_pd_list);
1824 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1828 * This function removes a protection domain to the global
1829 * protection domain list
1831 static void del_domain_from_list(struct protection_domain *domain)
1833 unsigned long flags;
1835 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1836 list_del(&domain->list);
1837 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1840 static u16 domain_id_alloc(void)
1842 unsigned long flags;
1845 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1846 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1848 if (id > 0 && id < MAX_DOMAIN_ID)
1849 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1852 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1857 static void domain_id_free(int id)
1859 unsigned long flags;
1861 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1862 if (id > 0 && id < MAX_DOMAIN_ID)
1863 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1864 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1867 #define DEFINE_FREE_PT_FN(LVL, FN) \
1868 static void free_pt_##LVL (unsigned long __pt) \
1876 for (i = 0; i < 512; ++i) { \
1877 /* PTE present? */ \
1878 if (!IOMMU_PTE_PRESENT(pt[i])) \
1882 if (PM_PTE_LEVEL(pt[i]) == 0 || \
1883 PM_PTE_LEVEL(pt[i]) == 7) \
1886 p = (unsigned long)IOMMU_PTE_PAGE(pt[i]); \
1889 free_page((unsigned long)pt); \
1892 DEFINE_FREE_PT_FN(l2, free_page)
1893 DEFINE_FREE_PT_FN(l3, free_pt_l2)
1894 DEFINE_FREE_PT_FN(l4, free_pt_l3)
1895 DEFINE_FREE_PT_FN(l5, free_pt_l4)
1896 DEFINE_FREE_PT_FN(l6, free_pt_l5)
1898 static void free_pagetable(struct protection_domain *domain)
1900 unsigned long root = (unsigned long)domain->pt_root;
1902 switch (domain->mode) {
1903 case PAGE_MODE_NONE:
1905 case PAGE_MODE_1_LEVEL:
1908 case PAGE_MODE_2_LEVEL:
1911 case PAGE_MODE_3_LEVEL:
1914 case PAGE_MODE_4_LEVEL:
1917 case PAGE_MODE_5_LEVEL:
1920 case PAGE_MODE_6_LEVEL:
1928 static void free_gcr3_tbl_level1(u64 *tbl)
1933 for (i = 0; i < 512; ++i) {
1934 if (!(tbl[i] & GCR3_VALID))
1937 ptr = __va(tbl[i] & PAGE_MASK);
1939 free_page((unsigned long)ptr);
1943 static void free_gcr3_tbl_level2(u64 *tbl)
1948 for (i = 0; i < 512; ++i) {
1949 if (!(tbl[i] & GCR3_VALID))
1952 ptr = __va(tbl[i] & PAGE_MASK);
1954 free_gcr3_tbl_level1(ptr);
1958 static void free_gcr3_table(struct protection_domain *domain)
1960 if (domain->glx == 2)
1961 free_gcr3_tbl_level2(domain->gcr3_tbl);
1962 else if (domain->glx == 1)
1963 free_gcr3_tbl_level1(domain->gcr3_tbl);
1965 BUG_ON(domain->glx != 0);
1967 free_page((unsigned long)domain->gcr3_tbl);
1971 * Free a domain, only used if something went wrong in the
1972 * allocation path and we need to free an already allocated page table
1974 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1981 put_iova_domain(&dom->iovad);
1983 free_percpu(dom->next_index);
1985 del_domain_from_list(&dom->domain);
1987 free_pagetable(&dom->domain);
1989 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1990 if (!dom->aperture[i])
1992 free_page((unsigned long)dom->aperture[i]->bitmap);
1993 kfree(dom->aperture[i]);
1999 static int dma_ops_domain_alloc_apertures(struct dma_ops_domain *dma_dom,
2002 int ret, i, apertures;
2004 apertures = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
2007 for (i = apertures; i < max_apertures; ++i) {
2008 ret = alloc_new_range(dma_dom, false, GFP_KERNEL);
2017 * Allocates a new protection domain usable for the dma_ops functions.
2018 * It also initializes the page table and the address allocator data
2019 * structures required for the dma_ops interface
2021 static struct dma_ops_domain *dma_ops_domain_alloc(void)
2023 struct dma_ops_domain *dma_dom;
2026 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
2030 if (protection_domain_init(&dma_dom->domain))
2033 dma_dom->next_index = alloc_percpu(u32);
2034 if (!dma_dom->next_index)
2037 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
2038 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2039 dma_dom->domain.flags = PD_DMA_OPS_MASK;
2040 dma_dom->domain.priv = dma_dom;
2041 if (!dma_dom->domain.pt_root)
2044 add_domain_to_list(&dma_dom->domain);
2046 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
2050 * mark the first page as allocated so we never return 0 as
2051 * a valid dma-address. So we can use 0 as error value
2053 dma_dom->aperture[0]->bitmap[0] = 1;
2055 for_each_possible_cpu(cpu)
2056 *per_cpu_ptr(dma_dom->next_index, cpu) = 0;
2058 init_iova_domain(&dma_dom->iovad, PAGE_SIZE,
2059 IOVA_START_PFN, DMA_32BIT_PFN);
2064 dma_ops_domain_free(dma_dom);
2070 * little helper function to check whether a given protection domain is a
2073 static bool dma_ops_domain(struct protection_domain *domain)
2075 return domain->flags & PD_DMA_OPS_MASK;
2078 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
2083 if (domain->mode != PAGE_MODE_NONE)
2084 pte_root = virt_to_phys(domain->pt_root);
2086 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
2087 << DEV_ENTRY_MODE_SHIFT;
2088 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
2090 flags = amd_iommu_dev_table[devid].data[1];
2093 flags |= DTE_FLAG_IOTLB;
2095 if (domain->flags & PD_IOMMUV2_MASK) {
2096 u64 gcr3 = __pa(domain->gcr3_tbl);
2097 u64 glx = domain->glx;
2100 pte_root |= DTE_FLAG_GV;
2101 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
2103 /* First mask out possible old values for GCR3 table */
2104 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
2107 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
2110 /* Encode GCR3 table into DTE */
2111 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
2114 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
2117 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
2121 flags &= ~(0xffffUL);
2122 flags |= domain->id;
2124 amd_iommu_dev_table[devid].data[1] = flags;
2125 amd_iommu_dev_table[devid].data[0] = pte_root;
2128 static void clear_dte_entry(u16 devid)
2130 /* remove entry from the device table seen by the hardware */
2131 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
2132 amd_iommu_dev_table[devid].data[1] &= DTE_FLAG_MASK;
2134 amd_iommu_apply_erratum_63(devid);
2137 static void do_attach(struct iommu_dev_data *dev_data,
2138 struct protection_domain *domain)
2140 struct amd_iommu *iommu;
2144 iommu = amd_iommu_rlookup_table[dev_data->devid];
2145 alias = dev_data->alias;
2146 ats = dev_data->ats.enabled;
2148 /* Update data structures */
2149 dev_data->domain = domain;
2150 list_add(&dev_data->list, &domain->dev_list);
2152 /* Do reference counting */
2153 domain->dev_iommu[iommu->index] += 1;
2154 domain->dev_cnt += 1;
2156 /* Update device table */
2157 set_dte_entry(dev_data->devid, domain, ats);
2158 if (alias != dev_data->devid)
2159 set_dte_entry(alias, domain, ats);
2161 device_flush_dte(dev_data);
2164 static void do_detach(struct iommu_dev_data *dev_data)
2166 struct amd_iommu *iommu;
2170 * First check if the device is still attached. It might already
2171 * be detached from its domain because the generic
2172 * iommu_detach_group code detached it and we try again here in
2173 * our alias handling.
2175 if (!dev_data->domain)
2178 iommu = amd_iommu_rlookup_table[dev_data->devid];
2179 alias = dev_data->alias;
2181 /* decrease reference counters */
2182 dev_data->domain->dev_iommu[iommu->index] -= 1;
2183 dev_data->domain->dev_cnt -= 1;
2185 /* Update data structures */
2186 dev_data->domain = NULL;
2187 list_del(&dev_data->list);
2188 clear_dte_entry(dev_data->devid);
2189 if (alias != dev_data->devid)
2190 clear_dte_entry(alias);
2192 /* Flush the DTE entry */
2193 device_flush_dte(dev_data);
2197 * If a device is not yet associated with a domain, this function does
2198 * assigns it visible for the hardware
2200 static int __attach_device(struct iommu_dev_data *dev_data,
2201 struct protection_domain *domain)
2206 * Must be called with IRQs disabled. Warn here to detect early
2209 WARN_ON(!irqs_disabled());
2212 spin_lock(&domain->lock);
2215 if (dev_data->domain != NULL)
2218 /* Attach alias group root */
2219 do_attach(dev_data, domain);
2226 spin_unlock(&domain->lock);
2232 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2234 pci_disable_ats(pdev);
2235 pci_disable_pri(pdev);
2236 pci_disable_pasid(pdev);
2239 /* FIXME: Change generic reset-function to do the same */
2240 static int pri_reset_while_enabled(struct pci_dev *pdev)
2245 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2249 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2250 control |= PCI_PRI_CTRL_RESET;
2251 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2256 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2261 /* FIXME: Hardcode number of outstanding requests for now */
2263 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2265 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2267 /* Only allow access to user-accessible pages */
2268 ret = pci_enable_pasid(pdev, 0);
2272 /* First reset the PRI state of the device */
2273 ret = pci_reset_pri(pdev);
2278 ret = pci_enable_pri(pdev, reqs);
2283 ret = pri_reset_while_enabled(pdev);
2288 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2295 pci_disable_pri(pdev);
2296 pci_disable_pasid(pdev);
2301 /* FIXME: Move this to PCI code */
2302 #define PCI_PRI_TLP_OFF (1 << 15)
2304 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2309 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2313 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2315 return (status & PCI_PRI_TLP_OFF) ? true : false;
2319 * If a device is not yet associated with a domain, this function
2320 * assigns it visible for the hardware
2322 static int attach_device(struct device *dev,
2323 struct protection_domain *domain)
2325 struct pci_dev *pdev;
2326 struct iommu_dev_data *dev_data;
2327 unsigned long flags;
2330 dev_data = get_dev_data(dev);
2332 if (!dev_is_pci(dev))
2333 goto skip_ats_check;
2335 pdev = to_pci_dev(dev);
2336 if (domain->flags & PD_IOMMUV2_MASK) {
2337 if (!dev_data->passthrough)
2340 if (dev_data->iommu_v2) {
2341 if (pdev_iommuv2_enable(pdev) != 0)
2344 dev_data->ats.enabled = true;
2345 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2346 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2348 } else if (amd_iommu_iotlb_sup &&
2349 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2350 dev_data->ats.enabled = true;
2351 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2355 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2356 ret = __attach_device(dev_data, domain);
2357 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2360 * We might boot into a crash-kernel here. The crashed kernel
2361 * left the caches in the IOMMU dirty. So we have to flush
2362 * here to evict all dirty stuff.
2364 domain_flush_tlb_pde(domain);
2370 * Removes a device from a protection domain (unlocked)
2372 static void __detach_device(struct iommu_dev_data *dev_data)
2374 struct protection_domain *domain;
2377 * Must be called with IRQs disabled. Warn here to detect early
2380 WARN_ON(!irqs_disabled());
2382 if (WARN_ON(!dev_data->domain))
2385 domain = dev_data->domain;
2387 spin_lock(&domain->lock);
2389 do_detach(dev_data);
2391 spin_unlock(&domain->lock);
2395 * Removes a device from a protection domain (with devtable_lock held)
2397 static void detach_device(struct device *dev)
2399 struct protection_domain *domain;
2400 struct iommu_dev_data *dev_data;
2401 unsigned long flags;
2403 dev_data = get_dev_data(dev);
2404 domain = dev_data->domain;
2406 /* lock device table */
2407 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2408 __detach_device(dev_data);
2409 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2411 if (!dev_is_pci(dev))
2414 if (domain->flags & PD_IOMMUV2_MASK && dev_data->iommu_v2)
2415 pdev_iommuv2_disable(to_pci_dev(dev));
2416 else if (dev_data->ats.enabled)
2417 pci_disable_ats(to_pci_dev(dev));
2419 dev_data->ats.enabled = false;
2422 static int amd_iommu_add_device(struct device *dev)
2424 struct iommu_dev_data *dev_data;
2425 struct iommu_domain *domain;
2426 struct amd_iommu *iommu;
2429 if (!check_device(dev) || get_dev_data(dev))
2432 devid = get_device_id(dev);
2436 iommu = amd_iommu_rlookup_table[devid];
2438 ret = iommu_init_device(dev);
2440 if (ret != -ENOTSUPP)
2441 pr_err("Failed to initialize device %s - trying to proceed anyway\n",
2444 iommu_ignore_device(dev);
2445 dev->archdata.dma_ops = &nommu_dma_ops;
2448 init_iommu_group(dev);
2450 dev_data = get_dev_data(dev);
2454 if (iommu_pass_through || dev_data->iommu_v2)
2455 iommu_request_dm_for_dev(dev);
2457 /* Domains are initialized for this device - have a look what we ended up with */
2458 domain = iommu_get_domain_for_dev(dev);
2459 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2460 dev_data->passthrough = true;
2462 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2465 iommu_completion_wait(iommu);
2470 static void amd_iommu_remove_device(struct device *dev)
2472 struct amd_iommu *iommu;
2475 if (!check_device(dev))
2478 devid = get_device_id(dev);
2482 iommu = amd_iommu_rlookup_table[devid];
2484 iommu_uninit_device(dev);
2485 iommu_completion_wait(iommu);
2488 static struct iommu_group *amd_iommu_device_group(struct device *dev)
2490 if (dev_is_pci(dev))
2491 return pci_device_group(dev);
2493 return acpihid_device_group(dev);
2496 /*****************************************************************************
2498 * The next functions belong to the dma_ops mapping/unmapping code.
2500 *****************************************************************************/
2503 * In the dma_ops path we only have the struct device. This function
2504 * finds the corresponding IOMMU, the protection domain and the
2505 * requestor id for a given device.
2506 * If the device is not yet associated with a domain this is also done
2509 static struct protection_domain *get_domain(struct device *dev)
2511 struct protection_domain *domain;
2512 struct iommu_domain *io_domain;
2514 if (!check_device(dev))
2515 return ERR_PTR(-EINVAL);
2517 io_domain = iommu_get_domain_for_dev(dev);
2521 domain = to_pdomain(io_domain);
2522 if (!dma_ops_domain(domain))
2523 return ERR_PTR(-EBUSY);
2528 static void update_device_table(struct protection_domain *domain)
2530 struct iommu_dev_data *dev_data;
2532 list_for_each_entry(dev_data, &domain->dev_list, list)
2533 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2536 static void update_domain(struct protection_domain *domain)
2538 if (!domain->updated)
2541 update_device_table(domain);
2543 domain_flush_devices(domain);
2544 domain_flush_tlb_pde(domain);
2546 domain->updated = false;
2550 * This function fetches the PTE for a given address in the aperture
2552 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2553 unsigned long address)
2555 struct aperture_range *aperture;
2556 u64 *pte, *pte_page;
2558 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2562 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2564 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2566 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2568 pte += PM_LEVEL_INDEX(0, address);
2570 update_domain(&dom->domain);
2576 * This is the generic map function. It maps one 4kb page at paddr to
2577 * the given address in the DMA address space for the domain.
2579 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2580 unsigned long address,
2586 WARN_ON(address > dom->aperture_size);
2590 pte = dma_ops_get_pte(dom, address);
2592 return DMA_ERROR_CODE;
2594 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2596 if (direction == DMA_TO_DEVICE)
2597 __pte |= IOMMU_PTE_IR;
2598 else if (direction == DMA_FROM_DEVICE)
2599 __pte |= IOMMU_PTE_IW;
2600 else if (direction == DMA_BIDIRECTIONAL)
2601 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2607 return (dma_addr_t)address;
2611 * The generic unmapping function for on page in the DMA address space.
2613 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2614 unsigned long address)
2616 struct aperture_range *aperture;
2619 if (address >= dom->aperture_size)
2622 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2626 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2630 pte += PM_LEVEL_INDEX(0, address);
2632 WARN_ON_ONCE(!*pte);
2638 * This function contains common code for mapping of a physically
2639 * contiguous memory region into DMA address space. It is used by all
2640 * mapping functions provided with this IOMMU driver.
2641 * Must be called with the domain lock held.
2643 static dma_addr_t __map_single(struct device *dev,
2644 struct dma_ops_domain *dma_dom,
2651 dma_addr_t offset = paddr & ~PAGE_MASK;
2652 dma_addr_t address, start, ret;
2654 unsigned long align_mask = 0;
2657 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2661 align_mask = (1UL << get_order(size)) - 1;
2663 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2666 if (address == DMA_ERROR_CODE)
2670 for (i = 0; i < pages; ++i) {
2671 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2672 if (ret == DMA_ERROR_CODE)
2680 if (unlikely(amd_iommu_np_cache)) {
2681 domain_flush_pages(&dma_dom->domain, address, size);
2682 domain_flush_complete(&dma_dom->domain);
2690 for (--i; i >= 0; --i) {
2692 dma_ops_domain_unmap(dma_dom, start);
2695 dma_ops_free_addresses(dma_dom, address, pages);
2697 return DMA_ERROR_CODE;
2701 * Does the reverse of the __map_single function. Must be called with
2702 * the domain lock held too
2704 static void __unmap_single(struct dma_ops_domain *dma_dom,
2705 dma_addr_t dma_addr,
2709 dma_addr_t flush_addr;
2710 dma_addr_t i, start;
2713 if ((dma_addr == DMA_ERROR_CODE) ||
2714 (dma_addr + size > dma_dom->aperture_size))
2717 flush_addr = dma_addr;
2718 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2719 dma_addr &= PAGE_MASK;
2722 for (i = 0; i < pages; ++i) {
2723 dma_ops_domain_unmap(dma_dom, start);
2727 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2731 * The exported map_single function for dma_ops.
2733 static dma_addr_t map_page(struct device *dev, struct page *page,
2734 unsigned long offset, size_t size,
2735 enum dma_data_direction dir,
2736 struct dma_attrs *attrs)
2738 phys_addr_t paddr = page_to_phys(page) + offset;
2739 struct protection_domain *domain;
2742 domain = get_domain(dev);
2743 if (PTR_ERR(domain) == -EINVAL)
2744 return (dma_addr_t)paddr;
2745 else if (IS_ERR(domain))
2746 return DMA_ERROR_CODE;
2748 dma_mask = *dev->dma_mask;
2750 return __map_single(dev, domain->priv, paddr, size, dir, false,
2755 * The exported unmap_single function for dma_ops.
2757 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2758 enum dma_data_direction dir, struct dma_attrs *attrs)
2760 struct protection_domain *domain;
2762 domain = get_domain(dev);
2766 __unmap_single(domain->priv, dma_addr, size, dir);
2770 * The exported map_sg function for dma_ops (handles scatter-gather
2773 static int map_sg(struct device *dev, struct scatterlist *sglist,
2774 int nelems, enum dma_data_direction dir,
2775 struct dma_attrs *attrs)
2777 struct protection_domain *domain;
2779 struct scatterlist *s;
2781 int mapped_elems = 0;
2784 domain = get_domain(dev);
2788 dma_mask = *dev->dma_mask;
2790 for_each_sg(sglist, s, nelems, i) {
2793 s->dma_address = __map_single(dev, domain->priv,
2794 paddr, s->length, dir, false,
2797 if (s->dma_address) {
2798 s->dma_length = s->length;
2804 return mapped_elems;
2807 for_each_sg(sglist, s, mapped_elems, i) {
2809 __unmap_single(domain->priv, s->dma_address,
2810 s->dma_length, dir);
2811 s->dma_address = s->dma_length = 0;
2818 * The exported map_sg function for dma_ops (handles scatter-gather
2821 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2822 int nelems, enum dma_data_direction dir,
2823 struct dma_attrs *attrs)
2825 struct protection_domain *domain;
2826 struct scatterlist *s;
2829 domain = get_domain(dev);
2833 for_each_sg(sglist, s, nelems, i) {
2834 __unmap_single(domain->priv, s->dma_address,
2835 s->dma_length, dir);
2836 s->dma_address = s->dma_length = 0;
2841 * The exported alloc_coherent function for dma_ops.
2843 static void *alloc_coherent(struct device *dev, size_t size,
2844 dma_addr_t *dma_addr, gfp_t flag,
2845 struct dma_attrs *attrs)
2847 u64 dma_mask = dev->coherent_dma_mask;
2848 struct protection_domain *domain;
2851 domain = get_domain(dev);
2852 if (PTR_ERR(domain) == -EINVAL) {
2853 page = alloc_pages(flag, get_order(size));
2854 *dma_addr = page_to_phys(page);
2855 return page_address(page);
2856 } else if (IS_ERR(domain))
2859 size = PAGE_ALIGN(size);
2860 dma_mask = dev->coherent_dma_mask;
2861 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2864 page = alloc_pages(flag | __GFP_NOWARN, get_order(size));
2866 if (!gfpflags_allow_blocking(flag))
2869 page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
2876 dma_mask = *dev->dma_mask;
2878 *dma_addr = __map_single(dev, domain->priv, page_to_phys(page),
2879 size, DMA_BIDIRECTIONAL, true, dma_mask);
2881 if (*dma_addr == DMA_ERROR_CODE)
2884 return page_address(page);
2888 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2889 __free_pages(page, get_order(size));
2895 * The exported free_coherent function for dma_ops.
2897 static void free_coherent(struct device *dev, size_t size,
2898 void *virt_addr, dma_addr_t dma_addr,
2899 struct dma_attrs *attrs)
2901 struct protection_domain *domain;
2904 page = virt_to_page(virt_addr);
2905 size = PAGE_ALIGN(size);
2907 domain = get_domain(dev);
2911 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2914 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2915 __free_pages(page, get_order(size));
2919 * This function is called by the DMA layer to find out if we can handle a
2920 * particular device. It is part of the dma_ops.
2922 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2924 return check_device(dev);
2927 static int set_dma_mask(struct device *dev, u64 mask)
2929 struct protection_domain *domain;
2930 int max_apertures = 1;
2932 domain = get_domain(dev);
2934 return PTR_ERR(domain);
2936 if (mask == DMA_BIT_MASK(64))
2938 else if (mask > DMA_BIT_MASK(32))
2942 * To prevent lock contention it doesn't make sense to allocate more
2943 * apertures than online cpus
2945 if (max_apertures > num_online_cpus())
2946 max_apertures = num_online_cpus();
2948 if (dma_ops_domain_alloc_apertures(domain->priv, max_apertures))
2949 dev_err(dev, "Can't allocate %d iommu apertures\n",
2955 static struct dma_map_ops amd_iommu_dma_ops = {
2956 .alloc = alloc_coherent,
2957 .free = free_coherent,
2958 .map_page = map_page,
2959 .unmap_page = unmap_page,
2961 .unmap_sg = unmap_sg,
2962 .dma_supported = amd_iommu_dma_supported,
2963 .set_dma_mask = set_dma_mask,
2966 int __init amd_iommu_init_api(void)
2970 ret = iova_cache_get();
2974 err = bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2977 #ifdef CONFIG_ARM_AMBA
2978 err = bus_set_iommu(&amba_bustype, &amd_iommu_ops);
2982 err = bus_set_iommu(&platform_bus_type, &amd_iommu_ops);
2988 int __init amd_iommu_init_dma_ops(void)
2990 swiotlb = iommu_pass_through ? 1 : 0;
2994 * In case we don't initialize SWIOTLB (actually the common case
2995 * when AMD IOMMU is enabled), make sure there are global
2996 * dma_ops set as a fall-back for devices not handled by this
2997 * driver (for example non-PCI devices).
3000 dma_ops = &nommu_dma_ops;
3002 if (amd_iommu_unmap_flush)
3003 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
3005 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
3010 /*****************************************************************************
3012 * The following functions belong to the exported interface of AMD IOMMU
3014 * This interface allows access to lower level functions of the IOMMU
3015 * like protection domain handling and assignement of devices to domains
3016 * which is not possible with the dma_ops interface.
3018 *****************************************************************************/
3020 static void cleanup_domain(struct protection_domain *domain)
3022 struct iommu_dev_data *entry;
3023 unsigned long flags;
3025 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3027 while (!list_empty(&domain->dev_list)) {
3028 entry = list_first_entry(&domain->dev_list,
3029 struct iommu_dev_data, list);
3030 __detach_device(entry);
3033 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3036 static void protection_domain_free(struct protection_domain *domain)
3041 del_domain_from_list(domain);
3044 domain_id_free(domain->id);
3049 static int protection_domain_init(struct protection_domain *domain)
3051 spin_lock_init(&domain->lock);
3052 mutex_init(&domain->api_lock);
3053 domain->id = domain_id_alloc();
3056 INIT_LIST_HEAD(&domain->dev_list);
3061 static struct protection_domain *protection_domain_alloc(void)
3063 struct protection_domain *domain;
3065 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
3069 if (protection_domain_init(domain))
3072 add_domain_to_list(domain);
3082 static struct iommu_domain *amd_iommu_domain_alloc(unsigned type)
3084 struct protection_domain *pdomain;
3085 struct dma_ops_domain *dma_domain;
3088 case IOMMU_DOMAIN_UNMANAGED:
3089 pdomain = protection_domain_alloc();
3093 pdomain->mode = PAGE_MODE_3_LEVEL;
3094 pdomain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
3095 if (!pdomain->pt_root) {
3096 protection_domain_free(pdomain);
3100 pdomain->domain.geometry.aperture_start = 0;
3101 pdomain->domain.geometry.aperture_end = ~0ULL;
3102 pdomain->domain.geometry.force_aperture = true;
3105 case IOMMU_DOMAIN_DMA:
3106 dma_domain = dma_ops_domain_alloc();
3108 pr_err("AMD-Vi: Failed to allocate\n");
3111 pdomain = &dma_domain->domain;
3113 case IOMMU_DOMAIN_IDENTITY:
3114 pdomain = protection_domain_alloc();
3118 pdomain->mode = PAGE_MODE_NONE;
3124 return &pdomain->domain;
3127 static void amd_iommu_domain_free(struct iommu_domain *dom)
3129 struct protection_domain *domain;
3134 domain = to_pdomain(dom);
3136 if (domain->dev_cnt > 0)
3137 cleanup_domain(domain);
3139 BUG_ON(domain->dev_cnt != 0);
3141 if (domain->mode != PAGE_MODE_NONE)
3142 free_pagetable(domain);
3144 if (domain->flags & PD_IOMMUV2_MASK)
3145 free_gcr3_table(domain);
3147 protection_domain_free(domain);
3150 static void amd_iommu_detach_device(struct iommu_domain *dom,
3153 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3154 struct amd_iommu *iommu;
3157 if (!check_device(dev))
3160 devid = get_device_id(dev);
3164 if (dev_data->domain != NULL)
3167 iommu = amd_iommu_rlookup_table[devid];
3171 iommu_completion_wait(iommu);
3174 static int amd_iommu_attach_device(struct iommu_domain *dom,
3177 struct protection_domain *domain = to_pdomain(dom);
3178 struct iommu_dev_data *dev_data;
3179 struct amd_iommu *iommu;
3182 if (!check_device(dev))
3185 dev_data = dev->archdata.iommu;
3187 iommu = amd_iommu_rlookup_table[dev_data->devid];
3191 if (dev_data->domain)
3194 ret = attach_device(dev, domain);
3196 iommu_completion_wait(iommu);
3201 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3202 phys_addr_t paddr, size_t page_size, int iommu_prot)
3204 struct protection_domain *domain = to_pdomain(dom);
3208 if (domain->mode == PAGE_MODE_NONE)
3211 if (iommu_prot & IOMMU_READ)
3212 prot |= IOMMU_PROT_IR;
3213 if (iommu_prot & IOMMU_WRITE)
3214 prot |= IOMMU_PROT_IW;
3216 mutex_lock(&domain->api_lock);
3217 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3218 mutex_unlock(&domain->api_lock);
3223 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3226 struct protection_domain *domain = to_pdomain(dom);
3229 if (domain->mode == PAGE_MODE_NONE)
3232 mutex_lock(&domain->api_lock);
3233 unmap_size = iommu_unmap_page(domain, iova, page_size);
3234 mutex_unlock(&domain->api_lock);
3236 domain_flush_tlb_pde(domain);
3241 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3244 struct protection_domain *domain = to_pdomain(dom);
3245 unsigned long offset_mask, pte_pgsize;
3248 if (domain->mode == PAGE_MODE_NONE)
3251 pte = fetch_pte(domain, iova, &pte_pgsize);
3253 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3256 offset_mask = pte_pgsize - 1;
3257 __pte = *pte & PM_ADDR_MASK;
3259 return (__pte & ~offset_mask) | (iova & offset_mask);
3262 static bool amd_iommu_capable(enum iommu_cap cap)
3265 case IOMMU_CAP_CACHE_COHERENCY:
3267 case IOMMU_CAP_INTR_REMAP:
3268 return (irq_remapping_enabled == 1);
3269 case IOMMU_CAP_NOEXEC:
3276 static void amd_iommu_get_dm_regions(struct device *dev,
3277 struct list_head *head)
3279 struct unity_map_entry *entry;
3282 devid = get_device_id(dev);
3286 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
3287 struct iommu_dm_region *region;
3289 if (devid < entry->devid_start || devid > entry->devid_end)
3292 region = kzalloc(sizeof(*region), GFP_KERNEL);
3294 pr_err("Out of memory allocating dm-regions for %s\n",
3299 region->start = entry->address_start;
3300 region->length = entry->address_end - entry->address_start;
3301 if (entry->prot & IOMMU_PROT_IR)
3302 region->prot |= IOMMU_READ;
3303 if (entry->prot & IOMMU_PROT_IW)
3304 region->prot |= IOMMU_WRITE;
3306 list_add_tail(®ion->list, head);
3310 static void amd_iommu_put_dm_regions(struct device *dev,
3311 struct list_head *head)
3313 struct iommu_dm_region *entry, *next;
3315 list_for_each_entry_safe(entry, next, head, list)
3319 static const struct iommu_ops amd_iommu_ops = {
3320 .capable = amd_iommu_capable,
3321 .domain_alloc = amd_iommu_domain_alloc,
3322 .domain_free = amd_iommu_domain_free,
3323 .attach_dev = amd_iommu_attach_device,
3324 .detach_dev = amd_iommu_detach_device,
3325 .map = amd_iommu_map,
3326 .unmap = amd_iommu_unmap,
3327 .map_sg = default_iommu_map_sg,
3328 .iova_to_phys = amd_iommu_iova_to_phys,
3329 .add_device = amd_iommu_add_device,
3330 .remove_device = amd_iommu_remove_device,
3331 .device_group = amd_iommu_device_group,
3332 .get_dm_regions = amd_iommu_get_dm_regions,
3333 .put_dm_regions = amd_iommu_put_dm_regions,
3334 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3337 /*****************************************************************************
3339 * The next functions do a basic initialization of IOMMU for pass through
3342 * In passthrough mode the IOMMU is initialized and enabled but not used for
3343 * DMA-API translation.
3345 *****************************************************************************/
3347 /* IOMMUv2 specific functions */
3348 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3350 return atomic_notifier_chain_register(&ppr_notifier, nb);
3352 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3354 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3356 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3358 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3360 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3362 struct protection_domain *domain = to_pdomain(dom);
3363 unsigned long flags;
3365 spin_lock_irqsave(&domain->lock, flags);
3367 /* Update data structure */
3368 domain->mode = PAGE_MODE_NONE;
3369 domain->updated = true;
3371 /* Make changes visible to IOMMUs */
3372 update_domain(domain);
3374 /* Page-table is not visible to IOMMU anymore, so free it */
3375 free_pagetable(domain);
3377 spin_unlock_irqrestore(&domain->lock, flags);
3379 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3381 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3383 struct protection_domain *domain = to_pdomain(dom);
3384 unsigned long flags;
3387 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3390 /* Number of GCR3 table levels required */
3391 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3394 if (levels > amd_iommu_max_glx_val)
3397 spin_lock_irqsave(&domain->lock, flags);
3400 * Save us all sanity checks whether devices already in the
3401 * domain support IOMMUv2. Just force that the domain has no
3402 * devices attached when it is switched into IOMMUv2 mode.
3405 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3409 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3410 if (domain->gcr3_tbl == NULL)
3413 domain->glx = levels;
3414 domain->flags |= PD_IOMMUV2_MASK;
3415 domain->updated = true;
3417 update_domain(domain);
3422 spin_unlock_irqrestore(&domain->lock, flags);
3426 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3428 static int __flush_pasid(struct protection_domain *domain, int pasid,
3429 u64 address, bool size)
3431 struct iommu_dev_data *dev_data;
3432 struct iommu_cmd cmd;
3435 if (!(domain->flags & PD_IOMMUV2_MASK))
3438 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3441 * IOMMU TLB needs to be flushed before Device TLB to
3442 * prevent device TLB refill from IOMMU TLB
3444 for (i = 0; i < amd_iommus_present; ++i) {
3445 if (domain->dev_iommu[i] == 0)
3448 ret = iommu_queue_command(amd_iommus[i], &cmd);
3453 /* Wait until IOMMU TLB flushes are complete */
3454 domain_flush_complete(domain);
3456 /* Now flush device TLBs */
3457 list_for_each_entry(dev_data, &domain->dev_list, list) {
3458 struct amd_iommu *iommu;
3462 There might be non-IOMMUv2 capable devices in an IOMMUv2
3465 if (!dev_data->ats.enabled)
3468 qdep = dev_data->ats.qdep;
3469 iommu = amd_iommu_rlookup_table[dev_data->devid];
3471 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3472 qdep, address, size);
3474 ret = iommu_queue_command(iommu, &cmd);
3479 /* Wait until all device TLBs are flushed */
3480 domain_flush_complete(domain);
3489 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3492 return __flush_pasid(domain, pasid, address, false);
3495 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3498 struct protection_domain *domain = to_pdomain(dom);
3499 unsigned long flags;
3502 spin_lock_irqsave(&domain->lock, flags);
3503 ret = __amd_iommu_flush_page(domain, pasid, address);
3504 spin_unlock_irqrestore(&domain->lock, flags);
3508 EXPORT_SYMBOL(amd_iommu_flush_page);
3510 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3512 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3516 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3518 struct protection_domain *domain = to_pdomain(dom);
3519 unsigned long flags;
3522 spin_lock_irqsave(&domain->lock, flags);
3523 ret = __amd_iommu_flush_tlb(domain, pasid);
3524 spin_unlock_irqrestore(&domain->lock, flags);
3528 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3530 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3537 index = (pasid >> (9 * level)) & 0x1ff;
3543 if (!(*pte & GCR3_VALID)) {
3547 root = (void *)get_zeroed_page(GFP_ATOMIC);
3551 *pte = __pa(root) | GCR3_VALID;
3554 root = __va(*pte & PAGE_MASK);
3562 static int __set_gcr3(struct protection_domain *domain, int pasid,
3567 if (domain->mode != PAGE_MODE_NONE)
3570 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3574 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3576 return __amd_iommu_flush_tlb(domain, pasid);
3579 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3583 if (domain->mode != PAGE_MODE_NONE)
3586 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3592 return __amd_iommu_flush_tlb(domain, pasid);
3595 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3598 struct protection_domain *domain = to_pdomain(dom);
3599 unsigned long flags;
3602 spin_lock_irqsave(&domain->lock, flags);
3603 ret = __set_gcr3(domain, pasid, cr3);
3604 spin_unlock_irqrestore(&domain->lock, flags);
3608 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3610 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3612 struct protection_domain *domain = to_pdomain(dom);
3613 unsigned long flags;
3616 spin_lock_irqsave(&domain->lock, flags);
3617 ret = __clear_gcr3(domain, pasid);
3618 spin_unlock_irqrestore(&domain->lock, flags);
3622 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3624 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3625 int status, int tag)
3627 struct iommu_dev_data *dev_data;
3628 struct amd_iommu *iommu;
3629 struct iommu_cmd cmd;
3631 dev_data = get_dev_data(&pdev->dev);
3632 iommu = amd_iommu_rlookup_table[dev_data->devid];
3634 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3635 tag, dev_data->pri_tlp);
3637 return iommu_queue_command(iommu, &cmd);
3639 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3641 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3643 struct protection_domain *pdomain;
3645 pdomain = get_domain(&pdev->dev);
3646 if (IS_ERR(pdomain))
3649 /* Only return IOMMUv2 domains */
3650 if (!(pdomain->flags & PD_IOMMUV2_MASK))
3653 return &pdomain->domain;
3655 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3657 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3659 struct iommu_dev_data *dev_data;
3661 if (!amd_iommu_v2_supported())
3664 dev_data = get_dev_data(&pdev->dev);
3665 dev_data->errata |= (1 << erratum);
3667 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3669 int amd_iommu_device_info(struct pci_dev *pdev,
3670 struct amd_iommu_device_info *info)
3675 if (pdev == NULL || info == NULL)
3678 if (!amd_iommu_v2_supported())
3681 memset(info, 0, sizeof(*info));
3683 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3685 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3687 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3689 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3691 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3695 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3696 max_pasids = min(max_pasids, (1 << 20));
3698 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3699 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3701 features = pci_pasid_features(pdev);
3702 if (features & PCI_PASID_CAP_EXEC)
3703 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3704 if (features & PCI_PASID_CAP_PRIV)
3705 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3710 EXPORT_SYMBOL(amd_iommu_device_info);
3712 #ifdef CONFIG_IRQ_REMAP
3714 /*****************************************************************************
3716 * Interrupt Remapping Implementation
3718 *****************************************************************************/
3736 u16 devid; /* Device ID for IRTE table */
3737 u16 index; /* Index into IRTE table*/
3740 struct amd_ir_data {
3741 struct irq_2_irte irq_2_irte;
3742 union irte irte_entry;
3744 struct msi_msg msi_entry;
3748 static struct irq_chip amd_ir_chip;
3750 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3751 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3752 #define DTE_IRQ_TABLE_LEN (8ULL << 1)
3753 #define DTE_IRQ_REMAP_ENABLE 1ULL
3755 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3759 dte = amd_iommu_dev_table[devid].data[2];
3760 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3761 dte |= virt_to_phys(table->table);
3762 dte |= DTE_IRQ_REMAP_INTCTL;
3763 dte |= DTE_IRQ_TABLE_LEN;
3764 dte |= DTE_IRQ_REMAP_ENABLE;
3766 amd_iommu_dev_table[devid].data[2] = dte;
3769 #define IRTE_ALLOCATED (~1U)
3771 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3773 struct irq_remap_table *table = NULL;
3774 struct amd_iommu *iommu;
3775 unsigned long flags;
3778 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3780 iommu = amd_iommu_rlookup_table[devid];
3784 table = irq_lookup_table[devid];
3788 alias = amd_iommu_alias_table[devid];
3789 table = irq_lookup_table[alias];
3791 irq_lookup_table[devid] = table;
3792 set_dte_irq_entry(devid, table);
3793 iommu_flush_dte(iommu, devid);
3797 /* Nothing there yet, allocate new irq remapping table */
3798 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3802 /* Initialize table spin-lock */
3803 spin_lock_init(&table->lock);
3806 /* Keep the first 32 indexes free for IOAPIC interrupts */
3807 table->min_index = 32;
3809 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3810 if (!table->table) {
3816 memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3821 for (i = 0; i < 32; ++i)
3822 table->table[i] = IRTE_ALLOCATED;
3825 irq_lookup_table[devid] = table;
3826 set_dte_irq_entry(devid, table);
3827 iommu_flush_dte(iommu, devid);
3828 if (devid != alias) {
3829 irq_lookup_table[alias] = table;
3830 set_dte_irq_entry(alias, table);
3831 iommu_flush_dte(iommu, alias);
3835 iommu_completion_wait(iommu);
3838 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3843 static int alloc_irq_index(u16 devid, int count)
3845 struct irq_remap_table *table;
3846 unsigned long flags;
3849 table = get_irq_table(devid, false);
3853 spin_lock_irqsave(&table->lock, flags);
3855 /* Scan table for free entries */
3856 for (c = 0, index = table->min_index;
3857 index < MAX_IRQS_PER_TABLE;
3859 if (table->table[index] == 0)
3866 table->table[index - c + 1] = IRTE_ALLOCATED;
3876 spin_unlock_irqrestore(&table->lock, flags);
3881 static int modify_irte(u16 devid, int index, union irte irte)
3883 struct irq_remap_table *table;
3884 struct amd_iommu *iommu;
3885 unsigned long flags;
3887 iommu = amd_iommu_rlookup_table[devid];
3891 table = get_irq_table(devid, false);
3895 spin_lock_irqsave(&table->lock, flags);
3896 table->table[index] = irte.val;
3897 spin_unlock_irqrestore(&table->lock, flags);
3899 iommu_flush_irt(iommu, devid);
3900 iommu_completion_wait(iommu);
3905 static void free_irte(u16 devid, int index)
3907 struct irq_remap_table *table;
3908 struct amd_iommu *iommu;
3909 unsigned long flags;
3911 iommu = amd_iommu_rlookup_table[devid];
3915 table = get_irq_table(devid, false);
3919 spin_lock_irqsave(&table->lock, flags);
3920 table->table[index] = 0;
3921 spin_unlock_irqrestore(&table->lock, flags);
3923 iommu_flush_irt(iommu, devid);
3924 iommu_completion_wait(iommu);
3927 static int get_devid(struct irq_alloc_info *info)
3931 switch (info->type) {
3932 case X86_IRQ_ALLOC_TYPE_IOAPIC:
3933 devid = get_ioapic_devid(info->ioapic_id);
3935 case X86_IRQ_ALLOC_TYPE_HPET:
3936 devid = get_hpet_devid(info->hpet_id);
3938 case X86_IRQ_ALLOC_TYPE_MSI:
3939 case X86_IRQ_ALLOC_TYPE_MSIX:
3940 devid = get_device_id(&info->msi_dev->dev);
3950 static struct irq_domain *get_ir_irq_domain(struct irq_alloc_info *info)
3952 struct amd_iommu *iommu;
3958 devid = get_devid(info);
3960 iommu = amd_iommu_rlookup_table[devid];
3962 return iommu->ir_domain;
3968 static struct irq_domain *get_irq_domain(struct irq_alloc_info *info)
3970 struct amd_iommu *iommu;
3976 switch (info->type) {
3977 case X86_IRQ_ALLOC_TYPE_MSI:
3978 case X86_IRQ_ALLOC_TYPE_MSIX:
3979 devid = get_device_id(&info->msi_dev->dev);
3983 iommu = amd_iommu_rlookup_table[devid];
3985 return iommu->msi_domain;
3994 struct irq_remap_ops amd_iommu_irq_ops = {
3995 .prepare = amd_iommu_prepare,
3996 .enable = amd_iommu_enable,
3997 .disable = amd_iommu_disable,
3998 .reenable = amd_iommu_reenable,
3999 .enable_faulting = amd_iommu_enable_faulting,
4000 .get_ir_irq_domain = get_ir_irq_domain,
4001 .get_irq_domain = get_irq_domain,
4004 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
4005 struct irq_cfg *irq_cfg,
4006 struct irq_alloc_info *info,
4007 int devid, int index, int sub_handle)
4009 struct irq_2_irte *irte_info = &data->irq_2_irte;
4010 struct msi_msg *msg = &data->msi_entry;
4011 union irte *irte = &data->irte_entry;
4012 struct IO_APIC_route_entry *entry;
4014 data->irq_2_irte.devid = devid;
4015 data->irq_2_irte.index = index + sub_handle;
4017 /* Setup IRTE for IOMMU */
4019 irte->fields.vector = irq_cfg->vector;
4020 irte->fields.int_type = apic->irq_delivery_mode;
4021 irte->fields.destination = irq_cfg->dest_apicid;
4022 irte->fields.dm = apic->irq_dest_mode;
4023 irte->fields.valid = 1;
4025 switch (info->type) {
4026 case X86_IRQ_ALLOC_TYPE_IOAPIC:
4027 /* Setup IOAPIC entry */
4028 entry = info->ioapic_entry;
4029 info->ioapic_entry = NULL;
4030 memset(entry, 0, sizeof(*entry));
4031 entry->vector = index;
4033 entry->trigger = info->ioapic_trigger;
4034 entry->polarity = info->ioapic_polarity;
4035 /* Mask level triggered irqs. */
4036 if (info->ioapic_trigger)
4040 case X86_IRQ_ALLOC_TYPE_HPET:
4041 case X86_IRQ_ALLOC_TYPE_MSI:
4042 case X86_IRQ_ALLOC_TYPE_MSIX:
4043 msg->address_hi = MSI_ADDR_BASE_HI;
4044 msg->address_lo = MSI_ADDR_BASE_LO;
4045 msg->data = irte_info->index;
4054 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
4055 unsigned int nr_irqs, void *arg)
4057 struct irq_alloc_info *info = arg;
4058 struct irq_data *irq_data;
4059 struct amd_ir_data *data;
4060 struct irq_cfg *cfg;
4066 if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_MSI &&
4067 info->type != X86_IRQ_ALLOC_TYPE_MSIX)
4071 * With IRQ remapping enabled, don't need contiguous CPU vectors
4072 * to support multiple MSI interrupts.
4074 if (info->type == X86_IRQ_ALLOC_TYPE_MSI)
4075 info->flags &= ~X86_IRQ_ALLOC_CONTIGUOUS_VECTORS;
4077 devid = get_devid(info);
4081 ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
4085 if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
4086 if (get_irq_table(devid, true))
4087 index = info->ioapic_pin;
4091 index = alloc_irq_index(devid, nr_irqs);
4094 pr_warn("Failed to allocate IRTE\n");
4095 goto out_free_parent;
4098 for (i = 0; i < nr_irqs; i++) {
4099 irq_data = irq_domain_get_irq_data(domain, virq + i);
4100 cfg = irqd_cfg(irq_data);
4101 if (!irq_data || !cfg) {
4107 data = kzalloc(sizeof(*data), GFP_KERNEL);
4111 irq_data->hwirq = (devid << 16) + i;
4112 irq_data->chip_data = data;
4113 irq_data->chip = &amd_ir_chip;
4114 irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
4115 irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
4121 for (i--; i >= 0; i--) {
4122 irq_data = irq_domain_get_irq_data(domain, virq + i);
4124 kfree(irq_data->chip_data);
4126 for (i = 0; i < nr_irqs; i++)
4127 free_irte(devid, index + i);
4129 irq_domain_free_irqs_common(domain, virq, nr_irqs);
4133 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
4134 unsigned int nr_irqs)
4136 struct irq_2_irte *irte_info;
4137 struct irq_data *irq_data;
4138 struct amd_ir_data *data;
4141 for (i = 0; i < nr_irqs; i++) {
4142 irq_data = irq_domain_get_irq_data(domain, virq + i);
4143 if (irq_data && irq_data->chip_data) {
4144 data = irq_data->chip_data;
4145 irte_info = &data->irq_2_irte;
4146 free_irte(irte_info->devid, irte_info->index);
4150 irq_domain_free_irqs_common(domain, virq, nr_irqs);
4153 static void irq_remapping_activate(struct irq_domain *domain,
4154 struct irq_data *irq_data)
4156 struct amd_ir_data *data = irq_data->chip_data;
4157 struct irq_2_irte *irte_info = &data->irq_2_irte;
4159 modify_irte(irte_info->devid, irte_info->index, data->irte_entry);
4162 static void irq_remapping_deactivate(struct irq_domain *domain,
4163 struct irq_data *irq_data)
4165 struct amd_ir_data *data = irq_data->chip_data;
4166 struct irq_2_irte *irte_info = &data->irq_2_irte;
4170 modify_irte(irte_info->devid, irte_info->index, data->irte_entry);
4173 static struct irq_domain_ops amd_ir_domain_ops = {
4174 .alloc = irq_remapping_alloc,
4175 .free = irq_remapping_free,
4176 .activate = irq_remapping_activate,
4177 .deactivate = irq_remapping_deactivate,
4180 static int amd_ir_set_affinity(struct irq_data *data,
4181 const struct cpumask *mask, bool force)
4183 struct amd_ir_data *ir_data = data->chip_data;
4184 struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4185 struct irq_cfg *cfg = irqd_cfg(data);
4186 struct irq_data *parent = data->parent_data;
4189 ret = parent->chip->irq_set_affinity(parent, mask, force);
4190 if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
4194 * Atomically updates the IRTE with the new destination, vector
4195 * and flushes the interrupt entry cache.
4197 ir_data->irte_entry.fields.vector = cfg->vector;
4198 ir_data->irte_entry.fields.destination = cfg->dest_apicid;
4199 modify_irte(irte_info->devid, irte_info->index, ir_data->irte_entry);
4202 * After this point, all the interrupts will start arriving
4203 * at the new destination. So, time to cleanup the previous
4204 * vector allocation.
4206 send_cleanup_vector(cfg);
4208 return IRQ_SET_MASK_OK_DONE;
4211 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
4213 struct amd_ir_data *ir_data = irq_data->chip_data;
4215 *msg = ir_data->msi_entry;
4218 static struct irq_chip amd_ir_chip = {
4219 .irq_ack = ir_ack_apic_edge,
4220 .irq_set_affinity = amd_ir_set_affinity,
4221 .irq_compose_msi_msg = ir_compose_msi_msg,
4224 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
4226 iommu->ir_domain = irq_domain_add_tree(NULL, &amd_ir_domain_ops, iommu);
4227 if (!iommu->ir_domain)
4230 iommu->ir_domain->parent = arch_get_ir_parent_domain();
4231 iommu->msi_domain = arch_create_msi_irq_domain(iommu->ir_domain);