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/pci-ats.h>
23 #include <linux/bitmap.h>
24 #include <linux/slab.h>
25 #include <linux/debugfs.h>
26 #include <linux/scatterlist.h>
27 #include <linux/dma-mapping.h>
28 #include <linux/iommu-helper.h>
29 #include <linux/iommu.h>
30 #include <linux/delay.h>
31 #include <linux/amd-iommu.h>
32 #include <linux/notifier.h>
33 #include <linux/export.h>
34 #include <linux/irq.h>
35 #include <linux/msi.h>
36 #include <linux/dma-contiguous.h>
37 #include <linux/irqdomain.h>
38 #include <asm/irq_remapping.h>
39 #include <asm/io_apic.h>
41 #include <asm/hw_irq.h>
42 #include <asm/msidef.h>
43 #include <asm/proto.h>
44 #include <asm/iommu.h>
48 #include "amd_iommu_proto.h"
49 #include "amd_iommu_types.h"
50 #include "irq_remapping.h"
52 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
54 #define LOOP_TIMEOUT 100000
57 * This bitmap is used to advertise the page sizes our hardware support
58 * to the IOMMU core, which will then use this information to split
59 * physically contiguous memory regions it is mapping into page sizes
62 * 512GB Pages are not supported due to a hardware bug
64 #define AMD_IOMMU_PGSIZES ((~0xFFFUL) & ~(2ULL << 38))
66 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
68 /* List of all available dev_data structures */
69 static LIST_HEAD(dev_data_list);
70 static DEFINE_SPINLOCK(dev_data_list_lock);
72 LIST_HEAD(ioapic_map);
76 * Domain for untranslated devices - only allocated
77 * if iommu=pt passed on kernel cmd line.
79 static const struct iommu_ops amd_iommu_ops;
81 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
82 int amd_iommu_max_glx_val = -1;
84 static struct dma_map_ops amd_iommu_dma_ops;
87 * This struct contains device specific data for the IOMMU
89 struct iommu_dev_data {
90 struct list_head list; /* For domain->dev_list */
91 struct list_head dev_data_list; /* For global dev_data_list */
92 struct protection_domain *domain; /* Domain the device is bound to */
93 u16 devid; /* PCI Device ID */
94 bool iommu_v2; /* Device can make use of IOMMUv2 */
95 bool passthrough; /* Device is identity mapped */
99 } ats; /* ATS state */
100 bool pri_tlp; /* PASID TLB required for
102 u32 errata; /* Bitmap for errata to apply */
106 * general struct to manage commands send to an IOMMU
112 struct kmem_cache *amd_iommu_irq_cache;
114 static void update_domain(struct protection_domain *domain);
115 static int protection_domain_init(struct protection_domain *domain);
118 * For dynamic growth the aperture size is split into ranges of 128MB of
119 * DMA address space each. This struct represents one such range.
121 struct aperture_range {
123 spinlock_t bitmap_lock;
125 /* address allocation bitmap */
126 unsigned long *bitmap;
127 unsigned long offset;
128 unsigned long next_bit;
131 * Array of PTE pages for the aperture. In this array we save all the
132 * leaf pages of the domain page table used for the aperture. This way
133 * we don't need to walk the page table to find a specific PTE. We can
134 * just calculate its address in constant time.
140 * Data container for a dma_ops specific protection domain
142 struct dma_ops_domain {
143 /* generic protection domain information */
144 struct protection_domain domain;
146 /* size of the aperture for the mappings */
147 unsigned long aperture_size;
149 /* aperture index we start searching for free addresses */
150 unsigned long next_index;
152 /* address space relevant data */
153 struct aperture_range *aperture[APERTURE_MAX_RANGES];
156 /****************************************************************************
160 ****************************************************************************/
162 static struct protection_domain *to_pdomain(struct iommu_domain *dom)
164 return container_of(dom, struct protection_domain, domain);
167 static struct iommu_dev_data *alloc_dev_data(u16 devid)
169 struct iommu_dev_data *dev_data;
172 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
176 dev_data->devid = devid;
178 spin_lock_irqsave(&dev_data_list_lock, flags);
179 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
180 spin_unlock_irqrestore(&dev_data_list_lock, flags);
185 static struct iommu_dev_data *search_dev_data(u16 devid)
187 struct iommu_dev_data *dev_data;
190 spin_lock_irqsave(&dev_data_list_lock, flags);
191 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
192 if (dev_data->devid == devid)
199 spin_unlock_irqrestore(&dev_data_list_lock, flags);
204 static struct iommu_dev_data *find_dev_data(u16 devid)
206 struct iommu_dev_data *dev_data;
208 dev_data = search_dev_data(devid);
210 if (dev_data == NULL)
211 dev_data = alloc_dev_data(devid);
216 static inline u16 get_device_id(struct device *dev)
218 struct pci_dev *pdev = to_pci_dev(dev);
220 return PCI_DEVID(pdev->bus->number, pdev->devfn);
223 static struct iommu_dev_data *get_dev_data(struct device *dev)
225 return dev->archdata.iommu;
228 static bool pci_iommuv2_capable(struct pci_dev *pdev)
230 static const int caps[] = {
233 PCI_EXT_CAP_ID_PASID,
237 for (i = 0; i < 3; ++i) {
238 pos = pci_find_ext_capability(pdev, caps[i]);
246 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
248 struct iommu_dev_data *dev_data;
250 dev_data = get_dev_data(&pdev->dev);
252 return dev_data->errata & (1 << erratum) ? true : false;
256 * This function actually applies the mapping to the page table of the
259 static void alloc_unity_mapping(struct dma_ops_domain *dma_dom,
260 struct unity_map_entry *e)
264 for (addr = e->address_start; addr < e->address_end;
266 if (addr < dma_dom->aperture_size)
267 __set_bit(addr >> PAGE_SHIFT,
268 dma_dom->aperture[0]->bitmap);
273 * Inits the unity mappings required for a specific device
275 static void init_unity_mappings_for_device(struct device *dev,
276 struct dma_ops_domain *dma_dom)
278 struct unity_map_entry *e;
281 devid = get_device_id(dev);
283 list_for_each_entry(e, &amd_iommu_unity_map, list) {
284 if (!(devid >= e->devid_start && devid <= e->devid_end))
286 alloc_unity_mapping(dma_dom, e);
291 * This function checks if the driver got a valid device from the caller to
292 * avoid dereferencing invalid pointers.
294 static bool check_device(struct device *dev)
298 if (!dev || !dev->dma_mask)
302 if (!dev_is_pci(dev))
305 devid = get_device_id(dev);
307 /* Out of our scope? */
308 if (devid > amd_iommu_last_bdf)
311 if (amd_iommu_rlookup_table[devid] == NULL)
317 static void init_iommu_group(struct device *dev)
319 struct dma_ops_domain *dma_domain;
320 struct iommu_domain *domain;
321 struct iommu_group *group;
323 group = iommu_group_get_for_dev(dev);
327 domain = iommu_group_default_domain(group);
331 dma_domain = to_pdomain(domain)->priv;
333 init_unity_mappings_for_device(dev, dma_domain);
335 iommu_group_put(group);
338 static int iommu_init_device(struct device *dev)
340 struct pci_dev *pdev = to_pci_dev(dev);
341 struct iommu_dev_data *dev_data;
343 if (dev->archdata.iommu)
346 dev_data = find_dev_data(get_device_id(dev));
350 if (pci_iommuv2_capable(pdev)) {
351 struct amd_iommu *iommu;
353 iommu = amd_iommu_rlookup_table[dev_data->devid];
354 dev_data->iommu_v2 = iommu->is_iommu_v2;
357 dev->archdata.iommu = dev_data;
359 iommu_device_link(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
365 static void iommu_ignore_device(struct device *dev)
369 devid = get_device_id(dev);
370 alias = amd_iommu_alias_table[devid];
372 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
373 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
375 amd_iommu_rlookup_table[devid] = NULL;
376 amd_iommu_rlookup_table[alias] = NULL;
379 static void iommu_uninit_device(struct device *dev)
381 struct iommu_dev_data *dev_data = search_dev_data(get_device_id(dev));
386 iommu_device_unlink(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
389 iommu_group_remove_device(dev);
392 dev->archdata.dma_ops = NULL;
395 * We keep dev_data around for unplugged devices and reuse it when the
396 * device is re-plugged - not doing so would introduce a ton of races.
400 #ifdef CONFIG_AMD_IOMMU_STATS
403 * Initialization code for statistics collection
406 DECLARE_STATS_COUNTER(compl_wait);
407 DECLARE_STATS_COUNTER(cnt_map_single);
408 DECLARE_STATS_COUNTER(cnt_unmap_single);
409 DECLARE_STATS_COUNTER(cnt_map_sg);
410 DECLARE_STATS_COUNTER(cnt_unmap_sg);
411 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
412 DECLARE_STATS_COUNTER(cnt_free_coherent);
413 DECLARE_STATS_COUNTER(cross_page);
414 DECLARE_STATS_COUNTER(domain_flush_single);
415 DECLARE_STATS_COUNTER(domain_flush_all);
416 DECLARE_STATS_COUNTER(alloced_io_mem);
417 DECLARE_STATS_COUNTER(total_map_requests);
418 DECLARE_STATS_COUNTER(complete_ppr);
419 DECLARE_STATS_COUNTER(invalidate_iotlb);
420 DECLARE_STATS_COUNTER(invalidate_iotlb_all);
421 DECLARE_STATS_COUNTER(pri_requests);
423 static struct dentry *stats_dir;
424 static struct dentry *de_fflush;
426 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
428 if (stats_dir == NULL)
431 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
435 static void amd_iommu_stats_init(void)
437 stats_dir = debugfs_create_dir("amd-iommu", NULL);
438 if (stats_dir == NULL)
441 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
442 &amd_iommu_unmap_flush);
444 amd_iommu_stats_add(&compl_wait);
445 amd_iommu_stats_add(&cnt_map_single);
446 amd_iommu_stats_add(&cnt_unmap_single);
447 amd_iommu_stats_add(&cnt_map_sg);
448 amd_iommu_stats_add(&cnt_unmap_sg);
449 amd_iommu_stats_add(&cnt_alloc_coherent);
450 amd_iommu_stats_add(&cnt_free_coherent);
451 amd_iommu_stats_add(&cross_page);
452 amd_iommu_stats_add(&domain_flush_single);
453 amd_iommu_stats_add(&domain_flush_all);
454 amd_iommu_stats_add(&alloced_io_mem);
455 amd_iommu_stats_add(&total_map_requests);
456 amd_iommu_stats_add(&complete_ppr);
457 amd_iommu_stats_add(&invalidate_iotlb);
458 amd_iommu_stats_add(&invalidate_iotlb_all);
459 amd_iommu_stats_add(&pri_requests);
464 /****************************************************************************
466 * Interrupt handling functions
468 ****************************************************************************/
470 static void dump_dte_entry(u16 devid)
474 for (i = 0; i < 4; ++i)
475 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
476 amd_iommu_dev_table[devid].data[i]);
479 static void dump_command(unsigned long phys_addr)
481 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
484 for (i = 0; i < 4; ++i)
485 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
488 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
490 int type, devid, domid, flags;
491 volatile u32 *event = __evt;
496 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
497 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
498 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
499 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
500 address = (u64)(((u64)event[3]) << 32) | event[2];
503 /* Did we hit the erratum? */
504 if (++count == LOOP_TIMEOUT) {
505 pr_err("AMD-Vi: No event written to event log\n");
512 printk(KERN_ERR "AMD-Vi: Event logged [");
515 case EVENT_TYPE_ILL_DEV:
516 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
517 "address=0x%016llx flags=0x%04x]\n",
518 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
520 dump_dte_entry(devid);
522 case EVENT_TYPE_IO_FAULT:
523 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
524 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
525 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
526 domid, address, flags);
528 case EVENT_TYPE_DEV_TAB_ERR:
529 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
530 "address=0x%016llx flags=0x%04x]\n",
531 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
534 case EVENT_TYPE_PAGE_TAB_ERR:
535 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
536 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
537 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
538 domid, address, flags);
540 case EVENT_TYPE_ILL_CMD:
541 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
542 dump_command(address);
544 case EVENT_TYPE_CMD_HARD_ERR:
545 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
546 "flags=0x%04x]\n", address, flags);
548 case EVENT_TYPE_IOTLB_INV_TO:
549 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
550 "address=0x%016llx]\n",
551 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
554 case EVENT_TYPE_INV_DEV_REQ:
555 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
556 "address=0x%016llx flags=0x%04x]\n",
557 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
561 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
564 memset(__evt, 0, 4 * sizeof(u32));
567 static void iommu_poll_events(struct amd_iommu *iommu)
571 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
572 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
574 while (head != tail) {
575 iommu_print_event(iommu, iommu->evt_buf + head);
576 head = (head + EVENT_ENTRY_SIZE) % EVT_BUFFER_SIZE;
579 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
582 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
584 struct amd_iommu_fault fault;
586 INC_STATS_COUNTER(pri_requests);
588 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
589 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
593 fault.address = raw[1];
594 fault.pasid = PPR_PASID(raw[0]);
595 fault.device_id = PPR_DEVID(raw[0]);
596 fault.tag = PPR_TAG(raw[0]);
597 fault.flags = PPR_FLAGS(raw[0]);
599 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
602 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
606 if (iommu->ppr_log == NULL)
609 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
610 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
612 while (head != tail) {
617 raw = (u64 *)(iommu->ppr_log + head);
620 * Hardware bug: Interrupt may arrive before the entry is
621 * written to memory. If this happens we need to wait for the
624 for (i = 0; i < LOOP_TIMEOUT; ++i) {
625 if (PPR_REQ_TYPE(raw[0]) != 0)
630 /* Avoid memcpy function-call overhead */
635 * To detect the hardware bug we need to clear the entry
638 raw[0] = raw[1] = 0UL;
640 /* Update head pointer of hardware ring-buffer */
641 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
642 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
644 /* Handle PPR entry */
645 iommu_handle_ppr_entry(iommu, entry);
647 /* Refresh ring-buffer information */
648 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
649 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
653 irqreturn_t amd_iommu_int_thread(int irq, void *data)
655 struct amd_iommu *iommu = (struct amd_iommu *) data;
656 u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
658 while (status & (MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK)) {
659 /* Enable EVT and PPR interrupts again */
660 writel((MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK),
661 iommu->mmio_base + MMIO_STATUS_OFFSET);
663 if (status & MMIO_STATUS_EVT_INT_MASK) {
664 pr_devel("AMD-Vi: Processing IOMMU Event Log\n");
665 iommu_poll_events(iommu);
668 if (status & MMIO_STATUS_PPR_INT_MASK) {
669 pr_devel("AMD-Vi: Processing IOMMU PPR Log\n");
670 iommu_poll_ppr_log(iommu);
674 * Hardware bug: ERBT1312
675 * When re-enabling interrupt (by writing 1
676 * to clear the bit), the hardware might also try to set
677 * the interrupt bit in the event status register.
678 * In this scenario, the bit will be set, and disable
679 * subsequent interrupts.
681 * Workaround: The IOMMU driver should read back the
682 * status register and check if the interrupt bits are cleared.
683 * If not, driver will need to go through the interrupt handler
684 * again and re-clear the bits
686 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
691 irqreturn_t amd_iommu_int_handler(int irq, void *data)
693 return IRQ_WAKE_THREAD;
696 /****************************************************************************
698 * IOMMU command queuing functions
700 ****************************************************************************/
702 static int wait_on_sem(volatile u64 *sem)
706 while (*sem == 0 && i < LOOP_TIMEOUT) {
711 if (i == LOOP_TIMEOUT) {
712 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
719 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
720 struct iommu_cmd *cmd,
725 target = iommu->cmd_buf + tail;
726 tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
728 /* Copy command to buffer */
729 memcpy(target, cmd, sizeof(*cmd));
731 /* Tell the IOMMU about it */
732 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
735 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
737 WARN_ON(address & 0x7ULL);
739 memset(cmd, 0, sizeof(*cmd));
740 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
741 cmd->data[1] = upper_32_bits(__pa(address));
743 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
746 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
748 memset(cmd, 0, sizeof(*cmd));
749 cmd->data[0] = devid;
750 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
753 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
754 size_t size, u16 domid, int pde)
759 pages = iommu_num_pages(address, size, PAGE_SIZE);
764 * If we have to flush more than one page, flush all
765 * TLB entries for this domain
767 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
771 address &= PAGE_MASK;
773 memset(cmd, 0, sizeof(*cmd));
774 cmd->data[1] |= domid;
775 cmd->data[2] = lower_32_bits(address);
776 cmd->data[3] = upper_32_bits(address);
777 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
778 if (s) /* size bit - we flush more than one 4kb page */
779 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
780 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
781 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
784 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
785 u64 address, size_t size)
790 pages = iommu_num_pages(address, size, PAGE_SIZE);
795 * If we have to flush more than one page, flush all
796 * TLB entries for this domain
798 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
802 address &= PAGE_MASK;
804 memset(cmd, 0, sizeof(*cmd));
805 cmd->data[0] = devid;
806 cmd->data[0] |= (qdep & 0xff) << 24;
807 cmd->data[1] = devid;
808 cmd->data[2] = lower_32_bits(address);
809 cmd->data[3] = upper_32_bits(address);
810 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
812 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
815 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
816 u64 address, bool size)
818 memset(cmd, 0, sizeof(*cmd));
820 address &= ~(0xfffULL);
822 cmd->data[0] = pasid;
823 cmd->data[1] = domid;
824 cmd->data[2] = lower_32_bits(address);
825 cmd->data[3] = upper_32_bits(address);
826 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
827 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
829 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
830 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
833 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
834 int qdep, u64 address, bool size)
836 memset(cmd, 0, sizeof(*cmd));
838 address &= ~(0xfffULL);
840 cmd->data[0] = devid;
841 cmd->data[0] |= ((pasid >> 8) & 0xff) << 16;
842 cmd->data[0] |= (qdep & 0xff) << 24;
843 cmd->data[1] = devid;
844 cmd->data[1] |= (pasid & 0xff) << 16;
845 cmd->data[2] = lower_32_bits(address);
846 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
847 cmd->data[3] = upper_32_bits(address);
849 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
850 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
853 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
854 int status, int tag, bool gn)
856 memset(cmd, 0, sizeof(*cmd));
858 cmd->data[0] = devid;
860 cmd->data[1] = pasid;
861 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
863 cmd->data[3] = tag & 0x1ff;
864 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
866 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
869 static void build_inv_all(struct iommu_cmd *cmd)
871 memset(cmd, 0, sizeof(*cmd));
872 CMD_SET_TYPE(cmd, CMD_INV_ALL);
875 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
877 memset(cmd, 0, sizeof(*cmd));
878 cmd->data[0] = devid;
879 CMD_SET_TYPE(cmd, CMD_INV_IRT);
883 * Writes the command to the IOMMUs command buffer and informs the
884 * hardware about the new command.
886 static int iommu_queue_command_sync(struct amd_iommu *iommu,
887 struct iommu_cmd *cmd,
890 u32 left, tail, head, next_tail;
894 spin_lock_irqsave(&iommu->lock, flags);
896 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
897 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
898 next_tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
899 left = (head - next_tail) % CMD_BUFFER_SIZE;
902 struct iommu_cmd sync_cmd;
903 volatile u64 sem = 0;
906 build_completion_wait(&sync_cmd, (u64)&sem);
907 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
909 spin_unlock_irqrestore(&iommu->lock, flags);
911 if ((ret = wait_on_sem(&sem)) != 0)
917 copy_cmd_to_buffer(iommu, cmd, tail);
919 /* We need to sync now to make sure all commands are processed */
920 iommu->need_sync = sync;
922 spin_unlock_irqrestore(&iommu->lock, flags);
927 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
929 return iommu_queue_command_sync(iommu, cmd, true);
933 * This function queues a completion wait command into the command
936 static int iommu_completion_wait(struct amd_iommu *iommu)
938 struct iommu_cmd cmd;
939 volatile u64 sem = 0;
942 if (!iommu->need_sync)
945 build_completion_wait(&cmd, (u64)&sem);
947 ret = iommu_queue_command_sync(iommu, &cmd, false);
951 return wait_on_sem(&sem);
954 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
956 struct iommu_cmd cmd;
958 build_inv_dte(&cmd, devid);
960 return iommu_queue_command(iommu, &cmd);
963 static void iommu_flush_dte_all(struct amd_iommu *iommu)
967 for (devid = 0; devid <= 0xffff; ++devid)
968 iommu_flush_dte(iommu, devid);
970 iommu_completion_wait(iommu);
974 * This function uses heavy locking and may disable irqs for some time. But
975 * this is no issue because it is only called during resume.
977 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
981 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
982 struct iommu_cmd cmd;
983 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
985 iommu_queue_command(iommu, &cmd);
988 iommu_completion_wait(iommu);
991 static void iommu_flush_all(struct amd_iommu *iommu)
993 struct iommu_cmd cmd;
997 iommu_queue_command(iommu, &cmd);
998 iommu_completion_wait(iommu);
1001 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1003 struct iommu_cmd cmd;
1005 build_inv_irt(&cmd, devid);
1007 iommu_queue_command(iommu, &cmd);
1010 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1014 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1015 iommu_flush_irt(iommu, devid);
1017 iommu_completion_wait(iommu);
1020 void iommu_flush_all_caches(struct amd_iommu *iommu)
1022 if (iommu_feature(iommu, FEATURE_IA)) {
1023 iommu_flush_all(iommu);
1025 iommu_flush_dte_all(iommu);
1026 iommu_flush_irt_all(iommu);
1027 iommu_flush_tlb_all(iommu);
1032 * Command send function for flushing on-device TLB
1034 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1035 u64 address, size_t size)
1037 struct amd_iommu *iommu;
1038 struct iommu_cmd cmd;
1041 qdep = dev_data->ats.qdep;
1042 iommu = amd_iommu_rlookup_table[dev_data->devid];
1044 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1046 return iommu_queue_command(iommu, &cmd);
1050 * Command send function for invalidating a device table entry
1052 static int device_flush_dte(struct iommu_dev_data *dev_data)
1054 struct amd_iommu *iommu;
1058 iommu = amd_iommu_rlookup_table[dev_data->devid];
1059 alias = amd_iommu_alias_table[dev_data->devid];
1061 ret = iommu_flush_dte(iommu, dev_data->devid);
1062 if (!ret && alias != dev_data->devid)
1063 ret = iommu_flush_dte(iommu, alias);
1067 if (dev_data->ats.enabled)
1068 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1074 * TLB invalidation function which is called from the mapping functions.
1075 * It invalidates a single PTE if the range to flush is within a single
1076 * page. Otherwise it flushes the whole TLB of the IOMMU.
1078 static void __domain_flush_pages(struct protection_domain *domain,
1079 u64 address, size_t size, int pde)
1081 struct iommu_dev_data *dev_data;
1082 struct iommu_cmd cmd;
1085 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1087 for (i = 0; i < amd_iommus_present; ++i) {
1088 if (!domain->dev_iommu[i])
1092 * Devices of this domain are behind this IOMMU
1093 * We need a TLB flush
1095 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1098 list_for_each_entry(dev_data, &domain->dev_list, list) {
1100 if (!dev_data->ats.enabled)
1103 ret |= device_flush_iotlb(dev_data, address, size);
1109 static void domain_flush_pages(struct protection_domain *domain,
1110 u64 address, size_t size)
1112 __domain_flush_pages(domain, address, size, 0);
1115 /* Flush the whole IO/TLB for a given protection domain */
1116 static void domain_flush_tlb(struct protection_domain *domain)
1118 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1121 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1122 static void domain_flush_tlb_pde(struct protection_domain *domain)
1124 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1127 static void domain_flush_complete(struct protection_domain *domain)
1131 for (i = 0; i < amd_iommus_present; ++i) {
1132 if (!domain->dev_iommu[i])
1136 * Devices of this domain are behind this IOMMU
1137 * We need to wait for completion of all commands.
1139 iommu_completion_wait(amd_iommus[i]);
1145 * This function flushes the DTEs for all devices in domain
1147 static void domain_flush_devices(struct protection_domain *domain)
1149 struct iommu_dev_data *dev_data;
1151 list_for_each_entry(dev_data, &domain->dev_list, list)
1152 device_flush_dte(dev_data);
1155 /****************************************************************************
1157 * The functions below are used the create the page table mappings for
1158 * unity mapped regions.
1160 ****************************************************************************/
1163 * This function is used to add another level to an IO page table. Adding
1164 * another level increases the size of the address space by 9 bits to a size up
1167 static bool increase_address_space(struct protection_domain *domain,
1172 if (domain->mode == PAGE_MODE_6_LEVEL)
1173 /* address space already 64 bit large */
1176 pte = (void *)get_zeroed_page(gfp);
1180 *pte = PM_LEVEL_PDE(domain->mode,
1181 virt_to_phys(domain->pt_root));
1182 domain->pt_root = pte;
1184 domain->updated = true;
1189 static u64 *alloc_pte(struct protection_domain *domain,
1190 unsigned long address,
1191 unsigned long page_size,
1198 BUG_ON(!is_power_of_2(page_size));
1200 while (address > PM_LEVEL_SIZE(domain->mode))
1201 increase_address_space(domain, gfp);
1203 level = domain->mode - 1;
1204 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1205 address = PAGE_SIZE_ALIGN(address, page_size);
1206 end_lvl = PAGE_SIZE_LEVEL(page_size);
1208 while (level > end_lvl) {
1213 if (!IOMMU_PTE_PRESENT(__pte)) {
1214 page = (u64 *)get_zeroed_page(gfp);
1218 __npte = PM_LEVEL_PDE(level, virt_to_phys(page));
1220 if (cmpxchg64(pte, __pte, __npte)) {
1221 free_page((unsigned long)page);
1226 /* No level skipping support yet */
1227 if (PM_PTE_LEVEL(*pte) != level)
1232 pte = IOMMU_PTE_PAGE(*pte);
1234 if (pte_page && level == end_lvl)
1237 pte = &pte[PM_LEVEL_INDEX(level, address)];
1244 * This function checks if there is a PTE for a given dma address. If
1245 * there is one, it returns the pointer to it.
1247 static u64 *fetch_pte(struct protection_domain *domain,
1248 unsigned long address,
1249 unsigned long *page_size)
1254 if (address > PM_LEVEL_SIZE(domain->mode))
1257 level = domain->mode - 1;
1258 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1259 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1264 if (!IOMMU_PTE_PRESENT(*pte))
1268 if (PM_PTE_LEVEL(*pte) == 7 ||
1269 PM_PTE_LEVEL(*pte) == 0)
1272 /* No level skipping support yet */
1273 if (PM_PTE_LEVEL(*pte) != level)
1278 /* Walk to the next level */
1279 pte = IOMMU_PTE_PAGE(*pte);
1280 pte = &pte[PM_LEVEL_INDEX(level, address)];
1281 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1284 if (PM_PTE_LEVEL(*pte) == 0x07) {
1285 unsigned long pte_mask;
1288 * If we have a series of large PTEs, make
1289 * sure to return a pointer to the first one.
1291 *page_size = pte_mask = PTE_PAGE_SIZE(*pte);
1292 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1293 pte = (u64 *)(((unsigned long)pte) & pte_mask);
1300 * Generic mapping functions. It maps a physical address into a DMA
1301 * address space. It allocates the page table pages if necessary.
1302 * In the future it can be extended to a generic mapping function
1303 * supporting all features of AMD IOMMU page tables like level skipping
1304 * and full 64 bit address spaces.
1306 static int iommu_map_page(struct protection_domain *dom,
1307 unsigned long bus_addr,
1308 unsigned long phys_addr,
1310 unsigned long page_size)
1315 BUG_ON(!IS_ALIGNED(bus_addr, page_size));
1316 BUG_ON(!IS_ALIGNED(phys_addr, page_size));
1318 if (!(prot & IOMMU_PROT_MASK))
1321 count = PAGE_SIZE_PTE_COUNT(page_size);
1322 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1327 for (i = 0; i < count; ++i)
1328 if (IOMMU_PTE_PRESENT(pte[i]))
1332 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1333 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1335 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1337 if (prot & IOMMU_PROT_IR)
1338 __pte |= IOMMU_PTE_IR;
1339 if (prot & IOMMU_PROT_IW)
1340 __pte |= IOMMU_PTE_IW;
1342 for (i = 0; i < count; ++i)
1350 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1351 unsigned long bus_addr,
1352 unsigned long page_size)
1354 unsigned long long unmapped;
1355 unsigned long unmap_size;
1358 BUG_ON(!is_power_of_2(page_size));
1362 while (unmapped < page_size) {
1364 pte = fetch_pte(dom, bus_addr, &unmap_size);
1369 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1370 for (i = 0; i < count; i++)
1374 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1375 unmapped += unmap_size;
1378 BUG_ON(unmapped && !is_power_of_2(unmapped));
1383 /****************************************************************************
1385 * The next functions belong to the address allocator for the dma_ops
1386 * interface functions. They work like the allocators in the other IOMMU
1387 * drivers. Its basically a bitmap which marks the allocated pages in
1388 * the aperture. Maybe it could be enhanced in the future to a more
1389 * efficient allocator.
1391 ****************************************************************************/
1394 * The address allocator core functions.
1396 * called with domain->lock held
1400 * Used to reserve address ranges in the aperture (e.g. for exclusion
1403 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1404 unsigned long start_page,
1407 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1409 if (start_page + pages > last_page)
1410 pages = last_page - start_page;
1412 for (i = start_page; i < start_page + pages; ++i) {
1413 int index = i / APERTURE_RANGE_PAGES;
1414 int page = i % APERTURE_RANGE_PAGES;
1415 __set_bit(page, dom->aperture[index]->bitmap);
1420 * This function is used to add a new aperture range to an existing
1421 * aperture in case of dma_ops domain allocation or address allocation
1424 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1425 bool populate, gfp_t gfp)
1427 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1428 struct amd_iommu *iommu;
1429 unsigned long i, old_size, pte_pgsize;
1431 #ifdef CONFIG_IOMMU_STRESS
1435 if (index >= APERTURE_MAX_RANGES)
1438 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1439 if (!dma_dom->aperture[index])
1442 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1443 if (!dma_dom->aperture[index]->bitmap)
1446 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1448 spin_lock_init(&dma_dom->aperture[index]->bitmap_lock);
1451 unsigned long address = dma_dom->aperture_size;
1452 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1453 u64 *pte, *pte_page;
1455 for (i = 0; i < num_ptes; ++i) {
1456 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1461 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1463 address += APERTURE_RANGE_SIZE / 64;
1467 old_size = dma_dom->aperture_size;
1468 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1470 /* Reserve address range used for MSI messages */
1471 if (old_size < MSI_ADDR_BASE_LO &&
1472 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1473 unsigned long spage;
1476 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1477 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1479 dma_ops_reserve_addresses(dma_dom, spage, pages);
1482 /* Initialize the exclusion range if necessary */
1483 for_each_iommu(iommu) {
1484 if (iommu->exclusion_start &&
1485 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1486 && iommu->exclusion_start < dma_dom->aperture_size) {
1487 unsigned long startpage;
1488 int pages = iommu_num_pages(iommu->exclusion_start,
1489 iommu->exclusion_length,
1491 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1492 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1497 * Check for areas already mapped as present in the new aperture
1498 * range and mark those pages as reserved in the allocator. Such
1499 * mappings may already exist as a result of requested unity
1500 * mappings for devices.
1502 for (i = dma_dom->aperture[index]->offset;
1503 i < dma_dom->aperture_size;
1505 u64 *pte = fetch_pte(&dma_dom->domain, i, &pte_pgsize);
1506 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1509 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT,
1513 update_domain(&dma_dom->domain);
1518 update_domain(&dma_dom->domain);
1520 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1522 kfree(dma_dom->aperture[index]);
1523 dma_dom->aperture[index] = NULL;
1528 static dma_addr_t dma_ops_aperture_alloc(struct dma_ops_domain *dom,
1529 struct aperture_range *range,
1530 unsigned long pages,
1531 unsigned long dma_mask,
1532 unsigned long boundary_size,
1533 unsigned long align_mask)
1535 unsigned long offset, limit, flags;
1539 offset = range->offset >> PAGE_SHIFT;
1540 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1541 dma_mask >> PAGE_SHIFT);
1543 spin_lock_irqsave(&range->bitmap_lock, flags);
1544 address = iommu_area_alloc(range->bitmap, limit, range->next_bit,
1545 pages, offset, boundary_size, align_mask);
1546 if (address == -1) {
1547 /* Nothing found, retry one time */
1548 address = iommu_area_alloc(range->bitmap, limit,
1549 0, pages, offset, boundary_size,
1555 range->next_bit = address + pages;
1557 spin_unlock_irqrestore(&range->bitmap_lock, flags);
1560 domain_flush_tlb(&dom->domain);
1561 domain_flush_complete(&dom->domain);
1567 static unsigned long dma_ops_area_alloc(struct device *dev,
1568 struct dma_ops_domain *dom,
1570 unsigned long align_mask,
1573 unsigned long boundary_size, mask;
1574 unsigned long address = -1;
1575 int start = dom->next_index;
1578 mask = dma_get_seg_boundary(dev);
1580 boundary_size = mask + 1 ? ALIGN(mask + 1, PAGE_SIZE) >> PAGE_SHIFT :
1581 1UL << (BITS_PER_LONG - PAGE_SHIFT);
1583 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1584 struct aperture_range *range;
1586 range = dom->aperture[(start + i) % APERTURE_MAX_RANGES];
1588 if (!range || range->offset >= dma_mask)
1591 address = dma_ops_aperture_alloc(dom, range, pages,
1592 dma_mask, boundary_size,
1594 if (address != -1) {
1595 address = range->offset + (address << PAGE_SHIFT);
1596 dom->next_index = i;
1604 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1605 struct dma_ops_domain *dom,
1607 unsigned long align_mask,
1610 unsigned long address = -1;
1612 #ifdef CONFIG_IOMMU_STRESS
1613 dom->next_index = 0;
1616 while (address == -1) {
1617 address = dma_ops_area_alloc(dev, dom, pages,
1618 align_mask, dma_mask);
1620 if (address == -1 && alloc_new_range(dom, false, GFP_ATOMIC))
1624 if (unlikely(address == -1))
1625 address = DMA_ERROR_CODE;
1627 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1633 * The address free function.
1635 * called with domain->lock held
1637 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1638 unsigned long address,
1641 unsigned i = address >> APERTURE_RANGE_SHIFT;
1642 struct aperture_range *range = dom->aperture[i];
1643 unsigned long flags;
1645 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1647 #ifdef CONFIG_IOMMU_STRESS
1652 if (amd_iommu_unmap_flush) {
1653 domain_flush_tlb(&dom->domain);
1654 domain_flush_complete(&dom->domain);
1657 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1659 spin_lock_irqsave(&range->bitmap_lock, flags);
1660 if (address + pages > range->next_bit)
1661 range->next_bit = address + pages;
1662 bitmap_clear(range->bitmap, address, pages);
1663 spin_unlock_irqrestore(&range->bitmap_lock, flags);
1667 /****************************************************************************
1669 * The next functions belong to the domain allocation. A domain is
1670 * allocated for every IOMMU as the default domain. If device isolation
1671 * is enabled, every device get its own domain. The most important thing
1672 * about domains is the page table mapping the DMA address space they
1675 ****************************************************************************/
1678 * This function adds a protection domain to the global protection domain list
1680 static void add_domain_to_list(struct protection_domain *domain)
1682 unsigned long flags;
1684 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1685 list_add(&domain->list, &amd_iommu_pd_list);
1686 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1690 * This function removes a protection domain to the global
1691 * protection domain list
1693 static void del_domain_from_list(struct protection_domain *domain)
1695 unsigned long flags;
1697 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1698 list_del(&domain->list);
1699 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1702 static u16 domain_id_alloc(void)
1704 unsigned long flags;
1707 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1708 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1710 if (id > 0 && id < MAX_DOMAIN_ID)
1711 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1714 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1719 static void domain_id_free(int id)
1721 unsigned long flags;
1723 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1724 if (id > 0 && id < MAX_DOMAIN_ID)
1725 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1726 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1729 #define DEFINE_FREE_PT_FN(LVL, FN) \
1730 static void free_pt_##LVL (unsigned long __pt) \
1738 for (i = 0; i < 512; ++i) { \
1739 /* PTE present? */ \
1740 if (!IOMMU_PTE_PRESENT(pt[i])) \
1744 if (PM_PTE_LEVEL(pt[i]) == 0 || \
1745 PM_PTE_LEVEL(pt[i]) == 7) \
1748 p = (unsigned long)IOMMU_PTE_PAGE(pt[i]); \
1751 free_page((unsigned long)pt); \
1754 DEFINE_FREE_PT_FN(l2, free_page)
1755 DEFINE_FREE_PT_FN(l3, free_pt_l2)
1756 DEFINE_FREE_PT_FN(l4, free_pt_l3)
1757 DEFINE_FREE_PT_FN(l5, free_pt_l4)
1758 DEFINE_FREE_PT_FN(l6, free_pt_l5)
1760 static void free_pagetable(struct protection_domain *domain)
1762 unsigned long root = (unsigned long)domain->pt_root;
1764 switch (domain->mode) {
1765 case PAGE_MODE_NONE:
1767 case PAGE_MODE_1_LEVEL:
1770 case PAGE_MODE_2_LEVEL:
1773 case PAGE_MODE_3_LEVEL:
1776 case PAGE_MODE_4_LEVEL:
1779 case PAGE_MODE_5_LEVEL:
1782 case PAGE_MODE_6_LEVEL:
1790 static void free_gcr3_tbl_level1(u64 *tbl)
1795 for (i = 0; i < 512; ++i) {
1796 if (!(tbl[i] & GCR3_VALID))
1799 ptr = __va(tbl[i] & PAGE_MASK);
1801 free_page((unsigned long)ptr);
1805 static void free_gcr3_tbl_level2(u64 *tbl)
1810 for (i = 0; i < 512; ++i) {
1811 if (!(tbl[i] & GCR3_VALID))
1814 ptr = __va(tbl[i] & PAGE_MASK);
1816 free_gcr3_tbl_level1(ptr);
1820 static void free_gcr3_table(struct protection_domain *domain)
1822 if (domain->glx == 2)
1823 free_gcr3_tbl_level2(domain->gcr3_tbl);
1824 else if (domain->glx == 1)
1825 free_gcr3_tbl_level1(domain->gcr3_tbl);
1827 BUG_ON(domain->glx != 0);
1829 free_page((unsigned long)domain->gcr3_tbl);
1833 * Free a domain, only used if something went wrong in the
1834 * allocation path and we need to free an already allocated page table
1836 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1843 del_domain_from_list(&dom->domain);
1845 free_pagetable(&dom->domain);
1847 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1848 if (!dom->aperture[i])
1850 free_page((unsigned long)dom->aperture[i]->bitmap);
1851 kfree(dom->aperture[i]);
1858 * Allocates a new protection domain usable for the dma_ops functions.
1859 * It also initializes the page table and the address allocator data
1860 * structures required for the dma_ops interface
1862 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1864 struct dma_ops_domain *dma_dom;
1866 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1870 if (protection_domain_init(&dma_dom->domain))
1873 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1874 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1875 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1876 dma_dom->domain.priv = dma_dom;
1877 if (!dma_dom->domain.pt_root)
1880 add_domain_to_list(&dma_dom->domain);
1882 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1886 * mark the first page as allocated so we never return 0 as
1887 * a valid dma-address. So we can use 0 as error value
1889 dma_dom->aperture[0]->bitmap[0] = 1;
1890 dma_dom->next_index = 0;
1896 dma_ops_domain_free(dma_dom);
1902 * little helper function to check whether a given protection domain is a
1905 static bool dma_ops_domain(struct protection_domain *domain)
1907 return domain->flags & PD_DMA_OPS_MASK;
1910 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1915 if (domain->mode != PAGE_MODE_NONE)
1916 pte_root = virt_to_phys(domain->pt_root);
1918 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1919 << DEV_ENTRY_MODE_SHIFT;
1920 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1922 flags = amd_iommu_dev_table[devid].data[1];
1925 flags |= DTE_FLAG_IOTLB;
1927 if (domain->flags & PD_IOMMUV2_MASK) {
1928 u64 gcr3 = __pa(domain->gcr3_tbl);
1929 u64 glx = domain->glx;
1932 pte_root |= DTE_FLAG_GV;
1933 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1935 /* First mask out possible old values for GCR3 table */
1936 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1939 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1942 /* Encode GCR3 table into DTE */
1943 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1946 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1949 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
1953 flags &= ~(0xffffUL);
1954 flags |= domain->id;
1956 amd_iommu_dev_table[devid].data[1] = flags;
1957 amd_iommu_dev_table[devid].data[0] = pte_root;
1960 static void clear_dte_entry(u16 devid)
1962 /* remove entry from the device table seen by the hardware */
1963 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1964 amd_iommu_dev_table[devid].data[1] &= DTE_FLAG_MASK;
1966 amd_iommu_apply_erratum_63(devid);
1969 static void do_attach(struct iommu_dev_data *dev_data,
1970 struct protection_domain *domain)
1972 struct amd_iommu *iommu;
1976 iommu = amd_iommu_rlookup_table[dev_data->devid];
1977 alias = amd_iommu_alias_table[dev_data->devid];
1978 ats = dev_data->ats.enabled;
1980 /* Update data structures */
1981 dev_data->domain = domain;
1982 list_add(&dev_data->list, &domain->dev_list);
1984 /* Do reference counting */
1985 domain->dev_iommu[iommu->index] += 1;
1986 domain->dev_cnt += 1;
1988 /* Update device table */
1989 set_dte_entry(dev_data->devid, domain, ats);
1990 if (alias != dev_data->devid)
1991 set_dte_entry(dev_data->devid, domain, ats);
1993 device_flush_dte(dev_data);
1996 static void do_detach(struct iommu_dev_data *dev_data)
1998 struct amd_iommu *iommu;
2002 * First check if the device is still attached. It might already
2003 * be detached from its domain because the generic
2004 * iommu_detach_group code detached it and we try again here in
2005 * our alias handling.
2007 if (!dev_data->domain)
2010 iommu = amd_iommu_rlookup_table[dev_data->devid];
2011 alias = amd_iommu_alias_table[dev_data->devid];
2013 /* decrease reference counters */
2014 dev_data->domain->dev_iommu[iommu->index] -= 1;
2015 dev_data->domain->dev_cnt -= 1;
2017 /* Update data structures */
2018 dev_data->domain = NULL;
2019 list_del(&dev_data->list);
2020 clear_dte_entry(dev_data->devid);
2021 if (alias != dev_data->devid)
2022 clear_dte_entry(alias);
2024 /* Flush the DTE entry */
2025 device_flush_dte(dev_data);
2029 * If a device is not yet associated with a domain, this function does
2030 * assigns it visible for the hardware
2032 static int __attach_device(struct iommu_dev_data *dev_data,
2033 struct protection_domain *domain)
2038 * Must be called with IRQs disabled. Warn here to detect early
2041 WARN_ON(!irqs_disabled());
2044 spin_lock(&domain->lock);
2047 if (dev_data->domain != NULL)
2050 /* Attach alias group root */
2051 do_attach(dev_data, domain);
2058 spin_unlock(&domain->lock);
2064 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2066 pci_disable_ats(pdev);
2067 pci_disable_pri(pdev);
2068 pci_disable_pasid(pdev);
2071 /* FIXME: Change generic reset-function to do the same */
2072 static int pri_reset_while_enabled(struct pci_dev *pdev)
2077 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2081 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2082 control |= PCI_PRI_CTRL_RESET;
2083 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2088 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2093 /* FIXME: Hardcode number of outstanding requests for now */
2095 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2097 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2099 /* Only allow access to user-accessible pages */
2100 ret = pci_enable_pasid(pdev, 0);
2104 /* First reset the PRI state of the device */
2105 ret = pci_reset_pri(pdev);
2110 ret = pci_enable_pri(pdev, reqs);
2115 ret = pri_reset_while_enabled(pdev);
2120 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2127 pci_disable_pri(pdev);
2128 pci_disable_pasid(pdev);
2133 /* FIXME: Move this to PCI code */
2134 #define PCI_PRI_TLP_OFF (1 << 15)
2136 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2141 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2145 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2147 return (status & PCI_PRI_TLP_OFF) ? true : false;
2151 * If a device is not yet associated with a domain, this function
2152 * assigns it visible for the hardware
2154 static int attach_device(struct device *dev,
2155 struct protection_domain *domain)
2157 struct pci_dev *pdev = to_pci_dev(dev);
2158 struct iommu_dev_data *dev_data;
2159 unsigned long flags;
2162 dev_data = get_dev_data(dev);
2164 if (domain->flags & PD_IOMMUV2_MASK) {
2165 if (!dev_data->passthrough)
2168 if (dev_data->iommu_v2) {
2169 if (pdev_iommuv2_enable(pdev) != 0)
2172 dev_data->ats.enabled = true;
2173 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2174 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2176 } else if (amd_iommu_iotlb_sup &&
2177 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2178 dev_data->ats.enabled = true;
2179 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2182 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2183 ret = __attach_device(dev_data, domain);
2184 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2187 * We might boot into a crash-kernel here. The crashed kernel
2188 * left the caches in the IOMMU dirty. So we have to flush
2189 * here to evict all dirty stuff.
2191 domain_flush_tlb_pde(domain);
2197 * Removes a device from a protection domain (unlocked)
2199 static void __detach_device(struct iommu_dev_data *dev_data)
2201 struct protection_domain *domain;
2204 * Must be called with IRQs disabled. Warn here to detect early
2207 WARN_ON(!irqs_disabled());
2209 if (WARN_ON(!dev_data->domain))
2212 domain = dev_data->domain;
2214 spin_lock(&domain->lock);
2216 do_detach(dev_data);
2218 spin_unlock(&domain->lock);
2222 * Removes a device from a protection domain (with devtable_lock held)
2224 static void detach_device(struct device *dev)
2226 struct protection_domain *domain;
2227 struct iommu_dev_data *dev_data;
2228 unsigned long flags;
2230 dev_data = get_dev_data(dev);
2231 domain = dev_data->domain;
2233 /* lock device table */
2234 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2235 __detach_device(dev_data);
2236 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2238 if (domain->flags & PD_IOMMUV2_MASK && dev_data->iommu_v2)
2239 pdev_iommuv2_disable(to_pci_dev(dev));
2240 else if (dev_data->ats.enabled)
2241 pci_disable_ats(to_pci_dev(dev));
2243 dev_data->ats.enabled = false;
2246 static int amd_iommu_add_device(struct device *dev)
2248 struct iommu_dev_data *dev_data;
2249 struct iommu_domain *domain;
2250 struct amd_iommu *iommu;
2254 if (!check_device(dev) || get_dev_data(dev))
2257 devid = get_device_id(dev);
2258 iommu = amd_iommu_rlookup_table[devid];
2260 ret = iommu_init_device(dev);
2262 if (ret != -ENOTSUPP)
2263 pr_err("Failed to initialize device %s - trying to proceed anyway\n",
2266 iommu_ignore_device(dev);
2267 dev->archdata.dma_ops = &nommu_dma_ops;
2270 init_iommu_group(dev);
2272 dev_data = get_dev_data(dev);
2276 if (iommu_pass_through || dev_data->iommu_v2)
2277 iommu_request_dm_for_dev(dev);
2279 /* Domains are initialized for this device - have a look what we ended up with */
2280 domain = iommu_get_domain_for_dev(dev);
2281 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2282 dev_data->passthrough = true;
2284 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2287 iommu_completion_wait(iommu);
2292 static void amd_iommu_remove_device(struct device *dev)
2294 struct amd_iommu *iommu;
2297 if (!check_device(dev))
2300 devid = get_device_id(dev);
2301 iommu = amd_iommu_rlookup_table[devid];
2303 iommu_uninit_device(dev);
2304 iommu_completion_wait(iommu);
2307 /*****************************************************************************
2309 * The next functions belong to the dma_ops mapping/unmapping code.
2311 *****************************************************************************/
2314 * In the dma_ops path we only have the struct device. This function
2315 * finds the corresponding IOMMU, the protection domain and the
2316 * requestor id for a given device.
2317 * If the device is not yet associated with a domain this is also done
2320 static struct protection_domain *get_domain(struct device *dev)
2322 struct protection_domain *domain;
2323 struct iommu_domain *io_domain;
2325 if (!check_device(dev))
2326 return ERR_PTR(-EINVAL);
2328 io_domain = iommu_get_domain_for_dev(dev);
2332 domain = to_pdomain(io_domain);
2333 if (!dma_ops_domain(domain))
2334 return ERR_PTR(-EBUSY);
2339 static void update_device_table(struct protection_domain *domain)
2341 struct iommu_dev_data *dev_data;
2343 list_for_each_entry(dev_data, &domain->dev_list, list)
2344 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2347 static void update_domain(struct protection_domain *domain)
2349 if (!domain->updated)
2352 update_device_table(domain);
2354 domain_flush_devices(domain);
2355 domain_flush_tlb_pde(domain);
2357 domain->updated = false;
2361 * This function fetches the PTE for a given address in the aperture
2363 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2364 unsigned long address)
2366 struct aperture_range *aperture;
2367 u64 *pte, *pte_page;
2369 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2373 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2375 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2377 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2379 pte += PM_LEVEL_INDEX(0, address);
2381 update_domain(&dom->domain);
2387 * This is the generic map function. It maps one 4kb page at paddr to
2388 * the given address in the DMA address space for the domain.
2390 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2391 unsigned long address,
2397 WARN_ON(address > dom->aperture_size);
2401 pte = dma_ops_get_pte(dom, address);
2403 return DMA_ERROR_CODE;
2405 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2407 if (direction == DMA_TO_DEVICE)
2408 __pte |= IOMMU_PTE_IR;
2409 else if (direction == DMA_FROM_DEVICE)
2410 __pte |= IOMMU_PTE_IW;
2411 else if (direction == DMA_BIDIRECTIONAL)
2412 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2418 return (dma_addr_t)address;
2422 * The generic unmapping function for on page in the DMA address space.
2424 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2425 unsigned long address)
2427 struct aperture_range *aperture;
2430 if (address >= dom->aperture_size)
2433 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2437 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2441 pte += PM_LEVEL_INDEX(0, address);
2443 WARN_ON_ONCE(!*pte);
2449 * This function contains common code for mapping of a physically
2450 * contiguous memory region into DMA address space. It is used by all
2451 * mapping functions provided with this IOMMU driver.
2452 * Must be called with the domain lock held.
2454 static dma_addr_t __map_single(struct device *dev,
2455 struct dma_ops_domain *dma_dom,
2462 dma_addr_t offset = paddr & ~PAGE_MASK;
2463 dma_addr_t address, start, ret;
2465 unsigned long align_mask = 0;
2468 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2471 INC_STATS_COUNTER(total_map_requests);
2474 INC_STATS_COUNTER(cross_page);
2477 align_mask = (1UL << get_order(size)) - 1;
2479 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2482 if (address == DMA_ERROR_CODE)
2486 for (i = 0; i < pages; ++i) {
2487 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2488 if (ret == DMA_ERROR_CODE)
2496 ADD_STATS_COUNTER(alloced_io_mem, size);
2498 if (unlikely(amd_iommu_np_cache)) {
2499 domain_flush_pages(&dma_dom->domain, address, size);
2500 domain_flush_complete(&dma_dom->domain);
2508 for (--i; i >= 0; --i) {
2510 dma_ops_domain_unmap(dma_dom, start);
2513 dma_ops_free_addresses(dma_dom, address, pages);
2515 return DMA_ERROR_CODE;
2519 * Does the reverse of the __map_single function. Must be called with
2520 * the domain lock held too
2522 static void __unmap_single(struct dma_ops_domain *dma_dom,
2523 dma_addr_t dma_addr,
2527 dma_addr_t flush_addr;
2528 dma_addr_t i, start;
2531 if ((dma_addr == DMA_ERROR_CODE) ||
2532 (dma_addr + size > dma_dom->aperture_size))
2535 flush_addr = dma_addr;
2536 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2537 dma_addr &= PAGE_MASK;
2540 for (i = 0; i < pages; ++i) {
2541 dma_ops_domain_unmap(dma_dom, start);
2545 SUB_STATS_COUNTER(alloced_io_mem, size);
2547 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2551 * The exported map_single function for dma_ops.
2553 static dma_addr_t map_page(struct device *dev, struct page *page,
2554 unsigned long offset, size_t size,
2555 enum dma_data_direction dir,
2556 struct dma_attrs *attrs)
2558 unsigned long flags;
2559 struct protection_domain *domain;
2562 phys_addr_t paddr = page_to_phys(page) + offset;
2564 INC_STATS_COUNTER(cnt_map_single);
2566 domain = get_domain(dev);
2567 if (PTR_ERR(domain) == -EINVAL)
2568 return (dma_addr_t)paddr;
2569 else if (IS_ERR(domain))
2570 return DMA_ERROR_CODE;
2572 dma_mask = *dev->dma_mask;
2574 spin_lock_irqsave(&domain->lock, flags);
2576 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2578 if (addr == DMA_ERROR_CODE)
2581 domain_flush_complete(domain);
2584 spin_unlock_irqrestore(&domain->lock, flags);
2590 * The exported unmap_single function for dma_ops.
2592 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2593 enum dma_data_direction dir, struct dma_attrs *attrs)
2595 unsigned long flags;
2596 struct protection_domain *domain;
2598 INC_STATS_COUNTER(cnt_unmap_single);
2600 domain = get_domain(dev);
2604 spin_lock_irqsave(&domain->lock, flags);
2606 __unmap_single(domain->priv, dma_addr, size, dir);
2608 domain_flush_complete(domain);
2610 spin_unlock_irqrestore(&domain->lock, flags);
2614 * The exported map_sg function for dma_ops (handles scatter-gather
2617 static int map_sg(struct device *dev, struct scatterlist *sglist,
2618 int nelems, enum dma_data_direction dir,
2619 struct dma_attrs *attrs)
2621 unsigned long flags;
2622 struct protection_domain *domain;
2624 struct scatterlist *s;
2626 int mapped_elems = 0;
2629 INC_STATS_COUNTER(cnt_map_sg);
2631 domain = get_domain(dev);
2635 dma_mask = *dev->dma_mask;
2637 spin_lock_irqsave(&domain->lock, flags);
2639 for_each_sg(sglist, s, nelems, i) {
2642 s->dma_address = __map_single(dev, domain->priv,
2643 paddr, s->length, dir, false,
2646 if (s->dma_address) {
2647 s->dma_length = s->length;
2653 domain_flush_complete(domain);
2656 spin_unlock_irqrestore(&domain->lock, flags);
2658 return mapped_elems;
2660 for_each_sg(sglist, s, mapped_elems, i) {
2662 __unmap_single(domain->priv, s->dma_address,
2663 s->dma_length, dir);
2664 s->dma_address = s->dma_length = 0;
2673 * The exported map_sg function for dma_ops (handles scatter-gather
2676 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2677 int nelems, enum dma_data_direction dir,
2678 struct dma_attrs *attrs)
2680 unsigned long flags;
2681 struct protection_domain *domain;
2682 struct scatterlist *s;
2685 INC_STATS_COUNTER(cnt_unmap_sg);
2687 domain = get_domain(dev);
2691 spin_lock_irqsave(&domain->lock, flags);
2693 for_each_sg(sglist, s, nelems, i) {
2694 __unmap_single(domain->priv, s->dma_address,
2695 s->dma_length, dir);
2696 s->dma_address = s->dma_length = 0;
2699 domain_flush_complete(domain);
2701 spin_unlock_irqrestore(&domain->lock, flags);
2705 * The exported alloc_coherent function for dma_ops.
2707 static void *alloc_coherent(struct device *dev, size_t size,
2708 dma_addr_t *dma_addr, gfp_t flag,
2709 struct dma_attrs *attrs)
2711 u64 dma_mask = dev->coherent_dma_mask;
2712 struct protection_domain *domain;
2713 unsigned long flags;
2716 INC_STATS_COUNTER(cnt_alloc_coherent);
2718 domain = get_domain(dev);
2719 if (PTR_ERR(domain) == -EINVAL) {
2720 page = alloc_pages(flag, get_order(size));
2721 *dma_addr = page_to_phys(page);
2722 return page_address(page);
2723 } else if (IS_ERR(domain))
2726 size = PAGE_ALIGN(size);
2727 dma_mask = dev->coherent_dma_mask;
2728 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2731 page = alloc_pages(flag | __GFP_NOWARN, get_order(size));
2733 if (!gfpflags_allow_blocking(flag))
2736 page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
2743 dma_mask = *dev->dma_mask;
2745 spin_lock_irqsave(&domain->lock, flags);
2747 *dma_addr = __map_single(dev, domain->priv, page_to_phys(page),
2748 size, DMA_BIDIRECTIONAL, true, dma_mask);
2750 if (*dma_addr == DMA_ERROR_CODE) {
2751 spin_unlock_irqrestore(&domain->lock, flags);
2755 domain_flush_complete(domain);
2757 spin_unlock_irqrestore(&domain->lock, flags);
2759 return page_address(page);
2763 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2764 __free_pages(page, get_order(size));
2770 * The exported free_coherent function for dma_ops.
2772 static void free_coherent(struct device *dev, size_t size,
2773 void *virt_addr, dma_addr_t dma_addr,
2774 struct dma_attrs *attrs)
2776 struct protection_domain *domain;
2777 unsigned long flags;
2780 INC_STATS_COUNTER(cnt_free_coherent);
2782 page = virt_to_page(virt_addr);
2783 size = PAGE_ALIGN(size);
2785 domain = get_domain(dev);
2789 spin_lock_irqsave(&domain->lock, flags);
2791 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2793 domain_flush_complete(domain);
2795 spin_unlock_irqrestore(&domain->lock, flags);
2798 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2799 __free_pages(page, get_order(size));
2803 * This function is called by the DMA layer to find out if we can handle a
2804 * particular device. It is part of the dma_ops.
2806 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2808 return check_device(dev);
2811 static struct dma_map_ops amd_iommu_dma_ops = {
2812 .alloc = alloc_coherent,
2813 .free = free_coherent,
2814 .map_page = map_page,
2815 .unmap_page = unmap_page,
2817 .unmap_sg = unmap_sg,
2818 .dma_supported = amd_iommu_dma_supported,
2821 int __init amd_iommu_init_api(void)
2823 return bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2826 int __init amd_iommu_init_dma_ops(void)
2828 swiotlb = iommu_pass_through ? 1 : 0;
2832 * In case we don't initialize SWIOTLB (actually the common case
2833 * when AMD IOMMU is enabled), make sure there are global
2834 * dma_ops set as a fall-back for devices not handled by this
2835 * driver (for example non-PCI devices).
2838 dma_ops = &nommu_dma_ops;
2840 amd_iommu_stats_init();
2842 if (amd_iommu_unmap_flush)
2843 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
2845 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
2850 /*****************************************************************************
2852 * The following functions belong to the exported interface of AMD IOMMU
2854 * This interface allows access to lower level functions of the IOMMU
2855 * like protection domain handling and assignement of devices to domains
2856 * which is not possible with the dma_ops interface.
2858 *****************************************************************************/
2860 static void cleanup_domain(struct protection_domain *domain)
2862 struct iommu_dev_data *entry;
2863 unsigned long flags;
2865 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2867 while (!list_empty(&domain->dev_list)) {
2868 entry = list_first_entry(&domain->dev_list,
2869 struct iommu_dev_data, list);
2870 __detach_device(entry);
2873 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2876 static void protection_domain_free(struct protection_domain *domain)
2881 del_domain_from_list(domain);
2884 domain_id_free(domain->id);
2889 static int protection_domain_init(struct protection_domain *domain)
2891 spin_lock_init(&domain->lock);
2892 mutex_init(&domain->api_lock);
2893 domain->id = domain_id_alloc();
2896 INIT_LIST_HEAD(&domain->dev_list);
2901 static struct protection_domain *protection_domain_alloc(void)
2903 struct protection_domain *domain;
2905 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2909 if (protection_domain_init(domain))
2912 add_domain_to_list(domain);
2922 static struct iommu_domain *amd_iommu_domain_alloc(unsigned type)
2924 struct protection_domain *pdomain;
2925 struct dma_ops_domain *dma_domain;
2928 case IOMMU_DOMAIN_UNMANAGED:
2929 pdomain = protection_domain_alloc();
2933 pdomain->mode = PAGE_MODE_3_LEVEL;
2934 pdomain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2935 if (!pdomain->pt_root) {
2936 protection_domain_free(pdomain);
2940 pdomain->domain.geometry.aperture_start = 0;
2941 pdomain->domain.geometry.aperture_end = ~0ULL;
2942 pdomain->domain.geometry.force_aperture = true;
2945 case IOMMU_DOMAIN_DMA:
2946 dma_domain = dma_ops_domain_alloc();
2948 pr_err("AMD-Vi: Failed to allocate\n");
2951 pdomain = &dma_domain->domain;
2953 case IOMMU_DOMAIN_IDENTITY:
2954 pdomain = protection_domain_alloc();
2958 pdomain->mode = PAGE_MODE_NONE;
2964 return &pdomain->domain;
2967 static void amd_iommu_domain_free(struct iommu_domain *dom)
2969 struct protection_domain *domain;
2974 domain = to_pdomain(dom);
2976 if (domain->dev_cnt > 0)
2977 cleanup_domain(domain);
2979 BUG_ON(domain->dev_cnt != 0);
2981 if (domain->mode != PAGE_MODE_NONE)
2982 free_pagetable(domain);
2984 if (domain->flags & PD_IOMMUV2_MASK)
2985 free_gcr3_table(domain);
2987 protection_domain_free(domain);
2990 static void amd_iommu_detach_device(struct iommu_domain *dom,
2993 struct iommu_dev_data *dev_data = dev->archdata.iommu;
2994 struct amd_iommu *iommu;
2997 if (!check_device(dev))
3000 devid = get_device_id(dev);
3002 if (dev_data->domain != NULL)
3005 iommu = amd_iommu_rlookup_table[devid];
3009 iommu_completion_wait(iommu);
3012 static int amd_iommu_attach_device(struct iommu_domain *dom,
3015 struct protection_domain *domain = to_pdomain(dom);
3016 struct iommu_dev_data *dev_data;
3017 struct amd_iommu *iommu;
3020 if (!check_device(dev))
3023 dev_data = dev->archdata.iommu;
3025 iommu = amd_iommu_rlookup_table[dev_data->devid];
3029 if (dev_data->domain)
3032 ret = attach_device(dev, domain);
3034 iommu_completion_wait(iommu);
3039 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3040 phys_addr_t paddr, size_t page_size, int iommu_prot)
3042 struct protection_domain *domain = to_pdomain(dom);
3046 if (domain->mode == PAGE_MODE_NONE)
3049 if (iommu_prot & IOMMU_READ)
3050 prot |= IOMMU_PROT_IR;
3051 if (iommu_prot & IOMMU_WRITE)
3052 prot |= IOMMU_PROT_IW;
3054 mutex_lock(&domain->api_lock);
3055 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3056 mutex_unlock(&domain->api_lock);
3061 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3064 struct protection_domain *domain = to_pdomain(dom);
3067 if (domain->mode == PAGE_MODE_NONE)
3070 mutex_lock(&domain->api_lock);
3071 unmap_size = iommu_unmap_page(domain, iova, page_size);
3072 mutex_unlock(&domain->api_lock);
3074 domain_flush_tlb_pde(domain);
3079 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3082 struct protection_domain *domain = to_pdomain(dom);
3083 unsigned long offset_mask, pte_pgsize;
3086 if (domain->mode == PAGE_MODE_NONE)
3089 pte = fetch_pte(domain, iova, &pte_pgsize);
3091 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3094 offset_mask = pte_pgsize - 1;
3095 __pte = *pte & PM_ADDR_MASK;
3097 return (__pte & ~offset_mask) | (iova & offset_mask);
3100 static bool amd_iommu_capable(enum iommu_cap cap)
3103 case IOMMU_CAP_CACHE_COHERENCY:
3105 case IOMMU_CAP_INTR_REMAP:
3106 return (irq_remapping_enabled == 1);
3107 case IOMMU_CAP_NOEXEC:
3114 static void amd_iommu_get_dm_regions(struct device *dev,
3115 struct list_head *head)
3117 struct unity_map_entry *entry;
3120 devid = get_device_id(dev);
3122 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
3123 struct iommu_dm_region *region;
3125 if (devid < entry->devid_start || devid > entry->devid_end)
3128 region = kzalloc(sizeof(*region), GFP_KERNEL);
3130 pr_err("Out of memory allocating dm-regions for %s\n",
3135 region->start = entry->address_start;
3136 region->length = entry->address_end - entry->address_start;
3137 if (entry->prot & IOMMU_PROT_IR)
3138 region->prot |= IOMMU_READ;
3139 if (entry->prot & IOMMU_PROT_IW)
3140 region->prot |= IOMMU_WRITE;
3142 list_add_tail(®ion->list, head);
3146 static void amd_iommu_put_dm_regions(struct device *dev,
3147 struct list_head *head)
3149 struct iommu_dm_region *entry, *next;
3151 list_for_each_entry_safe(entry, next, head, list)
3155 static const struct iommu_ops amd_iommu_ops = {
3156 .capable = amd_iommu_capable,
3157 .domain_alloc = amd_iommu_domain_alloc,
3158 .domain_free = amd_iommu_domain_free,
3159 .attach_dev = amd_iommu_attach_device,
3160 .detach_dev = amd_iommu_detach_device,
3161 .map = amd_iommu_map,
3162 .unmap = amd_iommu_unmap,
3163 .map_sg = default_iommu_map_sg,
3164 .iova_to_phys = amd_iommu_iova_to_phys,
3165 .add_device = amd_iommu_add_device,
3166 .remove_device = amd_iommu_remove_device,
3167 .device_group = pci_device_group,
3168 .get_dm_regions = amd_iommu_get_dm_regions,
3169 .put_dm_regions = amd_iommu_put_dm_regions,
3170 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3173 /*****************************************************************************
3175 * The next functions do a basic initialization of IOMMU for pass through
3178 * In passthrough mode the IOMMU is initialized and enabled but not used for
3179 * DMA-API translation.
3181 *****************************************************************************/
3183 /* IOMMUv2 specific functions */
3184 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3186 return atomic_notifier_chain_register(&ppr_notifier, nb);
3188 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3190 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3192 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3194 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3196 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3198 struct protection_domain *domain = to_pdomain(dom);
3199 unsigned long flags;
3201 spin_lock_irqsave(&domain->lock, flags);
3203 /* Update data structure */
3204 domain->mode = PAGE_MODE_NONE;
3205 domain->updated = true;
3207 /* Make changes visible to IOMMUs */
3208 update_domain(domain);
3210 /* Page-table is not visible to IOMMU anymore, so free it */
3211 free_pagetable(domain);
3213 spin_unlock_irqrestore(&domain->lock, flags);
3215 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3217 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3219 struct protection_domain *domain = to_pdomain(dom);
3220 unsigned long flags;
3223 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3226 /* Number of GCR3 table levels required */
3227 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3230 if (levels > amd_iommu_max_glx_val)
3233 spin_lock_irqsave(&domain->lock, flags);
3236 * Save us all sanity checks whether devices already in the
3237 * domain support IOMMUv2. Just force that the domain has no
3238 * devices attached when it is switched into IOMMUv2 mode.
3241 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3245 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3246 if (domain->gcr3_tbl == NULL)
3249 domain->glx = levels;
3250 domain->flags |= PD_IOMMUV2_MASK;
3251 domain->updated = true;
3253 update_domain(domain);
3258 spin_unlock_irqrestore(&domain->lock, flags);
3262 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3264 static int __flush_pasid(struct protection_domain *domain, int pasid,
3265 u64 address, bool size)
3267 struct iommu_dev_data *dev_data;
3268 struct iommu_cmd cmd;
3271 if (!(domain->flags & PD_IOMMUV2_MASK))
3274 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3277 * IOMMU TLB needs to be flushed before Device TLB to
3278 * prevent device TLB refill from IOMMU TLB
3280 for (i = 0; i < amd_iommus_present; ++i) {
3281 if (domain->dev_iommu[i] == 0)
3284 ret = iommu_queue_command(amd_iommus[i], &cmd);
3289 /* Wait until IOMMU TLB flushes are complete */
3290 domain_flush_complete(domain);
3292 /* Now flush device TLBs */
3293 list_for_each_entry(dev_data, &domain->dev_list, list) {
3294 struct amd_iommu *iommu;
3298 There might be non-IOMMUv2 capable devices in an IOMMUv2
3301 if (!dev_data->ats.enabled)
3304 qdep = dev_data->ats.qdep;
3305 iommu = amd_iommu_rlookup_table[dev_data->devid];
3307 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3308 qdep, address, size);
3310 ret = iommu_queue_command(iommu, &cmd);
3315 /* Wait until all device TLBs are flushed */
3316 domain_flush_complete(domain);
3325 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3328 INC_STATS_COUNTER(invalidate_iotlb);
3330 return __flush_pasid(domain, pasid, address, false);
3333 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3336 struct protection_domain *domain = to_pdomain(dom);
3337 unsigned long flags;
3340 spin_lock_irqsave(&domain->lock, flags);
3341 ret = __amd_iommu_flush_page(domain, pasid, address);
3342 spin_unlock_irqrestore(&domain->lock, flags);
3346 EXPORT_SYMBOL(amd_iommu_flush_page);
3348 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3350 INC_STATS_COUNTER(invalidate_iotlb_all);
3352 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3356 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3358 struct protection_domain *domain = to_pdomain(dom);
3359 unsigned long flags;
3362 spin_lock_irqsave(&domain->lock, flags);
3363 ret = __amd_iommu_flush_tlb(domain, pasid);
3364 spin_unlock_irqrestore(&domain->lock, flags);
3368 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3370 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3377 index = (pasid >> (9 * level)) & 0x1ff;
3383 if (!(*pte & GCR3_VALID)) {
3387 root = (void *)get_zeroed_page(GFP_ATOMIC);
3391 *pte = __pa(root) | GCR3_VALID;
3394 root = __va(*pte & PAGE_MASK);
3402 static int __set_gcr3(struct protection_domain *domain, int pasid,
3407 if (domain->mode != PAGE_MODE_NONE)
3410 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3414 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3416 return __amd_iommu_flush_tlb(domain, pasid);
3419 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3423 if (domain->mode != PAGE_MODE_NONE)
3426 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3432 return __amd_iommu_flush_tlb(domain, pasid);
3435 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3438 struct protection_domain *domain = to_pdomain(dom);
3439 unsigned long flags;
3442 spin_lock_irqsave(&domain->lock, flags);
3443 ret = __set_gcr3(domain, pasid, cr3);
3444 spin_unlock_irqrestore(&domain->lock, flags);
3448 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3450 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3452 struct protection_domain *domain = to_pdomain(dom);
3453 unsigned long flags;
3456 spin_lock_irqsave(&domain->lock, flags);
3457 ret = __clear_gcr3(domain, pasid);
3458 spin_unlock_irqrestore(&domain->lock, flags);
3462 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3464 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3465 int status, int tag)
3467 struct iommu_dev_data *dev_data;
3468 struct amd_iommu *iommu;
3469 struct iommu_cmd cmd;
3471 INC_STATS_COUNTER(complete_ppr);
3473 dev_data = get_dev_data(&pdev->dev);
3474 iommu = amd_iommu_rlookup_table[dev_data->devid];
3476 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3477 tag, dev_data->pri_tlp);
3479 return iommu_queue_command(iommu, &cmd);
3481 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3483 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3485 struct protection_domain *pdomain;
3487 pdomain = get_domain(&pdev->dev);
3488 if (IS_ERR(pdomain))
3491 /* Only return IOMMUv2 domains */
3492 if (!(pdomain->flags & PD_IOMMUV2_MASK))
3495 return &pdomain->domain;
3497 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3499 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3501 struct iommu_dev_data *dev_data;
3503 if (!amd_iommu_v2_supported())
3506 dev_data = get_dev_data(&pdev->dev);
3507 dev_data->errata |= (1 << erratum);
3509 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3511 int amd_iommu_device_info(struct pci_dev *pdev,
3512 struct amd_iommu_device_info *info)
3517 if (pdev == NULL || info == NULL)
3520 if (!amd_iommu_v2_supported())
3523 memset(info, 0, sizeof(*info));
3525 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3527 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3529 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3531 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3533 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3537 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3538 max_pasids = min(max_pasids, (1 << 20));
3540 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3541 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3543 features = pci_pasid_features(pdev);
3544 if (features & PCI_PASID_CAP_EXEC)
3545 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3546 if (features & PCI_PASID_CAP_PRIV)
3547 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3552 EXPORT_SYMBOL(amd_iommu_device_info);
3554 #ifdef CONFIG_IRQ_REMAP
3556 /*****************************************************************************
3558 * Interrupt Remapping Implementation
3560 *****************************************************************************/
3578 u16 devid; /* Device ID for IRTE table */
3579 u16 index; /* Index into IRTE table*/
3582 struct amd_ir_data {
3583 struct irq_2_irte irq_2_irte;
3584 union irte irte_entry;
3586 struct msi_msg msi_entry;
3590 static struct irq_chip amd_ir_chip;
3592 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3593 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3594 #define DTE_IRQ_TABLE_LEN (8ULL << 1)
3595 #define DTE_IRQ_REMAP_ENABLE 1ULL
3597 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3601 dte = amd_iommu_dev_table[devid].data[2];
3602 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3603 dte |= virt_to_phys(table->table);
3604 dte |= DTE_IRQ_REMAP_INTCTL;
3605 dte |= DTE_IRQ_TABLE_LEN;
3606 dte |= DTE_IRQ_REMAP_ENABLE;
3608 amd_iommu_dev_table[devid].data[2] = dte;
3611 #define IRTE_ALLOCATED (~1U)
3613 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3615 struct irq_remap_table *table = NULL;
3616 struct amd_iommu *iommu;
3617 unsigned long flags;
3620 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3622 iommu = amd_iommu_rlookup_table[devid];
3626 table = irq_lookup_table[devid];
3630 alias = amd_iommu_alias_table[devid];
3631 table = irq_lookup_table[alias];
3633 irq_lookup_table[devid] = table;
3634 set_dte_irq_entry(devid, table);
3635 iommu_flush_dte(iommu, devid);
3639 /* Nothing there yet, allocate new irq remapping table */
3640 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3644 /* Initialize table spin-lock */
3645 spin_lock_init(&table->lock);
3648 /* Keep the first 32 indexes free for IOAPIC interrupts */
3649 table->min_index = 32;
3651 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3652 if (!table->table) {
3658 memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3663 for (i = 0; i < 32; ++i)
3664 table->table[i] = IRTE_ALLOCATED;
3667 irq_lookup_table[devid] = table;
3668 set_dte_irq_entry(devid, table);
3669 iommu_flush_dte(iommu, devid);
3670 if (devid != alias) {
3671 irq_lookup_table[alias] = table;
3672 set_dte_irq_entry(alias, table);
3673 iommu_flush_dte(iommu, alias);
3677 iommu_completion_wait(iommu);
3680 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3685 static int alloc_irq_index(u16 devid, int count)
3687 struct irq_remap_table *table;
3688 unsigned long flags;
3691 table = get_irq_table(devid, false);
3695 spin_lock_irqsave(&table->lock, flags);
3697 /* Scan table for free entries */
3698 for (c = 0, index = table->min_index;
3699 index < MAX_IRQS_PER_TABLE;
3701 if (table->table[index] == 0)
3708 table->table[index - c + 1] = IRTE_ALLOCATED;
3718 spin_unlock_irqrestore(&table->lock, flags);
3723 static int modify_irte(u16 devid, int index, union irte irte)
3725 struct irq_remap_table *table;
3726 struct amd_iommu *iommu;
3727 unsigned long flags;
3729 iommu = amd_iommu_rlookup_table[devid];
3733 table = get_irq_table(devid, false);
3737 spin_lock_irqsave(&table->lock, flags);
3738 table->table[index] = irte.val;
3739 spin_unlock_irqrestore(&table->lock, flags);
3741 iommu_flush_irt(iommu, devid);
3742 iommu_completion_wait(iommu);
3747 static void free_irte(u16 devid, int index)
3749 struct irq_remap_table *table;
3750 struct amd_iommu *iommu;
3751 unsigned long flags;
3753 iommu = amd_iommu_rlookup_table[devid];
3757 table = get_irq_table(devid, false);
3761 spin_lock_irqsave(&table->lock, flags);
3762 table->table[index] = 0;
3763 spin_unlock_irqrestore(&table->lock, flags);
3765 iommu_flush_irt(iommu, devid);
3766 iommu_completion_wait(iommu);
3769 static int get_devid(struct irq_alloc_info *info)
3773 switch (info->type) {
3774 case X86_IRQ_ALLOC_TYPE_IOAPIC:
3775 devid = get_ioapic_devid(info->ioapic_id);
3777 case X86_IRQ_ALLOC_TYPE_HPET:
3778 devid = get_hpet_devid(info->hpet_id);
3780 case X86_IRQ_ALLOC_TYPE_MSI:
3781 case X86_IRQ_ALLOC_TYPE_MSIX:
3782 devid = get_device_id(&info->msi_dev->dev);
3792 static struct irq_domain *get_ir_irq_domain(struct irq_alloc_info *info)
3794 struct amd_iommu *iommu;
3800 devid = get_devid(info);
3802 iommu = amd_iommu_rlookup_table[devid];
3804 return iommu->ir_domain;
3810 static struct irq_domain *get_irq_domain(struct irq_alloc_info *info)
3812 struct amd_iommu *iommu;
3818 switch (info->type) {
3819 case X86_IRQ_ALLOC_TYPE_MSI:
3820 case X86_IRQ_ALLOC_TYPE_MSIX:
3821 devid = get_device_id(&info->msi_dev->dev);
3823 iommu = amd_iommu_rlookup_table[devid];
3825 return iommu->msi_domain;
3835 struct irq_remap_ops amd_iommu_irq_ops = {
3836 .prepare = amd_iommu_prepare,
3837 .enable = amd_iommu_enable,
3838 .disable = amd_iommu_disable,
3839 .reenable = amd_iommu_reenable,
3840 .enable_faulting = amd_iommu_enable_faulting,
3841 .get_ir_irq_domain = get_ir_irq_domain,
3842 .get_irq_domain = get_irq_domain,
3845 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
3846 struct irq_cfg *irq_cfg,
3847 struct irq_alloc_info *info,
3848 int devid, int index, int sub_handle)
3850 struct irq_2_irte *irte_info = &data->irq_2_irte;
3851 struct msi_msg *msg = &data->msi_entry;
3852 union irte *irte = &data->irte_entry;
3853 struct IO_APIC_route_entry *entry;
3855 data->irq_2_irte.devid = devid;
3856 data->irq_2_irte.index = index + sub_handle;
3858 /* Setup IRTE for IOMMU */
3860 irte->fields.vector = irq_cfg->vector;
3861 irte->fields.int_type = apic->irq_delivery_mode;
3862 irte->fields.destination = irq_cfg->dest_apicid;
3863 irte->fields.dm = apic->irq_dest_mode;
3864 irte->fields.valid = 1;
3866 switch (info->type) {
3867 case X86_IRQ_ALLOC_TYPE_IOAPIC:
3868 /* Setup IOAPIC entry */
3869 entry = info->ioapic_entry;
3870 info->ioapic_entry = NULL;
3871 memset(entry, 0, sizeof(*entry));
3872 entry->vector = index;
3874 entry->trigger = info->ioapic_trigger;
3875 entry->polarity = info->ioapic_polarity;
3876 /* Mask level triggered irqs. */
3877 if (info->ioapic_trigger)
3881 case X86_IRQ_ALLOC_TYPE_HPET:
3882 case X86_IRQ_ALLOC_TYPE_MSI:
3883 case X86_IRQ_ALLOC_TYPE_MSIX:
3884 msg->address_hi = MSI_ADDR_BASE_HI;
3885 msg->address_lo = MSI_ADDR_BASE_LO;
3886 msg->data = irte_info->index;
3895 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
3896 unsigned int nr_irqs, void *arg)
3898 struct irq_alloc_info *info = arg;
3899 struct irq_data *irq_data;
3900 struct amd_ir_data *data;
3901 struct irq_cfg *cfg;
3907 if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_MSI &&
3908 info->type != X86_IRQ_ALLOC_TYPE_MSIX)
3912 * With IRQ remapping enabled, don't need contiguous CPU vectors
3913 * to support multiple MSI interrupts.
3915 if (info->type == X86_IRQ_ALLOC_TYPE_MSI)
3916 info->flags &= ~X86_IRQ_ALLOC_CONTIGUOUS_VECTORS;
3918 devid = get_devid(info);
3922 ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
3926 if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
3927 if (get_irq_table(devid, true))
3928 index = info->ioapic_pin;
3932 index = alloc_irq_index(devid, nr_irqs);
3935 pr_warn("Failed to allocate IRTE\n");
3936 goto out_free_parent;
3939 for (i = 0; i < nr_irqs; i++) {
3940 irq_data = irq_domain_get_irq_data(domain, virq + i);
3941 cfg = irqd_cfg(irq_data);
3942 if (!irq_data || !cfg) {
3948 data = kzalloc(sizeof(*data), GFP_KERNEL);
3952 irq_data->hwirq = (devid << 16) + i;
3953 irq_data->chip_data = data;
3954 irq_data->chip = &amd_ir_chip;
3955 irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
3956 irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
3962 for (i--; i >= 0; i--) {
3963 irq_data = irq_domain_get_irq_data(domain, virq + i);
3965 kfree(irq_data->chip_data);
3967 for (i = 0; i < nr_irqs; i++)
3968 free_irte(devid, index + i);
3970 irq_domain_free_irqs_common(domain, virq, nr_irqs);
3974 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
3975 unsigned int nr_irqs)
3977 struct irq_2_irte *irte_info;
3978 struct irq_data *irq_data;
3979 struct amd_ir_data *data;
3982 for (i = 0; i < nr_irqs; i++) {
3983 irq_data = irq_domain_get_irq_data(domain, virq + i);
3984 if (irq_data && irq_data->chip_data) {
3985 data = irq_data->chip_data;
3986 irte_info = &data->irq_2_irte;
3987 free_irte(irte_info->devid, irte_info->index);
3991 irq_domain_free_irqs_common(domain, virq, nr_irqs);
3994 static void irq_remapping_activate(struct irq_domain *domain,
3995 struct irq_data *irq_data)
3997 struct amd_ir_data *data = irq_data->chip_data;
3998 struct irq_2_irte *irte_info = &data->irq_2_irte;
4000 modify_irte(irte_info->devid, irte_info->index, data->irte_entry);
4003 static void irq_remapping_deactivate(struct irq_domain *domain,
4004 struct irq_data *irq_data)
4006 struct amd_ir_data *data = irq_data->chip_data;
4007 struct irq_2_irte *irte_info = &data->irq_2_irte;
4011 modify_irte(irte_info->devid, irte_info->index, data->irte_entry);
4014 static struct irq_domain_ops amd_ir_domain_ops = {
4015 .alloc = irq_remapping_alloc,
4016 .free = irq_remapping_free,
4017 .activate = irq_remapping_activate,
4018 .deactivate = irq_remapping_deactivate,
4021 static int amd_ir_set_affinity(struct irq_data *data,
4022 const struct cpumask *mask, bool force)
4024 struct amd_ir_data *ir_data = data->chip_data;
4025 struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4026 struct irq_cfg *cfg = irqd_cfg(data);
4027 struct irq_data *parent = data->parent_data;
4030 ret = parent->chip->irq_set_affinity(parent, mask, force);
4031 if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
4035 * Atomically updates the IRTE with the new destination, vector
4036 * and flushes the interrupt entry cache.
4038 ir_data->irte_entry.fields.vector = cfg->vector;
4039 ir_data->irte_entry.fields.destination = cfg->dest_apicid;
4040 modify_irte(irte_info->devid, irte_info->index, ir_data->irte_entry);
4043 * After this point, all the interrupts will start arriving
4044 * at the new destination. So, time to cleanup the previous
4045 * vector allocation.
4047 send_cleanup_vector(cfg);
4049 return IRQ_SET_MASK_OK_DONE;
4052 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
4054 struct amd_ir_data *ir_data = irq_data->chip_data;
4056 *msg = ir_data->msi_entry;
4059 static struct irq_chip amd_ir_chip = {
4060 .irq_ack = ir_ack_apic_edge,
4061 .irq_set_affinity = amd_ir_set_affinity,
4062 .irq_compose_msi_msg = ir_compose_msi_msg,
4065 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
4067 iommu->ir_domain = irq_domain_add_tree(NULL, &amd_ir_domain_ops, iommu);
4068 if (!iommu->ir_domain)
4071 iommu->ir_domain->parent = arch_get_ir_parent_domain();
4072 iommu->msi_domain = arch_create_msi_irq_domain(iommu->ir_domain);