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 /* address we start to search for free addresses */
150 unsigned long next_address;
152 /* address space relevant data */
153 struct aperture_range *aperture[APERTURE_MAX_RANGES];
155 /* This will be set to true when TLB needs to be flushed */
159 /****************************************************************************
163 ****************************************************************************/
165 static struct protection_domain *to_pdomain(struct iommu_domain *dom)
167 return container_of(dom, struct protection_domain, domain);
170 static struct iommu_dev_data *alloc_dev_data(u16 devid)
172 struct iommu_dev_data *dev_data;
175 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
179 dev_data->devid = devid;
181 spin_lock_irqsave(&dev_data_list_lock, flags);
182 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
183 spin_unlock_irqrestore(&dev_data_list_lock, flags);
188 static struct iommu_dev_data *search_dev_data(u16 devid)
190 struct iommu_dev_data *dev_data;
193 spin_lock_irqsave(&dev_data_list_lock, flags);
194 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
195 if (dev_data->devid == devid)
202 spin_unlock_irqrestore(&dev_data_list_lock, flags);
207 static struct iommu_dev_data *find_dev_data(u16 devid)
209 struct iommu_dev_data *dev_data;
211 dev_data = search_dev_data(devid);
213 if (dev_data == NULL)
214 dev_data = alloc_dev_data(devid);
219 static inline u16 get_device_id(struct device *dev)
221 struct pci_dev *pdev = to_pci_dev(dev);
223 return PCI_DEVID(pdev->bus->number, pdev->devfn);
226 static struct iommu_dev_data *get_dev_data(struct device *dev)
228 return dev->archdata.iommu;
231 static bool pci_iommuv2_capable(struct pci_dev *pdev)
233 static const int caps[] = {
236 PCI_EXT_CAP_ID_PASID,
240 for (i = 0; i < 3; ++i) {
241 pos = pci_find_ext_capability(pdev, caps[i]);
249 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
251 struct iommu_dev_data *dev_data;
253 dev_data = get_dev_data(&pdev->dev);
255 return dev_data->errata & (1 << erratum) ? true : false;
259 * This function actually applies the mapping to the page table of the
262 static void alloc_unity_mapping(struct dma_ops_domain *dma_dom,
263 struct unity_map_entry *e)
267 for (addr = e->address_start; addr < e->address_end;
269 if (addr < dma_dom->aperture_size)
270 __set_bit(addr >> PAGE_SHIFT,
271 dma_dom->aperture[0]->bitmap);
276 * Inits the unity mappings required for a specific device
278 static void init_unity_mappings_for_device(struct device *dev,
279 struct dma_ops_domain *dma_dom)
281 struct unity_map_entry *e;
284 devid = get_device_id(dev);
286 list_for_each_entry(e, &amd_iommu_unity_map, list) {
287 if (!(devid >= e->devid_start && devid <= e->devid_end))
289 alloc_unity_mapping(dma_dom, e);
294 * This function checks if the driver got a valid device from the caller to
295 * avoid dereferencing invalid pointers.
297 static bool check_device(struct device *dev)
301 if (!dev || !dev->dma_mask)
305 if (!dev_is_pci(dev))
308 devid = get_device_id(dev);
310 /* Out of our scope? */
311 if (devid > amd_iommu_last_bdf)
314 if (amd_iommu_rlookup_table[devid] == NULL)
320 static void init_iommu_group(struct device *dev)
322 struct dma_ops_domain *dma_domain;
323 struct iommu_domain *domain;
324 struct iommu_group *group;
326 group = iommu_group_get_for_dev(dev);
330 domain = iommu_group_default_domain(group);
334 dma_domain = to_pdomain(domain)->priv;
336 init_unity_mappings_for_device(dev, dma_domain);
338 iommu_group_put(group);
341 static int iommu_init_device(struct device *dev)
343 struct pci_dev *pdev = to_pci_dev(dev);
344 struct iommu_dev_data *dev_data;
346 if (dev->archdata.iommu)
349 dev_data = find_dev_data(get_device_id(dev));
353 if (pci_iommuv2_capable(pdev)) {
354 struct amd_iommu *iommu;
356 iommu = amd_iommu_rlookup_table[dev_data->devid];
357 dev_data->iommu_v2 = iommu->is_iommu_v2;
360 dev->archdata.iommu = dev_data;
362 iommu_device_link(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
368 static void iommu_ignore_device(struct device *dev)
372 devid = get_device_id(dev);
373 alias = amd_iommu_alias_table[devid];
375 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
376 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
378 amd_iommu_rlookup_table[devid] = NULL;
379 amd_iommu_rlookup_table[alias] = NULL;
382 static void iommu_uninit_device(struct device *dev)
384 struct iommu_dev_data *dev_data = search_dev_data(get_device_id(dev));
389 iommu_device_unlink(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
392 iommu_group_remove_device(dev);
395 dev->archdata.dma_ops = NULL;
398 * We keep dev_data around for unplugged devices and reuse it when the
399 * device is re-plugged - not doing so would introduce a ton of races.
403 #ifdef CONFIG_AMD_IOMMU_STATS
406 * Initialization code for statistics collection
409 DECLARE_STATS_COUNTER(compl_wait);
410 DECLARE_STATS_COUNTER(cnt_map_single);
411 DECLARE_STATS_COUNTER(cnt_unmap_single);
412 DECLARE_STATS_COUNTER(cnt_map_sg);
413 DECLARE_STATS_COUNTER(cnt_unmap_sg);
414 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
415 DECLARE_STATS_COUNTER(cnt_free_coherent);
416 DECLARE_STATS_COUNTER(cross_page);
417 DECLARE_STATS_COUNTER(domain_flush_single);
418 DECLARE_STATS_COUNTER(domain_flush_all);
419 DECLARE_STATS_COUNTER(alloced_io_mem);
420 DECLARE_STATS_COUNTER(total_map_requests);
421 DECLARE_STATS_COUNTER(complete_ppr);
422 DECLARE_STATS_COUNTER(invalidate_iotlb);
423 DECLARE_STATS_COUNTER(invalidate_iotlb_all);
424 DECLARE_STATS_COUNTER(pri_requests);
426 static struct dentry *stats_dir;
427 static struct dentry *de_fflush;
429 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
431 if (stats_dir == NULL)
434 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
438 static void amd_iommu_stats_init(void)
440 stats_dir = debugfs_create_dir("amd-iommu", NULL);
441 if (stats_dir == NULL)
444 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
445 &amd_iommu_unmap_flush);
447 amd_iommu_stats_add(&compl_wait);
448 amd_iommu_stats_add(&cnt_map_single);
449 amd_iommu_stats_add(&cnt_unmap_single);
450 amd_iommu_stats_add(&cnt_map_sg);
451 amd_iommu_stats_add(&cnt_unmap_sg);
452 amd_iommu_stats_add(&cnt_alloc_coherent);
453 amd_iommu_stats_add(&cnt_free_coherent);
454 amd_iommu_stats_add(&cross_page);
455 amd_iommu_stats_add(&domain_flush_single);
456 amd_iommu_stats_add(&domain_flush_all);
457 amd_iommu_stats_add(&alloced_io_mem);
458 amd_iommu_stats_add(&total_map_requests);
459 amd_iommu_stats_add(&complete_ppr);
460 amd_iommu_stats_add(&invalidate_iotlb);
461 amd_iommu_stats_add(&invalidate_iotlb_all);
462 amd_iommu_stats_add(&pri_requests);
467 /****************************************************************************
469 * Interrupt handling functions
471 ****************************************************************************/
473 static void dump_dte_entry(u16 devid)
477 for (i = 0; i < 4; ++i)
478 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
479 amd_iommu_dev_table[devid].data[i]);
482 static void dump_command(unsigned long phys_addr)
484 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
487 for (i = 0; i < 4; ++i)
488 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
491 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
493 int type, devid, domid, flags;
494 volatile u32 *event = __evt;
499 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
500 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
501 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
502 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
503 address = (u64)(((u64)event[3]) << 32) | event[2];
506 /* Did we hit the erratum? */
507 if (++count == LOOP_TIMEOUT) {
508 pr_err("AMD-Vi: No event written to event log\n");
515 printk(KERN_ERR "AMD-Vi: Event logged [");
518 case EVENT_TYPE_ILL_DEV:
519 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
520 "address=0x%016llx flags=0x%04x]\n",
521 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
523 dump_dte_entry(devid);
525 case EVENT_TYPE_IO_FAULT:
526 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
527 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
528 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
529 domid, address, flags);
531 case EVENT_TYPE_DEV_TAB_ERR:
532 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
533 "address=0x%016llx flags=0x%04x]\n",
534 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
537 case EVENT_TYPE_PAGE_TAB_ERR:
538 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
539 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
540 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
541 domid, address, flags);
543 case EVENT_TYPE_ILL_CMD:
544 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
545 dump_command(address);
547 case EVENT_TYPE_CMD_HARD_ERR:
548 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
549 "flags=0x%04x]\n", address, flags);
551 case EVENT_TYPE_IOTLB_INV_TO:
552 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
553 "address=0x%016llx]\n",
554 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
557 case EVENT_TYPE_INV_DEV_REQ:
558 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
559 "address=0x%016llx flags=0x%04x]\n",
560 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
564 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
567 memset(__evt, 0, 4 * sizeof(u32));
570 static void iommu_poll_events(struct amd_iommu *iommu)
574 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
575 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
577 while (head != tail) {
578 iommu_print_event(iommu, iommu->evt_buf + head);
579 head = (head + EVENT_ENTRY_SIZE) % EVT_BUFFER_SIZE;
582 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
585 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
587 struct amd_iommu_fault fault;
589 INC_STATS_COUNTER(pri_requests);
591 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
592 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
596 fault.address = raw[1];
597 fault.pasid = PPR_PASID(raw[0]);
598 fault.device_id = PPR_DEVID(raw[0]);
599 fault.tag = PPR_TAG(raw[0]);
600 fault.flags = PPR_FLAGS(raw[0]);
602 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
605 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
609 if (iommu->ppr_log == NULL)
612 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
613 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
615 while (head != tail) {
620 raw = (u64 *)(iommu->ppr_log + head);
623 * Hardware bug: Interrupt may arrive before the entry is
624 * written to memory. If this happens we need to wait for the
627 for (i = 0; i < LOOP_TIMEOUT; ++i) {
628 if (PPR_REQ_TYPE(raw[0]) != 0)
633 /* Avoid memcpy function-call overhead */
638 * To detect the hardware bug we need to clear the entry
641 raw[0] = raw[1] = 0UL;
643 /* Update head pointer of hardware ring-buffer */
644 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
645 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
647 /* Handle PPR entry */
648 iommu_handle_ppr_entry(iommu, entry);
650 /* Refresh ring-buffer information */
651 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
652 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
656 irqreturn_t amd_iommu_int_thread(int irq, void *data)
658 struct amd_iommu *iommu = (struct amd_iommu *) data;
659 u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
661 while (status & (MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK)) {
662 /* Enable EVT and PPR interrupts again */
663 writel((MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK),
664 iommu->mmio_base + MMIO_STATUS_OFFSET);
666 if (status & MMIO_STATUS_EVT_INT_MASK) {
667 pr_devel("AMD-Vi: Processing IOMMU Event Log\n");
668 iommu_poll_events(iommu);
671 if (status & MMIO_STATUS_PPR_INT_MASK) {
672 pr_devel("AMD-Vi: Processing IOMMU PPR Log\n");
673 iommu_poll_ppr_log(iommu);
677 * Hardware bug: ERBT1312
678 * When re-enabling interrupt (by writing 1
679 * to clear the bit), the hardware might also try to set
680 * the interrupt bit in the event status register.
681 * In this scenario, the bit will be set, and disable
682 * subsequent interrupts.
684 * Workaround: The IOMMU driver should read back the
685 * status register and check if the interrupt bits are cleared.
686 * If not, driver will need to go through the interrupt handler
687 * again and re-clear the bits
689 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
694 irqreturn_t amd_iommu_int_handler(int irq, void *data)
696 return IRQ_WAKE_THREAD;
699 /****************************************************************************
701 * IOMMU command queuing functions
703 ****************************************************************************/
705 static int wait_on_sem(volatile u64 *sem)
709 while (*sem == 0 && i < LOOP_TIMEOUT) {
714 if (i == LOOP_TIMEOUT) {
715 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
722 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
723 struct iommu_cmd *cmd,
728 target = iommu->cmd_buf + tail;
729 tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
731 /* Copy command to buffer */
732 memcpy(target, cmd, sizeof(*cmd));
734 /* Tell the IOMMU about it */
735 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
738 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
740 WARN_ON(address & 0x7ULL);
742 memset(cmd, 0, sizeof(*cmd));
743 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
744 cmd->data[1] = upper_32_bits(__pa(address));
746 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
749 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
751 memset(cmd, 0, sizeof(*cmd));
752 cmd->data[0] = devid;
753 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
756 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
757 size_t size, u16 domid, int pde)
762 pages = iommu_num_pages(address, size, PAGE_SIZE);
767 * If we have to flush more than one page, flush all
768 * TLB entries for this domain
770 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
774 address &= PAGE_MASK;
776 memset(cmd, 0, sizeof(*cmd));
777 cmd->data[1] |= domid;
778 cmd->data[2] = lower_32_bits(address);
779 cmd->data[3] = upper_32_bits(address);
780 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
781 if (s) /* size bit - we flush more than one 4kb page */
782 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
783 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
784 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
787 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
788 u64 address, size_t size)
793 pages = iommu_num_pages(address, size, PAGE_SIZE);
798 * If we have to flush more than one page, flush all
799 * TLB entries for this domain
801 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
805 address &= PAGE_MASK;
807 memset(cmd, 0, sizeof(*cmd));
808 cmd->data[0] = devid;
809 cmd->data[0] |= (qdep & 0xff) << 24;
810 cmd->data[1] = devid;
811 cmd->data[2] = lower_32_bits(address);
812 cmd->data[3] = upper_32_bits(address);
813 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
815 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
818 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
819 u64 address, bool size)
821 memset(cmd, 0, sizeof(*cmd));
823 address &= ~(0xfffULL);
825 cmd->data[0] = pasid;
826 cmd->data[1] = domid;
827 cmd->data[2] = lower_32_bits(address);
828 cmd->data[3] = upper_32_bits(address);
829 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
830 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
832 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
833 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
836 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
837 int qdep, u64 address, bool size)
839 memset(cmd, 0, sizeof(*cmd));
841 address &= ~(0xfffULL);
843 cmd->data[0] = devid;
844 cmd->data[0] |= ((pasid >> 8) & 0xff) << 16;
845 cmd->data[0] |= (qdep & 0xff) << 24;
846 cmd->data[1] = devid;
847 cmd->data[1] |= (pasid & 0xff) << 16;
848 cmd->data[2] = lower_32_bits(address);
849 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
850 cmd->data[3] = upper_32_bits(address);
852 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
853 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
856 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
857 int status, int tag, bool gn)
859 memset(cmd, 0, sizeof(*cmd));
861 cmd->data[0] = devid;
863 cmd->data[1] = pasid;
864 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
866 cmd->data[3] = tag & 0x1ff;
867 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
869 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
872 static void build_inv_all(struct iommu_cmd *cmd)
874 memset(cmd, 0, sizeof(*cmd));
875 CMD_SET_TYPE(cmd, CMD_INV_ALL);
878 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
880 memset(cmd, 0, sizeof(*cmd));
881 cmd->data[0] = devid;
882 CMD_SET_TYPE(cmd, CMD_INV_IRT);
886 * Writes the command to the IOMMUs command buffer and informs the
887 * hardware about the new command.
889 static int iommu_queue_command_sync(struct amd_iommu *iommu,
890 struct iommu_cmd *cmd,
893 u32 left, tail, head, next_tail;
897 spin_lock_irqsave(&iommu->lock, flags);
899 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
900 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
901 next_tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
902 left = (head - next_tail) % CMD_BUFFER_SIZE;
905 struct iommu_cmd sync_cmd;
906 volatile u64 sem = 0;
909 build_completion_wait(&sync_cmd, (u64)&sem);
910 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
912 spin_unlock_irqrestore(&iommu->lock, flags);
914 if ((ret = wait_on_sem(&sem)) != 0)
920 copy_cmd_to_buffer(iommu, cmd, tail);
922 /* We need to sync now to make sure all commands are processed */
923 iommu->need_sync = sync;
925 spin_unlock_irqrestore(&iommu->lock, flags);
930 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
932 return iommu_queue_command_sync(iommu, cmd, true);
936 * This function queues a completion wait command into the command
939 static int iommu_completion_wait(struct amd_iommu *iommu)
941 struct iommu_cmd cmd;
942 volatile u64 sem = 0;
945 if (!iommu->need_sync)
948 build_completion_wait(&cmd, (u64)&sem);
950 ret = iommu_queue_command_sync(iommu, &cmd, false);
954 return wait_on_sem(&sem);
957 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
959 struct iommu_cmd cmd;
961 build_inv_dte(&cmd, devid);
963 return iommu_queue_command(iommu, &cmd);
966 static void iommu_flush_dte_all(struct amd_iommu *iommu)
970 for (devid = 0; devid <= 0xffff; ++devid)
971 iommu_flush_dte(iommu, devid);
973 iommu_completion_wait(iommu);
977 * This function uses heavy locking and may disable irqs for some time. But
978 * this is no issue because it is only called during resume.
980 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
984 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
985 struct iommu_cmd cmd;
986 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
988 iommu_queue_command(iommu, &cmd);
991 iommu_completion_wait(iommu);
994 static void iommu_flush_all(struct amd_iommu *iommu)
996 struct iommu_cmd cmd;
1000 iommu_queue_command(iommu, &cmd);
1001 iommu_completion_wait(iommu);
1004 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1006 struct iommu_cmd cmd;
1008 build_inv_irt(&cmd, devid);
1010 iommu_queue_command(iommu, &cmd);
1013 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1017 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1018 iommu_flush_irt(iommu, devid);
1020 iommu_completion_wait(iommu);
1023 void iommu_flush_all_caches(struct amd_iommu *iommu)
1025 if (iommu_feature(iommu, FEATURE_IA)) {
1026 iommu_flush_all(iommu);
1028 iommu_flush_dte_all(iommu);
1029 iommu_flush_irt_all(iommu);
1030 iommu_flush_tlb_all(iommu);
1035 * Command send function for flushing on-device TLB
1037 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1038 u64 address, size_t size)
1040 struct amd_iommu *iommu;
1041 struct iommu_cmd cmd;
1044 qdep = dev_data->ats.qdep;
1045 iommu = amd_iommu_rlookup_table[dev_data->devid];
1047 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1049 return iommu_queue_command(iommu, &cmd);
1053 * Command send function for invalidating a device table entry
1055 static int device_flush_dte(struct iommu_dev_data *dev_data)
1057 struct amd_iommu *iommu;
1061 iommu = amd_iommu_rlookup_table[dev_data->devid];
1062 alias = amd_iommu_alias_table[dev_data->devid];
1064 ret = iommu_flush_dte(iommu, dev_data->devid);
1065 if (!ret && alias != dev_data->devid)
1066 ret = iommu_flush_dte(iommu, alias);
1070 if (dev_data->ats.enabled)
1071 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1077 * TLB invalidation function which is called from the mapping functions.
1078 * It invalidates a single PTE if the range to flush is within a single
1079 * page. Otherwise it flushes the whole TLB of the IOMMU.
1081 static void __domain_flush_pages(struct protection_domain *domain,
1082 u64 address, size_t size, int pde)
1084 struct iommu_dev_data *dev_data;
1085 struct iommu_cmd cmd;
1088 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1090 for (i = 0; i < amd_iommus_present; ++i) {
1091 if (!domain->dev_iommu[i])
1095 * Devices of this domain are behind this IOMMU
1096 * We need a TLB flush
1098 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1101 list_for_each_entry(dev_data, &domain->dev_list, list) {
1103 if (!dev_data->ats.enabled)
1106 ret |= device_flush_iotlb(dev_data, address, size);
1112 static void domain_flush_pages(struct protection_domain *domain,
1113 u64 address, size_t size)
1115 __domain_flush_pages(domain, address, size, 0);
1118 /* Flush the whole IO/TLB for a given protection domain */
1119 static void domain_flush_tlb(struct protection_domain *domain)
1121 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1124 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1125 static void domain_flush_tlb_pde(struct protection_domain *domain)
1127 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1130 static void domain_flush_complete(struct protection_domain *domain)
1134 for (i = 0; i < amd_iommus_present; ++i) {
1135 if (!domain->dev_iommu[i])
1139 * Devices of this domain are behind this IOMMU
1140 * We need to wait for completion of all commands.
1142 iommu_completion_wait(amd_iommus[i]);
1148 * This function flushes the DTEs for all devices in domain
1150 static void domain_flush_devices(struct protection_domain *domain)
1152 struct iommu_dev_data *dev_data;
1154 list_for_each_entry(dev_data, &domain->dev_list, list)
1155 device_flush_dte(dev_data);
1158 /****************************************************************************
1160 * The functions below are used the create the page table mappings for
1161 * unity mapped regions.
1163 ****************************************************************************/
1166 * This function is used to add another level to an IO page table. Adding
1167 * another level increases the size of the address space by 9 bits to a size up
1170 static bool increase_address_space(struct protection_domain *domain,
1175 if (domain->mode == PAGE_MODE_6_LEVEL)
1176 /* address space already 64 bit large */
1179 pte = (void *)get_zeroed_page(gfp);
1183 *pte = PM_LEVEL_PDE(domain->mode,
1184 virt_to_phys(domain->pt_root));
1185 domain->pt_root = pte;
1187 domain->updated = true;
1192 static u64 *alloc_pte(struct protection_domain *domain,
1193 unsigned long address,
1194 unsigned long page_size,
1201 BUG_ON(!is_power_of_2(page_size));
1203 while (address > PM_LEVEL_SIZE(domain->mode))
1204 increase_address_space(domain, gfp);
1206 level = domain->mode - 1;
1207 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1208 address = PAGE_SIZE_ALIGN(address, page_size);
1209 end_lvl = PAGE_SIZE_LEVEL(page_size);
1211 while (level > end_lvl) {
1212 if (!IOMMU_PTE_PRESENT(*pte)) {
1213 page = (u64 *)get_zeroed_page(gfp);
1216 *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1219 /* No level skipping support yet */
1220 if (PM_PTE_LEVEL(*pte) != level)
1225 pte = IOMMU_PTE_PAGE(*pte);
1227 if (pte_page && level == end_lvl)
1230 pte = &pte[PM_LEVEL_INDEX(level, address)];
1237 * This function checks if there is a PTE for a given dma address. If
1238 * there is one, it returns the pointer to it.
1240 static u64 *fetch_pte(struct protection_domain *domain,
1241 unsigned long address,
1242 unsigned long *page_size)
1247 if (address > PM_LEVEL_SIZE(domain->mode))
1250 level = domain->mode - 1;
1251 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1252 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1257 if (!IOMMU_PTE_PRESENT(*pte))
1261 if (PM_PTE_LEVEL(*pte) == 7 ||
1262 PM_PTE_LEVEL(*pte) == 0)
1265 /* No level skipping support yet */
1266 if (PM_PTE_LEVEL(*pte) != level)
1271 /* Walk to the next level */
1272 pte = IOMMU_PTE_PAGE(*pte);
1273 pte = &pte[PM_LEVEL_INDEX(level, address)];
1274 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1277 if (PM_PTE_LEVEL(*pte) == 0x07) {
1278 unsigned long pte_mask;
1281 * If we have a series of large PTEs, make
1282 * sure to return a pointer to the first one.
1284 *page_size = pte_mask = PTE_PAGE_SIZE(*pte);
1285 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1286 pte = (u64 *)(((unsigned long)pte) & pte_mask);
1293 * Generic mapping functions. It maps a physical address into a DMA
1294 * address space. It allocates the page table pages if necessary.
1295 * In the future it can be extended to a generic mapping function
1296 * supporting all features of AMD IOMMU page tables like level skipping
1297 * and full 64 bit address spaces.
1299 static int iommu_map_page(struct protection_domain *dom,
1300 unsigned long bus_addr,
1301 unsigned long phys_addr,
1303 unsigned long page_size)
1308 BUG_ON(!IS_ALIGNED(bus_addr, page_size));
1309 BUG_ON(!IS_ALIGNED(phys_addr, page_size));
1311 if (!(prot & IOMMU_PROT_MASK))
1314 count = PAGE_SIZE_PTE_COUNT(page_size);
1315 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1320 for (i = 0; i < count; ++i)
1321 if (IOMMU_PTE_PRESENT(pte[i]))
1325 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1326 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1328 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1330 if (prot & IOMMU_PROT_IR)
1331 __pte |= IOMMU_PTE_IR;
1332 if (prot & IOMMU_PROT_IW)
1333 __pte |= IOMMU_PTE_IW;
1335 for (i = 0; i < count; ++i)
1343 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1344 unsigned long bus_addr,
1345 unsigned long page_size)
1347 unsigned long long unmapped;
1348 unsigned long unmap_size;
1351 BUG_ON(!is_power_of_2(page_size));
1355 while (unmapped < page_size) {
1357 pte = fetch_pte(dom, bus_addr, &unmap_size);
1362 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1363 for (i = 0; i < count; i++)
1367 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1368 unmapped += unmap_size;
1371 BUG_ON(unmapped && !is_power_of_2(unmapped));
1376 /****************************************************************************
1378 * The next functions belong to the address allocator for the dma_ops
1379 * interface functions. They work like the allocators in the other IOMMU
1380 * drivers. Its basically a bitmap which marks the allocated pages in
1381 * the aperture. Maybe it could be enhanced in the future to a more
1382 * efficient allocator.
1384 ****************************************************************************/
1387 * The address allocator core functions.
1389 * called with domain->lock held
1393 * Used to reserve address ranges in the aperture (e.g. for exclusion
1396 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1397 unsigned long start_page,
1400 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1402 if (start_page + pages > last_page)
1403 pages = last_page - start_page;
1405 for (i = start_page; i < start_page + pages; ++i) {
1406 int index = i / APERTURE_RANGE_PAGES;
1407 int page = i % APERTURE_RANGE_PAGES;
1408 __set_bit(page, dom->aperture[index]->bitmap);
1413 * This function is used to add a new aperture range to an existing
1414 * aperture in case of dma_ops domain allocation or address allocation
1417 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1418 bool populate, gfp_t gfp)
1420 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1421 struct amd_iommu *iommu;
1422 unsigned long i, old_size, pte_pgsize;
1424 #ifdef CONFIG_IOMMU_STRESS
1428 if (index >= APERTURE_MAX_RANGES)
1431 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1432 if (!dma_dom->aperture[index])
1435 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1436 if (!dma_dom->aperture[index]->bitmap)
1439 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1441 spin_lock_init(&dma_dom->aperture[index]->bitmap_lock);
1444 unsigned long address = dma_dom->aperture_size;
1445 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1446 u64 *pte, *pte_page;
1448 for (i = 0; i < num_ptes; ++i) {
1449 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1454 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1456 address += APERTURE_RANGE_SIZE / 64;
1460 old_size = dma_dom->aperture_size;
1461 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1463 /* Reserve address range used for MSI messages */
1464 if (old_size < MSI_ADDR_BASE_LO &&
1465 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1466 unsigned long spage;
1469 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1470 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1472 dma_ops_reserve_addresses(dma_dom, spage, pages);
1475 /* Initialize the exclusion range if necessary */
1476 for_each_iommu(iommu) {
1477 if (iommu->exclusion_start &&
1478 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1479 && iommu->exclusion_start < dma_dom->aperture_size) {
1480 unsigned long startpage;
1481 int pages = iommu_num_pages(iommu->exclusion_start,
1482 iommu->exclusion_length,
1484 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1485 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1490 * Check for areas already mapped as present in the new aperture
1491 * range and mark those pages as reserved in the allocator. Such
1492 * mappings may already exist as a result of requested unity
1493 * mappings for devices.
1495 for (i = dma_dom->aperture[index]->offset;
1496 i < dma_dom->aperture_size;
1498 u64 *pte = fetch_pte(&dma_dom->domain, i, &pte_pgsize);
1499 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1502 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT,
1506 update_domain(&dma_dom->domain);
1511 update_domain(&dma_dom->domain);
1513 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1515 kfree(dma_dom->aperture[index]);
1516 dma_dom->aperture[index] = NULL;
1521 static dma_addr_t dma_ops_aperture_alloc(struct aperture_range *range,
1522 unsigned long pages,
1523 unsigned long dma_mask,
1524 unsigned long boundary_size,
1525 unsigned long align_mask)
1527 unsigned long offset, limit, flags;
1530 offset = range->offset >> PAGE_SHIFT;
1531 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1532 dma_mask >> PAGE_SHIFT);
1534 spin_lock_irqsave(&range->bitmap_lock, flags);
1535 address = iommu_area_alloc(range->bitmap, limit, range->next_bit,
1536 pages, offset, boundary_size, align_mask);
1538 /* Nothing found, retry one time */
1539 address = iommu_area_alloc(range->bitmap, limit,
1540 0, pages, offset, boundary_size,
1544 range->next_bit = address + pages;
1546 spin_unlock_irqrestore(&range->bitmap_lock, flags);
1551 static unsigned long dma_ops_area_alloc(struct device *dev,
1552 struct dma_ops_domain *dom,
1554 unsigned long align_mask,
1556 unsigned long start)
1558 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1559 int i = start >> APERTURE_RANGE_SHIFT;
1560 unsigned long next_bit, boundary_size, mask;
1561 unsigned long address = -1;
1563 mask = dma_get_seg_boundary(dev);
1565 boundary_size = mask + 1 ? ALIGN(mask + 1, PAGE_SIZE) >> PAGE_SHIFT :
1566 1UL << (BITS_PER_LONG - PAGE_SHIFT);
1568 for (;i < max_index; ++i) {
1569 if (dom->aperture[i]->offset >= dma_mask)
1572 next_bit = dom->aperture[i]->next_bit;
1574 address = dma_ops_aperture_alloc(dom->aperture[i], pages,
1575 dma_mask, boundary_size,
1577 if (address != -1) {
1578 address = dom->aperture[i]->offset +
1579 (address << PAGE_SHIFT);
1580 dom->next_address = address + (pages << PAGE_SHIFT);
1584 if (next_bit > dom->aperture[i]->next_bit)
1585 dom->need_flush = true;
1591 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1592 struct dma_ops_domain *dom,
1594 unsigned long align_mask,
1597 unsigned long address;
1599 #ifdef CONFIG_IOMMU_STRESS
1600 dom->next_address = 0;
1601 dom->need_flush = true;
1604 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1605 dma_mask, dom->next_address);
1607 if (address == -1) {
1608 dom->next_address = 0;
1609 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1611 dom->need_flush = true;
1614 if (unlikely(address == -1))
1615 address = DMA_ERROR_CODE;
1617 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1623 * The address free function.
1625 * called with domain->lock held
1627 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1628 unsigned long address,
1631 unsigned i = address >> APERTURE_RANGE_SHIFT;
1632 struct aperture_range *range = dom->aperture[i];
1633 unsigned long flags;
1635 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1637 #ifdef CONFIG_IOMMU_STRESS
1642 if (address >= dom->next_address)
1643 dom->need_flush = true;
1645 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1647 spin_lock_irqsave(&range->bitmap_lock, flags);
1648 bitmap_clear(range->bitmap, address, pages);
1649 spin_unlock_irqrestore(&range->bitmap_lock, flags);
1653 /****************************************************************************
1655 * The next functions belong to the domain allocation. A domain is
1656 * allocated for every IOMMU as the default domain. If device isolation
1657 * is enabled, every device get its own domain. The most important thing
1658 * about domains is the page table mapping the DMA address space they
1661 ****************************************************************************/
1664 * This function adds a protection domain to the global protection domain list
1666 static void add_domain_to_list(struct protection_domain *domain)
1668 unsigned long flags;
1670 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1671 list_add(&domain->list, &amd_iommu_pd_list);
1672 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1676 * This function removes a protection domain to the global
1677 * protection domain list
1679 static void del_domain_from_list(struct protection_domain *domain)
1681 unsigned long flags;
1683 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1684 list_del(&domain->list);
1685 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1688 static u16 domain_id_alloc(void)
1690 unsigned long flags;
1693 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1694 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1696 if (id > 0 && id < MAX_DOMAIN_ID)
1697 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1700 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1705 static void domain_id_free(int id)
1707 unsigned long flags;
1709 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1710 if (id > 0 && id < MAX_DOMAIN_ID)
1711 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1712 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1715 #define DEFINE_FREE_PT_FN(LVL, FN) \
1716 static void free_pt_##LVL (unsigned long __pt) \
1724 for (i = 0; i < 512; ++i) { \
1725 /* PTE present? */ \
1726 if (!IOMMU_PTE_PRESENT(pt[i])) \
1730 if (PM_PTE_LEVEL(pt[i]) == 0 || \
1731 PM_PTE_LEVEL(pt[i]) == 7) \
1734 p = (unsigned long)IOMMU_PTE_PAGE(pt[i]); \
1737 free_page((unsigned long)pt); \
1740 DEFINE_FREE_PT_FN(l2, free_page)
1741 DEFINE_FREE_PT_FN(l3, free_pt_l2)
1742 DEFINE_FREE_PT_FN(l4, free_pt_l3)
1743 DEFINE_FREE_PT_FN(l5, free_pt_l4)
1744 DEFINE_FREE_PT_FN(l6, free_pt_l5)
1746 static void free_pagetable(struct protection_domain *domain)
1748 unsigned long root = (unsigned long)domain->pt_root;
1750 switch (domain->mode) {
1751 case PAGE_MODE_NONE:
1753 case PAGE_MODE_1_LEVEL:
1756 case PAGE_MODE_2_LEVEL:
1759 case PAGE_MODE_3_LEVEL:
1762 case PAGE_MODE_4_LEVEL:
1765 case PAGE_MODE_5_LEVEL:
1768 case PAGE_MODE_6_LEVEL:
1776 static void free_gcr3_tbl_level1(u64 *tbl)
1781 for (i = 0; i < 512; ++i) {
1782 if (!(tbl[i] & GCR3_VALID))
1785 ptr = __va(tbl[i] & PAGE_MASK);
1787 free_page((unsigned long)ptr);
1791 static void free_gcr3_tbl_level2(u64 *tbl)
1796 for (i = 0; i < 512; ++i) {
1797 if (!(tbl[i] & GCR3_VALID))
1800 ptr = __va(tbl[i] & PAGE_MASK);
1802 free_gcr3_tbl_level1(ptr);
1806 static void free_gcr3_table(struct protection_domain *domain)
1808 if (domain->glx == 2)
1809 free_gcr3_tbl_level2(domain->gcr3_tbl);
1810 else if (domain->glx == 1)
1811 free_gcr3_tbl_level1(domain->gcr3_tbl);
1813 BUG_ON(domain->glx != 0);
1815 free_page((unsigned long)domain->gcr3_tbl);
1819 * Free a domain, only used if something went wrong in the
1820 * allocation path and we need to free an already allocated page table
1822 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1829 del_domain_from_list(&dom->domain);
1831 free_pagetable(&dom->domain);
1833 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1834 if (!dom->aperture[i])
1836 free_page((unsigned long)dom->aperture[i]->bitmap);
1837 kfree(dom->aperture[i]);
1844 * Allocates a new protection domain usable for the dma_ops functions.
1845 * It also initializes the page table and the address allocator data
1846 * structures required for the dma_ops interface
1848 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1850 struct dma_ops_domain *dma_dom;
1852 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1856 if (protection_domain_init(&dma_dom->domain))
1859 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1860 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1861 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1862 dma_dom->domain.priv = dma_dom;
1863 if (!dma_dom->domain.pt_root)
1866 dma_dom->need_flush = false;
1868 add_domain_to_list(&dma_dom->domain);
1870 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1874 * mark the first page as allocated so we never return 0 as
1875 * a valid dma-address. So we can use 0 as error value
1877 dma_dom->aperture[0]->bitmap[0] = 1;
1878 dma_dom->next_address = 0;
1884 dma_ops_domain_free(dma_dom);
1890 * little helper function to check whether a given protection domain is a
1893 static bool dma_ops_domain(struct protection_domain *domain)
1895 return domain->flags & PD_DMA_OPS_MASK;
1898 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1903 if (domain->mode != PAGE_MODE_NONE)
1904 pte_root = virt_to_phys(domain->pt_root);
1906 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1907 << DEV_ENTRY_MODE_SHIFT;
1908 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1910 flags = amd_iommu_dev_table[devid].data[1];
1913 flags |= DTE_FLAG_IOTLB;
1915 if (domain->flags & PD_IOMMUV2_MASK) {
1916 u64 gcr3 = __pa(domain->gcr3_tbl);
1917 u64 glx = domain->glx;
1920 pte_root |= DTE_FLAG_GV;
1921 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1923 /* First mask out possible old values for GCR3 table */
1924 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1927 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1930 /* Encode GCR3 table into DTE */
1931 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1934 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1937 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
1941 flags &= ~(0xffffUL);
1942 flags |= domain->id;
1944 amd_iommu_dev_table[devid].data[1] = flags;
1945 amd_iommu_dev_table[devid].data[0] = pte_root;
1948 static void clear_dte_entry(u16 devid)
1950 /* remove entry from the device table seen by the hardware */
1951 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1952 amd_iommu_dev_table[devid].data[1] &= DTE_FLAG_MASK;
1954 amd_iommu_apply_erratum_63(devid);
1957 static void do_attach(struct iommu_dev_data *dev_data,
1958 struct protection_domain *domain)
1960 struct amd_iommu *iommu;
1964 iommu = amd_iommu_rlookup_table[dev_data->devid];
1965 alias = amd_iommu_alias_table[dev_data->devid];
1966 ats = dev_data->ats.enabled;
1968 /* Update data structures */
1969 dev_data->domain = domain;
1970 list_add(&dev_data->list, &domain->dev_list);
1972 /* Do reference counting */
1973 domain->dev_iommu[iommu->index] += 1;
1974 domain->dev_cnt += 1;
1976 /* Update device table */
1977 set_dte_entry(dev_data->devid, domain, ats);
1978 if (alias != dev_data->devid)
1979 set_dte_entry(dev_data->devid, domain, ats);
1981 device_flush_dte(dev_data);
1984 static void do_detach(struct iommu_dev_data *dev_data)
1986 struct amd_iommu *iommu;
1990 * First check if the device is still attached. It might already
1991 * be detached from its domain because the generic
1992 * iommu_detach_group code detached it and we try again here in
1993 * our alias handling.
1995 if (!dev_data->domain)
1998 iommu = amd_iommu_rlookup_table[dev_data->devid];
1999 alias = amd_iommu_alias_table[dev_data->devid];
2001 /* decrease reference counters */
2002 dev_data->domain->dev_iommu[iommu->index] -= 1;
2003 dev_data->domain->dev_cnt -= 1;
2005 /* Update data structures */
2006 dev_data->domain = NULL;
2007 list_del(&dev_data->list);
2008 clear_dte_entry(dev_data->devid);
2009 if (alias != dev_data->devid)
2010 clear_dte_entry(alias);
2012 /* Flush the DTE entry */
2013 device_flush_dte(dev_data);
2017 * If a device is not yet associated with a domain, this function does
2018 * assigns it visible for the hardware
2020 static int __attach_device(struct iommu_dev_data *dev_data,
2021 struct protection_domain *domain)
2026 * Must be called with IRQs disabled. Warn here to detect early
2029 WARN_ON(!irqs_disabled());
2032 spin_lock(&domain->lock);
2035 if (dev_data->domain != NULL)
2038 /* Attach alias group root */
2039 do_attach(dev_data, domain);
2046 spin_unlock(&domain->lock);
2052 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2054 pci_disable_ats(pdev);
2055 pci_disable_pri(pdev);
2056 pci_disable_pasid(pdev);
2059 /* FIXME: Change generic reset-function to do the same */
2060 static int pri_reset_while_enabled(struct pci_dev *pdev)
2065 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2069 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2070 control |= PCI_PRI_CTRL_RESET;
2071 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2076 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2081 /* FIXME: Hardcode number of outstanding requests for now */
2083 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2085 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2087 /* Only allow access to user-accessible pages */
2088 ret = pci_enable_pasid(pdev, 0);
2092 /* First reset the PRI state of the device */
2093 ret = pci_reset_pri(pdev);
2098 ret = pci_enable_pri(pdev, reqs);
2103 ret = pri_reset_while_enabled(pdev);
2108 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2115 pci_disable_pri(pdev);
2116 pci_disable_pasid(pdev);
2121 /* FIXME: Move this to PCI code */
2122 #define PCI_PRI_TLP_OFF (1 << 15)
2124 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2129 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2133 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2135 return (status & PCI_PRI_TLP_OFF) ? true : false;
2139 * If a device is not yet associated with a domain, this function
2140 * assigns it visible for the hardware
2142 static int attach_device(struct device *dev,
2143 struct protection_domain *domain)
2145 struct pci_dev *pdev = to_pci_dev(dev);
2146 struct iommu_dev_data *dev_data;
2147 unsigned long flags;
2150 dev_data = get_dev_data(dev);
2152 if (domain->flags & PD_IOMMUV2_MASK) {
2153 if (!dev_data->passthrough)
2156 if (dev_data->iommu_v2) {
2157 if (pdev_iommuv2_enable(pdev) != 0)
2160 dev_data->ats.enabled = true;
2161 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2162 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2164 } else if (amd_iommu_iotlb_sup &&
2165 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2166 dev_data->ats.enabled = true;
2167 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2170 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2171 ret = __attach_device(dev_data, domain);
2172 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2175 * We might boot into a crash-kernel here. The crashed kernel
2176 * left the caches in the IOMMU dirty. So we have to flush
2177 * here to evict all dirty stuff.
2179 domain_flush_tlb_pde(domain);
2185 * Removes a device from a protection domain (unlocked)
2187 static void __detach_device(struct iommu_dev_data *dev_data)
2189 struct protection_domain *domain;
2192 * Must be called with IRQs disabled. Warn here to detect early
2195 WARN_ON(!irqs_disabled());
2197 if (WARN_ON(!dev_data->domain))
2200 domain = dev_data->domain;
2202 spin_lock(&domain->lock);
2204 do_detach(dev_data);
2206 spin_unlock(&domain->lock);
2210 * Removes a device from a protection domain (with devtable_lock held)
2212 static void detach_device(struct device *dev)
2214 struct protection_domain *domain;
2215 struct iommu_dev_data *dev_data;
2216 unsigned long flags;
2218 dev_data = get_dev_data(dev);
2219 domain = dev_data->domain;
2221 /* lock device table */
2222 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2223 __detach_device(dev_data);
2224 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2226 if (domain->flags & PD_IOMMUV2_MASK && dev_data->iommu_v2)
2227 pdev_iommuv2_disable(to_pci_dev(dev));
2228 else if (dev_data->ats.enabled)
2229 pci_disable_ats(to_pci_dev(dev));
2231 dev_data->ats.enabled = false;
2234 static int amd_iommu_add_device(struct device *dev)
2236 struct iommu_dev_data *dev_data;
2237 struct iommu_domain *domain;
2238 struct amd_iommu *iommu;
2242 if (!check_device(dev) || get_dev_data(dev))
2245 devid = get_device_id(dev);
2246 iommu = amd_iommu_rlookup_table[devid];
2248 ret = iommu_init_device(dev);
2250 if (ret != -ENOTSUPP)
2251 pr_err("Failed to initialize device %s - trying to proceed anyway\n",
2254 iommu_ignore_device(dev);
2255 dev->archdata.dma_ops = &nommu_dma_ops;
2258 init_iommu_group(dev);
2260 dev_data = get_dev_data(dev);
2264 if (iommu_pass_through || dev_data->iommu_v2)
2265 iommu_request_dm_for_dev(dev);
2267 /* Domains are initialized for this device - have a look what we ended up with */
2268 domain = iommu_get_domain_for_dev(dev);
2269 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2270 dev_data->passthrough = true;
2272 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2275 iommu_completion_wait(iommu);
2280 static void amd_iommu_remove_device(struct device *dev)
2282 struct amd_iommu *iommu;
2285 if (!check_device(dev))
2288 devid = get_device_id(dev);
2289 iommu = amd_iommu_rlookup_table[devid];
2291 iommu_uninit_device(dev);
2292 iommu_completion_wait(iommu);
2295 /*****************************************************************************
2297 * The next functions belong to the dma_ops mapping/unmapping code.
2299 *****************************************************************************/
2302 * In the dma_ops path we only have the struct device. This function
2303 * finds the corresponding IOMMU, the protection domain and the
2304 * requestor id for a given device.
2305 * If the device is not yet associated with a domain this is also done
2308 static struct protection_domain *get_domain(struct device *dev)
2310 struct protection_domain *domain;
2311 struct iommu_domain *io_domain;
2313 if (!check_device(dev))
2314 return ERR_PTR(-EINVAL);
2316 io_domain = iommu_get_domain_for_dev(dev);
2320 domain = to_pdomain(io_domain);
2321 if (!dma_ops_domain(domain))
2322 return ERR_PTR(-EBUSY);
2327 static void update_device_table(struct protection_domain *domain)
2329 struct iommu_dev_data *dev_data;
2331 list_for_each_entry(dev_data, &domain->dev_list, list)
2332 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2335 static void update_domain(struct protection_domain *domain)
2337 if (!domain->updated)
2340 update_device_table(domain);
2342 domain_flush_devices(domain);
2343 domain_flush_tlb_pde(domain);
2345 domain->updated = false;
2349 * This function fetches the PTE for a given address in the aperture
2351 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2352 unsigned long address)
2354 struct aperture_range *aperture;
2355 u64 *pte, *pte_page;
2357 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2361 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2363 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2365 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2367 pte += PM_LEVEL_INDEX(0, address);
2369 update_domain(&dom->domain);
2375 * This is the generic map function. It maps one 4kb page at paddr to
2376 * the given address in the DMA address space for the domain.
2378 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2379 unsigned long address,
2385 WARN_ON(address > dom->aperture_size);
2389 pte = dma_ops_get_pte(dom, address);
2391 return DMA_ERROR_CODE;
2393 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2395 if (direction == DMA_TO_DEVICE)
2396 __pte |= IOMMU_PTE_IR;
2397 else if (direction == DMA_FROM_DEVICE)
2398 __pte |= IOMMU_PTE_IW;
2399 else if (direction == DMA_BIDIRECTIONAL)
2400 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2406 return (dma_addr_t)address;
2410 * The generic unmapping function for on page in the DMA address space.
2412 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2413 unsigned long address)
2415 struct aperture_range *aperture;
2418 if (address >= dom->aperture_size)
2421 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2425 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2429 pte += PM_LEVEL_INDEX(0, address);
2431 WARN_ON_ONCE(!*pte);
2437 * This function contains common code for mapping of a physically
2438 * contiguous memory region into DMA address space. It is used by all
2439 * mapping functions provided with this IOMMU driver.
2440 * Must be called with the domain lock held.
2442 static dma_addr_t __map_single(struct device *dev,
2443 struct dma_ops_domain *dma_dom,
2450 dma_addr_t offset = paddr & ~PAGE_MASK;
2451 dma_addr_t address, start, ret;
2453 unsigned long align_mask = 0;
2456 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2459 INC_STATS_COUNTER(total_map_requests);
2462 INC_STATS_COUNTER(cross_page);
2465 align_mask = (1UL << get_order(size)) - 1;
2468 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2470 if (unlikely(address == DMA_ERROR_CODE)) {
2472 * setting next_address here will let the address
2473 * allocator only scan the new allocated range in the
2474 * first run. This is a small optimization.
2476 dma_dom->next_address = dma_dom->aperture_size;
2478 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2482 * aperture was successfully enlarged by 128 MB, try
2489 for (i = 0; i < pages; ++i) {
2490 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2491 if (ret == DMA_ERROR_CODE)
2499 ADD_STATS_COUNTER(alloced_io_mem, size);
2501 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2502 domain_flush_tlb(&dma_dom->domain);
2503 dma_dom->need_flush = false;
2504 } else if (unlikely(amd_iommu_np_cache))
2505 domain_flush_pages(&dma_dom->domain, address, size);
2512 for (--i; i >= 0; --i) {
2514 dma_ops_domain_unmap(dma_dom, start);
2517 domain_flush_pages(&dma_dom->domain, address, size);
2519 dma_ops_free_addresses(dma_dom, address, pages);
2521 return DMA_ERROR_CODE;
2525 * Does the reverse of the __map_single function. Must be called with
2526 * the domain lock held too
2528 static void __unmap_single(struct dma_ops_domain *dma_dom,
2529 dma_addr_t dma_addr,
2533 dma_addr_t flush_addr;
2534 dma_addr_t i, start;
2537 if ((dma_addr == DMA_ERROR_CODE) ||
2538 (dma_addr + size > dma_dom->aperture_size))
2541 flush_addr = dma_addr;
2542 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2543 dma_addr &= PAGE_MASK;
2546 for (i = 0; i < pages; ++i) {
2547 dma_ops_domain_unmap(dma_dom, start);
2551 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2552 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2553 dma_dom->need_flush = false;
2556 SUB_STATS_COUNTER(alloced_io_mem, size);
2558 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2562 * The exported map_single function for dma_ops.
2564 static dma_addr_t map_page(struct device *dev, struct page *page,
2565 unsigned long offset, size_t size,
2566 enum dma_data_direction dir,
2567 struct dma_attrs *attrs)
2569 unsigned long flags;
2570 struct protection_domain *domain;
2573 phys_addr_t paddr = page_to_phys(page) + offset;
2575 INC_STATS_COUNTER(cnt_map_single);
2577 domain = get_domain(dev);
2578 if (PTR_ERR(domain) == -EINVAL)
2579 return (dma_addr_t)paddr;
2580 else if (IS_ERR(domain))
2581 return DMA_ERROR_CODE;
2583 dma_mask = *dev->dma_mask;
2585 spin_lock_irqsave(&domain->lock, flags);
2587 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2589 if (addr == DMA_ERROR_CODE)
2592 domain_flush_complete(domain);
2595 spin_unlock_irqrestore(&domain->lock, flags);
2601 * The exported unmap_single function for dma_ops.
2603 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2604 enum dma_data_direction dir, struct dma_attrs *attrs)
2606 unsigned long flags;
2607 struct protection_domain *domain;
2609 INC_STATS_COUNTER(cnt_unmap_single);
2611 domain = get_domain(dev);
2615 spin_lock_irqsave(&domain->lock, flags);
2617 __unmap_single(domain->priv, dma_addr, size, dir);
2619 domain_flush_complete(domain);
2621 spin_unlock_irqrestore(&domain->lock, flags);
2625 * The exported map_sg function for dma_ops (handles scatter-gather
2628 static int map_sg(struct device *dev, struct scatterlist *sglist,
2629 int nelems, enum dma_data_direction dir,
2630 struct dma_attrs *attrs)
2632 unsigned long flags;
2633 struct protection_domain *domain;
2635 struct scatterlist *s;
2637 int mapped_elems = 0;
2640 INC_STATS_COUNTER(cnt_map_sg);
2642 domain = get_domain(dev);
2646 dma_mask = *dev->dma_mask;
2648 spin_lock_irqsave(&domain->lock, flags);
2650 for_each_sg(sglist, s, nelems, i) {
2653 s->dma_address = __map_single(dev, domain->priv,
2654 paddr, s->length, dir, false,
2657 if (s->dma_address) {
2658 s->dma_length = s->length;
2664 domain_flush_complete(domain);
2667 spin_unlock_irqrestore(&domain->lock, flags);
2669 return mapped_elems;
2671 for_each_sg(sglist, s, mapped_elems, i) {
2673 __unmap_single(domain->priv, s->dma_address,
2674 s->dma_length, dir);
2675 s->dma_address = s->dma_length = 0;
2684 * The exported map_sg function for dma_ops (handles scatter-gather
2687 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2688 int nelems, enum dma_data_direction dir,
2689 struct dma_attrs *attrs)
2691 unsigned long flags;
2692 struct protection_domain *domain;
2693 struct scatterlist *s;
2696 INC_STATS_COUNTER(cnt_unmap_sg);
2698 domain = get_domain(dev);
2702 spin_lock_irqsave(&domain->lock, flags);
2704 for_each_sg(sglist, s, nelems, i) {
2705 __unmap_single(domain->priv, s->dma_address,
2706 s->dma_length, dir);
2707 s->dma_address = s->dma_length = 0;
2710 domain_flush_complete(domain);
2712 spin_unlock_irqrestore(&domain->lock, flags);
2716 * The exported alloc_coherent function for dma_ops.
2718 static void *alloc_coherent(struct device *dev, size_t size,
2719 dma_addr_t *dma_addr, gfp_t flag,
2720 struct dma_attrs *attrs)
2722 u64 dma_mask = dev->coherent_dma_mask;
2723 struct protection_domain *domain;
2724 unsigned long flags;
2727 INC_STATS_COUNTER(cnt_alloc_coherent);
2729 domain = get_domain(dev);
2730 if (PTR_ERR(domain) == -EINVAL) {
2731 page = alloc_pages(flag, get_order(size));
2732 *dma_addr = page_to_phys(page);
2733 return page_address(page);
2734 } else if (IS_ERR(domain))
2737 size = PAGE_ALIGN(size);
2738 dma_mask = dev->coherent_dma_mask;
2739 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2742 page = alloc_pages(flag | __GFP_NOWARN, get_order(size));
2744 if (!gfpflags_allow_blocking(flag))
2747 page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
2754 dma_mask = *dev->dma_mask;
2756 spin_lock_irqsave(&domain->lock, flags);
2758 *dma_addr = __map_single(dev, domain->priv, page_to_phys(page),
2759 size, DMA_BIDIRECTIONAL, true, dma_mask);
2761 if (*dma_addr == DMA_ERROR_CODE) {
2762 spin_unlock_irqrestore(&domain->lock, flags);
2766 domain_flush_complete(domain);
2768 spin_unlock_irqrestore(&domain->lock, flags);
2770 return page_address(page);
2774 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2775 __free_pages(page, get_order(size));
2781 * The exported free_coherent function for dma_ops.
2783 static void free_coherent(struct device *dev, size_t size,
2784 void *virt_addr, dma_addr_t dma_addr,
2785 struct dma_attrs *attrs)
2787 struct protection_domain *domain;
2788 unsigned long flags;
2791 INC_STATS_COUNTER(cnt_free_coherent);
2793 page = virt_to_page(virt_addr);
2794 size = PAGE_ALIGN(size);
2796 domain = get_domain(dev);
2800 spin_lock_irqsave(&domain->lock, flags);
2802 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2804 domain_flush_complete(domain);
2806 spin_unlock_irqrestore(&domain->lock, flags);
2809 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2810 __free_pages(page, get_order(size));
2814 * This function is called by the DMA layer to find out if we can handle a
2815 * particular device. It is part of the dma_ops.
2817 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2819 return check_device(dev);
2822 static struct dma_map_ops amd_iommu_dma_ops = {
2823 .alloc = alloc_coherent,
2824 .free = free_coherent,
2825 .map_page = map_page,
2826 .unmap_page = unmap_page,
2828 .unmap_sg = unmap_sg,
2829 .dma_supported = amd_iommu_dma_supported,
2832 int __init amd_iommu_init_api(void)
2834 return bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2837 int __init amd_iommu_init_dma_ops(void)
2839 swiotlb = iommu_pass_through ? 1 : 0;
2843 * In case we don't initialize SWIOTLB (actually the common case
2844 * when AMD IOMMU is enabled), make sure there are global
2845 * dma_ops set as a fall-back for devices not handled by this
2846 * driver (for example non-PCI devices).
2849 dma_ops = &nommu_dma_ops;
2851 amd_iommu_stats_init();
2853 if (amd_iommu_unmap_flush)
2854 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
2856 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
2861 /*****************************************************************************
2863 * The following functions belong to the exported interface of AMD IOMMU
2865 * This interface allows access to lower level functions of the IOMMU
2866 * like protection domain handling and assignement of devices to domains
2867 * which is not possible with the dma_ops interface.
2869 *****************************************************************************/
2871 static void cleanup_domain(struct protection_domain *domain)
2873 struct iommu_dev_data *entry;
2874 unsigned long flags;
2876 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2878 while (!list_empty(&domain->dev_list)) {
2879 entry = list_first_entry(&domain->dev_list,
2880 struct iommu_dev_data, list);
2881 __detach_device(entry);
2884 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2887 static void protection_domain_free(struct protection_domain *domain)
2892 del_domain_from_list(domain);
2895 domain_id_free(domain->id);
2900 static int protection_domain_init(struct protection_domain *domain)
2902 spin_lock_init(&domain->lock);
2903 mutex_init(&domain->api_lock);
2904 domain->id = domain_id_alloc();
2907 INIT_LIST_HEAD(&domain->dev_list);
2912 static struct protection_domain *protection_domain_alloc(void)
2914 struct protection_domain *domain;
2916 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2920 if (protection_domain_init(domain))
2923 add_domain_to_list(domain);
2933 static struct iommu_domain *amd_iommu_domain_alloc(unsigned type)
2935 struct protection_domain *pdomain;
2936 struct dma_ops_domain *dma_domain;
2939 case IOMMU_DOMAIN_UNMANAGED:
2940 pdomain = protection_domain_alloc();
2944 pdomain->mode = PAGE_MODE_3_LEVEL;
2945 pdomain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2946 if (!pdomain->pt_root) {
2947 protection_domain_free(pdomain);
2951 pdomain->domain.geometry.aperture_start = 0;
2952 pdomain->domain.geometry.aperture_end = ~0ULL;
2953 pdomain->domain.geometry.force_aperture = true;
2956 case IOMMU_DOMAIN_DMA:
2957 dma_domain = dma_ops_domain_alloc();
2959 pr_err("AMD-Vi: Failed to allocate\n");
2962 pdomain = &dma_domain->domain;
2964 case IOMMU_DOMAIN_IDENTITY:
2965 pdomain = protection_domain_alloc();
2969 pdomain->mode = PAGE_MODE_NONE;
2975 return &pdomain->domain;
2978 static void amd_iommu_domain_free(struct iommu_domain *dom)
2980 struct protection_domain *domain;
2985 domain = to_pdomain(dom);
2987 if (domain->dev_cnt > 0)
2988 cleanup_domain(domain);
2990 BUG_ON(domain->dev_cnt != 0);
2992 if (domain->mode != PAGE_MODE_NONE)
2993 free_pagetable(domain);
2995 if (domain->flags & PD_IOMMUV2_MASK)
2996 free_gcr3_table(domain);
2998 protection_domain_free(domain);
3001 static void amd_iommu_detach_device(struct iommu_domain *dom,
3004 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3005 struct amd_iommu *iommu;
3008 if (!check_device(dev))
3011 devid = get_device_id(dev);
3013 if (dev_data->domain != NULL)
3016 iommu = amd_iommu_rlookup_table[devid];
3020 iommu_completion_wait(iommu);
3023 static int amd_iommu_attach_device(struct iommu_domain *dom,
3026 struct protection_domain *domain = to_pdomain(dom);
3027 struct iommu_dev_data *dev_data;
3028 struct amd_iommu *iommu;
3031 if (!check_device(dev))
3034 dev_data = dev->archdata.iommu;
3036 iommu = amd_iommu_rlookup_table[dev_data->devid];
3040 if (dev_data->domain)
3043 ret = attach_device(dev, domain);
3045 iommu_completion_wait(iommu);
3050 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3051 phys_addr_t paddr, size_t page_size, int iommu_prot)
3053 struct protection_domain *domain = to_pdomain(dom);
3057 if (domain->mode == PAGE_MODE_NONE)
3060 if (iommu_prot & IOMMU_READ)
3061 prot |= IOMMU_PROT_IR;
3062 if (iommu_prot & IOMMU_WRITE)
3063 prot |= IOMMU_PROT_IW;
3065 mutex_lock(&domain->api_lock);
3066 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3067 mutex_unlock(&domain->api_lock);
3072 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3075 struct protection_domain *domain = to_pdomain(dom);
3078 if (domain->mode == PAGE_MODE_NONE)
3081 mutex_lock(&domain->api_lock);
3082 unmap_size = iommu_unmap_page(domain, iova, page_size);
3083 mutex_unlock(&domain->api_lock);
3085 domain_flush_tlb_pde(domain);
3090 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3093 struct protection_domain *domain = to_pdomain(dom);
3094 unsigned long offset_mask, pte_pgsize;
3097 if (domain->mode == PAGE_MODE_NONE)
3100 pte = fetch_pte(domain, iova, &pte_pgsize);
3102 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3105 offset_mask = pte_pgsize - 1;
3106 __pte = *pte & PM_ADDR_MASK;
3108 return (__pte & ~offset_mask) | (iova & offset_mask);
3111 static bool amd_iommu_capable(enum iommu_cap cap)
3114 case IOMMU_CAP_CACHE_COHERENCY:
3116 case IOMMU_CAP_INTR_REMAP:
3117 return (irq_remapping_enabled == 1);
3118 case IOMMU_CAP_NOEXEC:
3125 static void amd_iommu_get_dm_regions(struct device *dev,
3126 struct list_head *head)
3128 struct unity_map_entry *entry;
3131 devid = get_device_id(dev);
3133 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
3134 struct iommu_dm_region *region;
3136 if (devid < entry->devid_start || devid > entry->devid_end)
3139 region = kzalloc(sizeof(*region), GFP_KERNEL);
3141 pr_err("Out of memory allocating dm-regions for %s\n",
3146 region->start = entry->address_start;
3147 region->length = entry->address_end - entry->address_start;
3148 if (entry->prot & IOMMU_PROT_IR)
3149 region->prot |= IOMMU_READ;
3150 if (entry->prot & IOMMU_PROT_IW)
3151 region->prot |= IOMMU_WRITE;
3153 list_add_tail(®ion->list, head);
3157 static void amd_iommu_put_dm_regions(struct device *dev,
3158 struct list_head *head)
3160 struct iommu_dm_region *entry, *next;
3162 list_for_each_entry_safe(entry, next, head, list)
3166 static const struct iommu_ops amd_iommu_ops = {
3167 .capable = amd_iommu_capable,
3168 .domain_alloc = amd_iommu_domain_alloc,
3169 .domain_free = amd_iommu_domain_free,
3170 .attach_dev = amd_iommu_attach_device,
3171 .detach_dev = amd_iommu_detach_device,
3172 .map = amd_iommu_map,
3173 .unmap = amd_iommu_unmap,
3174 .map_sg = default_iommu_map_sg,
3175 .iova_to_phys = amd_iommu_iova_to_phys,
3176 .add_device = amd_iommu_add_device,
3177 .remove_device = amd_iommu_remove_device,
3178 .device_group = pci_device_group,
3179 .get_dm_regions = amd_iommu_get_dm_regions,
3180 .put_dm_regions = amd_iommu_put_dm_regions,
3181 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3184 /*****************************************************************************
3186 * The next functions do a basic initialization of IOMMU for pass through
3189 * In passthrough mode the IOMMU is initialized and enabled but not used for
3190 * DMA-API translation.
3192 *****************************************************************************/
3194 /* IOMMUv2 specific functions */
3195 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3197 return atomic_notifier_chain_register(&ppr_notifier, nb);
3199 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3201 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3203 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3205 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3207 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3209 struct protection_domain *domain = to_pdomain(dom);
3210 unsigned long flags;
3212 spin_lock_irqsave(&domain->lock, flags);
3214 /* Update data structure */
3215 domain->mode = PAGE_MODE_NONE;
3216 domain->updated = true;
3218 /* Make changes visible to IOMMUs */
3219 update_domain(domain);
3221 /* Page-table is not visible to IOMMU anymore, so free it */
3222 free_pagetable(domain);
3224 spin_unlock_irqrestore(&domain->lock, flags);
3226 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3228 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3230 struct protection_domain *domain = to_pdomain(dom);
3231 unsigned long flags;
3234 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3237 /* Number of GCR3 table levels required */
3238 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3241 if (levels > amd_iommu_max_glx_val)
3244 spin_lock_irqsave(&domain->lock, flags);
3247 * Save us all sanity checks whether devices already in the
3248 * domain support IOMMUv2. Just force that the domain has no
3249 * devices attached when it is switched into IOMMUv2 mode.
3252 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3256 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3257 if (domain->gcr3_tbl == NULL)
3260 domain->glx = levels;
3261 domain->flags |= PD_IOMMUV2_MASK;
3262 domain->updated = true;
3264 update_domain(domain);
3269 spin_unlock_irqrestore(&domain->lock, flags);
3273 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3275 static int __flush_pasid(struct protection_domain *domain, int pasid,
3276 u64 address, bool size)
3278 struct iommu_dev_data *dev_data;
3279 struct iommu_cmd cmd;
3282 if (!(domain->flags & PD_IOMMUV2_MASK))
3285 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3288 * IOMMU TLB needs to be flushed before Device TLB to
3289 * prevent device TLB refill from IOMMU TLB
3291 for (i = 0; i < amd_iommus_present; ++i) {
3292 if (domain->dev_iommu[i] == 0)
3295 ret = iommu_queue_command(amd_iommus[i], &cmd);
3300 /* Wait until IOMMU TLB flushes are complete */
3301 domain_flush_complete(domain);
3303 /* Now flush device TLBs */
3304 list_for_each_entry(dev_data, &domain->dev_list, list) {
3305 struct amd_iommu *iommu;
3309 There might be non-IOMMUv2 capable devices in an IOMMUv2
3312 if (!dev_data->ats.enabled)
3315 qdep = dev_data->ats.qdep;
3316 iommu = amd_iommu_rlookup_table[dev_data->devid];
3318 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3319 qdep, address, size);
3321 ret = iommu_queue_command(iommu, &cmd);
3326 /* Wait until all device TLBs are flushed */
3327 domain_flush_complete(domain);
3336 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3339 INC_STATS_COUNTER(invalidate_iotlb);
3341 return __flush_pasid(domain, pasid, address, false);
3344 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3347 struct protection_domain *domain = to_pdomain(dom);
3348 unsigned long flags;
3351 spin_lock_irqsave(&domain->lock, flags);
3352 ret = __amd_iommu_flush_page(domain, pasid, address);
3353 spin_unlock_irqrestore(&domain->lock, flags);
3357 EXPORT_SYMBOL(amd_iommu_flush_page);
3359 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3361 INC_STATS_COUNTER(invalidate_iotlb_all);
3363 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3367 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3369 struct protection_domain *domain = to_pdomain(dom);
3370 unsigned long flags;
3373 spin_lock_irqsave(&domain->lock, flags);
3374 ret = __amd_iommu_flush_tlb(domain, pasid);
3375 spin_unlock_irqrestore(&domain->lock, flags);
3379 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3381 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3388 index = (pasid >> (9 * level)) & 0x1ff;
3394 if (!(*pte & GCR3_VALID)) {
3398 root = (void *)get_zeroed_page(GFP_ATOMIC);
3402 *pte = __pa(root) | GCR3_VALID;
3405 root = __va(*pte & PAGE_MASK);
3413 static int __set_gcr3(struct protection_domain *domain, int pasid,
3418 if (domain->mode != PAGE_MODE_NONE)
3421 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3425 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3427 return __amd_iommu_flush_tlb(domain, pasid);
3430 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3434 if (domain->mode != PAGE_MODE_NONE)
3437 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3443 return __amd_iommu_flush_tlb(domain, pasid);
3446 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3449 struct protection_domain *domain = to_pdomain(dom);
3450 unsigned long flags;
3453 spin_lock_irqsave(&domain->lock, flags);
3454 ret = __set_gcr3(domain, pasid, cr3);
3455 spin_unlock_irqrestore(&domain->lock, flags);
3459 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3461 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3463 struct protection_domain *domain = to_pdomain(dom);
3464 unsigned long flags;
3467 spin_lock_irqsave(&domain->lock, flags);
3468 ret = __clear_gcr3(domain, pasid);
3469 spin_unlock_irqrestore(&domain->lock, flags);
3473 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3475 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3476 int status, int tag)
3478 struct iommu_dev_data *dev_data;
3479 struct amd_iommu *iommu;
3480 struct iommu_cmd cmd;
3482 INC_STATS_COUNTER(complete_ppr);
3484 dev_data = get_dev_data(&pdev->dev);
3485 iommu = amd_iommu_rlookup_table[dev_data->devid];
3487 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3488 tag, dev_data->pri_tlp);
3490 return iommu_queue_command(iommu, &cmd);
3492 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3494 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3496 struct protection_domain *pdomain;
3498 pdomain = get_domain(&pdev->dev);
3499 if (IS_ERR(pdomain))
3502 /* Only return IOMMUv2 domains */
3503 if (!(pdomain->flags & PD_IOMMUV2_MASK))
3506 return &pdomain->domain;
3508 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3510 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3512 struct iommu_dev_data *dev_data;
3514 if (!amd_iommu_v2_supported())
3517 dev_data = get_dev_data(&pdev->dev);
3518 dev_data->errata |= (1 << erratum);
3520 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3522 int amd_iommu_device_info(struct pci_dev *pdev,
3523 struct amd_iommu_device_info *info)
3528 if (pdev == NULL || info == NULL)
3531 if (!amd_iommu_v2_supported())
3534 memset(info, 0, sizeof(*info));
3536 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3538 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3540 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3542 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3544 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3548 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3549 max_pasids = min(max_pasids, (1 << 20));
3551 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3552 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3554 features = pci_pasid_features(pdev);
3555 if (features & PCI_PASID_CAP_EXEC)
3556 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3557 if (features & PCI_PASID_CAP_PRIV)
3558 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3563 EXPORT_SYMBOL(amd_iommu_device_info);
3565 #ifdef CONFIG_IRQ_REMAP
3567 /*****************************************************************************
3569 * Interrupt Remapping Implementation
3571 *****************************************************************************/
3589 u16 devid; /* Device ID for IRTE table */
3590 u16 index; /* Index into IRTE table*/
3593 struct amd_ir_data {
3594 struct irq_2_irte irq_2_irte;
3595 union irte irte_entry;
3597 struct msi_msg msi_entry;
3601 static struct irq_chip amd_ir_chip;
3603 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3604 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3605 #define DTE_IRQ_TABLE_LEN (8ULL << 1)
3606 #define DTE_IRQ_REMAP_ENABLE 1ULL
3608 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3612 dte = amd_iommu_dev_table[devid].data[2];
3613 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3614 dte |= virt_to_phys(table->table);
3615 dte |= DTE_IRQ_REMAP_INTCTL;
3616 dte |= DTE_IRQ_TABLE_LEN;
3617 dte |= DTE_IRQ_REMAP_ENABLE;
3619 amd_iommu_dev_table[devid].data[2] = dte;
3622 #define IRTE_ALLOCATED (~1U)
3624 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3626 struct irq_remap_table *table = NULL;
3627 struct amd_iommu *iommu;
3628 unsigned long flags;
3631 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3633 iommu = amd_iommu_rlookup_table[devid];
3637 table = irq_lookup_table[devid];
3641 alias = amd_iommu_alias_table[devid];
3642 table = irq_lookup_table[alias];
3644 irq_lookup_table[devid] = table;
3645 set_dte_irq_entry(devid, table);
3646 iommu_flush_dte(iommu, devid);
3650 /* Nothing there yet, allocate new irq remapping table */
3651 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3655 /* Initialize table spin-lock */
3656 spin_lock_init(&table->lock);
3659 /* Keep the first 32 indexes free for IOAPIC interrupts */
3660 table->min_index = 32;
3662 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3663 if (!table->table) {
3669 memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3674 for (i = 0; i < 32; ++i)
3675 table->table[i] = IRTE_ALLOCATED;
3678 irq_lookup_table[devid] = table;
3679 set_dte_irq_entry(devid, table);
3680 iommu_flush_dte(iommu, devid);
3681 if (devid != alias) {
3682 irq_lookup_table[alias] = table;
3683 set_dte_irq_entry(alias, table);
3684 iommu_flush_dte(iommu, alias);
3688 iommu_completion_wait(iommu);
3691 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3696 static int alloc_irq_index(u16 devid, int count)
3698 struct irq_remap_table *table;
3699 unsigned long flags;
3702 table = get_irq_table(devid, false);
3706 spin_lock_irqsave(&table->lock, flags);
3708 /* Scan table for free entries */
3709 for (c = 0, index = table->min_index;
3710 index < MAX_IRQS_PER_TABLE;
3712 if (table->table[index] == 0)
3719 table->table[index - c + 1] = IRTE_ALLOCATED;
3729 spin_unlock_irqrestore(&table->lock, flags);
3734 static int modify_irte(u16 devid, int index, union irte irte)
3736 struct irq_remap_table *table;
3737 struct amd_iommu *iommu;
3738 unsigned long flags;
3740 iommu = amd_iommu_rlookup_table[devid];
3744 table = get_irq_table(devid, false);
3748 spin_lock_irqsave(&table->lock, flags);
3749 table->table[index] = irte.val;
3750 spin_unlock_irqrestore(&table->lock, flags);
3752 iommu_flush_irt(iommu, devid);
3753 iommu_completion_wait(iommu);
3758 static void free_irte(u16 devid, int index)
3760 struct irq_remap_table *table;
3761 struct amd_iommu *iommu;
3762 unsigned long flags;
3764 iommu = amd_iommu_rlookup_table[devid];
3768 table = get_irq_table(devid, false);
3772 spin_lock_irqsave(&table->lock, flags);
3773 table->table[index] = 0;
3774 spin_unlock_irqrestore(&table->lock, flags);
3776 iommu_flush_irt(iommu, devid);
3777 iommu_completion_wait(iommu);
3780 static int get_devid(struct irq_alloc_info *info)
3784 switch (info->type) {
3785 case X86_IRQ_ALLOC_TYPE_IOAPIC:
3786 devid = get_ioapic_devid(info->ioapic_id);
3788 case X86_IRQ_ALLOC_TYPE_HPET:
3789 devid = get_hpet_devid(info->hpet_id);
3791 case X86_IRQ_ALLOC_TYPE_MSI:
3792 case X86_IRQ_ALLOC_TYPE_MSIX:
3793 devid = get_device_id(&info->msi_dev->dev);
3803 static struct irq_domain *get_ir_irq_domain(struct irq_alloc_info *info)
3805 struct amd_iommu *iommu;
3811 devid = get_devid(info);
3813 iommu = amd_iommu_rlookup_table[devid];
3815 return iommu->ir_domain;
3821 static struct irq_domain *get_irq_domain(struct irq_alloc_info *info)
3823 struct amd_iommu *iommu;
3829 switch (info->type) {
3830 case X86_IRQ_ALLOC_TYPE_MSI:
3831 case X86_IRQ_ALLOC_TYPE_MSIX:
3832 devid = get_device_id(&info->msi_dev->dev);
3834 iommu = amd_iommu_rlookup_table[devid];
3836 return iommu->msi_domain;
3846 struct irq_remap_ops amd_iommu_irq_ops = {
3847 .prepare = amd_iommu_prepare,
3848 .enable = amd_iommu_enable,
3849 .disable = amd_iommu_disable,
3850 .reenable = amd_iommu_reenable,
3851 .enable_faulting = amd_iommu_enable_faulting,
3852 .get_ir_irq_domain = get_ir_irq_domain,
3853 .get_irq_domain = get_irq_domain,
3856 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
3857 struct irq_cfg *irq_cfg,
3858 struct irq_alloc_info *info,
3859 int devid, int index, int sub_handle)
3861 struct irq_2_irte *irte_info = &data->irq_2_irte;
3862 struct msi_msg *msg = &data->msi_entry;
3863 union irte *irte = &data->irte_entry;
3864 struct IO_APIC_route_entry *entry;
3866 data->irq_2_irte.devid = devid;
3867 data->irq_2_irte.index = index + sub_handle;
3869 /* Setup IRTE for IOMMU */
3871 irte->fields.vector = irq_cfg->vector;
3872 irte->fields.int_type = apic->irq_delivery_mode;
3873 irte->fields.destination = irq_cfg->dest_apicid;
3874 irte->fields.dm = apic->irq_dest_mode;
3875 irte->fields.valid = 1;
3877 switch (info->type) {
3878 case X86_IRQ_ALLOC_TYPE_IOAPIC:
3879 /* Setup IOAPIC entry */
3880 entry = info->ioapic_entry;
3881 info->ioapic_entry = NULL;
3882 memset(entry, 0, sizeof(*entry));
3883 entry->vector = index;
3885 entry->trigger = info->ioapic_trigger;
3886 entry->polarity = info->ioapic_polarity;
3887 /* Mask level triggered irqs. */
3888 if (info->ioapic_trigger)
3892 case X86_IRQ_ALLOC_TYPE_HPET:
3893 case X86_IRQ_ALLOC_TYPE_MSI:
3894 case X86_IRQ_ALLOC_TYPE_MSIX:
3895 msg->address_hi = MSI_ADDR_BASE_HI;
3896 msg->address_lo = MSI_ADDR_BASE_LO;
3897 msg->data = irte_info->index;
3906 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
3907 unsigned int nr_irqs, void *arg)
3909 struct irq_alloc_info *info = arg;
3910 struct irq_data *irq_data;
3911 struct amd_ir_data *data;
3912 struct irq_cfg *cfg;
3918 if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_MSI &&
3919 info->type != X86_IRQ_ALLOC_TYPE_MSIX)
3923 * With IRQ remapping enabled, don't need contiguous CPU vectors
3924 * to support multiple MSI interrupts.
3926 if (info->type == X86_IRQ_ALLOC_TYPE_MSI)
3927 info->flags &= ~X86_IRQ_ALLOC_CONTIGUOUS_VECTORS;
3929 devid = get_devid(info);
3933 ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
3937 if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
3938 if (get_irq_table(devid, true))
3939 index = info->ioapic_pin;
3943 index = alloc_irq_index(devid, nr_irqs);
3946 pr_warn("Failed to allocate IRTE\n");
3947 goto out_free_parent;
3950 for (i = 0; i < nr_irqs; i++) {
3951 irq_data = irq_domain_get_irq_data(domain, virq + i);
3952 cfg = irqd_cfg(irq_data);
3953 if (!irq_data || !cfg) {
3959 data = kzalloc(sizeof(*data), GFP_KERNEL);
3963 irq_data->hwirq = (devid << 16) + i;
3964 irq_data->chip_data = data;
3965 irq_data->chip = &amd_ir_chip;
3966 irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
3967 irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
3973 for (i--; i >= 0; i--) {
3974 irq_data = irq_domain_get_irq_data(domain, virq + i);
3976 kfree(irq_data->chip_data);
3978 for (i = 0; i < nr_irqs; i++)
3979 free_irte(devid, index + i);
3981 irq_domain_free_irqs_common(domain, virq, nr_irqs);
3985 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
3986 unsigned int nr_irqs)
3988 struct irq_2_irte *irte_info;
3989 struct irq_data *irq_data;
3990 struct amd_ir_data *data;
3993 for (i = 0; i < nr_irqs; i++) {
3994 irq_data = irq_domain_get_irq_data(domain, virq + i);
3995 if (irq_data && irq_data->chip_data) {
3996 data = irq_data->chip_data;
3997 irte_info = &data->irq_2_irte;
3998 free_irte(irte_info->devid, irte_info->index);
4002 irq_domain_free_irqs_common(domain, virq, nr_irqs);
4005 static void irq_remapping_activate(struct irq_domain *domain,
4006 struct irq_data *irq_data)
4008 struct amd_ir_data *data = irq_data->chip_data;
4009 struct irq_2_irte *irte_info = &data->irq_2_irte;
4011 modify_irte(irte_info->devid, irte_info->index, data->irte_entry);
4014 static void irq_remapping_deactivate(struct irq_domain *domain,
4015 struct irq_data *irq_data)
4017 struct amd_ir_data *data = irq_data->chip_data;
4018 struct irq_2_irte *irte_info = &data->irq_2_irte;
4022 modify_irte(irte_info->devid, irte_info->index, data->irte_entry);
4025 static struct irq_domain_ops amd_ir_domain_ops = {
4026 .alloc = irq_remapping_alloc,
4027 .free = irq_remapping_free,
4028 .activate = irq_remapping_activate,
4029 .deactivate = irq_remapping_deactivate,
4032 static int amd_ir_set_affinity(struct irq_data *data,
4033 const struct cpumask *mask, bool force)
4035 struct amd_ir_data *ir_data = data->chip_data;
4036 struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4037 struct irq_cfg *cfg = irqd_cfg(data);
4038 struct irq_data *parent = data->parent_data;
4041 ret = parent->chip->irq_set_affinity(parent, mask, force);
4042 if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
4046 * Atomically updates the IRTE with the new destination, vector
4047 * and flushes the interrupt entry cache.
4049 ir_data->irte_entry.fields.vector = cfg->vector;
4050 ir_data->irte_entry.fields.destination = cfg->dest_apicid;
4051 modify_irte(irte_info->devid, irte_info->index, ir_data->irte_entry);
4054 * After this point, all the interrupts will start arriving
4055 * at the new destination. So, time to cleanup the previous
4056 * vector allocation.
4058 send_cleanup_vector(cfg);
4060 return IRQ_SET_MASK_OK_DONE;
4063 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
4065 struct amd_ir_data *ir_data = irq_data->chip_data;
4067 *msg = ir_data->msi_entry;
4070 static struct irq_chip amd_ir_chip = {
4071 .irq_ack = ir_ack_apic_edge,
4072 .irq_set_affinity = amd_ir_set_affinity,
4073 .irq_compose_msi_msg = ir_compose_msi_msg,
4076 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
4078 iommu->ir_domain = irq_domain_add_tree(NULL, &amd_ir_domain_ops, iommu);
4079 if (!iommu->ir_domain)
4082 iommu->ir_domain->parent = arch_get_ir_parent_domain();
4083 iommu->msi_domain = arch_create_msi_irq_domain(iommu->ir_domain);