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 * Traditionally the IOMMU core just handed us the mappings directly,
61 * after making sure the size is an order of a 4KiB page and that the
62 * mapping has natural alignment.
64 * To retain this behavior, we currently advertise that we support
65 * all page sizes that are an order of 4KiB.
67 * If at some point we'd like to utilize the IOMMU core's new behavior,
68 * we could change this to advertise the real page sizes we support.
70 #define AMD_IOMMU_PGSIZES (~0xFFFUL)
72 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
74 /* A list of preallocated protection domains */
75 static LIST_HEAD(iommu_pd_list);
76 static DEFINE_SPINLOCK(iommu_pd_list_lock);
78 /* List of all available dev_data structures */
79 static LIST_HEAD(dev_data_list);
80 static DEFINE_SPINLOCK(dev_data_list_lock);
82 LIST_HEAD(ioapic_map);
86 * Domain for untranslated devices - only allocated
87 * if iommu=pt passed on kernel cmd line.
89 static struct protection_domain *pt_domain;
91 static struct iommu_ops amd_iommu_ops;
93 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
94 int amd_iommu_max_glx_val = -1;
96 static struct dma_map_ops amd_iommu_dma_ops;
99 * general struct to manage commands send to an IOMMU
105 struct kmem_cache *amd_iommu_irq_cache;
107 static void update_domain(struct protection_domain *domain);
108 static int __init alloc_passthrough_domain(void);
110 /****************************************************************************
114 ****************************************************************************/
116 static struct iommu_dev_data *alloc_dev_data(u16 devid)
118 struct iommu_dev_data *dev_data;
121 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
125 dev_data->devid = devid;
126 atomic_set(&dev_data->bind, 0);
128 spin_lock_irqsave(&dev_data_list_lock, flags);
129 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
130 spin_unlock_irqrestore(&dev_data_list_lock, flags);
135 static void free_dev_data(struct iommu_dev_data *dev_data)
139 spin_lock_irqsave(&dev_data_list_lock, flags);
140 list_del(&dev_data->dev_data_list);
141 spin_unlock_irqrestore(&dev_data_list_lock, flags);
146 static struct iommu_dev_data *search_dev_data(u16 devid)
148 struct iommu_dev_data *dev_data;
151 spin_lock_irqsave(&dev_data_list_lock, flags);
152 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
153 if (dev_data->devid == devid)
160 spin_unlock_irqrestore(&dev_data_list_lock, flags);
165 static struct iommu_dev_data *find_dev_data(u16 devid)
167 struct iommu_dev_data *dev_data;
169 dev_data = search_dev_data(devid);
171 if (dev_data == NULL)
172 dev_data = alloc_dev_data(devid);
177 static inline u16 get_device_id(struct device *dev)
179 struct pci_dev *pdev = to_pci_dev(dev);
181 return calc_devid(pdev->bus->number, pdev->devfn);
184 static struct iommu_dev_data *get_dev_data(struct device *dev)
186 return dev->archdata.iommu;
189 static bool pci_iommuv2_capable(struct pci_dev *pdev)
191 static const int caps[] = {
194 PCI_EXT_CAP_ID_PASID,
198 for (i = 0; i < 3; ++i) {
199 pos = pci_find_ext_capability(pdev, caps[i]);
207 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
209 struct iommu_dev_data *dev_data;
211 dev_data = get_dev_data(&pdev->dev);
213 return dev_data->errata & (1 << erratum) ? true : false;
217 * In this function the list of preallocated protection domains is traversed to
218 * find the domain for a specific device
220 static struct dma_ops_domain *find_protection_domain(u16 devid)
222 struct dma_ops_domain *entry, *ret = NULL;
224 u16 alias = amd_iommu_alias_table[devid];
226 if (list_empty(&iommu_pd_list))
229 spin_lock_irqsave(&iommu_pd_list_lock, flags);
231 list_for_each_entry(entry, &iommu_pd_list, list) {
232 if (entry->target_dev == devid ||
233 entry->target_dev == alias) {
239 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
245 * This function checks if the driver got a valid device from the caller to
246 * avoid dereferencing invalid pointers.
248 static bool check_device(struct device *dev)
252 if (!dev || !dev->dma_mask)
255 /* No device or no PCI device */
256 if (dev->bus != &pci_bus_type)
259 devid = get_device_id(dev);
261 /* Out of our scope? */
262 if (devid > amd_iommu_last_bdf)
265 if (amd_iommu_rlookup_table[devid] == NULL)
271 static void swap_pci_ref(struct pci_dev **from, struct pci_dev *to)
277 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
279 static int iommu_init_device(struct device *dev)
281 struct pci_dev *dma_pdev, *pdev = to_pci_dev(dev);
282 struct iommu_dev_data *dev_data;
283 struct iommu_group *group;
287 if (dev->archdata.iommu)
290 dev_data = find_dev_data(get_device_id(dev));
294 alias = amd_iommu_alias_table[dev_data->devid];
295 if (alias != dev_data->devid) {
296 struct iommu_dev_data *alias_data;
298 alias_data = find_dev_data(alias);
299 if (alias_data == NULL) {
300 pr_err("AMD-Vi: Warning: Unhandled device %s\n",
302 free_dev_data(dev_data);
305 dev_data->alias_data = alias_data;
307 dma_pdev = pci_get_bus_and_slot(alias >> 8, alias & 0xff);
309 dma_pdev = pci_dev_get(pdev);
311 /* Account for quirked devices */
312 swap_pci_ref(&dma_pdev, pci_get_dma_source(dma_pdev));
315 * If it's a multifunction device that does not support our
316 * required ACS flags, add to the same group as function 0.
318 if (dma_pdev->multifunction &&
319 !pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS))
320 swap_pci_ref(&dma_pdev,
321 pci_get_slot(dma_pdev->bus,
322 PCI_DEVFN(PCI_SLOT(dma_pdev->devfn),
326 * Devices on the root bus go through the iommu. If that's not us,
327 * find the next upstream device and test ACS up to the root bus.
328 * Finding the next device may require skipping virtual buses.
330 while (!pci_is_root_bus(dma_pdev->bus)) {
331 struct pci_bus *bus = dma_pdev->bus;
334 if (!pci_is_root_bus(bus))
340 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
343 swap_pci_ref(&dma_pdev, pci_dev_get(bus->self));
347 group = iommu_group_get(&dma_pdev->dev);
348 pci_dev_put(dma_pdev);
350 group = iommu_group_alloc();
352 return PTR_ERR(group);
355 ret = iommu_group_add_device(group, dev);
357 iommu_group_put(group);
362 if (pci_iommuv2_capable(pdev)) {
363 struct amd_iommu *iommu;
365 iommu = amd_iommu_rlookup_table[dev_data->devid];
366 dev_data->iommu_v2 = iommu->is_iommu_v2;
369 dev->archdata.iommu = dev_data;
374 static void iommu_ignore_device(struct device *dev)
378 devid = get_device_id(dev);
379 alias = amd_iommu_alias_table[devid];
381 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
382 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
384 amd_iommu_rlookup_table[devid] = NULL;
385 amd_iommu_rlookup_table[alias] = NULL;
388 static void iommu_uninit_device(struct device *dev)
390 iommu_group_remove_device(dev);
393 * Nothing to do here - we keep dev_data around for unplugged devices
394 * and reuse it when the device is re-plugged - not doing so would
395 * introduce a ton of races.
399 void __init amd_iommu_uninit_devices(void)
401 struct iommu_dev_data *dev_data, *n;
402 struct pci_dev *pdev = NULL;
404 for_each_pci_dev(pdev) {
406 if (!check_device(&pdev->dev))
409 iommu_uninit_device(&pdev->dev);
412 /* Free all of our dev_data structures */
413 list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
414 free_dev_data(dev_data);
417 int __init amd_iommu_init_devices(void)
419 struct pci_dev *pdev = NULL;
422 for_each_pci_dev(pdev) {
424 if (!check_device(&pdev->dev))
427 ret = iommu_init_device(&pdev->dev);
428 if (ret == -ENOTSUPP)
429 iommu_ignore_device(&pdev->dev);
438 amd_iommu_uninit_devices();
442 #ifdef CONFIG_AMD_IOMMU_STATS
445 * Initialization code for statistics collection
448 DECLARE_STATS_COUNTER(compl_wait);
449 DECLARE_STATS_COUNTER(cnt_map_single);
450 DECLARE_STATS_COUNTER(cnt_unmap_single);
451 DECLARE_STATS_COUNTER(cnt_map_sg);
452 DECLARE_STATS_COUNTER(cnt_unmap_sg);
453 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
454 DECLARE_STATS_COUNTER(cnt_free_coherent);
455 DECLARE_STATS_COUNTER(cross_page);
456 DECLARE_STATS_COUNTER(domain_flush_single);
457 DECLARE_STATS_COUNTER(domain_flush_all);
458 DECLARE_STATS_COUNTER(alloced_io_mem);
459 DECLARE_STATS_COUNTER(total_map_requests);
460 DECLARE_STATS_COUNTER(complete_ppr);
461 DECLARE_STATS_COUNTER(invalidate_iotlb);
462 DECLARE_STATS_COUNTER(invalidate_iotlb_all);
463 DECLARE_STATS_COUNTER(pri_requests);
465 static struct dentry *stats_dir;
466 static struct dentry *de_fflush;
468 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
470 if (stats_dir == NULL)
473 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
477 static void amd_iommu_stats_init(void)
479 stats_dir = debugfs_create_dir("amd-iommu", NULL);
480 if (stats_dir == NULL)
483 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
484 &amd_iommu_unmap_flush);
486 amd_iommu_stats_add(&compl_wait);
487 amd_iommu_stats_add(&cnt_map_single);
488 amd_iommu_stats_add(&cnt_unmap_single);
489 amd_iommu_stats_add(&cnt_map_sg);
490 amd_iommu_stats_add(&cnt_unmap_sg);
491 amd_iommu_stats_add(&cnt_alloc_coherent);
492 amd_iommu_stats_add(&cnt_free_coherent);
493 amd_iommu_stats_add(&cross_page);
494 amd_iommu_stats_add(&domain_flush_single);
495 amd_iommu_stats_add(&domain_flush_all);
496 amd_iommu_stats_add(&alloced_io_mem);
497 amd_iommu_stats_add(&total_map_requests);
498 amd_iommu_stats_add(&complete_ppr);
499 amd_iommu_stats_add(&invalidate_iotlb);
500 amd_iommu_stats_add(&invalidate_iotlb_all);
501 amd_iommu_stats_add(&pri_requests);
506 /****************************************************************************
508 * Interrupt handling functions
510 ****************************************************************************/
512 static void dump_dte_entry(u16 devid)
516 for (i = 0; i < 4; ++i)
517 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
518 amd_iommu_dev_table[devid].data[i]);
521 static void dump_command(unsigned long phys_addr)
523 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
526 for (i = 0; i < 4; ++i)
527 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
530 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
532 int type, devid, domid, flags;
533 volatile u32 *event = __evt;
538 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
539 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
540 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
541 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
542 address = (u64)(((u64)event[3]) << 32) | event[2];
545 /* Did we hit the erratum? */
546 if (++count == LOOP_TIMEOUT) {
547 pr_err("AMD-Vi: No event written to event log\n");
554 printk(KERN_ERR "AMD-Vi: Event logged [");
557 case EVENT_TYPE_ILL_DEV:
558 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
559 "address=0x%016llx flags=0x%04x]\n",
560 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
562 dump_dte_entry(devid);
564 case EVENT_TYPE_IO_FAULT:
565 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
566 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
567 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
568 domid, address, flags);
570 case EVENT_TYPE_DEV_TAB_ERR:
571 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
572 "address=0x%016llx flags=0x%04x]\n",
573 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
576 case EVENT_TYPE_PAGE_TAB_ERR:
577 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
578 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
579 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
580 domid, address, flags);
582 case EVENT_TYPE_ILL_CMD:
583 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
584 dump_command(address);
586 case EVENT_TYPE_CMD_HARD_ERR:
587 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
588 "flags=0x%04x]\n", address, flags);
590 case EVENT_TYPE_IOTLB_INV_TO:
591 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
592 "address=0x%016llx]\n",
593 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
596 case EVENT_TYPE_INV_DEV_REQ:
597 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
598 "address=0x%016llx flags=0x%04x]\n",
599 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
603 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
606 memset(__evt, 0, 4 * sizeof(u32));
609 static void iommu_poll_events(struct amd_iommu *iommu)
614 spin_lock_irqsave(&iommu->lock, flags);
616 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
617 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
619 while (head != tail) {
620 iommu_print_event(iommu, iommu->evt_buf + head);
621 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
624 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
626 spin_unlock_irqrestore(&iommu->lock, flags);
629 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
631 struct amd_iommu_fault fault;
633 INC_STATS_COUNTER(pri_requests);
635 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
636 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
640 fault.address = raw[1];
641 fault.pasid = PPR_PASID(raw[0]);
642 fault.device_id = PPR_DEVID(raw[0]);
643 fault.tag = PPR_TAG(raw[0]);
644 fault.flags = PPR_FLAGS(raw[0]);
646 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
649 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
654 if (iommu->ppr_log == NULL)
657 /* enable ppr interrupts again */
658 writel(MMIO_STATUS_PPR_INT_MASK, iommu->mmio_base + MMIO_STATUS_OFFSET);
660 spin_lock_irqsave(&iommu->lock, flags);
662 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
663 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
665 while (head != tail) {
670 raw = (u64 *)(iommu->ppr_log + head);
673 * Hardware bug: Interrupt may arrive before the entry is
674 * written to memory. If this happens we need to wait for the
677 for (i = 0; i < LOOP_TIMEOUT; ++i) {
678 if (PPR_REQ_TYPE(raw[0]) != 0)
683 /* Avoid memcpy function-call overhead */
688 * To detect the hardware bug we need to clear the entry
691 raw[0] = raw[1] = 0UL;
693 /* Update head pointer of hardware ring-buffer */
694 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
695 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
698 * Release iommu->lock because ppr-handling might need to
701 spin_unlock_irqrestore(&iommu->lock, flags);
703 /* Handle PPR entry */
704 iommu_handle_ppr_entry(iommu, entry);
706 spin_lock_irqsave(&iommu->lock, flags);
708 /* Refresh ring-buffer information */
709 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
710 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
713 spin_unlock_irqrestore(&iommu->lock, flags);
716 irqreturn_t amd_iommu_int_thread(int irq, void *data)
718 struct amd_iommu *iommu;
720 for_each_iommu(iommu) {
721 iommu_poll_events(iommu);
722 iommu_poll_ppr_log(iommu);
728 irqreturn_t amd_iommu_int_handler(int irq, void *data)
730 return IRQ_WAKE_THREAD;
733 /****************************************************************************
735 * IOMMU command queuing functions
737 ****************************************************************************/
739 static int wait_on_sem(volatile u64 *sem)
743 while (*sem == 0 && i < LOOP_TIMEOUT) {
748 if (i == LOOP_TIMEOUT) {
749 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
756 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
757 struct iommu_cmd *cmd,
762 target = iommu->cmd_buf + tail;
763 tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
765 /* Copy command to buffer */
766 memcpy(target, cmd, sizeof(*cmd));
768 /* Tell the IOMMU about it */
769 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
772 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
774 WARN_ON(address & 0x7ULL);
776 memset(cmd, 0, sizeof(*cmd));
777 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
778 cmd->data[1] = upper_32_bits(__pa(address));
780 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
783 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
785 memset(cmd, 0, sizeof(*cmd));
786 cmd->data[0] = devid;
787 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
790 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
791 size_t size, u16 domid, int pde)
796 pages = iommu_num_pages(address, size, PAGE_SIZE);
801 * If we have to flush more than one page, flush all
802 * TLB entries for this domain
804 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
808 address &= PAGE_MASK;
810 memset(cmd, 0, sizeof(*cmd));
811 cmd->data[1] |= domid;
812 cmd->data[2] = lower_32_bits(address);
813 cmd->data[3] = upper_32_bits(address);
814 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
815 if (s) /* size bit - we flush more than one 4kb page */
816 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
817 if (pde) /* PDE bit - we wan't flush everything not only the PTEs */
818 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
821 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
822 u64 address, size_t size)
827 pages = iommu_num_pages(address, size, PAGE_SIZE);
832 * If we have to flush more than one page, flush all
833 * TLB entries for this domain
835 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
839 address &= PAGE_MASK;
841 memset(cmd, 0, sizeof(*cmd));
842 cmd->data[0] = devid;
843 cmd->data[0] |= (qdep & 0xff) << 24;
844 cmd->data[1] = devid;
845 cmd->data[2] = lower_32_bits(address);
846 cmd->data[3] = upper_32_bits(address);
847 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
849 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
852 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
853 u64 address, bool size)
855 memset(cmd, 0, sizeof(*cmd));
857 address &= ~(0xfffULL);
859 cmd->data[0] = pasid & PASID_MASK;
860 cmd->data[1] = domid;
861 cmd->data[2] = lower_32_bits(address);
862 cmd->data[3] = upper_32_bits(address);
863 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
864 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
866 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
867 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
870 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
871 int qdep, u64 address, bool size)
873 memset(cmd, 0, sizeof(*cmd));
875 address &= ~(0xfffULL);
877 cmd->data[0] = devid;
878 cmd->data[0] |= (pasid & 0xff) << 16;
879 cmd->data[0] |= (qdep & 0xff) << 24;
880 cmd->data[1] = devid;
881 cmd->data[1] |= ((pasid >> 8) & 0xfff) << 16;
882 cmd->data[2] = lower_32_bits(address);
883 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
884 cmd->data[3] = upper_32_bits(address);
886 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
887 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
890 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
891 int status, int tag, bool gn)
893 memset(cmd, 0, sizeof(*cmd));
895 cmd->data[0] = devid;
897 cmd->data[1] = pasid & PASID_MASK;
898 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
900 cmd->data[3] = tag & 0x1ff;
901 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
903 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
906 static void build_inv_all(struct iommu_cmd *cmd)
908 memset(cmd, 0, sizeof(*cmd));
909 CMD_SET_TYPE(cmd, CMD_INV_ALL);
912 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
914 memset(cmd, 0, sizeof(*cmd));
915 cmd->data[0] = devid;
916 CMD_SET_TYPE(cmd, CMD_INV_IRT);
920 * Writes the command to the IOMMUs command buffer and informs the
921 * hardware about the new command.
923 static int iommu_queue_command_sync(struct amd_iommu *iommu,
924 struct iommu_cmd *cmd,
927 u32 left, tail, head, next_tail;
930 WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
933 spin_lock_irqsave(&iommu->lock, flags);
935 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
936 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
937 next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
938 left = (head - next_tail) % iommu->cmd_buf_size;
941 struct iommu_cmd sync_cmd;
942 volatile u64 sem = 0;
945 build_completion_wait(&sync_cmd, (u64)&sem);
946 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
948 spin_unlock_irqrestore(&iommu->lock, flags);
950 if ((ret = wait_on_sem(&sem)) != 0)
956 copy_cmd_to_buffer(iommu, cmd, tail);
958 /* We need to sync now to make sure all commands are processed */
959 iommu->need_sync = sync;
961 spin_unlock_irqrestore(&iommu->lock, flags);
966 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
968 return iommu_queue_command_sync(iommu, cmd, true);
972 * This function queues a completion wait command into the command
975 static int iommu_completion_wait(struct amd_iommu *iommu)
977 struct iommu_cmd cmd;
978 volatile u64 sem = 0;
981 if (!iommu->need_sync)
984 build_completion_wait(&cmd, (u64)&sem);
986 ret = iommu_queue_command_sync(iommu, &cmd, false);
990 return wait_on_sem(&sem);
993 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
995 struct iommu_cmd cmd;
997 build_inv_dte(&cmd, devid);
999 return iommu_queue_command(iommu, &cmd);
1002 static void iommu_flush_dte_all(struct amd_iommu *iommu)
1006 for (devid = 0; devid <= 0xffff; ++devid)
1007 iommu_flush_dte(iommu, devid);
1009 iommu_completion_wait(iommu);
1013 * This function uses heavy locking and may disable irqs for some time. But
1014 * this is no issue because it is only called during resume.
1016 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1020 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1021 struct iommu_cmd cmd;
1022 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1024 iommu_queue_command(iommu, &cmd);
1027 iommu_completion_wait(iommu);
1030 static void iommu_flush_all(struct amd_iommu *iommu)
1032 struct iommu_cmd cmd;
1034 build_inv_all(&cmd);
1036 iommu_queue_command(iommu, &cmd);
1037 iommu_completion_wait(iommu);
1040 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1042 struct iommu_cmd cmd;
1044 build_inv_irt(&cmd, devid);
1046 iommu_queue_command(iommu, &cmd);
1049 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1053 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1054 iommu_flush_irt(iommu, devid);
1056 iommu_completion_wait(iommu);
1059 void iommu_flush_all_caches(struct amd_iommu *iommu)
1061 if (iommu_feature(iommu, FEATURE_IA)) {
1062 iommu_flush_all(iommu);
1064 iommu_flush_dte_all(iommu);
1065 iommu_flush_irt_all(iommu);
1066 iommu_flush_tlb_all(iommu);
1071 * Command send function for flushing on-device TLB
1073 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1074 u64 address, size_t size)
1076 struct amd_iommu *iommu;
1077 struct iommu_cmd cmd;
1080 qdep = dev_data->ats.qdep;
1081 iommu = amd_iommu_rlookup_table[dev_data->devid];
1083 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1085 return iommu_queue_command(iommu, &cmd);
1089 * Command send function for invalidating a device table entry
1091 static int device_flush_dte(struct iommu_dev_data *dev_data)
1093 struct amd_iommu *iommu;
1096 iommu = amd_iommu_rlookup_table[dev_data->devid];
1098 ret = iommu_flush_dte(iommu, dev_data->devid);
1102 if (dev_data->ats.enabled)
1103 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1109 * TLB invalidation function which is called from the mapping functions.
1110 * It invalidates a single PTE if the range to flush is within a single
1111 * page. Otherwise it flushes the whole TLB of the IOMMU.
1113 static void __domain_flush_pages(struct protection_domain *domain,
1114 u64 address, size_t size, int pde)
1116 struct iommu_dev_data *dev_data;
1117 struct iommu_cmd cmd;
1120 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1122 for (i = 0; i < amd_iommus_present; ++i) {
1123 if (!domain->dev_iommu[i])
1127 * Devices of this domain are behind this IOMMU
1128 * We need a TLB flush
1130 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1133 list_for_each_entry(dev_data, &domain->dev_list, list) {
1135 if (!dev_data->ats.enabled)
1138 ret |= device_flush_iotlb(dev_data, address, size);
1144 static void domain_flush_pages(struct protection_domain *domain,
1145 u64 address, size_t size)
1147 __domain_flush_pages(domain, address, size, 0);
1150 /* Flush the whole IO/TLB for a given protection domain */
1151 static void domain_flush_tlb(struct protection_domain *domain)
1153 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1156 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1157 static void domain_flush_tlb_pde(struct protection_domain *domain)
1159 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1162 static void domain_flush_complete(struct protection_domain *domain)
1166 for (i = 0; i < amd_iommus_present; ++i) {
1167 if (!domain->dev_iommu[i])
1171 * Devices of this domain are behind this IOMMU
1172 * We need to wait for completion of all commands.
1174 iommu_completion_wait(amd_iommus[i]);
1180 * This function flushes the DTEs for all devices in domain
1182 static void domain_flush_devices(struct protection_domain *domain)
1184 struct iommu_dev_data *dev_data;
1186 list_for_each_entry(dev_data, &domain->dev_list, list)
1187 device_flush_dte(dev_data);
1190 /****************************************************************************
1192 * The functions below are used the create the page table mappings for
1193 * unity mapped regions.
1195 ****************************************************************************/
1198 * This function is used to add another level to an IO page table. Adding
1199 * another level increases the size of the address space by 9 bits to a size up
1202 static bool increase_address_space(struct protection_domain *domain,
1207 if (domain->mode == PAGE_MODE_6_LEVEL)
1208 /* address space already 64 bit large */
1211 pte = (void *)get_zeroed_page(gfp);
1215 *pte = PM_LEVEL_PDE(domain->mode,
1216 virt_to_phys(domain->pt_root));
1217 domain->pt_root = pte;
1219 domain->updated = true;
1224 static u64 *alloc_pte(struct protection_domain *domain,
1225 unsigned long address,
1226 unsigned long page_size,
1233 BUG_ON(!is_power_of_2(page_size));
1235 while (address > PM_LEVEL_SIZE(domain->mode))
1236 increase_address_space(domain, gfp);
1238 level = domain->mode - 1;
1239 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1240 address = PAGE_SIZE_ALIGN(address, page_size);
1241 end_lvl = PAGE_SIZE_LEVEL(page_size);
1243 while (level > end_lvl) {
1244 if (!IOMMU_PTE_PRESENT(*pte)) {
1245 page = (u64 *)get_zeroed_page(gfp);
1248 *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1251 /* No level skipping support yet */
1252 if (PM_PTE_LEVEL(*pte) != level)
1257 pte = IOMMU_PTE_PAGE(*pte);
1259 if (pte_page && level == end_lvl)
1262 pte = &pte[PM_LEVEL_INDEX(level, address)];
1269 * This function checks if there is a PTE for a given dma address. If
1270 * there is one, it returns the pointer to it.
1272 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
1277 if (address > PM_LEVEL_SIZE(domain->mode))
1280 level = domain->mode - 1;
1281 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1286 if (!IOMMU_PTE_PRESENT(*pte))
1290 if (PM_PTE_LEVEL(*pte) == 0x07) {
1291 unsigned long pte_mask, __pte;
1294 * If we have a series of large PTEs, make
1295 * sure to return a pointer to the first one.
1297 pte_mask = PTE_PAGE_SIZE(*pte);
1298 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1299 __pte = ((unsigned long)pte) & pte_mask;
1301 return (u64 *)__pte;
1304 /* No level skipping support yet */
1305 if (PM_PTE_LEVEL(*pte) != level)
1310 /* Walk to the next level */
1311 pte = IOMMU_PTE_PAGE(*pte);
1312 pte = &pte[PM_LEVEL_INDEX(level, address)];
1319 * Generic mapping functions. It maps a physical address into a DMA
1320 * address space. It allocates the page table pages if necessary.
1321 * In the future it can be extended to a generic mapping function
1322 * supporting all features of AMD IOMMU page tables like level skipping
1323 * and full 64 bit address spaces.
1325 static int iommu_map_page(struct protection_domain *dom,
1326 unsigned long bus_addr,
1327 unsigned long phys_addr,
1329 unsigned long page_size)
1334 if (!(prot & IOMMU_PROT_MASK))
1337 bus_addr = PAGE_ALIGN(bus_addr);
1338 phys_addr = PAGE_ALIGN(phys_addr);
1339 count = PAGE_SIZE_PTE_COUNT(page_size);
1340 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1342 for (i = 0; i < count; ++i)
1343 if (IOMMU_PTE_PRESENT(pte[i]))
1346 if (page_size > PAGE_SIZE) {
1347 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1348 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1350 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1352 if (prot & IOMMU_PROT_IR)
1353 __pte |= IOMMU_PTE_IR;
1354 if (prot & IOMMU_PROT_IW)
1355 __pte |= IOMMU_PTE_IW;
1357 for (i = 0; i < count; ++i)
1365 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1366 unsigned long bus_addr,
1367 unsigned long page_size)
1369 unsigned long long unmap_size, unmapped;
1372 BUG_ON(!is_power_of_2(page_size));
1376 while (unmapped < page_size) {
1378 pte = fetch_pte(dom, bus_addr);
1382 * No PTE for this address
1383 * move forward in 4kb steps
1385 unmap_size = PAGE_SIZE;
1386 } else if (PM_PTE_LEVEL(*pte) == 0) {
1387 /* 4kb PTE found for this address */
1388 unmap_size = PAGE_SIZE;
1393 /* Large PTE found which maps this address */
1394 unmap_size = PTE_PAGE_SIZE(*pte);
1395 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1396 for (i = 0; i < count; i++)
1400 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1401 unmapped += unmap_size;
1404 BUG_ON(!is_power_of_2(unmapped));
1410 * This function checks if a specific unity mapping entry is needed for
1411 * this specific IOMMU.
1413 static int iommu_for_unity_map(struct amd_iommu *iommu,
1414 struct unity_map_entry *entry)
1418 for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1419 bdf = amd_iommu_alias_table[i];
1420 if (amd_iommu_rlookup_table[bdf] == iommu)
1428 * This function actually applies the mapping to the page table of the
1431 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1432 struct unity_map_entry *e)
1437 for (addr = e->address_start; addr < e->address_end;
1438 addr += PAGE_SIZE) {
1439 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1444 * if unity mapping is in aperture range mark the page
1445 * as allocated in the aperture
1447 if (addr < dma_dom->aperture_size)
1448 __set_bit(addr >> PAGE_SHIFT,
1449 dma_dom->aperture[0]->bitmap);
1456 * Init the unity mappings for a specific IOMMU in the system
1458 * Basically iterates over all unity mapping entries and applies them to
1459 * the default domain DMA of that IOMMU if necessary.
1461 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1463 struct unity_map_entry *entry;
1466 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1467 if (!iommu_for_unity_map(iommu, entry))
1469 ret = dma_ops_unity_map(iommu->default_dom, entry);
1478 * Inits the unity mappings required for a specific device
1480 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1483 struct unity_map_entry *e;
1486 list_for_each_entry(e, &amd_iommu_unity_map, list) {
1487 if (!(devid >= e->devid_start && devid <= e->devid_end))
1489 ret = dma_ops_unity_map(dma_dom, e);
1497 /****************************************************************************
1499 * The next functions belong to the address allocator for the dma_ops
1500 * interface functions. They work like the allocators in the other IOMMU
1501 * drivers. Its basically a bitmap which marks the allocated pages in
1502 * the aperture. Maybe it could be enhanced in the future to a more
1503 * efficient allocator.
1505 ****************************************************************************/
1508 * The address allocator core functions.
1510 * called with domain->lock held
1514 * Used to reserve address ranges in the aperture (e.g. for exclusion
1517 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1518 unsigned long start_page,
1521 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1523 if (start_page + pages > last_page)
1524 pages = last_page - start_page;
1526 for (i = start_page; i < start_page + pages; ++i) {
1527 int index = i / APERTURE_RANGE_PAGES;
1528 int page = i % APERTURE_RANGE_PAGES;
1529 __set_bit(page, dom->aperture[index]->bitmap);
1534 * This function is used to add a new aperture range to an existing
1535 * aperture in case of dma_ops domain allocation or address allocation
1538 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1539 bool populate, gfp_t gfp)
1541 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1542 struct amd_iommu *iommu;
1543 unsigned long i, old_size;
1545 #ifdef CONFIG_IOMMU_STRESS
1549 if (index >= APERTURE_MAX_RANGES)
1552 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1553 if (!dma_dom->aperture[index])
1556 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1557 if (!dma_dom->aperture[index]->bitmap)
1560 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1563 unsigned long address = dma_dom->aperture_size;
1564 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1565 u64 *pte, *pte_page;
1567 for (i = 0; i < num_ptes; ++i) {
1568 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1573 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1575 address += APERTURE_RANGE_SIZE / 64;
1579 old_size = dma_dom->aperture_size;
1580 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1582 /* Reserve address range used for MSI messages */
1583 if (old_size < MSI_ADDR_BASE_LO &&
1584 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1585 unsigned long spage;
1588 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1589 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1591 dma_ops_reserve_addresses(dma_dom, spage, pages);
1594 /* Initialize the exclusion range if necessary */
1595 for_each_iommu(iommu) {
1596 if (iommu->exclusion_start &&
1597 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1598 && iommu->exclusion_start < dma_dom->aperture_size) {
1599 unsigned long startpage;
1600 int pages = iommu_num_pages(iommu->exclusion_start,
1601 iommu->exclusion_length,
1603 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1604 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1609 * Check for areas already mapped as present in the new aperture
1610 * range and mark those pages as reserved in the allocator. Such
1611 * mappings may already exist as a result of requested unity
1612 * mappings for devices.
1614 for (i = dma_dom->aperture[index]->offset;
1615 i < dma_dom->aperture_size;
1617 u64 *pte = fetch_pte(&dma_dom->domain, i);
1618 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1621 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1624 update_domain(&dma_dom->domain);
1629 update_domain(&dma_dom->domain);
1631 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1633 kfree(dma_dom->aperture[index]);
1634 dma_dom->aperture[index] = NULL;
1639 static unsigned long dma_ops_area_alloc(struct device *dev,
1640 struct dma_ops_domain *dom,
1642 unsigned long align_mask,
1644 unsigned long start)
1646 unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1647 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1648 int i = start >> APERTURE_RANGE_SHIFT;
1649 unsigned long boundary_size;
1650 unsigned long address = -1;
1651 unsigned long limit;
1653 next_bit >>= PAGE_SHIFT;
1655 boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1656 PAGE_SIZE) >> PAGE_SHIFT;
1658 for (;i < max_index; ++i) {
1659 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1661 if (dom->aperture[i]->offset >= dma_mask)
1664 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1665 dma_mask >> PAGE_SHIFT);
1667 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1668 limit, next_bit, pages, 0,
1669 boundary_size, align_mask);
1670 if (address != -1) {
1671 address = dom->aperture[i]->offset +
1672 (address << PAGE_SHIFT);
1673 dom->next_address = address + (pages << PAGE_SHIFT);
1683 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1684 struct dma_ops_domain *dom,
1686 unsigned long align_mask,
1689 unsigned long address;
1691 #ifdef CONFIG_IOMMU_STRESS
1692 dom->next_address = 0;
1693 dom->need_flush = true;
1696 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1697 dma_mask, dom->next_address);
1699 if (address == -1) {
1700 dom->next_address = 0;
1701 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1703 dom->need_flush = true;
1706 if (unlikely(address == -1))
1707 address = DMA_ERROR_CODE;
1709 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1715 * The address free function.
1717 * called with domain->lock held
1719 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1720 unsigned long address,
1723 unsigned i = address >> APERTURE_RANGE_SHIFT;
1724 struct aperture_range *range = dom->aperture[i];
1726 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1728 #ifdef CONFIG_IOMMU_STRESS
1733 if (address >= dom->next_address)
1734 dom->need_flush = true;
1736 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1738 bitmap_clear(range->bitmap, address, pages);
1742 /****************************************************************************
1744 * The next functions belong to the domain allocation. A domain is
1745 * allocated for every IOMMU as the default domain. If device isolation
1746 * is enabled, every device get its own domain. The most important thing
1747 * about domains is the page table mapping the DMA address space they
1750 ****************************************************************************/
1753 * This function adds a protection domain to the global protection domain list
1755 static void add_domain_to_list(struct protection_domain *domain)
1757 unsigned long flags;
1759 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1760 list_add(&domain->list, &amd_iommu_pd_list);
1761 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1765 * This function removes a protection domain to the global
1766 * protection domain list
1768 static void del_domain_from_list(struct protection_domain *domain)
1770 unsigned long flags;
1772 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1773 list_del(&domain->list);
1774 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1777 static u16 domain_id_alloc(void)
1779 unsigned long flags;
1782 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1783 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1785 if (id > 0 && id < MAX_DOMAIN_ID)
1786 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1789 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1794 static void domain_id_free(int id)
1796 unsigned long flags;
1798 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1799 if (id > 0 && id < MAX_DOMAIN_ID)
1800 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1801 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1804 static void free_pagetable(struct protection_domain *domain)
1809 p1 = domain->pt_root;
1814 for (i = 0; i < 512; ++i) {
1815 if (!IOMMU_PTE_PRESENT(p1[i]))
1818 p2 = IOMMU_PTE_PAGE(p1[i]);
1819 for (j = 0; j < 512; ++j) {
1820 if (!IOMMU_PTE_PRESENT(p2[j]))
1822 p3 = IOMMU_PTE_PAGE(p2[j]);
1823 free_page((unsigned long)p3);
1826 free_page((unsigned long)p2);
1829 free_page((unsigned long)p1);
1831 domain->pt_root = NULL;
1834 static void free_gcr3_tbl_level1(u64 *tbl)
1839 for (i = 0; i < 512; ++i) {
1840 if (!(tbl[i] & GCR3_VALID))
1843 ptr = __va(tbl[i] & PAGE_MASK);
1845 free_page((unsigned long)ptr);
1849 static void free_gcr3_tbl_level2(u64 *tbl)
1854 for (i = 0; i < 512; ++i) {
1855 if (!(tbl[i] & GCR3_VALID))
1858 ptr = __va(tbl[i] & PAGE_MASK);
1860 free_gcr3_tbl_level1(ptr);
1864 static void free_gcr3_table(struct protection_domain *domain)
1866 if (domain->glx == 2)
1867 free_gcr3_tbl_level2(domain->gcr3_tbl);
1868 else if (domain->glx == 1)
1869 free_gcr3_tbl_level1(domain->gcr3_tbl);
1870 else if (domain->glx != 0)
1873 free_page((unsigned long)domain->gcr3_tbl);
1877 * Free a domain, only used if something went wrong in the
1878 * allocation path and we need to free an already allocated page table
1880 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1887 del_domain_from_list(&dom->domain);
1889 free_pagetable(&dom->domain);
1891 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1892 if (!dom->aperture[i])
1894 free_page((unsigned long)dom->aperture[i]->bitmap);
1895 kfree(dom->aperture[i]);
1902 * Allocates a new protection domain usable for the dma_ops functions.
1903 * It also initializes the page table and the address allocator data
1904 * structures required for the dma_ops interface
1906 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1908 struct dma_ops_domain *dma_dom;
1910 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1914 spin_lock_init(&dma_dom->domain.lock);
1916 dma_dom->domain.id = domain_id_alloc();
1917 if (dma_dom->domain.id == 0)
1919 INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1920 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1921 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1922 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1923 dma_dom->domain.priv = dma_dom;
1924 if (!dma_dom->domain.pt_root)
1927 dma_dom->need_flush = false;
1928 dma_dom->target_dev = 0xffff;
1930 add_domain_to_list(&dma_dom->domain);
1932 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1936 * mark the first page as allocated so we never return 0 as
1937 * a valid dma-address. So we can use 0 as error value
1939 dma_dom->aperture[0]->bitmap[0] = 1;
1940 dma_dom->next_address = 0;
1946 dma_ops_domain_free(dma_dom);
1952 * little helper function to check whether a given protection domain is a
1955 static bool dma_ops_domain(struct protection_domain *domain)
1957 return domain->flags & PD_DMA_OPS_MASK;
1960 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1965 if (domain->mode != PAGE_MODE_NONE)
1966 pte_root = virt_to_phys(domain->pt_root);
1968 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1969 << DEV_ENTRY_MODE_SHIFT;
1970 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1972 flags = amd_iommu_dev_table[devid].data[1];
1975 flags |= DTE_FLAG_IOTLB;
1977 if (domain->flags & PD_IOMMUV2_MASK) {
1978 u64 gcr3 = __pa(domain->gcr3_tbl);
1979 u64 glx = domain->glx;
1982 pte_root |= DTE_FLAG_GV;
1983 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1985 /* First mask out possible old values for GCR3 table */
1986 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1989 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1992 /* Encode GCR3 table into DTE */
1993 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1996 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1999 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
2003 flags &= ~(0xffffUL);
2004 flags |= domain->id;
2006 amd_iommu_dev_table[devid].data[1] = flags;
2007 amd_iommu_dev_table[devid].data[0] = pte_root;
2010 static void clear_dte_entry(u16 devid)
2012 /* remove entry from the device table seen by the hardware */
2013 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
2014 amd_iommu_dev_table[devid].data[1] = 0;
2016 amd_iommu_apply_erratum_63(devid);
2019 static void do_attach(struct iommu_dev_data *dev_data,
2020 struct protection_domain *domain)
2022 struct amd_iommu *iommu;
2025 iommu = amd_iommu_rlookup_table[dev_data->devid];
2026 ats = dev_data->ats.enabled;
2028 /* Update data structures */
2029 dev_data->domain = domain;
2030 list_add(&dev_data->list, &domain->dev_list);
2031 set_dte_entry(dev_data->devid, domain, ats);
2033 /* Do reference counting */
2034 domain->dev_iommu[iommu->index] += 1;
2035 domain->dev_cnt += 1;
2037 /* Flush the DTE entry */
2038 device_flush_dte(dev_data);
2041 static void do_detach(struct iommu_dev_data *dev_data)
2043 struct amd_iommu *iommu;
2045 iommu = amd_iommu_rlookup_table[dev_data->devid];
2047 /* decrease reference counters */
2048 dev_data->domain->dev_iommu[iommu->index] -= 1;
2049 dev_data->domain->dev_cnt -= 1;
2051 /* Update data structures */
2052 dev_data->domain = NULL;
2053 list_del(&dev_data->list);
2054 clear_dte_entry(dev_data->devid);
2056 /* Flush the DTE entry */
2057 device_flush_dte(dev_data);
2061 * If a device is not yet associated with a domain, this function does
2062 * assigns it visible for the hardware
2064 static int __attach_device(struct iommu_dev_data *dev_data,
2065 struct protection_domain *domain)
2070 spin_lock(&domain->lock);
2072 if (dev_data->alias_data != NULL) {
2073 struct iommu_dev_data *alias_data = dev_data->alias_data;
2075 /* Some sanity checks */
2077 if (alias_data->domain != NULL &&
2078 alias_data->domain != domain)
2081 if (dev_data->domain != NULL &&
2082 dev_data->domain != domain)
2085 /* Do real assignment */
2086 if (alias_data->domain == NULL)
2087 do_attach(alias_data, domain);
2089 atomic_inc(&alias_data->bind);
2092 if (dev_data->domain == NULL)
2093 do_attach(dev_data, domain);
2095 atomic_inc(&dev_data->bind);
2102 spin_unlock(&domain->lock);
2108 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2110 pci_disable_ats(pdev);
2111 pci_disable_pri(pdev);
2112 pci_disable_pasid(pdev);
2115 /* FIXME: Change generic reset-function to do the same */
2116 static int pri_reset_while_enabled(struct pci_dev *pdev)
2121 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2125 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2126 control |= PCI_PRI_CTRL_RESET;
2127 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2132 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2137 /* FIXME: Hardcode number of outstanding requests for now */
2139 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2141 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2143 /* Only allow access to user-accessible pages */
2144 ret = pci_enable_pasid(pdev, 0);
2148 /* First reset the PRI state of the device */
2149 ret = pci_reset_pri(pdev);
2154 ret = pci_enable_pri(pdev, reqs);
2159 ret = pri_reset_while_enabled(pdev);
2164 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2171 pci_disable_pri(pdev);
2172 pci_disable_pasid(pdev);
2177 /* FIXME: Move this to PCI code */
2178 #define PCI_PRI_TLP_OFF (1 << 15)
2180 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2185 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2189 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2191 return (status & PCI_PRI_TLP_OFF) ? true : false;
2195 * If a device is not yet associated with a domain, this function does
2196 * assigns it visible for the hardware
2198 static int attach_device(struct device *dev,
2199 struct protection_domain *domain)
2201 struct pci_dev *pdev = to_pci_dev(dev);
2202 struct iommu_dev_data *dev_data;
2203 unsigned long flags;
2206 dev_data = get_dev_data(dev);
2208 if (domain->flags & PD_IOMMUV2_MASK) {
2209 if (!dev_data->iommu_v2 || !dev_data->passthrough)
2212 if (pdev_iommuv2_enable(pdev) != 0)
2215 dev_data->ats.enabled = true;
2216 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2217 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2218 } else if (amd_iommu_iotlb_sup &&
2219 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2220 dev_data->ats.enabled = true;
2221 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2224 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2225 ret = __attach_device(dev_data, domain);
2226 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2229 * We might boot into a crash-kernel here. The crashed kernel
2230 * left the caches in the IOMMU dirty. So we have to flush
2231 * here to evict all dirty stuff.
2233 domain_flush_tlb_pde(domain);
2239 * Removes a device from a protection domain (unlocked)
2241 static void __detach_device(struct iommu_dev_data *dev_data)
2243 struct protection_domain *domain;
2244 unsigned long flags;
2246 BUG_ON(!dev_data->domain);
2248 domain = dev_data->domain;
2250 spin_lock_irqsave(&domain->lock, flags);
2252 if (dev_data->alias_data != NULL) {
2253 struct iommu_dev_data *alias_data = dev_data->alias_data;
2255 if (atomic_dec_and_test(&alias_data->bind))
2256 do_detach(alias_data);
2259 if (atomic_dec_and_test(&dev_data->bind))
2260 do_detach(dev_data);
2262 spin_unlock_irqrestore(&domain->lock, flags);
2265 * If we run in passthrough mode the device must be assigned to the
2266 * passthrough domain if it is detached from any other domain.
2267 * Make sure we can deassign from the pt_domain itself.
2269 if (dev_data->passthrough &&
2270 (dev_data->domain == NULL && domain != pt_domain))
2271 __attach_device(dev_data, pt_domain);
2275 * Removes a device from a protection domain (with devtable_lock held)
2277 static void detach_device(struct device *dev)
2279 struct protection_domain *domain;
2280 struct iommu_dev_data *dev_data;
2281 unsigned long flags;
2283 dev_data = get_dev_data(dev);
2284 domain = dev_data->domain;
2286 /* lock device table */
2287 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2288 __detach_device(dev_data);
2289 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2291 if (domain->flags & PD_IOMMUV2_MASK)
2292 pdev_iommuv2_disable(to_pci_dev(dev));
2293 else if (dev_data->ats.enabled)
2294 pci_disable_ats(to_pci_dev(dev));
2296 dev_data->ats.enabled = false;
2300 * Find out the protection domain structure for a given PCI device. This
2301 * will give us the pointer to the page table root for example.
2303 static struct protection_domain *domain_for_device(struct device *dev)
2305 struct iommu_dev_data *dev_data;
2306 struct protection_domain *dom = NULL;
2307 unsigned long flags;
2309 dev_data = get_dev_data(dev);
2311 if (dev_data->domain)
2312 return dev_data->domain;
2314 if (dev_data->alias_data != NULL) {
2315 struct iommu_dev_data *alias_data = dev_data->alias_data;
2317 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
2318 if (alias_data->domain != NULL) {
2319 __attach_device(dev_data, alias_data->domain);
2320 dom = alias_data->domain;
2322 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2328 static int device_change_notifier(struct notifier_block *nb,
2329 unsigned long action, void *data)
2331 struct dma_ops_domain *dma_domain;
2332 struct protection_domain *domain;
2333 struct iommu_dev_data *dev_data;
2334 struct device *dev = data;
2335 struct amd_iommu *iommu;
2336 unsigned long flags;
2339 if (!check_device(dev))
2342 devid = get_device_id(dev);
2343 iommu = amd_iommu_rlookup_table[devid];
2344 dev_data = get_dev_data(dev);
2347 case BUS_NOTIFY_UNBOUND_DRIVER:
2349 domain = domain_for_device(dev);
2353 if (dev_data->passthrough)
2357 case BUS_NOTIFY_ADD_DEVICE:
2359 iommu_init_device(dev);
2362 * dev_data is still NULL and
2363 * got initialized in iommu_init_device
2365 dev_data = get_dev_data(dev);
2367 if (iommu_pass_through || dev_data->iommu_v2) {
2368 dev_data->passthrough = true;
2369 attach_device(dev, pt_domain);
2373 domain = domain_for_device(dev);
2375 /* allocate a protection domain if a device is added */
2376 dma_domain = find_protection_domain(devid);
2379 dma_domain = dma_ops_domain_alloc();
2382 dma_domain->target_dev = devid;
2384 spin_lock_irqsave(&iommu_pd_list_lock, flags);
2385 list_add_tail(&dma_domain->list, &iommu_pd_list);
2386 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
2388 dev_data = get_dev_data(dev);
2390 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2393 case BUS_NOTIFY_DEL_DEVICE:
2395 iommu_uninit_device(dev);
2401 iommu_completion_wait(iommu);
2407 static struct notifier_block device_nb = {
2408 .notifier_call = device_change_notifier,
2411 void amd_iommu_init_notifier(void)
2413 bus_register_notifier(&pci_bus_type, &device_nb);
2416 /*****************************************************************************
2418 * The next functions belong to the dma_ops mapping/unmapping code.
2420 *****************************************************************************/
2423 * In the dma_ops path we only have the struct device. This function
2424 * finds the corresponding IOMMU, the protection domain and the
2425 * requestor id for a given device.
2426 * If the device is not yet associated with a domain this is also done
2429 static struct protection_domain *get_domain(struct device *dev)
2431 struct protection_domain *domain;
2432 struct dma_ops_domain *dma_dom;
2433 u16 devid = get_device_id(dev);
2435 if (!check_device(dev))
2436 return ERR_PTR(-EINVAL);
2438 domain = domain_for_device(dev);
2439 if (domain != NULL && !dma_ops_domain(domain))
2440 return ERR_PTR(-EBUSY);
2445 /* Device not bount yet - bind it */
2446 dma_dom = find_protection_domain(devid);
2448 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
2449 attach_device(dev, &dma_dom->domain);
2450 DUMP_printk("Using protection domain %d for device %s\n",
2451 dma_dom->domain.id, dev_name(dev));
2453 return &dma_dom->domain;
2456 static void update_device_table(struct protection_domain *domain)
2458 struct iommu_dev_data *dev_data;
2460 list_for_each_entry(dev_data, &domain->dev_list, list)
2461 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2464 static void update_domain(struct protection_domain *domain)
2466 if (!domain->updated)
2469 update_device_table(domain);
2471 domain_flush_devices(domain);
2472 domain_flush_tlb_pde(domain);
2474 domain->updated = false;
2478 * This function fetches the PTE for a given address in the aperture
2480 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2481 unsigned long address)
2483 struct aperture_range *aperture;
2484 u64 *pte, *pte_page;
2486 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2490 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2492 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2494 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2496 pte += PM_LEVEL_INDEX(0, address);
2498 update_domain(&dom->domain);
2504 * This is the generic map function. It maps one 4kb page at paddr to
2505 * the given address in the DMA address space for the domain.
2507 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2508 unsigned long address,
2514 WARN_ON(address > dom->aperture_size);
2518 pte = dma_ops_get_pte(dom, address);
2520 return DMA_ERROR_CODE;
2522 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2524 if (direction == DMA_TO_DEVICE)
2525 __pte |= IOMMU_PTE_IR;
2526 else if (direction == DMA_FROM_DEVICE)
2527 __pte |= IOMMU_PTE_IW;
2528 else if (direction == DMA_BIDIRECTIONAL)
2529 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2535 return (dma_addr_t)address;
2539 * The generic unmapping function for on page in the DMA address space.
2541 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2542 unsigned long address)
2544 struct aperture_range *aperture;
2547 if (address >= dom->aperture_size)
2550 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2554 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2558 pte += PM_LEVEL_INDEX(0, address);
2566 * This function contains common code for mapping of a physically
2567 * contiguous memory region into DMA address space. It is used by all
2568 * mapping functions provided with this IOMMU driver.
2569 * Must be called with the domain lock held.
2571 static dma_addr_t __map_single(struct device *dev,
2572 struct dma_ops_domain *dma_dom,
2579 dma_addr_t offset = paddr & ~PAGE_MASK;
2580 dma_addr_t address, start, ret;
2582 unsigned long align_mask = 0;
2585 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2588 INC_STATS_COUNTER(total_map_requests);
2591 INC_STATS_COUNTER(cross_page);
2594 align_mask = (1UL << get_order(size)) - 1;
2597 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2599 if (unlikely(address == DMA_ERROR_CODE)) {
2601 * setting next_address here will let the address
2602 * allocator only scan the new allocated range in the
2603 * first run. This is a small optimization.
2605 dma_dom->next_address = dma_dom->aperture_size;
2607 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2611 * aperture was successfully enlarged by 128 MB, try
2618 for (i = 0; i < pages; ++i) {
2619 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2620 if (ret == DMA_ERROR_CODE)
2628 ADD_STATS_COUNTER(alloced_io_mem, size);
2630 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2631 domain_flush_tlb(&dma_dom->domain);
2632 dma_dom->need_flush = false;
2633 } else if (unlikely(amd_iommu_np_cache))
2634 domain_flush_pages(&dma_dom->domain, address, size);
2641 for (--i; i >= 0; --i) {
2643 dma_ops_domain_unmap(dma_dom, start);
2646 dma_ops_free_addresses(dma_dom, address, pages);
2648 return DMA_ERROR_CODE;
2652 * Does the reverse of the __map_single function. Must be called with
2653 * the domain lock held too
2655 static void __unmap_single(struct dma_ops_domain *dma_dom,
2656 dma_addr_t dma_addr,
2660 dma_addr_t flush_addr;
2661 dma_addr_t i, start;
2664 if ((dma_addr == DMA_ERROR_CODE) ||
2665 (dma_addr + size > dma_dom->aperture_size))
2668 flush_addr = dma_addr;
2669 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2670 dma_addr &= PAGE_MASK;
2673 for (i = 0; i < pages; ++i) {
2674 dma_ops_domain_unmap(dma_dom, start);
2678 SUB_STATS_COUNTER(alloced_io_mem, size);
2680 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2682 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2683 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2684 dma_dom->need_flush = false;
2689 * The exported map_single function for dma_ops.
2691 static dma_addr_t map_page(struct device *dev, struct page *page,
2692 unsigned long offset, size_t size,
2693 enum dma_data_direction dir,
2694 struct dma_attrs *attrs)
2696 unsigned long flags;
2697 struct protection_domain *domain;
2700 phys_addr_t paddr = page_to_phys(page) + offset;
2702 INC_STATS_COUNTER(cnt_map_single);
2704 domain = get_domain(dev);
2705 if (PTR_ERR(domain) == -EINVAL)
2706 return (dma_addr_t)paddr;
2707 else if (IS_ERR(domain))
2708 return DMA_ERROR_CODE;
2710 dma_mask = *dev->dma_mask;
2712 spin_lock_irqsave(&domain->lock, flags);
2714 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2716 if (addr == DMA_ERROR_CODE)
2719 domain_flush_complete(domain);
2722 spin_unlock_irqrestore(&domain->lock, flags);
2728 * The exported unmap_single function for dma_ops.
2730 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2731 enum dma_data_direction dir, struct dma_attrs *attrs)
2733 unsigned long flags;
2734 struct protection_domain *domain;
2736 INC_STATS_COUNTER(cnt_unmap_single);
2738 domain = get_domain(dev);
2742 spin_lock_irqsave(&domain->lock, flags);
2744 __unmap_single(domain->priv, dma_addr, size, dir);
2746 domain_flush_complete(domain);
2748 spin_unlock_irqrestore(&domain->lock, flags);
2752 * This is a special map_sg function which is used if we should map a
2753 * device which is not handled by an AMD IOMMU in the system.
2755 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2756 int nelems, int dir)
2758 struct scatterlist *s;
2761 for_each_sg(sglist, s, nelems, i) {
2762 s->dma_address = (dma_addr_t)sg_phys(s);
2763 s->dma_length = s->length;
2770 * The exported map_sg function for dma_ops (handles scatter-gather
2773 static int map_sg(struct device *dev, struct scatterlist *sglist,
2774 int nelems, enum dma_data_direction dir,
2775 struct dma_attrs *attrs)
2777 unsigned long flags;
2778 struct protection_domain *domain;
2780 struct scatterlist *s;
2782 int mapped_elems = 0;
2785 INC_STATS_COUNTER(cnt_map_sg);
2787 domain = get_domain(dev);
2788 if (PTR_ERR(domain) == -EINVAL)
2789 return map_sg_no_iommu(dev, sglist, nelems, dir);
2790 else if (IS_ERR(domain))
2793 dma_mask = *dev->dma_mask;
2795 spin_lock_irqsave(&domain->lock, flags);
2797 for_each_sg(sglist, s, nelems, i) {
2800 s->dma_address = __map_single(dev, domain->priv,
2801 paddr, s->length, dir, false,
2804 if (s->dma_address) {
2805 s->dma_length = s->length;
2811 domain_flush_complete(domain);
2814 spin_unlock_irqrestore(&domain->lock, flags);
2816 return mapped_elems;
2818 for_each_sg(sglist, s, mapped_elems, i) {
2820 __unmap_single(domain->priv, s->dma_address,
2821 s->dma_length, dir);
2822 s->dma_address = s->dma_length = 0;
2831 * The exported map_sg function for dma_ops (handles scatter-gather
2834 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2835 int nelems, enum dma_data_direction dir,
2836 struct dma_attrs *attrs)
2838 unsigned long flags;
2839 struct protection_domain *domain;
2840 struct scatterlist *s;
2843 INC_STATS_COUNTER(cnt_unmap_sg);
2845 domain = get_domain(dev);
2849 spin_lock_irqsave(&domain->lock, flags);
2851 for_each_sg(sglist, s, nelems, i) {
2852 __unmap_single(domain->priv, s->dma_address,
2853 s->dma_length, dir);
2854 s->dma_address = s->dma_length = 0;
2857 domain_flush_complete(domain);
2859 spin_unlock_irqrestore(&domain->lock, flags);
2863 * The exported alloc_coherent function for dma_ops.
2865 static void *alloc_coherent(struct device *dev, size_t size,
2866 dma_addr_t *dma_addr, gfp_t flag,
2867 struct dma_attrs *attrs)
2869 unsigned long flags;
2871 struct protection_domain *domain;
2873 u64 dma_mask = dev->coherent_dma_mask;
2875 INC_STATS_COUNTER(cnt_alloc_coherent);
2877 domain = get_domain(dev);
2878 if (PTR_ERR(domain) == -EINVAL) {
2879 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2880 *dma_addr = __pa(virt_addr);
2882 } else if (IS_ERR(domain))
2885 dma_mask = dev->coherent_dma_mask;
2886 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2889 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2893 paddr = virt_to_phys(virt_addr);
2896 dma_mask = *dev->dma_mask;
2898 spin_lock_irqsave(&domain->lock, flags);
2900 *dma_addr = __map_single(dev, domain->priv, paddr,
2901 size, DMA_BIDIRECTIONAL, true, dma_mask);
2903 if (*dma_addr == DMA_ERROR_CODE) {
2904 spin_unlock_irqrestore(&domain->lock, flags);
2908 domain_flush_complete(domain);
2910 spin_unlock_irqrestore(&domain->lock, flags);
2916 free_pages((unsigned long)virt_addr, get_order(size));
2922 * The exported free_coherent function for dma_ops.
2924 static void free_coherent(struct device *dev, size_t size,
2925 void *virt_addr, dma_addr_t dma_addr,
2926 struct dma_attrs *attrs)
2928 unsigned long flags;
2929 struct protection_domain *domain;
2931 INC_STATS_COUNTER(cnt_free_coherent);
2933 domain = get_domain(dev);
2937 spin_lock_irqsave(&domain->lock, flags);
2939 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2941 domain_flush_complete(domain);
2943 spin_unlock_irqrestore(&domain->lock, flags);
2946 free_pages((unsigned long)virt_addr, get_order(size));
2950 * This function is called by the DMA layer to find out if we can handle a
2951 * particular device. It is part of the dma_ops.
2953 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2955 return check_device(dev);
2959 * The function for pre-allocating protection domains.
2961 * If the driver core informs the DMA layer if a driver grabs a device
2962 * we don't need to preallocate the protection domains anymore.
2963 * For now we have to.
2965 static void __init prealloc_protection_domains(void)
2967 struct iommu_dev_data *dev_data;
2968 struct dma_ops_domain *dma_dom;
2969 struct pci_dev *dev = NULL;
2972 for_each_pci_dev(dev) {
2974 /* Do we handle this device? */
2975 if (!check_device(&dev->dev))
2978 dev_data = get_dev_data(&dev->dev);
2979 if (!amd_iommu_force_isolation && dev_data->iommu_v2) {
2980 /* Make sure passthrough domain is allocated */
2981 alloc_passthrough_domain();
2982 dev_data->passthrough = true;
2983 attach_device(&dev->dev, pt_domain);
2984 pr_info("AMD-Vi: Using passthough domain for device %s\n",
2985 dev_name(&dev->dev));
2988 /* Is there already any domain for it? */
2989 if (domain_for_device(&dev->dev))
2992 devid = get_device_id(&dev->dev);
2994 dma_dom = dma_ops_domain_alloc();
2997 init_unity_mappings_for_device(dma_dom, devid);
2998 dma_dom->target_dev = devid;
3000 attach_device(&dev->dev, &dma_dom->domain);
3002 list_add_tail(&dma_dom->list, &iommu_pd_list);
3006 static struct dma_map_ops amd_iommu_dma_ops = {
3007 .alloc = alloc_coherent,
3008 .free = free_coherent,
3009 .map_page = map_page,
3010 .unmap_page = unmap_page,
3012 .unmap_sg = unmap_sg,
3013 .dma_supported = amd_iommu_dma_supported,
3016 static unsigned device_dma_ops_init(void)
3018 struct iommu_dev_data *dev_data;
3019 struct pci_dev *pdev = NULL;
3020 unsigned unhandled = 0;
3022 for_each_pci_dev(pdev) {
3023 if (!check_device(&pdev->dev)) {
3025 iommu_ignore_device(&pdev->dev);
3031 dev_data = get_dev_data(&pdev->dev);
3033 if (!dev_data->passthrough)
3034 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
3036 pdev->dev.archdata.dma_ops = &nommu_dma_ops;
3043 * The function which clues the AMD IOMMU driver into dma_ops.
3046 void __init amd_iommu_init_api(void)
3048 bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
3051 int __init amd_iommu_init_dma_ops(void)
3053 struct amd_iommu *iommu;
3057 * first allocate a default protection domain for every IOMMU we
3058 * found in the system. Devices not assigned to any other
3059 * protection domain will be assigned to the default one.
3061 for_each_iommu(iommu) {
3062 iommu->default_dom = dma_ops_domain_alloc();
3063 if (iommu->default_dom == NULL)
3065 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
3066 ret = iommu_init_unity_mappings(iommu);
3072 * Pre-allocate the protection domains for each device.
3074 prealloc_protection_domains();
3079 /* Make the driver finally visible to the drivers */
3080 unhandled = device_dma_ops_init();
3081 if (unhandled && max_pfn > MAX_DMA32_PFN) {
3082 /* There are unhandled devices - initialize swiotlb for them */
3086 amd_iommu_stats_init();
3088 if (amd_iommu_unmap_flush)
3089 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
3091 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
3097 for_each_iommu(iommu) {
3098 if (iommu->default_dom)
3099 dma_ops_domain_free(iommu->default_dom);
3105 /*****************************************************************************
3107 * The following functions belong to the exported interface of AMD IOMMU
3109 * This interface allows access to lower level functions of the IOMMU
3110 * like protection domain handling and assignement of devices to domains
3111 * which is not possible with the dma_ops interface.
3113 *****************************************************************************/
3115 static void cleanup_domain(struct protection_domain *domain)
3117 struct iommu_dev_data *dev_data, *next;
3118 unsigned long flags;
3120 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3122 list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
3123 __detach_device(dev_data);
3124 atomic_set(&dev_data->bind, 0);
3127 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3130 static void protection_domain_free(struct protection_domain *domain)
3135 del_domain_from_list(domain);
3138 domain_id_free(domain->id);
3143 static struct protection_domain *protection_domain_alloc(void)
3145 struct protection_domain *domain;
3147 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
3151 spin_lock_init(&domain->lock);
3152 mutex_init(&domain->api_lock);
3153 domain->id = domain_id_alloc();
3156 INIT_LIST_HEAD(&domain->dev_list);
3158 add_domain_to_list(domain);
3168 static int __init alloc_passthrough_domain(void)
3170 if (pt_domain != NULL)
3173 /* allocate passthrough domain */
3174 pt_domain = protection_domain_alloc();
3178 pt_domain->mode = PAGE_MODE_NONE;
3182 static int amd_iommu_domain_init(struct iommu_domain *dom)
3184 struct protection_domain *domain;
3186 domain = protection_domain_alloc();
3190 domain->mode = PAGE_MODE_3_LEVEL;
3191 domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
3192 if (!domain->pt_root)
3195 domain->iommu_domain = dom;
3199 dom->geometry.aperture_start = 0;
3200 dom->geometry.aperture_end = ~0ULL;
3201 dom->geometry.force_aperture = true;
3206 protection_domain_free(domain);
3211 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
3213 struct protection_domain *domain = dom->priv;
3218 if (domain->dev_cnt > 0)
3219 cleanup_domain(domain);
3221 BUG_ON(domain->dev_cnt != 0);
3223 if (domain->mode != PAGE_MODE_NONE)
3224 free_pagetable(domain);
3226 if (domain->flags & PD_IOMMUV2_MASK)
3227 free_gcr3_table(domain);
3229 protection_domain_free(domain);
3234 static void amd_iommu_detach_device(struct iommu_domain *dom,
3237 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3238 struct amd_iommu *iommu;
3241 if (!check_device(dev))
3244 devid = get_device_id(dev);
3246 if (dev_data->domain != NULL)
3249 iommu = amd_iommu_rlookup_table[devid];
3253 iommu_completion_wait(iommu);
3256 static int amd_iommu_attach_device(struct iommu_domain *dom,
3259 struct protection_domain *domain = dom->priv;
3260 struct iommu_dev_data *dev_data;
3261 struct amd_iommu *iommu;
3264 if (!check_device(dev))
3267 dev_data = dev->archdata.iommu;
3269 iommu = amd_iommu_rlookup_table[dev_data->devid];
3273 if (dev_data->domain)
3276 ret = attach_device(dev, domain);
3278 iommu_completion_wait(iommu);
3283 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3284 phys_addr_t paddr, size_t page_size, int iommu_prot)
3286 struct protection_domain *domain = dom->priv;
3290 if (domain->mode == PAGE_MODE_NONE)
3293 if (iommu_prot & IOMMU_READ)
3294 prot |= IOMMU_PROT_IR;
3295 if (iommu_prot & IOMMU_WRITE)
3296 prot |= IOMMU_PROT_IW;
3298 mutex_lock(&domain->api_lock);
3299 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3300 mutex_unlock(&domain->api_lock);
3305 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3308 struct protection_domain *domain = dom->priv;
3311 if (domain->mode == PAGE_MODE_NONE)
3314 mutex_lock(&domain->api_lock);
3315 unmap_size = iommu_unmap_page(domain, iova, page_size);
3316 mutex_unlock(&domain->api_lock);
3318 domain_flush_tlb_pde(domain);
3323 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3326 struct protection_domain *domain = dom->priv;
3327 unsigned long offset_mask;
3331 if (domain->mode == PAGE_MODE_NONE)
3334 pte = fetch_pte(domain, iova);
3336 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3339 if (PM_PTE_LEVEL(*pte) == 0)
3340 offset_mask = PAGE_SIZE - 1;
3342 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
3344 __pte = *pte & PM_ADDR_MASK;
3345 paddr = (__pte & ~offset_mask) | (iova & offset_mask);
3350 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
3354 case IOMMU_CAP_CACHE_COHERENCY:
3356 case IOMMU_CAP_INTR_REMAP:
3357 return irq_remapping_enabled;
3363 static struct iommu_ops amd_iommu_ops = {
3364 .domain_init = amd_iommu_domain_init,
3365 .domain_destroy = amd_iommu_domain_destroy,
3366 .attach_dev = amd_iommu_attach_device,
3367 .detach_dev = amd_iommu_detach_device,
3368 .map = amd_iommu_map,
3369 .unmap = amd_iommu_unmap,
3370 .iova_to_phys = amd_iommu_iova_to_phys,
3371 .domain_has_cap = amd_iommu_domain_has_cap,
3372 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3375 /*****************************************************************************
3377 * The next functions do a basic initialization of IOMMU for pass through
3380 * In passthrough mode the IOMMU is initialized and enabled but not used for
3381 * DMA-API translation.
3383 *****************************************************************************/
3385 int __init amd_iommu_init_passthrough(void)
3387 struct iommu_dev_data *dev_data;
3388 struct pci_dev *dev = NULL;
3389 struct amd_iommu *iommu;
3393 ret = alloc_passthrough_domain();
3397 for_each_pci_dev(dev) {
3398 if (!check_device(&dev->dev))
3401 dev_data = get_dev_data(&dev->dev);
3402 dev_data->passthrough = true;
3404 devid = get_device_id(&dev->dev);
3406 iommu = amd_iommu_rlookup_table[devid];
3410 attach_device(&dev->dev, pt_domain);
3413 amd_iommu_stats_init();
3415 pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
3420 /* IOMMUv2 specific functions */
3421 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3423 return atomic_notifier_chain_register(&ppr_notifier, nb);
3425 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3427 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3429 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3431 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3433 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3435 struct protection_domain *domain = dom->priv;
3436 unsigned long flags;
3438 spin_lock_irqsave(&domain->lock, flags);
3440 /* Update data structure */
3441 domain->mode = PAGE_MODE_NONE;
3442 domain->updated = true;
3444 /* Make changes visible to IOMMUs */
3445 update_domain(domain);
3447 /* Page-table is not visible to IOMMU anymore, so free it */
3448 free_pagetable(domain);
3450 spin_unlock_irqrestore(&domain->lock, flags);
3452 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3454 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3456 struct protection_domain *domain = dom->priv;
3457 unsigned long flags;
3460 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3463 /* Number of GCR3 table levels required */
3464 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3467 if (levels > amd_iommu_max_glx_val)
3470 spin_lock_irqsave(&domain->lock, flags);
3473 * Save us all sanity checks whether devices already in the
3474 * domain support IOMMUv2. Just force that the domain has no
3475 * devices attached when it is switched into IOMMUv2 mode.
3478 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3482 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3483 if (domain->gcr3_tbl == NULL)
3486 domain->glx = levels;
3487 domain->flags |= PD_IOMMUV2_MASK;
3488 domain->updated = true;
3490 update_domain(domain);
3495 spin_unlock_irqrestore(&domain->lock, flags);
3499 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3501 static int __flush_pasid(struct protection_domain *domain, int pasid,
3502 u64 address, bool size)
3504 struct iommu_dev_data *dev_data;
3505 struct iommu_cmd cmd;
3508 if (!(domain->flags & PD_IOMMUV2_MASK))
3511 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3514 * IOMMU TLB needs to be flushed before Device TLB to
3515 * prevent device TLB refill from IOMMU TLB
3517 for (i = 0; i < amd_iommus_present; ++i) {
3518 if (domain->dev_iommu[i] == 0)
3521 ret = iommu_queue_command(amd_iommus[i], &cmd);
3526 /* Wait until IOMMU TLB flushes are complete */
3527 domain_flush_complete(domain);
3529 /* Now flush device TLBs */
3530 list_for_each_entry(dev_data, &domain->dev_list, list) {
3531 struct amd_iommu *iommu;
3534 BUG_ON(!dev_data->ats.enabled);
3536 qdep = dev_data->ats.qdep;
3537 iommu = amd_iommu_rlookup_table[dev_data->devid];
3539 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3540 qdep, address, size);
3542 ret = iommu_queue_command(iommu, &cmd);
3547 /* Wait until all device TLBs are flushed */
3548 domain_flush_complete(domain);
3557 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3560 INC_STATS_COUNTER(invalidate_iotlb);
3562 return __flush_pasid(domain, pasid, address, false);
3565 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3568 struct protection_domain *domain = dom->priv;
3569 unsigned long flags;
3572 spin_lock_irqsave(&domain->lock, flags);
3573 ret = __amd_iommu_flush_page(domain, pasid, address);
3574 spin_unlock_irqrestore(&domain->lock, flags);
3578 EXPORT_SYMBOL(amd_iommu_flush_page);
3580 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3582 INC_STATS_COUNTER(invalidate_iotlb_all);
3584 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3588 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3590 struct protection_domain *domain = dom->priv;
3591 unsigned long flags;
3594 spin_lock_irqsave(&domain->lock, flags);
3595 ret = __amd_iommu_flush_tlb(domain, pasid);
3596 spin_unlock_irqrestore(&domain->lock, flags);
3600 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3602 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3609 index = (pasid >> (9 * level)) & 0x1ff;
3615 if (!(*pte & GCR3_VALID)) {
3619 root = (void *)get_zeroed_page(GFP_ATOMIC);
3623 *pte = __pa(root) | GCR3_VALID;
3626 root = __va(*pte & PAGE_MASK);
3634 static int __set_gcr3(struct protection_domain *domain, int pasid,
3639 if (domain->mode != PAGE_MODE_NONE)
3642 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3646 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3648 return __amd_iommu_flush_tlb(domain, pasid);
3651 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3655 if (domain->mode != PAGE_MODE_NONE)
3658 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3664 return __amd_iommu_flush_tlb(domain, pasid);
3667 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3670 struct protection_domain *domain = dom->priv;
3671 unsigned long flags;
3674 spin_lock_irqsave(&domain->lock, flags);
3675 ret = __set_gcr3(domain, pasid, cr3);
3676 spin_unlock_irqrestore(&domain->lock, flags);
3680 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3682 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3684 struct protection_domain *domain = dom->priv;
3685 unsigned long flags;
3688 spin_lock_irqsave(&domain->lock, flags);
3689 ret = __clear_gcr3(domain, pasid);
3690 spin_unlock_irqrestore(&domain->lock, flags);
3694 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3696 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3697 int status, int tag)
3699 struct iommu_dev_data *dev_data;
3700 struct amd_iommu *iommu;
3701 struct iommu_cmd cmd;
3703 INC_STATS_COUNTER(complete_ppr);
3705 dev_data = get_dev_data(&pdev->dev);
3706 iommu = amd_iommu_rlookup_table[dev_data->devid];
3708 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3709 tag, dev_data->pri_tlp);
3711 return iommu_queue_command(iommu, &cmd);
3713 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3715 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3717 struct protection_domain *domain;
3719 domain = get_domain(&pdev->dev);
3723 /* Only return IOMMUv2 domains */
3724 if (!(domain->flags & PD_IOMMUV2_MASK))
3727 return domain->iommu_domain;
3729 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3731 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3733 struct iommu_dev_data *dev_data;
3735 if (!amd_iommu_v2_supported())
3738 dev_data = get_dev_data(&pdev->dev);
3739 dev_data->errata |= (1 << erratum);
3741 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3743 int amd_iommu_device_info(struct pci_dev *pdev,
3744 struct amd_iommu_device_info *info)
3749 if (pdev == NULL || info == NULL)
3752 if (!amd_iommu_v2_supported())
3755 memset(info, 0, sizeof(*info));
3757 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3759 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3761 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3763 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3765 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3769 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3770 max_pasids = min(max_pasids, (1 << 20));
3772 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3773 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3775 features = pci_pasid_features(pdev);
3776 if (features & PCI_PASID_CAP_EXEC)
3777 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3778 if (features & PCI_PASID_CAP_PRIV)
3779 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3784 EXPORT_SYMBOL(amd_iommu_device_info);
3786 #ifdef CONFIG_IRQ_REMAP
3788 /*****************************************************************************
3790 * Interrupt Remapping Implementation
3792 *****************************************************************************/
3809 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3810 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3811 #define DTE_IRQ_TABLE_LEN (8ULL << 1)
3812 #define DTE_IRQ_REMAP_ENABLE 1ULL
3814 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3818 dte = amd_iommu_dev_table[devid].data[2];
3819 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3820 dte |= virt_to_phys(table->table);
3821 dte |= DTE_IRQ_REMAP_INTCTL;
3822 dte |= DTE_IRQ_TABLE_LEN;
3823 dte |= DTE_IRQ_REMAP_ENABLE;
3825 amd_iommu_dev_table[devid].data[2] = dte;
3828 #define IRTE_ALLOCATED (~1U)
3830 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3832 struct irq_remap_table *table = NULL;
3833 struct amd_iommu *iommu;
3834 unsigned long flags;
3837 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3839 iommu = amd_iommu_rlookup_table[devid];
3843 table = irq_lookup_table[devid];
3847 alias = amd_iommu_alias_table[devid];
3848 table = irq_lookup_table[alias];
3850 irq_lookup_table[devid] = table;
3851 set_dte_irq_entry(devid, table);
3852 iommu_flush_dte(iommu, devid);
3856 /* Nothing there yet, allocate new irq remapping table */
3857 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3862 /* Keep the first 32 indexes free for IOAPIC interrupts */
3863 table->min_index = 32;
3865 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3866 if (!table->table) {
3872 memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3877 for (i = 0; i < 32; ++i)
3878 table->table[i] = IRTE_ALLOCATED;
3881 irq_lookup_table[devid] = table;
3882 set_dte_irq_entry(devid, table);
3883 iommu_flush_dte(iommu, devid);
3884 if (devid != alias) {
3885 irq_lookup_table[alias] = table;
3886 set_dte_irq_entry(devid, table);
3887 iommu_flush_dte(iommu, alias);
3891 iommu_completion_wait(iommu);
3894 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3899 static int alloc_irq_index(struct irq_cfg *cfg, u16 devid, int count)
3901 struct irq_remap_table *table;
3902 unsigned long flags;
3905 table = get_irq_table(devid, false);
3909 spin_lock_irqsave(&table->lock, flags);
3911 /* Scan table for free entries */
3912 for (c = 0, index = table->min_index;
3913 index < MAX_IRQS_PER_TABLE;
3915 if (table->table[index] == 0)
3921 struct irq_2_iommu *irte_info;
3924 table->table[index - c + 1] = IRTE_ALLOCATED;
3928 irte_info = &cfg->irq_2_iommu;
3929 irte_info->sub_handle = devid;
3930 irte_info->irte_index = index;
3931 irte_info->iommu = (void *)cfg;
3940 spin_unlock_irqrestore(&table->lock, flags);
3945 static int get_irte(u16 devid, int index, union irte *irte)
3947 struct irq_remap_table *table;
3948 unsigned long flags;
3950 table = get_irq_table(devid, false);
3954 spin_lock_irqsave(&table->lock, flags);
3955 irte->val = table->table[index];
3956 spin_unlock_irqrestore(&table->lock, flags);
3961 static int modify_irte(u16 devid, int index, union irte irte)
3963 struct irq_remap_table *table;
3964 struct amd_iommu *iommu;
3965 unsigned long flags;
3967 iommu = amd_iommu_rlookup_table[devid];
3971 table = get_irq_table(devid, false);
3975 spin_lock_irqsave(&table->lock, flags);
3976 table->table[index] = irte.val;
3977 spin_unlock_irqrestore(&table->lock, flags);
3979 iommu_flush_irt(iommu, devid);
3980 iommu_completion_wait(iommu);
3985 static void free_irte(u16 devid, int index)
3987 struct irq_remap_table *table;
3988 struct amd_iommu *iommu;
3989 unsigned long flags;
3991 iommu = amd_iommu_rlookup_table[devid];
3995 table = get_irq_table(devid, false);
3999 spin_lock_irqsave(&table->lock, flags);
4000 table->table[index] = 0;
4001 spin_unlock_irqrestore(&table->lock, flags);
4003 iommu_flush_irt(iommu, devid);
4004 iommu_completion_wait(iommu);
4007 static int setup_ioapic_entry(int irq, struct IO_APIC_route_entry *entry,
4008 unsigned int destination, int vector,
4009 struct io_apic_irq_attr *attr)
4011 struct irq_remap_table *table;
4012 struct irq_2_iommu *irte_info;
4013 struct irq_cfg *cfg;
4020 cfg = irq_get_chip_data(irq);
4024 irte_info = &cfg->irq_2_iommu;
4025 ioapic_id = mpc_ioapic_id(attr->ioapic);
4026 devid = get_ioapic_devid(ioapic_id);
4031 table = get_irq_table(devid, true);
4035 index = attr->ioapic_pin;
4037 /* Setup IRQ remapping info */
4038 irte_info->sub_handle = devid;
4039 irte_info->irte_index = index;
4040 irte_info->iommu = (void *)cfg;
4042 /* Setup IRTE for IOMMU */
4044 irte.fields.vector = vector;
4045 irte.fields.int_type = apic->irq_delivery_mode;
4046 irte.fields.destination = destination;
4047 irte.fields.dm = apic->irq_dest_mode;
4048 irte.fields.valid = 1;
4050 ret = modify_irte(devid, index, irte);
4054 /* Setup IOAPIC entry */
4055 memset(entry, 0, sizeof(*entry));
4057 entry->vector = index;
4059 entry->trigger = attr->trigger;
4060 entry->polarity = attr->polarity;
4063 * Mask level triggered irqs.
4064 * Use IRQ_DELAYED_DISABLE for edge triggered irqs.
4072 static int set_affinity(struct irq_data *data, const struct cpumask *mask,
4075 struct irq_2_iommu *irte_info;
4076 unsigned int dest, irq;
4077 struct irq_cfg *cfg;
4081 if (!config_enabled(CONFIG_SMP))
4084 cfg = data->chip_data;
4086 irte_info = &cfg->irq_2_iommu;
4088 if (!cpumask_intersects(mask, cpu_online_mask))
4091 if (get_irte(irte_info->sub_handle, irte_info->irte_index, &irte))
4094 if (assign_irq_vector(irq, cfg, mask))
4097 err = apic->cpu_mask_to_apicid_and(cfg->domain, mask, &dest);
4099 if (assign_irq_vector(irq, cfg, data->affinity))
4100 pr_err("AMD-Vi: Failed to recover vector for irq %d\n", irq);
4104 irte.fields.vector = cfg->vector;
4105 irte.fields.destination = dest;
4107 modify_irte(irte_info->sub_handle, irte_info->irte_index, irte);
4109 if (cfg->move_in_progress)
4110 send_cleanup_vector(cfg);
4112 cpumask_copy(data->affinity, mask);
4117 static int free_irq(int irq)
4119 struct irq_2_iommu *irte_info;
4120 struct irq_cfg *cfg;
4122 cfg = irq_get_chip_data(irq);
4126 irte_info = &cfg->irq_2_iommu;
4128 free_irte(irte_info->sub_handle, irte_info->irte_index);
4133 static void compose_msi_msg(struct pci_dev *pdev,
4134 unsigned int irq, unsigned int dest,
4135 struct msi_msg *msg, u8 hpet_id)
4137 struct irq_2_iommu *irte_info;
4138 struct irq_cfg *cfg;
4141 cfg = irq_get_chip_data(irq);
4145 irte_info = &cfg->irq_2_iommu;
4148 irte.fields.vector = cfg->vector;
4149 irte.fields.int_type = apic->irq_delivery_mode;
4150 irte.fields.destination = dest;
4151 irte.fields.dm = apic->irq_dest_mode;
4152 irte.fields.valid = 1;
4154 modify_irte(irte_info->sub_handle, irte_info->irte_index, irte);
4156 msg->address_hi = MSI_ADDR_BASE_HI;
4157 msg->address_lo = MSI_ADDR_BASE_LO;
4158 msg->data = irte_info->irte_index;
4161 static int msi_alloc_irq(struct pci_dev *pdev, int irq, int nvec)
4163 struct irq_cfg *cfg;
4170 cfg = irq_get_chip_data(irq);
4174 devid = get_device_id(&pdev->dev);
4175 index = alloc_irq_index(cfg, devid, nvec);
4177 return index < 0 ? MAX_IRQS_PER_TABLE : index;
4180 static int msi_setup_irq(struct pci_dev *pdev, unsigned int irq,
4181 int index, int offset)
4183 struct irq_2_iommu *irte_info;
4184 struct irq_cfg *cfg;
4190 cfg = irq_get_chip_data(irq);
4194 if (index >= MAX_IRQS_PER_TABLE)
4197 devid = get_device_id(&pdev->dev);
4198 irte_info = &cfg->irq_2_iommu;
4200 irte_info->sub_handle = devid;
4201 irte_info->irte_index = index + offset;
4202 irte_info->iommu = (void *)cfg;
4207 static int setup_hpet_msi(unsigned int irq, unsigned int id)
4209 struct irq_2_iommu *irte_info;
4210 struct irq_cfg *cfg;
4213 cfg = irq_get_chip_data(irq);
4217 irte_info = &cfg->irq_2_iommu;
4218 devid = get_hpet_devid(id);
4222 index = alloc_irq_index(cfg, devid, 1);
4226 irte_info->sub_handle = devid;
4227 irte_info->irte_index = index;
4228 irte_info->iommu = (void *)cfg;
4233 struct irq_remap_ops amd_iommu_irq_ops = {
4234 .supported = amd_iommu_supported,
4235 .prepare = amd_iommu_prepare,
4236 .enable = amd_iommu_enable,
4237 .disable = amd_iommu_disable,
4238 .reenable = amd_iommu_reenable,
4239 .enable_faulting = amd_iommu_enable_faulting,
4240 .setup_ioapic_entry = setup_ioapic_entry,
4241 .set_affinity = set_affinity,
4242 .free_irq = free_irq,
4243 .compose_msi_msg = compose_msi_msg,
4244 .msi_alloc_irq = msi_alloc_irq,
4245 .msi_setup_irq = msi_setup_irq,
4246 .setup_hpet_msi = setup_hpet_msi,