2 * Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
3 * Author: Joerg Roedel <joerg.roedel@amd.com>
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 <asm/irq_remapping.h>
37 #include <asm/io_apic.h>
39 #include <asm/hw_irq.h>
40 #include <asm/msidef.h>
41 #include <asm/proto.h>
42 #include <asm/iommu.h>
46 #include "amd_iommu_proto.h"
47 #include "amd_iommu_types.h"
48 #include "irq_remapping.h"
50 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
52 #define LOOP_TIMEOUT 100000
55 * This bitmap is used to advertise the page sizes our hardware support
56 * to the IOMMU core, which will then use this information to split
57 * physically contiguous memory regions it is mapping into page sizes
60 * 512GB Pages are not supported due to a hardware bug
62 #define AMD_IOMMU_PGSIZES ((~0xFFFUL) & ~(2ULL << 38))
64 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
66 /* A list of preallocated protection domains */
67 static LIST_HEAD(iommu_pd_list);
68 static DEFINE_SPINLOCK(iommu_pd_list_lock);
70 /* List of all available dev_data structures */
71 static LIST_HEAD(dev_data_list);
72 static DEFINE_SPINLOCK(dev_data_list_lock);
74 LIST_HEAD(ioapic_map);
78 * Domain for untranslated devices - only allocated
79 * if iommu=pt passed on kernel cmd line.
81 static struct protection_domain *pt_domain;
83 static const struct iommu_ops amd_iommu_ops;
85 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
86 int amd_iommu_max_glx_val = -1;
88 static struct dma_map_ops amd_iommu_dma_ops;
91 * general struct to manage commands send to an IOMMU
97 struct kmem_cache *amd_iommu_irq_cache;
99 static void update_domain(struct protection_domain *domain);
100 static int __init alloc_passthrough_domain(void);
102 /****************************************************************************
106 ****************************************************************************/
108 static struct iommu_dev_data *alloc_dev_data(u16 devid)
110 struct iommu_dev_data *dev_data;
113 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
117 dev_data->devid = devid;
118 atomic_set(&dev_data->bind, 0);
120 spin_lock_irqsave(&dev_data_list_lock, flags);
121 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
122 spin_unlock_irqrestore(&dev_data_list_lock, flags);
127 static void free_dev_data(struct iommu_dev_data *dev_data)
131 spin_lock_irqsave(&dev_data_list_lock, flags);
132 list_del(&dev_data->dev_data_list);
133 spin_unlock_irqrestore(&dev_data_list_lock, flags);
138 static struct iommu_dev_data *search_dev_data(u16 devid)
140 struct iommu_dev_data *dev_data;
143 spin_lock_irqsave(&dev_data_list_lock, flags);
144 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
145 if (dev_data->devid == devid)
152 spin_unlock_irqrestore(&dev_data_list_lock, flags);
157 static struct iommu_dev_data *find_dev_data(u16 devid)
159 struct iommu_dev_data *dev_data;
161 dev_data = search_dev_data(devid);
163 if (dev_data == NULL)
164 dev_data = alloc_dev_data(devid);
169 static inline u16 get_device_id(struct device *dev)
171 struct pci_dev *pdev = to_pci_dev(dev);
173 return PCI_DEVID(pdev->bus->number, pdev->devfn);
176 static struct iommu_dev_data *get_dev_data(struct device *dev)
178 return dev->archdata.iommu;
181 static bool pci_iommuv2_capable(struct pci_dev *pdev)
183 static const int caps[] = {
186 PCI_EXT_CAP_ID_PASID,
190 for (i = 0; i < 3; ++i) {
191 pos = pci_find_ext_capability(pdev, caps[i]);
199 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
201 struct iommu_dev_data *dev_data;
203 dev_data = get_dev_data(&pdev->dev);
205 return dev_data->errata & (1 << erratum) ? true : false;
209 * In this function the list of preallocated protection domains is traversed to
210 * find the domain for a specific device
212 static struct dma_ops_domain *find_protection_domain(u16 devid)
214 struct dma_ops_domain *entry, *ret = NULL;
216 u16 alias = amd_iommu_alias_table[devid];
218 if (list_empty(&iommu_pd_list))
221 spin_lock_irqsave(&iommu_pd_list_lock, flags);
223 list_for_each_entry(entry, &iommu_pd_list, list) {
224 if (entry->target_dev == devid ||
225 entry->target_dev == alias) {
231 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
237 * This function checks if the driver got a valid device from the caller to
238 * avoid dereferencing invalid pointers.
240 static bool check_device(struct device *dev)
244 if (!dev || !dev->dma_mask)
248 if (!dev_is_pci(dev))
251 devid = get_device_id(dev);
253 /* Out of our scope? */
254 if (devid > amd_iommu_last_bdf)
257 if (amd_iommu_rlookup_table[devid] == NULL)
263 static int init_iommu_group(struct device *dev)
265 struct iommu_group *group;
267 group = iommu_group_get_for_dev(dev);
270 return PTR_ERR(group);
272 iommu_group_put(group);
276 static int __last_alias(struct pci_dev *pdev, u16 alias, void *data)
278 *(u16 *)data = alias;
282 static u16 get_alias(struct device *dev)
284 struct pci_dev *pdev = to_pci_dev(dev);
285 u16 devid, ivrs_alias, pci_alias;
287 devid = get_device_id(dev);
288 ivrs_alias = amd_iommu_alias_table[devid];
289 pci_for_each_dma_alias(pdev, __last_alias, &pci_alias);
291 if (ivrs_alias == pci_alias)
297 * The IVRS is fairly reliable in telling us about aliases, but it
298 * can't know about every screwy device. If we don't have an IVRS
299 * reported alias, use the PCI reported alias. In that case we may
300 * still need to initialize the rlookup and dev_table entries if the
301 * alias is to a non-existent device.
303 if (ivrs_alias == devid) {
304 if (!amd_iommu_rlookup_table[pci_alias]) {
305 amd_iommu_rlookup_table[pci_alias] =
306 amd_iommu_rlookup_table[devid];
307 memcpy(amd_iommu_dev_table[pci_alias].data,
308 amd_iommu_dev_table[devid].data,
309 sizeof(amd_iommu_dev_table[pci_alias].data));
315 pr_info("AMD-Vi: Using IVRS reported alias %02x:%02x.%d "
316 "for device %s[%04x:%04x], kernel reported alias "
317 "%02x:%02x.%d\n", PCI_BUS_NUM(ivrs_alias), PCI_SLOT(ivrs_alias),
318 PCI_FUNC(ivrs_alias), dev_name(dev), pdev->vendor, pdev->device,
319 PCI_BUS_NUM(pci_alias), PCI_SLOT(pci_alias),
320 PCI_FUNC(pci_alias));
323 * If we don't have a PCI DMA alias and the IVRS alias is on the same
324 * bus, then the IVRS table may know about a quirk that we don't.
326 if (pci_alias == devid &&
327 PCI_BUS_NUM(ivrs_alias) == pdev->bus->number) {
328 pdev->dev_flags |= PCI_DEV_FLAGS_DMA_ALIAS_DEVFN;
329 pdev->dma_alias_devfn = ivrs_alias & 0xff;
330 pr_info("AMD-Vi: Added PCI DMA alias %02x.%d for %s\n",
331 PCI_SLOT(ivrs_alias), PCI_FUNC(ivrs_alias),
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;
345 if (dev->archdata.iommu)
348 dev_data = find_dev_data(get_device_id(dev));
352 alias = get_alias(dev);
354 if (alias != dev_data->devid) {
355 struct iommu_dev_data *alias_data;
357 alias_data = find_dev_data(alias);
358 if (alias_data == NULL) {
359 pr_err("AMD-Vi: Warning: Unhandled device %s\n",
361 free_dev_data(dev_data);
364 dev_data->alias_data = alias_data;
367 ret = init_iommu_group(dev);
369 free_dev_data(dev_data);
373 if (pci_iommuv2_capable(pdev)) {
374 struct amd_iommu *iommu;
376 iommu = amd_iommu_rlookup_table[dev_data->devid];
377 dev_data->iommu_v2 = iommu->is_iommu_v2;
380 dev->archdata.iommu = dev_data;
382 iommu_device_link(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
388 static void iommu_ignore_device(struct device *dev)
392 devid = get_device_id(dev);
393 alias = amd_iommu_alias_table[devid];
395 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
396 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
398 amd_iommu_rlookup_table[devid] = NULL;
399 amd_iommu_rlookup_table[alias] = NULL;
402 static void iommu_uninit_device(struct device *dev)
404 struct iommu_dev_data *dev_data = search_dev_data(get_device_id(dev));
409 iommu_device_unlink(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
412 iommu_group_remove_device(dev);
414 /* Unlink from alias, it may change if another device is re-plugged */
415 dev_data->alias_data = NULL;
418 * We keep dev_data around for unplugged devices and reuse it when the
419 * device is re-plugged - not doing so would introduce a ton of races.
423 void __init amd_iommu_uninit_devices(void)
425 struct iommu_dev_data *dev_data, *n;
426 struct pci_dev *pdev = NULL;
428 for_each_pci_dev(pdev) {
430 if (!check_device(&pdev->dev))
433 iommu_uninit_device(&pdev->dev);
436 /* Free all of our dev_data structures */
437 list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
438 free_dev_data(dev_data);
441 int __init amd_iommu_init_devices(void)
443 struct pci_dev *pdev = NULL;
446 for_each_pci_dev(pdev) {
448 if (!check_device(&pdev->dev))
451 ret = iommu_init_device(&pdev->dev);
452 if (ret == -ENOTSUPP)
453 iommu_ignore_device(&pdev->dev);
462 amd_iommu_uninit_devices();
466 #ifdef CONFIG_AMD_IOMMU_STATS
469 * Initialization code for statistics collection
472 DECLARE_STATS_COUNTER(compl_wait);
473 DECLARE_STATS_COUNTER(cnt_map_single);
474 DECLARE_STATS_COUNTER(cnt_unmap_single);
475 DECLARE_STATS_COUNTER(cnt_map_sg);
476 DECLARE_STATS_COUNTER(cnt_unmap_sg);
477 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
478 DECLARE_STATS_COUNTER(cnt_free_coherent);
479 DECLARE_STATS_COUNTER(cross_page);
480 DECLARE_STATS_COUNTER(domain_flush_single);
481 DECLARE_STATS_COUNTER(domain_flush_all);
482 DECLARE_STATS_COUNTER(alloced_io_mem);
483 DECLARE_STATS_COUNTER(total_map_requests);
484 DECLARE_STATS_COUNTER(complete_ppr);
485 DECLARE_STATS_COUNTER(invalidate_iotlb);
486 DECLARE_STATS_COUNTER(invalidate_iotlb_all);
487 DECLARE_STATS_COUNTER(pri_requests);
489 static struct dentry *stats_dir;
490 static struct dentry *de_fflush;
492 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
494 if (stats_dir == NULL)
497 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
501 static void amd_iommu_stats_init(void)
503 stats_dir = debugfs_create_dir("amd-iommu", NULL);
504 if (stats_dir == NULL)
507 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
508 &amd_iommu_unmap_flush);
510 amd_iommu_stats_add(&compl_wait);
511 amd_iommu_stats_add(&cnt_map_single);
512 amd_iommu_stats_add(&cnt_unmap_single);
513 amd_iommu_stats_add(&cnt_map_sg);
514 amd_iommu_stats_add(&cnt_unmap_sg);
515 amd_iommu_stats_add(&cnt_alloc_coherent);
516 amd_iommu_stats_add(&cnt_free_coherent);
517 amd_iommu_stats_add(&cross_page);
518 amd_iommu_stats_add(&domain_flush_single);
519 amd_iommu_stats_add(&domain_flush_all);
520 amd_iommu_stats_add(&alloced_io_mem);
521 amd_iommu_stats_add(&total_map_requests);
522 amd_iommu_stats_add(&complete_ppr);
523 amd_iommu_stats_add(&invalidate_iotlb);
524 amd_iommu_stats_add(&invalidate_iotlb_all);
525 amd_iommu_stats_add(&pri_requests);
530 /****************************************************************************
532 * Interrupt handling functions
534 ****************************************************************************/
536 static void dump_dte_entry(u16 devid)
540 for (i = 0; i < 4; ++i)
541 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
542 amd_iommu_dev_table[devid].data[i]);
545 static void dump_command(unsigned long phys_addr)
547 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
550 for (i = 0; i < 4; ++i)
551 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
554 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
556 int type, devid, domid, flags;
557 volatile u32 *event = __evt;
562 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
563 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
564 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
565 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
566 address = (u64)(((u64)event[3]) << 32) | event[2];
569 /* Did we hit the erratum? */
570 if (++count == LOOP_TIMEOUT) {
571 pr_err("AMD-Vi: No event written to event log\n");
578 printk(KERN_ERR "AMD-Vi: Event logged [");
581 case EVENT_TYPE_ILL_DEV:
582 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
583 "address=0x%016llx flags=0x%04x]\n",
584 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
586 dump_dte_entry(devid);
588 case EVENT_TYPE_IO_FAULT:
589 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
590 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
591 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
592 domid, address, flags);
594 case EVENT_TYPE_DEV_TAB_ERR:
595 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
596 "address=0x%016llx flags=0x%04x]\n",
597 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
600 case EVENT_TYPE_PAGE_TAB_ERR:
601 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
602 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
603 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
604 domid, address, flags);
606 case EVENT_TYPE_ILL_CMD:
607 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
608 dump_command(address);
610 case EVENT_TYPE_CMD_HARD_ERR:
611 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
612 "flags=0x%04x]\n", address, flags);
614 case EVENT_TYPE_IOTLB_INV_TO:
615 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
616 "address=0x%016llx]\n",
617 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
620 case EVENT_TYPE_INV_DEV_REQ:
621 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
622 "address=0x%016llx flags=0x%04x]\n",
623 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
627 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
630 memset(__evt, 0, 4 * sizeof(u32));
633 static void iommu_poll_events(struct amd_iommu *iommu)
637 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
638 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
640 while (head != tail) {
641 iommu_print_event(iommu, iommu->evt_buf + head);
642 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
645 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
648 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
650 struct amd_iommu_fault fault;
652 INC_STATS_COUNTER(pri_requests);
654 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
655 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
659 fault.address = raw[1];
660 fault.pasid = PPR_PASID(raw[0]);
661 fault.device_id = PPR_DEVID(raw[0]);
662 fault.tag = PPR_TAG(raw[0]);
663 fault.flags = PPR_FLAGS(raw[0]);
665 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
668 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
672 if (iommu->ppr_log == NULL)
675 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
676 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
678 while (head != tail) {
683 raw = (u64 *)(iommu->ppr_log + head);
686 * Hardware bug: Interrupt may arrive before the entry is
687 * written to memory. If this happens we need to wait for the
690 for (i = 0; i < LOOP_TIMEOUT; ++i) {
691 if (PPR_REQ_TYPE(raw[0]) != 0)
696 /* Avoid memcpy function-call overhead */
701 * To detect the hardware bug we need to clear the entry
704 raw[0] = raw[1] = 0UL;
706 /* Update head pointer of hardware ring-buffer */
707 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
708 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
710 /* Handle PPR entry */
711 iommu_handle_ppr_entry(iommu, entry);
713 /* Refresh ring-buffer information */
714 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
715 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
719 irqreturn_t amd_iommu_int_thread(int irq, void *data)
721 struct amd_iommu *iommu = (struct amd_iommu *) data;
722 u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
724 while (status & (MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK)) {
725 /* Enable EVT and PPR interrupts again */
726 writel((MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK),
727 iommu->mmio_base + MMIO_STATUS_OFFSET);
729 if (status & MMIO_STATUS_EVT_INT_MASK) {
730 pr_devel("AMD-Vi: Processing IOMMU Event Log\n");
731 iommu_poll_events(iommu);
734 if (status & MMIO_STATUS_PPR_INT_MASK) {
735 pr_devel("AMD-Vi: Processing IOMMU PPR Log\n");
736 iommu_poll_ppr_log(iommu);
740 * Hardware bug: ERBT1312
741 * When re-enabling interrupt (by writing 1
742 * to clear the bit), the hardware might also try to set
743 * the interrupt bit in the event status register.
744 * In this scenario, the bit will be set, and disable
745 * subsequent interrupts.
747 * Workaround: The IOMMU driver should read back the
748 * status register and check if the interrupt bits are cleared.
749 * If not, driver will need to go through the interrupt handler
750 * again and re-clear the bits
752 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
757 irqreturn_t amd_iommu_int_handler(int irq, void *data)
759 return IRQ_WAKE_THREAD;
762 /****************************************************************************
764 * IOMMU command queuing functions
766 ****************************************************************************/
768 static int wait_on_sem(volatile u64 *sem)
772 while (*sem == 0 && i < LOOP_TIMEOUT) {
777 if (i == LOOP_TIMEOUT) {
778 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
785 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
786 struct iommu_cmd *cmd,
791 target = iommu->cmd_buf + tail;
792 tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
794 /* Copy command to buffer */
795 memcpy(target, cmd, sizeof(*cmd));
797 /* Tell the IOMMU about it */
798 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
801 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
803 WARN_ON(address & 0x7ULL);
805 memset(cmd, 0, sizeof(*cmd));
806 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
807 cmd->data[1] = upper_32_bits(__pa(address));
809 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
812 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
814 memset(cmd, 0, sizeof(*cmd));
815 cmd->data[0] = devid;
816 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
819 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
820 size_t size, u16 domid, int pde)
825 pages = iommu_num_pages(address, size, PAGE_SIZE);
830 * If we have to flush more than one page, flush all
831 * TLB entries for this domain
833 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
837 address &= PAGE_MASK;
839 memset(cmd, 0, sizeof(*cmd));
840 cmd->data[1] |= domid;
841 cmd->data[2] = lower_32_bits(address);
842 cmd->data[3] = upper_32_bits(address);
843 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
844 if (s) /* size bit - we flush more than one 4kb page */
845 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
846 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
847 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
850 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
851 u64 address, size_t size)
856 pages = iommu_num_pages(address, size, PAGE_SIZE);
861 * If we have to flush more than one page, flush all
862 * TLB entries for this domain
864 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
868 address &= PAGE_MASK;
870 memset(cmd, 0, sizeof(*cmd));
871 cmd->data[0] = devid;
872 cmd->data[0] |= (qdep & 0xff) << 24;
873 cmd->data[1] = devid;
874 cmd->data[2] = lower_32_bits(address);
875 cmd->data[3] = upper_32_bits(address);
876 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
878 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
881 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
882 u64 address, bool size)
884 memset(cmd, 0, sizeof(*cmd));
886 address &= ~(0xfffULL);
888 cmd->data[0] = pasid;
889 cmd->data[1] = domid;
890 cmd->data[2] = lower_32_bits(address);
891 cmd->data[3] = upper_32_bits(address);
892 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
893 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
895 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
896 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
899 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
900 int qdep, u64 address, bool size)
902 memset(cmd, 0, sizeof(*cmd));
904 address &= ~(0xfffULL);
906 cmd->data[0] = devid;
907 cmd->data[0] |= ((pasid >> 8) & 0xff) << 16;
908 cmd->data[0] |= (qdep & 0xff) << 24;
909 cmd->data[1] = devid;
910 cmd->data[1] |= (pasid & 0xff) << 16;
911 cmd->data[2] = lower_32_bits(address);
912 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
913 cmd->data[3] = upper_32_bits(address);
915 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
916 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
919 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
920 int status, int tag, bool gn)
922 memset(cmd, 0, sizeof(*cmd));
924 cmd->data[0] = devid;
926 cmd->data[1] = pasid;
927 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
929 cmd->data[3] = tag & 0x1ff;
930 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
932 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
935 static void build_inv_all(struct iommu_cmd *cmd)
937 memset(cmd, 0, sizeof(*cmd));
938 CMD_SET_TYPE(cmd, CMD_INV_ALL);
941 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
943 memset(cmd, 0, sizeof(*cmd));
944 cmd->data[0] = devid;
945 CMD_SET_TYPE(cmd, CMD_INV_IRT);
949 * Writes the command to the IOMMUs command buffer and informs the
950 * hardware about the new command.
952 static int iommu_queue_command_sync(struct amd_iommu *iommu,
953 struct iommu_cmd *cmd,
956 u32 left, tail, head, next_tail;
959 WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
962 spin_lock_irqsave(&iommu->lock, flags);
964 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
965 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
966 next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
967 left = (head - next_tail) % iommu->cmd_buf_size;
970 struct iommu_cmd sync_cmd;
971 volatile u64 sem = 0;
974 build_completion_wait(&sync_cmd, (u64)&sem);
975 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
977 spin_unlock_irqrestore(&iommu->lock, flags);
979 if ((ret = wait_on_sem(&sem)) != 0)
985 copy_cmd_to_buffer(iommu, cmd, tail);
987 /* We need to sync now to make sure all commands are processed */
988 iommu->need_sync = sync;
990 spin_unlock_irqrestore(&iommu->lock, flags);
995 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
997 return iommu_queue_command_sync(iommu, cmd, true);
1001 * This function queues a completion wait command into the command
1002 * buffer of an IOMMU
1004 static int iommu_completion_wait(struct amd_iommu *iommu)
1006 struct iommu_cmd cmd;
1007 volatile u64 sem = 0;
1010 if (!iommu->need_sync)
1013 build_completion_wait(&cmd, (u64)&sem);
1015 ret = iommu_queue_command_sync(iommu, &cmd, false);
1019 return wait_on_sem(&sem);
1022 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1024 struct iommu_cmd cmd;
1026 build_inv_dte(&cmd, devid);
1028 return iommu_queue_command(iommu, &cmd);
1031 static void iommu_flush_dte_all(struct amd_iommu *iommu)
1035 for (devid = 0; devid <= 0xffff; ++devid)
1036 iommu_flush_dte(iommu, devid);
1038 iommu_completion_wait(iommu);
1042 * This function uses heavy locking and may disable irqs for some time. But
1043 * this is no issue because it is only called during resume.
1045 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1049 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1050 struct iommu_cmd cmd;
1051 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1053 iommu_queue_command(iommu, &cmd);
1056 iommu_completion_wait(iommu);
1059 static void iommu_flush_all(struct amd_iommu *iommu)
1061 struct iommu_cmd cmd;
1063 build_inv_all(&cmd);
1065 iommu_queue_command(iommu, &cmd);
1066 iommu_completion_wait(iommu);
1069 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1071 struct iommu_cmd cmd;
1073 build_inv_irt(&cmd, devid);
1075 iommu_queue_command(iommu, &cmd);
1078 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1082 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1083 iommu_flush_irt(iommu, devid);
1085 iommu_completion_wait(iommu);
1088 void iommu_flush_all_caches(struct amd_iommu *iommu)
1090 if (iommu_feature(iommu, FEATURE_IA)) {
1091 iommu_flush_all(iommu);
1093 iommu_flush_dte_all(iommu);
1094 iommu_flush_irt_all(iommu);
1095 iommu_flush_tlb_all(iommu);
1100 * Command send function for flushing on-device TLB
1102 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1103 u64 address, size_t size)
1105 struct amd_iommu *iommu;
1106 struct iommu_cmd cmd;
1109 qdep = dev_data->ats.qdep;
1110 iommu = amd_iommu_rlookup_table[dev_data->devid];
1112 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1114 return iommu_queue_command(iommu, &cmd);
1118 * Command send function for invalidating a device table entry
1120 static int device_flush_dte(struct iommu_dev_data *dev_data)
1122 struct amd_iommu *iommu;
1125 iommu = amd_iommu_rlookup_table[dev_data->devid];
1127 ret = iommu_flush_dte(iommu, dev_data->devid);
1131 if (dev_data->ats.enabled)
1132 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1138 * TLB invalidation function which is called from the mapping functions.
1139 * It invalidates a single PTE if the range to flush is within a single
1140 * page. Otherwise it flushes the whole TLB of the IOMMU.
1142 static void __domain_flush_pages(struct protection_domain *domain,
1143 u64 address, size_t size, int pde)
1145 struct iommu_dev_data *dev_data;
1146 struct iommu_cmd cmd;
1149 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1151 for (i = 0; i < amd_iommus_present; ++i) {
1152 if (!domain->dev_iommu[i])
1156 * Devices of this domain are behind this IOMMU
1157 * We need a TLB flush
1159 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1162 list_for_each_entry(dev_data, &domain->dev_list, list) {
1164 if (!dev_data->ats.enabled)
1167 ret |= device_flush_iotlb(dev_data, address, size);
1173 static void domain_flush_pages(struct protection_domain *domain,
1174 u64 address, size_t size)
1176 __domain_flush_pages(domain, address, size, 0);
1179 /* Flush the whole IO/TLB for a given protection domain */
1180 static void domain_flush_tlb(struct protection_domain *domain)
1182 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1185 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1186 static void domain_flush_tlb_pde(struct protection_domain *domain)
1188 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1191 static void domain_flush_complete(struct protection_domain *domain)
1195 for (i = 0; i < amd_iommus_present; ++i) {
1196 if (!domain->dev_iommu[i])
1200 * Devices of this domain are behind this IOMMU
1201 * We need to wait for completion of all commands.
1203 iommu_completion_wait(amd_iommus[i]);
1209 * This function flushes the DTEs for all devices in domain
1211 static void domain_flush_devices(struct protection_domain *domain)
1213 struct iommu_dev_data *dev_data;
1215 list_for_each_entry(dev_data, &domain->dev_list, list)
1216 device_flush_dte(dev_data);
1219 /****************************************************************************
1221 * The functions below are used the create the page table mappings for
1222 * unity mapped regions.
1224 ****************************************************************************/
1227 * This function is used to add another level to an IO page table. Adding
1228 * another level increases the size of the address space by 9 bits to a size up
1231 static bool increase_address_space(struct protection_domain *domain,
1236 if (domain->mode == PAGE_MODE_6_LEVEL)
1237 /* address space already 64 bit large */
1240 pte = (void *)get_zeroed_page(gfp);
1244 *pte = PM_LEVEL_PDE(domain->mode,
1245 virt_to_phys(domain->pt_root));
1246 domain->pt_root = pte;
1248 domain->updated = true;
1253 static u64 *alloc_pte(struct protection_domain *domain,
1254 unsigned long address,
1255 unsigned long page_size,
1262 BUG_ON(!is_power_of_2(page_size));
1264 while (address > PM_LEVEL_SIZE(domain->mode))
1265 increase_address_space(domain, gfp);
1267 level = domain->mode - 1;
1268 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1269 address = PAGE_SIZE_ALIGN(address, page_size);
1270 end_lvl = PAGE_SIZE_LEVEL(page_size);
1272 while (level > end_lvl) {
1273 if (!IOMMU_PTE_PRESENT(*pte)) {
1274 page = (u64 *)get_zeroed_page(gfp);
1277 *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1280 /* No level skipping support yet */
1281 if (PM_PTE_LEVEL(*pte) != level)
1286 pte = IOMMU_PTE_PAGE(*pte);
1288 if (pte_page && level == end_lvl)
1291 pte = &pte[PM_LEVEL_INDEX(level, address)];
1298 * This function checks if there is a PTE for a given dma address. If
1299 * there is one, it returns the pointer to it.
1301 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
1306 if (address > PM_LEVEL_SIZE(domain->mode))
1309 level = domain->mode - 1;
1310 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1315 if (!IOMMU_PTE_PRESENT(*pte))
1319 if (PM_PTE_LEVEL(*pte) == 0x07) {
1320 unsigned long pte_mask, __pte;
1323 * If we have a series of large PTEs, make
1324 * sure to return a pointer to the first one.
1326 pte_mask = PTE_PAGE_SIZE(*pte);
1327 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1328 __pte = ((unsigned long)pte) & pte_mask;
1330 return (u64 *)__pte;
1333 /* No level skipping support yet */
1334 if (PM_PTE_LEVEL(*pte) != level)
1339 /* Walk to the next level */
1340 pte = IOMMU_PTE_PAGE(*pte);
1341 pte = &pte[PM_LEVEL_INDEX(level, address)];
1348 * Generic mapping functions. It maps a physical address into a DMA
1349 * address space. It allocates the page table pages if necessary.
1350 * In the future it can be extended to a generic mapping function
1351 * supporting all features of AMD IOMMU page tables like level skipping
1352 * and full 64 bit address spaces.
1354 static int iommu_map_page(struct protection_domain *dom,
1355 unsigned long bus_addr,
1356 unsigned long phys_addr,
1358 unsigned long page_size)
1363 if (!(prot & IOMMU_PROT_MASK))
1366 bus_addr = PAGE_ALIGN(bus_addr);
1367 phys_addr = PAGE_ALIGN(phys_addr);
1368 count = PAGE_SIZE_PTE_COUNT(page_size);
1369 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1371 for (i = 0; i < count; ++i)
1372 if (IOMMU_PTE_PRESENT(pte[i]))
1375 if (page_size > PAGE_SIZE) {
1376 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1377 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1379 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1381 if (prot & IOMMU_PROT_IR)
1382 __pte |= IOMMU_PTE_IR;
1383 if (prot & IOMMU_PROT_IW)
1384 __pte |= IOMMU_PTE_IW;
1386 for (i = 0; i < count; ++i)
1394 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1395 unsigned long bus_addr,
1396 unsigned long page_size)
1398 unsigned long long unmap_size, unmapped;
1401 BUG_ON(!is_power_of_2(page_size));
1405 while (unmapped < page_size) {
1407 pte = fetch_pte(dom, bus_addr);
1411 * No PTE for this address
1412 * move forward in 4kb steps
1414 unmap_size = PAGE_SIZE;
1415 } else if (PM_PTE_LEVEL(*pte) == 0) {
1416 /* 4kb PTE found for this address */
1417 unmap_size = PAGE_SIZE;
1422 /* Large PTE found which maps this address */
1423 unmap_size = PTE_PAGE_SIZE(*pte);
1425 /* Only unmap from the first pte in the page */
1426 if ((unmap_size - 1) & bus_addr)
1428 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1429 for (i = 0; i < count; i++)
1433 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1434 unmapped += unmap_size;
1437 BUG_ON(unmapped && !is_power_of_2(unmapped));
1443 * This function checks if a specific unity mapping entry is needed for
1444 * this specific IOMMU.
1446 static int iommu_for_unity_map(struct amd_iommu *iommu,
1447 struct unity_map_entry *entry)
1451 for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1452 bdf = amd_iommu_alias_table[i];
1453 if (amd_iommu_rlookup_table[bdf] == iommu)
1461 * This function actually applies the mapping to the page table of the
1464 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1465 struct unity_map_entry *e)
1470 for (addr = e->address_start; addr < e->address_end;
1471 addr += PAGE_SIZE) {
1472 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1477 * if unity mapping is in aperture range mark the page
1478 * as allocated in the aperture
1480 if (addr < dma_dom->aperture_size)
1481 __set_bit(addr >> PAGE_SHIFT,
1482 dma_dom->aperture[0]->bitmap);
1489 * Init the unity mappings for a specific IOMMU in the system
1491 * Basically iterates over all unity mapping entries and applies them to
1492 * the default domain DMA of that IOMMU if necessary.
1494 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1496 struct unity_map_entry *entry;
1499 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1500 if (!iommu_for_unity_map(iommu, entry))
1502 ret = dma_ops_unity_map(iommu->default_dom, entry);
1511 * Inits the unity mappings required for a specific device
1513 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1516 struct unity_map_entry *e;
1519 list_for_each_entry(e, &amd_iommu_unity_map, list) {
1520 if (!(devid >= e->devid_start && devid <= e->devid_end))
1522 ret = dma_ops_unity_map(dma_dom, e);
1530 /****************************************************************************
1532 * The next functions belong to the address allocator for the dma_ops
1533 * interface functions. They work like the allocators in the other IOMMU
1534 * drivers. Its basically a bitmap which marks the allocated pages in
1535 * the aperture. Maybe it could be enhanced in the future to a more
1536 * efficient allocator.
1538 ****************************************************************************/
1541 * The address allocator core functions.
1543 * called with domain->lock held
1547 * Used to reserve address ranges in the aperture (e.g. for exclusion
1550 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1551 unsigned long start_page,
1554 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1556 if (start_page + pages > last_page)
1557 pages = last_page - start_page;
1559 for (i = start_page; i < start_page + pages; ++i) {
1560 int index = i / APERTURE_RANGE_PAGES;
1561 int page = i % APERTURE_RANGE_PAGES;
1562 __set_bit(page, dom->aperture[index]->bitmap);
1567 * This function is used to add a new aperture range to an existing
1568 * aperture in case of dma_ops domain allocation or address allocation
1571 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1572 bool populate, gfp_t gfp)
1574 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1575 struct amd_iommu *iommu;
1576 unsigned long i, old_size;
1578 #ifdef CONFIG_IOMMU_STRESS
1582 if (index >= APERTURE_MAX_RANGES)
1585 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1586 if (!dma_dom->aperture[index])
1589 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1590 if (!dma_dom->aperture[index]->bitmap)
1593 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1596 unsigned long address = dma_dom->aperture_size;
1597 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1598 u64 *pte, *pte_page;
1600 for (i = 0; i < num_ptes; ++i) {
1601 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1606 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1608 address += APERTURE_RANGE_SIZE / 64;
1612 old_size = dma_dom->aperture_size;
1613 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1615 /* Reserve address range used for MSI messages */
1616 if (old_size < MSI_ADDR_BASE_LO &&
1617 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1618 unsigned long spage;
1621 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1622 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1624 dma_ops_reserve_addresses(dma_dom, spage, pages);
1627 /* Initialize the exclusion range if necessary */
1628 for_each_iommu(iommu) {
1629 if (iommu->exclusion_start &&
1630 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1631 && iommu->exclusion_start < dma_dom->aperture_size) {
1632 unsigned long startpage;
1633 int pages = iommu_num_pages(iommu->exclusion_start,
1634 iommu->exclusion_length,
1636 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1637 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1642 * Check for areas already mapped as present in the new aperture
1643 * range and mark those pages as reserved in the allocator. Such
1644 * mappings may already exist as a result of requested unity
1645 * mappings for devices.
1647 for (i = dma_dom->aperture[index]->offset;
1648 i < dma_dom->aperture_size;
1650 u64 *pte = fetch_pte(&dma_dom->domain, i);
1651 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1654 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1657 update_domain(&dma_dom->domain);
1662 update_domain(&dma_dom->domain);
1664 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1666 kfree(dma_dom->aperture[index]);
1667 dma_dom->aperture[index] = NULL;
1672 static unsigned long dma_ops_area_alloc(struct device *dev,
1673 struct dma_ops_domain *dom,
1675 unsigned long align_mask,
1677 unsigned long start)
1679 unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1680 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1681 int i = start >> APERTURE_RANGE_SHIFT;
1682 unsigned long boundary_size;
1683 unsigned long address = -1;
1684 unsigned long limit;
1686 next_bit >>= PAGE_SHIFT;
1688 boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1689 PAGE_SIZE) >> PAGE_SHIFT;
1691 for (;i < max_index; ++i) {
1692 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1694 if (dom->aperture[i]->offset >= dma_mask)
1697 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1698 dma_mask >> PAGE_SHIFT);
1700 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1701 limit, next_bit, pages, 0,
1702 boundary_size, align_mask);
1703 if (address != -1) {
1704 address = dom->aperture[i]->offset +
1705 (address << PAGE_SHIFT);
1706 dom->next_address = address + (pages << PAGE_SHIFT);
1716 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1717 struct dma_ops_domain *dom,
1719 unsigned long align_mask,
1722 unsigned long address;
1724 #ifdef CONFIG_IOMMU_STRESS
1725 dom->next_address = 0;
1726 dom->need_flush = true;
1729 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1730 dma_mask, dom->next_address);
1732 if (address == -1) {
1733 dom->next_address = 0;
1734 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1736 dom->need_flush = true;
1739 if (unlikely(address == -1))
1740 address = DMA_ERROR_CODE;
1742 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1748 * The address free function.
1750 * called with domain->lock held
1752 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1753 unsigned long address,
1756 unsigned i = address >> APERTURE_RANGE_SHIFT;
1757 struct aperture_range *range = dom->aperture[i];
1759 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1761 #ifdef CONFIG_IOMMU_STRESS
1766 if (address >= dom->next_address)
1767 dom->need_flush = true;
1769 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1771 bitmap_clear(range->bitmap, address, pages);
1775 /****************************************************************************
1777 * The next functions belong to the domain allocation. A domain is
1778 * allocated for every IOMMU as the default domain. If device isolation
1779 * is enabled, every device get its own domain. The most important thing
1780 * about domains is the page table mapping the DMA address space they
1783 ****************************************************************************/
1786 * This function adds a protection domain to the global protection domain list
1788 static void add_domain_to_list(struct protection_domain *domain)
1790 unsigned long flags;
1792 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1793 list_add(&domain->list, &amd_iommu_pd_list);
1794 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1798 * This function removes a protection domain to the global
1799 * protection domain list
1801 static void del_domain_from_list(struct protection_domain *domain)
1803 unsigned long flags;
1805 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1806 list_del(&domain->list);
1807 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1810 static u16 domain_id_alloc(void)
1812 unsigned long flags;
1815 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1816 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1818 if (id > 0 && id < MAX_DOMAIN_ID)
1819 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1822 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1827 static void domain_id_free(int id)
1829 unsigned long flags;
1831 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1832 if (id > 0 && id < MAX_DOMAIN_ID)
1833 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1834 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1837 #define DEFINE_FREE_PT_FN(LVL, FN) \
1838 static void free_pt_##LVL (unsigned long __pt) \
1846 for (i = 0; i < 512; ++i) { \
1847 if (!IOMMU_PTE_PRESENT(pt[i])) \
1850 p = (unsigned long)IOMMU_PTE_PAGE(pt[i]); \
1853 free_page((unsigned long)pt); \
1856 DEFINE_FREE_PT_FN(l2, free_page)
1857 DEFINE_FREE_PT_FN(l3, free_pt_l2)
1858 DEFINE_FREE_PT_FN(l4, free_pt_l3)
1859 DEFINE_FREE_PT_FN(l5, free_pt_l4)
1860 DEFINE_FREE_PT_FN(l6, free_pt_l5)
1862 static void free_pagetable(struct protection_domain *domain)
1864 unsigned long root = (unsigned long)domain->pt_root;
1866 switch (domain->mode) {
1867 case PAGE_MODE_NONE:
1869 case PAGE_MODE_1_LEVEL:
1872 case PAGE_MODE_2_LEVEL:
1875 case PAGE_MODE_3_LEVEL:
1878 case PAGE_MODE_4_LEVEL:
1881 case PAGE_MODE_5_LEVEL:
1884 case PAGE_MODE_6_LEVEL:
1892 static void free_gcr3_tbl_level1(u64 *tbl)
1897 for (i = 0; i < 512; ++i) {
1898 if (!(tbl[i] & GCR3_VALID))
1901 ptr = __va(tbl[i] & PAGE_MASK);
1903 free_page((unsigned long)ptr);
1907 static void free_gcr3_tbl_level2(u64 *tbl)
1912 for (i = 0; i < 512; ++i) {
1913 if (!(tbl[i] & GCR3_VALID))
1916 ptr = __va(tbl[i] & PAGE_MASK);
1918 free_gcr3_tbl_level1(ptr);
1922 static void free_gcr3_table(struct protection_domain *domain)
1924 if (domain->glx == 2)
1925 free_gcr3_tbl_level2(domain->gcr3_tbl);
1926 else if (domain->glx == 1)
1927 free_gcr3_tbl_level1(domain->gcr3_tbl);
1928 else if (domain->glx != 0)
1931 free_page((unsigned long)domain->gcr3_tbl);
1935 * Free a domain, only used if something went wrong in the
1936 * allocation path and we need to free an already allocated page table
1938 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1945 del_domain_from_list(&dom->domain);
1947 free_pagetable(&dom->domain);
1949 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1950 if (!dom->aperture[i])
1952 free_page((unsigned long)dom->aperture[i]->bitmap);
1953 kfree(dom->aperture[i]);
1960 * Allocates a new protection domain usable for the dma_ops functions.
1961 * It also initializes the page table and the address allocator data
1962 * structures required for the dma_ops interface
1964 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1966 struct dma_ops_domain *dma_dom;
1968 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1972 spin_lock_init(&dma_dom->domain.lock);
1974 dma_dom->domain.id = domain_id_alloc();
1975 if (dma_dom->domain.id == 0)
1977 INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1978 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1979 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1980 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1981 dma_dom->domain.priv = dma_dom;
1982 if (!dma_dom->domain.pt_root)
1985 dma_dom->need_flush = false;
1986 dma_dom->target_dev = 0xffff;
1988 add_domain_to_list(&dma_dom->domain);
1990 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1994 * mark the first page as allocated so we never return 0 as
1995 * a valid dma-address. So we can use 0 as error value
1997 dma_dom->aperture[0]->bitmap[0] = 1;
1998 dma_dom->next_address = 0;
2004 dma_ops_domain_free(dma_dom);
2010 * little helper function to check whether a given protection domain is a
2013 static bool dma_ops_domain(struct protection_domain *domain)
2015 return domain->flags & PD_DMA_OPS_MASK;
2018 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
2023 if (domain->mode != PAGE_MODE_NONE)
2024 pte_root = virt_to_phys(domain->pt_root);
2026 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
2027 << DEV_ENTRY_MODE_SHIFT;
2028 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
2030 flags = amd_iommu_dev_table[devid].data[1];
2033 flags |= DTE_FLAG_IOTLB;
2035 if (domain->flags & PD_IOMMUV2_MASK) {
2036 u64 gcr3 = __pa(domain->gcr3_tbl);
2037 u64 glx = domain->glx;
2040 pte_root |= DTE_FLAG_GV;
2041 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
2043 /* First mask out possible old values for GCR3 table */
2044 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
2047 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
2050 /* Encode GCR3 table into DTE */
2051 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
2054 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
2057 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
2061 flags &= ~(0xffffUL);
2062 flags |= domain->id;
2064 amd_iommu_dev_table[devid].data[1] = flags;
2065 amd_iommu_dev_table[devid].data[0] = pte_root;
2068 static void clear_dte_entry(u16 devid)
2070 /* remove entry from the device table seen by the hardware */
2071 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
2072 amd_iommu_dev_table[devid].data[1] = 0;
2074 amd_iommu_apply_erratum_63(devid);
2077 static void do_attach(struct iommu_dev_data *dev_data,
2078 struct protection_domain *domain)
2080 struct amd_iommu *iommu;
2083 iommu = amd_iommu_rlookup_table[dev_data->devid];
2084 ats = dev_data->ats.enabled;
2086 /* Update data structures */
2087 dev_data->domain = domain;
2088 list_add(&dev_data->list, &domain->dev_list);
2089 set_dte_entry(dev_data->devid, domain, ats);
2091 /* Do reference counting */
2092 domain->dev_iommu[iommu->index] += 1;
2093 domain->dev_cnt += 1;
2095 /* Flush the DTE entry */
2096 device_flush_dte(dev_data);
2099 static void do_detach(struct iommu_dev_data *dev_data)
2101 struct amd_iommu *iommu;
2103 iommu = amd_iommu_rlookup_table[dev_data->devid];
2105 /* decrease reference counters */
2106 dev_data->domain->dev_iommu[iommu->index] -= 1;
2107 dev_data->domain->dev_cnt -= 1;
2109 /* Update data structures */
2110 dev_data->domain = NULL;
2111 list_del(&dev_data->list);
2112 clear_dte_entry(dev_data->devid);
2114 /* Flush the DTE entry */
2115 device_flush_dte(dev_data);
2119 * If a device is not yet associated with a domain, this function does
2120 * assigns it visible for the hardware
2122 static int __attach_device(struct iommu_dev_data *dev_data,
2123 struct protection_domain *domain)
2128 spin_lock(&domain->lock);
2130 if (dev_data->alias_data != NULL) {
2131 struct iommu_dev_data *alias_data = dev_data->alias_data;
2133 /* Some sanity checks */
2135 if (alias_data->domain != NULL &&
2136 alias_data->domain != domain)
2139 if (dev_data->domain != NULL &&
2140 dev_data->domain != domain)
2143 /* Do real assignment */
2144 if (alias_data->domain == NULL)
2145 do_attach(alias_data, domain);
2147 atomic_inc(&alias_data->bind);
2150 if (dev_data->domain == NULL)
2151 do_attach(dev_data, domain);
2153 atomic_inc(&dev_data->bind);
2160 spin_unlock(&domain->lock);
2166 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2168 pci_disable_ats(pdev);
2169 pci_disable_pri(pdev);
2170 pci_disable_pasid(pdev);
2173 /* FIXME: Change generic reset-function to do the same */
2174 static int pri_reset_while_enabled(struct pci_dev *pdev)
2179 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2183 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2184 control |= PCI_PRI_CTRL_RESET;
2185 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2190 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2195 /* FIXME: Hardcode number of outstanding requests for now */
2197 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2199 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2201 /* Only allow access to user-accessible pages */
2202 ret = pci_enable_pasid(pdev, 0);
2206 /* First reset the PRI state of the device */
2207 ret = pci_reset_pri(pdev);
2212 ret = pci_enable_pri(pdev, reqs);
2217 ret = pri_reset_while_enabled(pdev);
2222 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2229 pci_disable_pri(pdev);
2230 pci_disable_pasid(pdev);
2235 /* FIXME: Move this to PCI code */
2236 #define PCI_PRI_TLP_OFF (1 << 15)
2238 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2243 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2247 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2249 return (status & PCI_PRI_TLP_OFF) ? true : false;
2253 * If a device is not yet associated with a domain, this function
2254 * assigns it visible for the hardware
2256 static int attach_device(struct device *dev,
2257 struct protection_domain *domain)
2259 struct pci_dev *pdev = to_pci_dev(dev);
2260 struct iommu_dev_data *dev_data;
2261 unsigned long flags;
2264 dev_data = get_dev_data(dev);
2266 if (domain->flags & PD_IOMMUV2_MASK) {
2267 if (!dev_data->iommu_v2 || !dev_data->passthrough)
2270 if (pdev_iommuv2_enable(pdev) != 0)
2273 dev_data->ats.enabled = true;
2274 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2275 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2276 } else if (amd_iommu_iotlb_sup &&
2277 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2278 dev_data->ats.enabled = true;
2279 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2282 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2283 ret = __attach_device(dev_data, domain);
2284 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2287 * We might boot into a crash-kernel here. The crashed kernel
2288 * left the caches in the IOMMU dirty. So we have to flush
2289 * here to evict all dirty stuff.
2291 domain_flush_tlb_pde(domain);
2297 * Removes a device from a protection domain (unlocked)
2299 static void __detach_device(struct iommu_dev_data *dev_data)
2301 struct protection_domain *domain;
2302 unsigned long flags;
2304 BUG_ON(!dev_data->domain);
2306 domain = dev_data->domain;
2308 spin_lock_irqsave(&domain->lock, flags);
2310 if (dev_data->alias_data != NULL) {
2311 struct iommu_dev_data *alias_data = dev_data->alias_data;
2313 if (atomic_dec_and_test(&alias_data->bind))
2314 do_detach(alias_data);
2317 if (atomic_dec_and_test(&dev_data->bind))
2318 do_detach(dev_data);
2320 spin_unlock_irqrestore(&domain->lock, flags);
2323 * If we run in passthrough mode the device must be assigned to the
2324 * passthrough domain if it is detached from any other domain.
2325 * Make sure we can deassign from the pt_domain itself.
2327 if (dev_data->passthrough &&
2328 (dev_data->domain == NULL && domain != pt_domain))
2329 __attach_device(dev_data, pt_domain);
2333 * Removes a device from a protection domain (with devtable_lock held)
2335 static void detach_device(struct device *dev)
2337 struct protection_domain *domain;
2338 struct iommu_dev_data *dev_data;
2339 unsigned long flags;
2341 dev_data = get_dev_data(dev);
2342 domain = dev_data->domain;
2344 /* lock device table */
2345 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2346 __detach_device(dev_data);
2347 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2349 if (domain->flags & PD_IOMMUV2_MASK)
2350 pdev_iommuv2_disable(to_pci_dev(dev));
2351 else if (dev_data->ats.enabled)
2352 pci_disable_ats(to_pci_dev(dev));
2354 dev_data->ats.enabled = false;
2358 * Find out the protection domain structure for a given PCI device. This
2359 * will give us the pointer to the page table root for example.
2361 static struct protection_domain *domain_for_device(struct device *dev)
2363 struct iommu_dev_data *dev_data;
2364 struct protection_domain *dom = NULL;
2365 unsigned long flags;
2367 dev_data = get_dev_data(dev);
2369 if (dev_data->domain)
2370 return dev_data->domain;
2372 if (dev_data->alias_data != NULL) {
2373 struct iommu_dev_data *alias_data = dev_data->alias_data;
2375 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
2376 if (alias_data->domain != NULL) {
2377 __attach_device(dev_data, alias_data->domain);
2378 dom = alias_data->domain;
2380 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2386 static int device_change_notifier(struct notifier_block *nb,
2387 unsigned long action, void *data)
2389 struct dma_ops_domain *dma_domain;
2390 struct protection_domain *domain;
2391 struct iommu_dev_data *dev_data;
2392 struct device *dev = data;
2393 struct amd_iommu *iommu;
2394 unsigned long flags;
2397 if (!check_device(dev))
2400 devid = get_device_id(dev);
2401 iommu = amd_iommu_rlookup_table[devid];
2402 dev_data = get_dev_data(dev);
2405 case BUS_NOTIFY_UNBOUND_DRIVER:
2407 domain = domain_for_device(dev);
2411 if (dev_data->passthrough)
2415 case BUS_NOTIFY_ADD_DEVICE:
2417 iommu_init_device(dev);
2420 * dev_data is still NULL and
2421 * got initialized in iommu_init_device
2423 dev_data = get_dev_data(dev);
2425 if (iommu_pass_through || dev_data->iommu_v2) {
2426 dev_data->passthrough = true;
2427 attach_device(dev, pt_domain);
2431 domain = domain_for_device(dev);
2433 /* allocate a protection domain if a device is added */
2434 dma_domain = find_protection_domain(devid);
2436 dma_domain = dma_ops_domain_alloc();
2439 dma_domain->target_dev = devid;
2441 spin_lock_irqsave(&iommu_pd_list_lock, flags);
2442 list_add_tail(&dma_domain->list, &iommu_pd_list);
2443 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
2446 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2449 case BUS_NOTIFY_DEL_DEVICE:
2451 iommu_uninit_device(dev);
2457 iommu_completion_wait(iommu);
2463 static struct notifier_block device_nb = {
2464 .notifier_call = device_change_notifier,
2467 void amd_iommu_init_notifier(void)
2469 bus_register_notifier(&pci_bus_type, &device_nb);
2472 /*****************************************************************************
2474 * The next functions belong to the dma_ops mapping/unmapping code.
2476 *****************************************************************************/
2479 * In the dma_ops path we only have the struct device. This function
2480 * finds the corresponding IOMMU, the protection domain and the
2481 * requestor id for a given device.
2482 * If the device is not yet associated with a domain this is also done
2485 static struct protection_domain *get_domain(struct device *dev)
2487 struct protection_domain *domain;
2488 struct dma_ops_domain *dma_dom;
2489 u16 devid = get_device_id(dev);
2491 if (!check_device(dev))
2492 return ERR_PTR(-EINVAL);
2494 domain = domain_for_device(dev);
2495 if (domain != NULL && !dma_ops_domain(domain))
2496 return ERR_PTR(-EBUSY);
2501 /* Device not bound yet - bind it */
2502 dma_dom = find_protection_domain(devid);
2504 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
2505 attach_device(dev, &dma_dom->domain);
2506 DUMP_printk("Using protection domain %d for device %s\n",
2507 dma_dom->domain.id, dev_name(dev));
2509 return &dma_dom->domain;
2512 static void update_device_table(struct protection_domain *domain)
2514 struct iommu_dev_data *dev_data;
2516 list_for_each_entry(dev_data, &domain->dev_list, list)
2517 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2520 static void update_domain(struct protection_domain *domain)
2522 if (!domain->updated)
2525 update_device_table(domain);
2527 domain_flush_devices(domain);
2528 domain_flush_tlb_pde(domain);
2530 domain->updated = false;
2534 * This function fetches the PTE for a given address in the aperture
2536 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2537 unsigned long address)
2539 struct aperture_range *aperture;
2540 u64 *pte, *pte_page;
2542 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2546 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2548 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2550 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2552 pte += PM_LEVEL_INDEX(0, address);
2554 update_domain(&dom->domain);
2560 * This is the generic map function. It maps one 4kb page at paddr to
2561 * the given address in the DMA address space for the domain.
2563 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2564 unsigned long address,
2570 WARN_ON(address > dom->aperture_size);
2574 pte = dma_ops_get_pte(dom, address);
2576 return DMA_ERROR_CODE;
2578 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2580 if (direction == DMA_TO_DEVICE)
2581 __pte |= IOMMU_PTE_IR;
2582 else if (direction == DMA_FROM_DEVICE)
2583 __pte |= IOMMU_PTE_IW;
2584 else if (direction == DMA_BIDIRECTIONAL)
2585 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2591 return (dma_addr_t)address;
2595 * The generic unmapping function for on page in the DMA address space.
2597 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2598 unsigned long address)
2600 struct aperture_range *aperture;
2603 if (address >= dom->aperture_size)
2606 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2610 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2614 pte += PM_LEVEL_INDEX(0, address);
2622 * This function contains common code for mapping of a physically
2623 * contiguous memory region into DMA address space. It is used by all
2624 * mapping functions provided with this IOMMU driver.
2625 * Must be called with the domain lock held.
2627 static dma_addr_t __map_single(struct device *dev,
2628 struct dma_ops_domain *dma_dom,
2635 dma_addr_t offset = paddr & ~PAGE_MASK;
2636 dma_addr_t address, start, ret;
2638 unsigned long align_mask = 0;
2641 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2644 INC_STATS_COUNTER(total_map_requests);
2647 INC_STATS_COUNTER(cross_page);
2650 align_mask = (1UL << get_order(size)) - 1;
2653 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2655 if (unlikely(address == DMA_ERROR_CODE)) {
2657 * setting next_address here will let the address
2658 * allocator only scan the new allocated range in the
2659 * first run. This is a small optimization.
2661 dma_dom->next_address = dma_dom->aperture_size;
2663 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2667 * aperture was successfully enlarged by 128 MB, try
2674 for (i = 0; i < pages; ++i) {
2675 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2676 if (ret == DMA_ERROR_CODE)
2684 ADD_STATS_COUNTER(alloced_io_mem, size);
2686 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2687 domain_flush_tlb(&dma_dom->domain);
2688 dma_dom->need_flush = false;
2689 } else if (unlikely(amd_iommu_np_cache))
2690 domain_flush_pages(&dma_dom->domain, address, size);
2697 for (--i; i >= 0; --i) {
2699 dma_ops_domain_unmap(dma_dom, start);
2702 dma_ops_free_addresses(dma_dom, address, pages);
2704 return DMA_ERROR_CODE;
2708 * Does the reverse of the __map_single function. Must be called with
2709 * the domain lock held too
2711 static void __unmap_single(struct dma_ops_domain *dma_dom,
2712 dma_addr_t dma_addr,
2716 dma_addr_t flush_addr;
2717 dma_addr_t i, start;
2720 if ((dma_addr == DMA_ERROR_CODE) ||
2721 (dma_addr + size > dma_dom->aperture_size))
2724 flush_addr = dma_addr;
2725 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2726 dma_addr &= PAGE_MASK;
2729 for (i = 0; i < pages; ++i) {
2730 dma_ops_domain_unmap(dma_dom, start);
2734 SUB_STATS_COUNTER(alloced_io_mem, size);
2736 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2738 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2739 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2740 dma_dom->need_flush = false;
2745 * The exported map_single function for dma_ops.
2747 static dma_addr_t map_page(struct device *dev, struct page *page,
2748 unsigned long offset, size_t size,
2749 enum dma_data_direction dir,
2750 struct dma_attrs *attrs)
2752 unsigned long flags;
2753 struct protection_domain *domain;
2756 phys_addr_t paddr = page_to_phys(page) + offset;
2758 INC_STATS_COUNTER(cnt_map_single);
2760 domain = get_domain(dev);
2761 if (PTR_ERR(domain) == -EINVAL)
2762 return (dma_addr_t)paddr;
2763 else if (IS_ERR(domain))
2764 return DMA_ERROR_CODE;
2766 dma_mask = *dev->dma_mask;
2768 spin_lock_irqsave(&domain->lock, flags);
2770 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2772 if (addr == DMA_ERROR_CODE)
2775 domain_flush_complete(domain);
2778 spin_unlock_irqrestore(&domain->lock, flags);
2784 * The exported unmap_single function for dma_ops.
2786 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2787 enum dma_data_direction dir, struct dma_attrs *attrs)
2789 unsigned long flags;
2790 struct protection_domain *domain;
2792 INC_STATS_COUNTER(cnt_unmap_single);
2794 domain = get_domain(dev);
2798 spin_lock_irqsave(&domain->lock, flags);
2800 __unmap_single(domain->priv, dma_addr, size, dir);
2802 domain_flush_complete(domain);
2804 spin_unlock_irqrestore(&domain->lock, flags);
2808 * The exported map_sg function for dma_ops (handles scatter-gather
2811 static int map_sg(struct device *dev, struct scatterlist *sglist,
2812 int nelems, enum dma_data_direction dir,
2813 struct dma_attrs *attrs)
2815 unsigned long flags;
2816 struct protection_domain *domain;
2818 struct scatterlist *s;
2820 int mapped_elems = 0;
2823 INC_STATS_COUNTER(cnt_map_sg);
2825 domain = get_domain(dev);
2829 dma_mask = *dev->dma_mask;
2831 spin_lock_irqsave(&domain->lock, flags);
2833 for_each_sg(sglist, s, nelems, i) {
2836 s->dma_address = __map_single(dev, domain->priv,
2837 paddr, s->length, dir, false,
2840 if (s->dma_address) {
2841 s->dma_length = s->length;
2847 domain_flush_complete(domain);
2850 spin_unlock_irqrestore(&domain->lock, flags);
2852 return mapped_elems;
2854 for_each_sg(sglist, s, mapped_elems, i) {
2856 __unmap_single(domain->priv, s->dma_address,
2857 s->dma_length, dir);
2858 s->dma_address = s->dma_length = 0;
2867 * The exported map_sg function for dma_ops (handles scatter-gather
2870 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2871 int nelems, enum dma_data_direction dir,
2872 struct dma_attrs *attrs)
2874 unsigned long flags;
2875 struct protection_domain *domain;
2876 struct scatterlist *s;
2879 INC_STATS_COUNTER(cnt_unmap_sg);
2881 domain = get_domain(dev);
2885 spin_lock_irqsave(&domain->lock, flags);
2887 for_each_sg(sglist, s, nelems, i) {
2888 __unmap_single(domain->priv, s->dma_address,
2889 s->dma_length, dir);
2890 s->dma_address = s->dma_length = 0;
2893 domain_flush_complete(domain);
2895 spin_unlock_irqrestore(&domain->lock, flags);
2899 * The exported alloc_coherent function for dma_ops.
2901 static void *alloc_coherent(struct device *dev, size_t size,
2902 dma_addr_t *dma_addr, gfp_t flag,
2903 struct dma_attrs *attrs)
2905 unsigned long flags;
2907 struct protection_domain *domain;
2909 u64 dma_mask = dev->coherent_dma_mask;
2911 INC_STATS_COUNTER(cnt_alloc_coherent);
2913 domain = get_domain(dev);
2914 if (PTR_ERR(domain) == -EINVAL) {
2915 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2916 *dma_addr = __pa(virt_addr);
2918 } else if (IS_ERR(domain))
2921 dma_mask = dev->coherent_dma_mask;
2922 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2925 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2929 paddr = virt_to_phys(virt_addr);
2932 dma_mask = *dev->dma_mask;
2934 spin_lock_irqsave(&domain->lock, flags);
2936 *dma_addr = __map_single(dev, domain->priv, paddr,
2937 size, DMA_BIDIRECTIONAL, true, dma_mask);
2939 if (*dma_addr == DMA_ERROR_CODE) {
2940 spin_unlock_irqrestore(&domain->lock, flags);
2944 domain_flush_complete(domain);
2946 spin_unlock_irqrestore(&domain->lock, flags);
2952 free_pages((unsigned long)virt_addr, get_order(size));
2958 * The exported free_coherent function for dma_ops.
2960 static void free_coherent(struct device *dev, size_t size,
2961 void *virt_addr, dma_addr_t dma_addr,
2962 struct dma_attrs *attrs)
2964 unsigned long flags;
2965 struct protection_domain *domain;
2967 INC_STATS_COUNTER(cnt_free_coherent);
2969 domain = get_domain(dev);
2973 spin_lock_irqsave(&domain->lock, flags);
2975 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2977 domain_flush_complete(domain);
2979 spin_unlock_irqrestore(&domain->lock, flags);
2982 free_pages((unsigned long)virt_addr, get_order(size));
2986 * This function is called by the DMA layer to find out if we can handle a
2987 * particular device. It is part of the dma_ops.
2989 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2991 return check_device(dev);
2995 * The function for pre-allocating protection domains.
2997 * If the driver core informs the DMA layer if a driver grabs a device
2998 * we don't need to preallocate the protection domains anymore.
2999 * For now we have to.
3001 static void __init prealloc_protection_domains(void)
3003 struct iommu_dev_data *dev_data;
3004 struct dma_ops_domain *dma_dom;
3005 struct pci_dev *dev = NULL;
3008 for_each_pci_dev(dev) {
3010 /* Do we handle this device? */
3011 if (!check_device(&dev->dev))
3014 dev_data = get_dev_data(&dev->dev);
3015 if (!amd_iommu_force_isolation && dev_data->iommu_v2) {
3016 /* Make sure passthrough domain is allocated */
3017 alloc_passthrough_domain();
3018 dev_data->passthrough = true;
3019 attach_device(&dev->dev, pt_domain);
3020 pr_info("AMD-Vi: Using passthrough domain for device %s\n",
3021 dev_name(&dev->dev));
3024 /* Is there already any domain for it? */
3025 if (domain_for_device(&dev->dev))
3028 devid = get_device_id(&dev->dev);
3030 dma_dom = dma_ops_domain_alloc();
3033 init_unity_mappings_for_device(dma_dom, devid);
3034 dma_dom->target_dev = devid;
3036 attach_device(&dev->dev, &dma_dom->domain);
3038 list_add_tail(&dma_dom->list, &iommu_pd_list);
3042 static struct dma_map_ops amd_iommu_dma_ops = {
3043 .alloc = alloc_coherent,
3044 .free = free_coherent,
3045 .map_page = map_page,
3046 .unmap_page = unmap_page,
3048 .unmap_sg = unmap_sg,
3049 .dma_supported = amd_iommu_dma_supported,
3052 static unsigned device_dma_ops_init(void)
3054 struct iommu_dev_data *dev_data;
3055 struct pci_dev *pdev = NULL;
3056 unsigned unhandled = 0;
3058 for_each_pci_dev(pdev) {
3059 if (!check_device(&pdev->dev)) {
3061 iommu_ignore_device(&pdev->dev);
3067 dev_data = get_dev_data(&pdev->dev);
3069 if (!dev_data->passthrough)
3070 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
3072 pdev->dev.archdata.dma_ops = &nommu_dma_ops;
3079 * The function which clues the AMD IOMMU driver into dma_ops.
3082 void __init amd_iommu_init_api(void)
3084 bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
3087 int __init amd_iommu_init_dma_ops(void)
3089 struct amd_iommu *iommu;
3093 * first allocate a default protection domain for every IOMMU we
3094 * found in the system. Devices not assigned to any other
3095 * protection domain will be assigned to the default one.
3097 for_each_iommu(iommu) {
3098 iommu->default_dom = dma_ops_domain_alloc();
3099 if (iommu->default_dom == NULL)
3101 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
3102 ret = iommu_init_unity_mappings(iommu);
3108 * Pre-allocate the protection domains for each device.
3110 prealloc_protection_domains();
3115 /* Make the driver finally visible to the drivers */
3116 unhandled = device_dma_ops_init();
3117 if (unhandled && max_pfn > MAX_DMA32_PFN) {
3118 /* There are unhandled devices - initialize swiotlb for them */
3122 amd_iommu_stats_init();
3124 if (amd_iommu_unmap_flush)
3125 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
3127 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
3133 for_each_iommu(iommu) {
3134 dma_ops_domain_free(iommu->default_dom);
3140 /*****************************************************************************
3142 * The following functions belong to the exported interface of AMD IOMMU
3144 * This interface allows access to lower level functions of the IOMMU
3145 * like protection domain handling and assignement of devices to domains
3146 * which is not possible with the dma_ops interface.
3148 *****************************************************************************/
3150 static void cleanup_domain(struct protection_domain *domain)
3152 struct iommu_dev_data *entry;
3153 unsigned long flags;
3155 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3157 while (!list_empty(&domain->dev_list)) {
3158 entry = list_first_entry(&domain->dev_list,
3159 struct iommu_dev_data, list);
3160 __detach_device(entry);
3161 atomic_set(&entry->bind, 0);
3164 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3167 static void protection_domain_free(struct protection_domain *domain)
3172 del_domain_from_list(domain);
3175 domain_id_free(domain->id);
3180 static struct protection_domain *protection_domain_alloc(void)
3182 struct protection_domain *domain;
3184 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
3188 spin_lock_init(&domain->lock);
3189 mutex_init(&domain->api_lock);
3190 domain->id = domain_id_alloc();
3193 INIT_LIST_HEAD(&domain->dev_list);
3195 add_domain_to_list(domain);
3205 static int __init alloc_passthrough_domain(void)
3207 if (pt_domain != NULL)
3210 /* allocate passthrough domain */
3211 pt_domain = protection_domain_alloc();
3215 pt_domain->mode = PAGE_MODE_NONE;
3219 static int amd_iommu_domain_init(struct iommu_domain *dom)
3221 struct protection_domain *domain;
3223 domain = protection_domain_alloc();
3227 domain->mode = PAGE_MODE_3_LEVEL;
3228 domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
3229 if (!domain->pt_root)
3232 domain->iommu_domain = dom;
3236 dom->geometry.aperture_start = 0;
3237 dom->geometry.aperture_end = ~0ULL;
3238 dom->geometry.force_aperture = true;
3243 protection_domain_free(domain);
3248 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
3250 struct protection_domain *domain = dom->priv;
3255 if (domain->dev_cnt > 0)
3256 cleanup_domain(domain);
3258 BUG_ON(domain->dev_cnt != 0);
3260 if (domain->mode != PAGE_MODE_NONE)
3261 free_pagetable(domain);
3263 if (domain->flags & PD_IOMMUV2_MASK)
3264 free_gcr3_table(domain);
3266 protection_domain_free(domain);
3271 static void amd_iommu_detach_device(struct iommu_domain *dom,
3274 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3275 struct amd_iommu *iommu;
3278 if (!check_device(dev))
3281 devid = get_device_id(dev);
3283 if (dev_data->domain != NULL)
3286 iommu = amd_iommu_rlookup_table[devid];
3290 iommu_completion_wait(iommu);
3293 static int amd_iommu_attach_device(struct iommu_domain *dom,
3296 struct protection_domain *domain = dom->priv;
3297 struct iommu_dev_data *dev_data;
3298 struct amd_iommu *iommu;
3301 if (!check_device(dev))
3304 dev_data = dev->archdata.iommu;
3306 iommu = amd_iommu_rlookup_table[dev_data->devid];
3310 if (dev_data->domain)
3313 ret = attach_device(dev, domain);
3315 iommu_completion_wait(iommu);
3320 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3321 phys_addr_t paddr, size_t page_size, int iommu_prot)
3323 struct protection_domain *domain = dom->priv;
3327 if (domain->mode == PAGE_MODE_NONE)
3330 if (iommu_prot & IOMMU_READ)
3331 prot |= IOMMU_PROT_IR;
3332 if (iommu_prot & IOMMU_WRITE)
3333 prot |= IOMMU_PROT_IW;
3335 mutex_lock(&domain->api_lock);
3336 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3337 mutex_unlock(&domain->api_lock);
3342 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3345 struct protection_domain *domain = dom->priv;
3348 if (domain->mode == PAGE_MODE_NONE)
3351 mutex_lock(&domain->api_lock);
3352 unmap_size = iommu_unmap_page(domain, iova, page_size);
3353 mutex_unlock(&domain->api_lock);
3355 domain_flush_tlb_pde(domain);
3360 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3363 struct protection_domain *domain = dom->priv;
3364 unsigned long offset_mask;
3368 if (domain->mode == PAGE_MODE_NONE)
3371 pte = fetch_pte(domain, iova);
3373 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3376 if (PM_PTE_LEVEL(*pte) == 0)
3377 offset_mask = PAGE_SIZE - 1;
3379 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
3381 __pte = *pte & PM_ADDR_MASK;
3382 paddr = (__pte & ~offset_mask) | (iova & offset_mask);
3387 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
3391 case IOMMU_CAP_CACHE_COHERENCY:
3393 case IOMMU_CAP_INTR_REMAP:
3394 return irq_remapping_enabled;
3400 static const struct iommu_ops amd_iommu_ops = {
3401 .domain_init = amd_iommu_domain_init,
3402 .domain_destroy = amd_iommu_domain_destroy,
3403 .attach_dev = amd_iommu_attach_device,
3404 .detach_dev = amd_iommu_detach_device,
3405 .map = amd_iommu_map,
3406 .unmap = amd_iommu_unmap,
3407 .iova_to_phys = amd_iommu_iova_to_phys,
3408 .domain_has_cap = amd_iommu_domain_has_cap,
3409 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3412 /*****************************************************************************
3414 * The next functions do a basic initialization of IOMMU for pass through
3417 * In passthrough mode the IOMMU is initialized and enabled but not used for
3418 * DMA-API translation.
3420 *****************************************************************************/
3422 int __init amd_iommu_init_passthrough(void)
3424 struct iommu_dev_data *dev_data;
3425 struct pci_dev *dev = NULL;
3428 ret = alloc_passthrough_domain();
3432 for_each_pci_dev(dev) {
3433 if (!check_device(&dev->dev))
3436 dev_data = get_dev_data(&dev->dev);
3437 dev_data->passthrough = true;
3439 attach_device(&dev->dev, pt_domain);
3442 amd_iommu_stats_init();
3444 pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
3449 /* IOMMUv2 specific functions */
3450 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3452 return atomic_notifier_chain_register(&ppr_notifier, nb);
3454 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3456 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3458 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3460 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3462 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3464 struct protection_domain *domain = dom->priv;
3465 unsigned long flags;
3467 spin_lock_irqsave(&domain->lock, flags);
3469 /* Update data structure */
3470 domain->mode = PAGE_MODE_NONE;
3471 domain->updated = true;
3473 /* Make changes visible to IOMMUs */
3474 update_domain(domain);
3476 /* Page-table is not visible to IOMMU anymore, so free it */
3477 free_pagetable(domain);
3479 spin_unlock_irqrestore(&domain->lock, flags);
3481 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3483 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3485 struct protection_domain *domain = dom->priv;
3486 unsigned long flags;
3489 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3492 /* Number of GCR3 table levels required */
3493 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3496 if (levels > amd_iommu_max_glx_val)
3499 spin_lock_irqsave(&domain->lock, flags);
3502 * Save us all sanity checks whether devices already in the
3503 * domain support IOMMUv2. Just force that the domain has no
3504 * devices attached when it is switched into IOMMUv2 mode.
3507 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3511 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3512 if (domain->gcr3_tbl == NULL)
3515 domain->glx = levels;
3516 domain->flags |= PD_IOMMUV2_MASK;
3517 domain->updated = true;
3519 update_domain(domain);
3524 spin_unlock_irqrestore(&domain->lock, flags);
3528 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3530 static int __flush_pasid(struct protection_domain *domain, int pasid,
3531 u64 address, bool size)
3533 struct iommu_dev_data *dev_data;
3534 struct iommu_cmd cmd;
3537 if (!(domain->flags & PD_IOMMUV2_MASK))
3540 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3543 * IOMMU TLB needs to be flushed before Device TLB to
3544 * prevent device TLB refill from IOMMU TLB
3546 for (i = 0; i < amd_iommus_present; ++i) {
3547 if (domain->dev_iommu[i] == 0)
3550 ret = iommu_queue_command(amd_iommus[i], &cmd);
3555 /* Wait until IOMMU TLB flushes are complete */
3556 domain_flush_complete(domain);
3558 /* Now flush device TLBs */
3559 list_for_each_entry(dev_data, &domain->dev_list, list) {
3560 struct amd_iommu *iommu;
3563 BUG_ON(!dev_data->ats.enabled);
3565 qdep = dev_data->ats.qdep;
3566 iommu = amd_iommu_rlookup_table[dev_data->devid];
3568 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3569 qdep, address, size);
3571 ret = iommu_queue_command(iommu, &cmd);
3576 /* Wait until all device TLBs are flushed */
3577 domain_flush_complete(domain);
3586 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3589 INC_STATS_COUNTER(invalidate_iotlb);
3591 return __flush_pasid(domain, pasid, address, false);
3594 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3597 struct protection_domain *domain = dom->priv;
3598 unsigned long flags;
3601 spin_lock_irqsave(&domain->lock, flags);
3602 ret = __amd_iommu_flush_page(domain, pasid, address);
3603 spin_unlock_irqrestore(&domain->lock, flags);
3607 EXPORT_SYMBOL(amd_iommu_flush_page);
3609 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3611 INC_STATS_COUNTER(invalidate_iotlb_all);
3613 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3617 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3619 struct protection_domain *domain = dom->priv;
3620 unsigned long flags;
3623 spin_lock_irqsave(&domain->lock, flags);
3624 ret = __amd_iommu_flush_tlb(domain, pasid);
3625 spin_unlock_irqrestore(&domain->lock, flags);
3629 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3631 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3638 index = (pasid >> (9 * level)) & 0x1ff;
3644 if (!(*pte & GCR3_VALID)) {
3648 root = (void *)get_zeroed_page(GFP_ATOMIC);
3652 *pte = __pa(root) | GCR3_VALID;
3655 root = __va(*pte & PAGE_MASK);
3663 static int __set_gcr3(struct protection_domain *domain, int pasid,
3668 if (domain->mode != PAGE_MODE_NONE)
3671 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3675 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3677 return __amd_iommu_flush_tlb(domain, pasid);
3680 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3684 if (domain->mode != PAGE_MODE_NONE)
3687 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3693 return __amd_iommu_flush_tlb(domain, pasid);
3696 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3699 struct protection_domain *domain = dom->priv;
3700 unsigned long flags;
3703 spin_lock_irqsave(&domain->lock, flags);
3704 ret = __set_gcr3(domain, pasid, cr3);
3705 spin_unlock_irqrestore(&domain->lock, flags);
3709 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3711 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3713 struct protection_domain *domain = dom->priv;
3714 unsigned long flags;
3717 spin_lock_irqsave(&domain->lock, flags);
3718 ret = __clear_gcr3(domain, pasid);
3719 spin_unlock_irqrestore(&domain->lock, flags);
3723 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3725 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3726 int status, int tag)
3728 struct iommu_dev_data *dev_data;
3729 struct amd_iommu *iommu;
3730 struct iommu_cmd cmd;
3732 INC_STATS_COUNTER(complete_ppr);
3734 dev_data = get_dev_data(&pdev->dev);
3735 iommu = amd_iommu_rlookup_table[dev_data->devid];
3737 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3738 tag, dev_data->pri_tlp);
3740 return iommu_queue_command(iommu, &cmd);
3742 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3744 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3746 struct protection_domain *domain;
3748 domain = get_domain(&pdev->dev);
3752 /* Only return IOMMUv2 domains */
3753 if (!(domain->flags & PD_IOMMUV2_MASK))
3756 return domain->iommu_domain;
3758 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3760 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3762 struct iommu_dev_data *dev_data;
3764 if (!amd_iommu_v2_supported())
3767 dev_data = get_dev_data(&pdev->dev);
3768 dev_data->errata |= (1 << erratum);
3770 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3772 int amd_iommu_device_info(struct pci_dev *pdev,
3773 struct amd_iommu_device_info *info)
3778 if (pdev == NULL || info == NULL)
3781 if (!amd_iommu_v2_supported())
3784 memset(info, 0, sizeof(*info));
3786 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3788 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3790 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3792 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3794 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3798 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3799 max_pasids = min(max_pasids, (1 << 20));
3801 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3802 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3804 features = pci_pasid_features(pdev);
3805 if (features & PCI_PASID_CAP_EXEC)
3806 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3807 if (features & PCI_PASID_CAP_PRIV)
3808 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3813 EXPORT_SYMBOL(amd_iommu_device_info);
3815 #ifdef CONFIG_IRQ_REMAP
3817 /*****************************************************************************
3819 * Interrupt Remapping Implementation
3821 *****************************************************************************/
3838 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3839 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3840 #define DTE_IRQ_TABLE_LEN (8ULL << 1)
3841 #define DTE_IRQ_REMAP_ENABLE 1ULL
3843 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3847 dte = amd_iommu_dev_table[devid].data[2];
3848 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3849 dte |= virt_to_phys(table->table);
3850 dte |= DTE_IRQ_REMAP_INTCTL;
3851 dte |= DTE_IRQ_TABLE_LEN;
3852 dte |= DTE_IRQ_REMAP_ENABLE;
3854 amd_iommu_dev_table[devid].data[2] = dte;
3857 #define IRTE_ALLOCATED (~1U)
3859 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3861 struct irq_remap_table *table = NULL;
3862 struct amd_iommu *iommu;
3863 unsigned long flags;
3866 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3868 iommu = amd_iommu_rlookup_table[devid];
3872 table = irq_lookup_table[devid];
3876 alias = amd_iommu_alias_table[devid];
3877 table = irq_lookup_table[alias];
3879 irq_lookup_table[devid] = table;
3880 set_dte_irq_entry(devid, table);
3881 iommu_flush_dte(iommu, devid);
3885 /* Nothing there yet, allocate new irq remapping table */
3886 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3890 /* Initialize table spin-lock */
3891 spin_lock_init(&table->lock);
3894 /* Keep the first 32 indexes free for IOAPIC interrupts */
3895 table->min_index = 32;
3897 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3898 if (!table->table) {
3904 memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3909 for (i = 0; i < 32; ++i)
3910 table->table[i] = IRTE_ALLOCATED;
3913 irq_lookup_table[devid] = table;
3914 set_dte_irq_entry(devid, table);
3915 iommu_flush_dte(iommu, devid);
3916 if (devid != alias) {
3917 irq_lookup_table[alias] = table;
3918 set_dte_irq_entry(alias, table);
3919 iommu_flush_dte(iommu, alias);
3923 iommu_completion_wait(iommu);
3926 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3931 static int alloc_irq_index(struct irq_cfg *cfg, u16 devid, int count)
3933 struct irq_remap_table *table;
3934 unsigned long flags;
3937 table = get_irq_table(devid, false);
3941 spin_lock_irqsave(&table->lock, flags);
3943 /* Scan table for free entries */
3944 for (c = 0, index = table->min_index;
3945 index < MAX_IRQS_PER_TABLE;
3947 if (table->table[index] == 0)
3953 struct irq_2_irte *irte_info;
3956 table->table[index - c + 1] = IRTE_ALLOCATED;
3961 irte_info = &cfg->irq_2_irte;
3962 irte_info->devid = devid;
3963 irte_info->index = index;
3972 spin_unlock_irqrestore(&table->lock, flags);
3977 static int get_irte(u16 devid, int index, union irte *irte)
3979 struct irq_remap_table *table;
3980 unsigned long flags;
3982 table = get_irq_table(devid, false);
3986 spin_lock_irqsave(&table->lock, flags);
3987 irte->val = table->table[index];
3988 spin_unlock_irqrestore(&table->lock, flags);
3993 static int modify_irte(u16 devid, int index, union irte irte)
3995 struct irq_remap_table *table;
3996 struct amd_iommu *iommu;
3997 unsigned long flags;
3999 iommu = amd_iommu_rlookup_table[devid];
4003 table = get_irq_table(devid, false);
4007 spin_lock_irqsave(&table->lock, flags);
4008 table->table[index] = irte.val;
4009 spin_unlock_irqrestore(&table->lock, flags);
4011 iommu_flush_irt(iommu, devid);
4012 iommu_completion_wait(iommu);
4017 static void free_irte(u16 devid, int index)
4019 struct irq_remap_table *table;
4020 struct amd_iommu *iommu;
4021 unsigned long flags;
4023 iommu = amd_iommu_rlookup_table[devid];
4027 table = get_irq_table(devid, false);
4031 spin_lock_irqsave(&table->lock, flags);
4032 table->table[index] = 0;
4033 spin_unlock_irqrestore(&table->lock, flags);
4035 iommu_flush_irt(iommu, devid);
4036 iommu_completion_wait(iommu);
4039 static int setup_ioapic_entry(int irq, struct IO_APIC_route_entry *entry,
4040 unsigned int destination, int vector,
4041 struct io_apic_irq_attr *attr)
4043 struct irq_remap_table *table;
4044 struct irq_2_irte *irte_info;
4045 struct irq_cfg *cfg;
4052 cfg = irq_get_chip_data(irq);
4056 irte_info = &cfg->irq_2_irte;
4057 ioapic_id = mpc_ioapic_id(attr->ioapic);
4058 devid = get_ioapic_devid(ioapic_id);
4063 table = get_irq_table(devid, true);
4067 index = attr->ioapic_pin;
4069 /* Setup IRQ remapping info */
4071 irte_info->devid = devid;
4072 irte_info->index = index;
4074 /* Setup IRTE for IOMMU */
4076 irte.fields.vector = vector;
4077 irte.fields.int_type = apic->irq_delivery_mode;
4078 irte.fields.destination = destination;
4079 irte.fields.dm = apic->irq_dest_mode;
4080 irte.fields.valid = 1;
4082 ret = modify_irte(devid, index, irte);
4086 /* Setup IOAPIC entry */
4087 memset(entry, 0, sizeof(*entry));
4089 entry->vector = index;
4091 entry->trigger = attr->trigger;
4092 entry->polarity = attr->polarity;
4095 * Mask level triggered irqs.
4103 static int set_affinity(struct irq_data *data, const struct cpumask *mask,
4106 struct irq_2_irte *irte_info;
4107 unsigned int dest, irq;
4108 struct irq_cfg *cfg;
4112 if (!config_enabled(CONFIG_SMP))
4115 cfg = data->chip_data;
4117 irte_info = &cfg->irq_2_irte;
4119 if (!cpumask_intersects(mask, cpu_online_mask))
4122 if (get_irte(irte_info->devid, irte_info->index, &irte))
4125 if (assign_irq_vector(irq, cfg, mask))
4128 err = apic->cpu_mask_to_apicid_and(cfg->domain, mask, &dest);
4130 if (assign_irq_vector(irq, cfg, data->affinity))
4131 pr_err("AMD-Vi: Failed to recover vector for irq %d\n", irq);
4135 irte.fields.vector = cfg->vector;
4136 irte.fields.destination = dest;
4138 modify_irte(irte_info->devid, irte_info->index, irte);
4140 if (cfg->move_in_progress)
4141 send_cleanup_vector(cfg);
4143 cpumask_copy(data->affinity, mask);
4148 static int free_irq(int irq)
4150 struct irq_2_irte *irte_info;
4151 struct irq_cfg *cfg;
4153 cfg = irq_get_chip_data(irq);
4157 irte_info = &cfg->irq_2_irte;
4159 free_irte(irte_info->devid, irte_info->index);
4164 static void compose_msi_msg(struct pci_dev *pdev,
4165 unsigned int irq, unsigned int dest,
4166 struct msi_msg *msg, u8 hpet_id)
4168 struct irq_2_irte *irte_info;
4169 struct irq_cfg *cfg;
4172 cfg = irq_get_chip_data(irq);
4176 irte_info = &cfg->irq_2_irte;
4179 irte.fields.vector = cfg->vector;
4180 irte.fields.int_type = apic->irq_delivery_mode;
4181 irte.fields.destination = dest;
4182 irte.fields.dm = apic->irq_dest_mode;
4183 irte.fields.valid = 1;
4185 modify_irte(irte_info->devid, irte_info->index, irte);
4187 msg->address_hi = MSI_ADDR_BASE_HI;
4188 msg->address_lo = MSI_ADDR_BASE_LO;
4189 msg->data = irte_info->index;
4192 static int msi_alloc_irq(struct pci_dev *pdev, int irq, int nvec)
4194 struct irq_cfg *cfg;
4201 cfg = irq_get_chip_data(irq);
4205 devid = get_device_id(&pdev->dev);
4206 index = alloc_irq_index(cfg, devid, nvec);
4208 return index < 0 ? MAX_IRQS_PER_TABLE : index;
4211 static int msi_setup_irq(struct pci_dev *pdev, unsigned int irq,
4212 int index, int offset)
4214 struct irq_2_irte *irte_info;
4215 struct irq_cfg *cfg;
4221 cfg = irq_get_chip_data(irq);
4225 if (index >= MAX_IRQS_PER_TABLE)
4228 devid = get_device_id(&pdev->dev);
4229 irte_info = &cfg->irq_2_irte;
4232 irte_info->devid = devid;
4233 irte_info->index = index + offset;
4238 static int setup_hpet_msi(unsigned int irq, unsigned int id)
4240 struct irq_2_irte *irte_info;
4241 struct irq_cfg *cfg;
4244 cfg = irq_get_chip_data(irq);
4248 irte_info = &cfg->irq_2_irte;
4249 devid = get_hpet_devid(id);
4253 index = alloc_irq_index(cfg, devid, 1);
4258 irte_info->devid = devid;
4259 irte_info->index = index;
4264 struct irq_remap_ops amd_iommu_irq_ops = {
4265 .supported = amd_iommu_supported,
4266 .prepare = amd_iommu_prepare,
4267 .enable = amd_iommu_enable,
4268 .disable = amd_iommu_disable,
4269 .reenable = amd_iommu_reenable,
4270 .enable_faulting = amd_iommu_enable_faulting,
4271 .setup_ioapic_entry = setup_ioapic_entry,
4272 .set_affinity = set_affinity,
4273 .free_irq = free_irq,
4274 .compose_msi_msg = compose_msi_msg,
4275 .msi_alloc_irq = msi_alloc_irq,
4276 .msi_setup_irq = msi_setup_irq,
4277 .setup_hpet_msi = setup_hpet_msi,