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 = NULL, *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);
310 if (dma_pdev == NULL)
311 dma_pdev = pci_dev_get(pdev);
313 /* Account for quirked devices */
314 swap_pci_ref(&dma_pdev, pci_get_dma_source(dma_pdev));
317 * If it's a multifunction device that does not support our
318 * required ACS flags, add to the same group as function 0.
320 if (dma_pdev->multifunction &&
321 !pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS))
322 swap_pci_ref(&dma_pdev,
323 pci_get_slot(dma_pdev->bus,
324 PCI_DEVFN(PCI_SLOT(dma_pdev->devfn),
328 * Devices on the root bus go through the iommu. If that's not us,
329 * find the next upstream device and test ACS up to the root bus.
330 * Finding the next device may require skipping virtual buses.
332 while (!pci_is_root_bus(dma_pdev->bus)) {
333 struct pci_bus *bus = dma_pdev->bus;
336 if (!pci_is_root_bus(bus))
342 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
345 swap_pci_ref(&dma_pdev, pci_dev_get(bus->self));
349 group = iommu_group_get(&dma_pdev->dev);
350 pci_dev_put(dma_pdev);
352 group = iommu_group_alloc();
354 return PTR_ERR(group);
357 ret = iommu_group_add_device(group, dev);
359 iommu_group_put(group);
364 if (pci_iommuv2_capable(pdev)) {
365 struct amd_iommu *iommu;
367 iommu = amd_iommu_rlookup_table[dev_data->devid];
368 dev_data->iommu_v2 = iommu->is_iommu_v2;
371 dev->archdata.iommu = dev_data;
376 static void iommu_ignore_device(struct device *dev)
380 devid = get_device_id(dev);
381 alias = amd_iommu_alias_table[devid];
383 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
384 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
386 amd_iommu_rlookup_table[devid] = NULL;
387 amd_iommu_rlookup_table[alias] = NULL;
390 static void iommu_uninit_device(struct device *dev)
392 iommu_group_remove_device(dev);
395 * Nothing to do here - we keep dev_data around for unplugged devices
396 * and reuse it when the device is re-plugged - not doing so would
397 * introduce a ton of races.
401 void __init amd_iommu_uninit_devices(void)
403 struct iommu_dev_data *dev_data, *n;
404 struct pci_dev *pdev = NULL;
406 for_each_pci_dev(pdev) {
408 if (!check_device(&pdev->dev))
411 iommu_uninit_device(&pdev->dev);
414 /* Free all of our dev_data structures */
415 list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
416 free_dev_data(dev_data);
419 int __init amd_iommu_init_devices(void)
421 struct pci_dev *pdev = NULL;
424 for_each_pci_dev(pdev) {
426 if (!check_device(&pdev->dev))
429 ret = iommu_init_device(&pdev->dev);
430 if (ret == -ENOTSUPP)
431 iommu_ignore_device(&pdev->dev);
440 amd_iommu_uninit_devices();
444 #ifdef CONFIG_AMD_IOMMU_STATS
447 * Initialization code for statistics collection
450 DECLARE_STATS_COUNTER(compl_wait);
451 DECLARE_STATS_COUNTER(cnt_map_single);
452 DECLARE_STATS_COUNTER(cnt_unmap_single);
453 DECLARE_STATS_COUNTER(cnt_map_sg);
454 DECLARE_STATS_COUNTER(cnt_unmap_sg);
455 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
456 DECLARE_STATS_COUNTER(cnt_free_coherent);
457 DECLARE_STATS_COUNTER(cross_page);
458 DECLARE_STATS_COUNTER(domain_flush_single);
459 DECLARE_STATS_COUNTER(domain_flush_all);
460 DECLARE_STATS_COUNTER(alloced_io_mem);
461 DECLARE_STATS_COUNTER(total_map_requests);
462 DECLARE_STATS_COUNTER(complete_ppr);
463 DECLARE_STATS_COUNTER(invalidate_iotlb);
464 DECLARE_STATS_COUNTER(invalidate_iotlb_all);
465 DECLARE_STATS_COUNTER(pri_requests);
467 static struct dentry *stats_dir;
468 static struct dentry *de_fflush;
470 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
472 if (stats_dir == NULL)
475 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
479 static void amd_iommu_stats_init(void)
481 stats_dir = debugfs_create_dir("amd-iommu", NULL);
482 if (stats_dir == NULL)
485 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
486 &amd_iommu_unmap_flush);
488 amd_iommu_stats_add(&compl_wait);
489 amd_iommu_stats_add(&cnt_map_single);
490 amd_iommu_stats_add(&cnt_unmap_single);
491 amd_iommu_stats_add(&cnt_map_sg);
492 amd_iommu_stats_add(&cnt_unmap_sg);
493 amd_iommu_stats_add(&cnt_alloc_coherent);
494 amd_iommu_stats_add(&cnt_free_coherent);
495 amd_iommu_stats_add(&cross_page);
496 amd_iommu_stats_add(&domain_flush_single);
497 amd_iommu_stats_add(&domain_flush_all);
498 amd_iommu_stats_add(&alloced_io_mem);
499 amd_iommu_stats_add(&total_map_requests);
500 amd_iommu_stats_add(&complete_ppr);
501 amd_iommu_stats_add(&invalidate_iotlb);
502 amd_iommu_stats_add(&invalidate_iotlb_all);
503 amd_iommu_stats_add(&pri_requests);
508 /****************************************************************************
510 * Interrupt handling functions
512 ****************************************************************************/
514 static void dump_dte_entry(u16 devid)
518 for (i = 0; i < 4; ++i)
519 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
520 amd_iommu_dev_table[devid].data[i]);
523 static void dump_command(unsigned long phys_addr)
525 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
528 for (i = 0; i < 4; ++i)
529 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
532 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
534 int type, devid, domid, flags;
535 volatile u32 *event = __evt;
540 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
541 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
542 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
543 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
544 address = (u64)(((u64)event[3]) << 32) | event[2];
547 /* Did we hit the erratum? */
548 if (++count == LOOP_TIMEOUT) {
549 pr_err("AMD-Vi: No event written to event log\n");
556 printk(KERN_ERR "AMD-Vi: Event logged [");
559 case EVENT_TYPE_ILL_DEV:
560 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
561 "address=0x%016llx flags=0x%04x]\n",
562 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
564 dump_dte_entry(devid);
566 case EVENT_TYPE_IO_FAULT:
567 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
568 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
569 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
570 domid, address, flags);
572 case EVENT_TYPE_DEV_TAB_ERR:
573 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
574 "address=0x%016llx flags=0x%04x]\n",
575 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
578 case EVENT_TYPE_PAGE_TAB_ERR:
579 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
580 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
581 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
582 domid, address, flags);
584 case EVENT_TYPE_ILL_CMD:
585 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
586 dump_command(address);
588 case EVENT_TYPE_CMD_HARD_ERR:
589 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
590 "flags=0x%04x]\n", address, flags);
592 case EVENT_TYPE_IOTLB_INV_TO:
593 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
594 "address=0x%016llx]\n",
595 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
598 case EVENT_TYPE_INV_DEV_REQ:
599 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
600 "address=0x%016llx flags=0x%04x]\n",
601 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
605 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
608 memset(__evt, 0, 4 * sizeof(u32));
611 static void iommu_poll_events(struct amd_iommu *iommu)
616 spin_lock_irqsave(&iommu->lock, flags);
618 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
619 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
621 while (head != tail) {
622 iommu_print_event(iommu, iommu->evt_buf + head);
623 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
626 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
628 spin_unlock_irqrestore(&iommu->lock, flags);
631 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
633 struct amd_iommu_fault fault;
635 INC_STATS_COUNTER(pri_requests);
637 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
638 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
642 fault.address = raw[1];
643 fault.pasid = PPR_PASID(raw[0]);
644 fault.device_id = PPR_DEVID(raw[0]);
645 fault.tag = PPR_TAG(raw[0]);
646 fault.flags = PPR_FLAGS(raw[0]);
648 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
651 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
656 if (iommu->ppr_log == NULL)
659 /* enable ppr interrupts again */
660 writel(MMIO_STATUS_PPR_INT_MASK, iommu->mmio_base + MMIO_STATUS_OFFSET);
662 spin_lock_irqsave(&iommu->lock, flags);
664 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
665 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
667 while (head != tail) {
672 raw = (u64 *)(iommu->ppr_log + head);
675 * Hardware bug: Interrupt may arrive before the entry is
676 * written to memory. If this happens we need to wait for the
679 for (i = 0; i < LOOP_TIMEOUT; ++i) {
680 if (PPR_REQ_TYPE(raw[0]) != 0)
685 /* Avoid memcpy function-call overhead */
690 * To detect the hardware bug we need to clear the entry
693 raw[0] = raw[1] = 0UL;
695 /* Update head pointer of hardware ring-buffer */
696 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
697 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
700 * Release iommu->lock because ppr-handling might need to
703 spin_unlock_irqrestore(&iommu->lock, flags);
705 /* Handle PPR entry */
706 iommu_handle_ppr_entry(iommu, entry);
708 spin_lock_irqsave(&iommu->lock, flags);
710 /* Refresh ring-buffer information */
711 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
712 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
715 spin_unlock_irqrestore(&iommu->lock, flags);
718 irqreturn_t amd_iommu_int_thread(int irq, void *data)
720 struct amd_iommu *iommu;
722 for_each_iommu(iommu) {
723 iommu_poll_events(iommu);
724 iommu_poll_ppr_log(iommu);
730 irqreturn_t amd_iommu_int_handler(int irq, void *data)
732 return IRQ_WAKE_THREAD;
735 /****************************************************************************
737 * IOMMU command queuing functions
739 ****************************************************************************/
741 static int wait_on_sem(volatile u64 *sem)
745 while (*sem == 0 && i < LOOP_TIMEOUT) {
750 if (i == LOOP_TIMEOUT) {
751 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
758 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
759 struct iommu_cmd *cmd,
764 target = iommu->cmd_buf + tail;
765 tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
767 /* Copy command to buffer */
768 memcpy(target, cmd, sizeof(*cmd));
770 /* Tell the IOMMU about it */
771 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
774 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
776 WARN_ON(address & 0x7ULL);
778 memset(cmd, 0, sizeof(*cmd));
779 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
780 cmd->data[1] = upper_32_bits(__pa(address));
782 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
785 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
787 memset(cmd, 0, sizeof(*cmd));
788 cmd->data[0] = devid;
789 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
792 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
793 size_t size, u16 domid, int pde)
798 pages = iommu_num_pages(address, size, PAGE_SIZE);
803 * If we have to flush more than one page, flush all
804 * TLB entries for this domain
806 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
810 address &= PAGE_MASK;
812 memset(cmd, 0, sizeof(*cmd));
813 cmd->data[1] |= domid;
814 cmd->data[2] = lower_32_bits(address);
815 cmd->data[3] = upper_32_bits(address);
816 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
817 if (s) /* size bit - we flush more than one 4kb page */
818 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
819 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
820 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
823 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
824 u64 address, size_t size)
829 pages = iommu_num_pages(address, size, PAGE_SIZE);
834 * If we have to flush more than one page, flush all
835 * TLB entries for this domain
837 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
841 address &= PAGE_MASK;
843 memset(cmd, 0, sizeof(*cmd));
844 cmd->data[0] = devid;
845 cmd->data[0] |= (qdep & 0xff) << 24;
846 cmd->data[1] = devid;
847 cmd->data[2] = lower_32_bits(address);
848 cmd->data[3] = upper_32_bits(address);
849 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
851 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
854 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
855 u64 address, bool size)
857 memset(cmd, 0, sizeof(*cmd));
859 address &= ~(0xfffULL);
861 cmd->data[0] = pasid & PASID_MASK;
862 cmd->data[1] = domid;
863 cmd->data[2] = lower_32_bits(address);
864 cmd->data[3] = upper_32_bits(address);
865 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
866 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
868 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
869 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
872 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
873 int qdep, u64 address, bool size)
875 memset(cmd, 0, sizeof(*cmd));
877 address &= ~(0xfffULL);
879 cmd->data[0] = devid;
880 cmd->data[0] |= (pasid & 0xff) << 16;
881 cmd->data[0] |= (qdep & 0xff) << 24;
882 cmd->data[1] = devid;
883 cmd->data[1] |= ((pasid >> 8) & 0xfff) << 16;
884 cmd->data[2] = lower_32_bits(address);
885 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
886 cmd->data[3] = upper_32_bits(address);
888 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
889 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
892 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
893 int status, int tag, bool gn)
895 memset(cmd, 0, sizeof(*cmd));
897 cmd->data[0] = devid;
899 cmd->data[1] = pasid & PASID_MASK;
900 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
902 cmd->data[3] = tag & 0x1ff;
903 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
905 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
908 static void build_inv_all(struct iommu_cmd *cmd)
910 memset(cmd, 0, sizeof(*cmd));
911 CMD_SET_TYPE(cmd, CMD_INV_ALL);
914 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
916 memset(cmd, 0, sizeof(*cmd));
917 cmd->data[0] = devid;
918 CMD_SET_TYPE(cmd, CMD_INV_IRT);
922 * Writes the command to the IOMMUs command buffer and informs the
923 * hardware about the new command.
925 static int iommu_queue_command_sync(struct amd_iommu *iommu,
926 struct iommu_cmd *cmd,
929 u32 left, tail, head, next_tail;
932 WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
935 spin_lock_irqsave(&iommu->lock, flags);
937 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
938 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
939 next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
940 left = (head - next_tail) % iommu->cmd_buf_size;
943 struct iommu_cmd sync_cmd;
944 volatile u64 sem = 0;
947 build_completion_wait(&sync_cmd, (u64)&sem);
948 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
950 spin_unlock_irqrestore(&iommu->lock, flags);
952 if ((ret = wait_on_sem(&sem)) != 0)
958 copy_cmd_to_buffer(iommu, cmd, tail);
960 /* We need to sync now to make sure all commands are processed */
961 iommu->need_sync = sync;
963 spin_unlock_irqrestore(&iommu->lock, flags);
968 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
970 return iommu_queue_command_sync(iommu, cmd, true);
974 * This function queues a completion wait command into the command
977 static int iommu_completion_wait(struct amd_iommu *iommu)
979 struct iommu_cmd cmd;
980 volatile u64 sem = 0;
983 if (!iommu->need_sync)
986 build_completion_wait(&cmd, (u64)&sem);
988 ret = iommu_queue_command_sync(iommu, &cmd, false);
992 return wait_on_sem(&sem);
995 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
997 struct iommu_cmd cmd;
999 build_inv_dte(&cmd, devid);
1001 return iommu_queue_command(iommu, &cmd);
1004 static void iommu_flush_dte_all(struct amd_iommu *iommu)
1008 for (devid = 0; devid <= 0xffff; ++devid)
1009 iommu_flush_dte(iommu, devid);
1011 iommu_completion_wait(iommu);
1015 * This function uses heavy locking and may disable irqs for some time. But
1016 * this is no issue because it is only called during resume.
1018 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1022 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1023 struct iommu_cmd cmd;
1024 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1026 iommu_queue_command(iommu, &cmd);
1029 iommu_completion_wait(iommu);
1032 static void iommu_flush_all(struct amd_iommu *iommu)
1034 struct iommu_cmd cmd;
1036 build_inv_all(&cmd);
1038 iommu_queue_command(iommu, &cmd);
1039 iommu_completion_wait(iommu);
1042 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1044 struct iommu_cmd cmd;
1046 build_inv_irt(&cmd, devid);
1048 iommu_queue_command(iommu, &cmd);
1051 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1055 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1056 iommu_flush_irt(iommu, devid);
1058 iommu_completion_wait(iommu);
1061 void iommu_flush_all_caches(struct amd_iommu *iommu)
1063 if (iommu_feature(iommu, FEATURE_IA)) {
1064 iommu_flush_all(iommu);
1066 iommu_flush_dte_all(iommu);
1067 iommu_flush_irt_all(iommu);
1068 iommu_flush_tlb_all(iommu);
1073 * Command send function for flushing on-device TLB
1075 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1076 u64 address, size_t size)
1078 struct amd_iommu *iommu;
1079 struct iommu_cmd cmd;
1082 qdep = dev_data->ats.qdep;
1083 iommu = amd_iommu_rlookup_table[dev_data->devid];
1085 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1087 return iommu_queue_command(iommu, &cmd);
1091 * Command send function for invalidating a device table entry
1093 static int device_flush_dte(struct iommu_dev_data *dev_data)
1095 struct amd_iommu *iommu;
1098 iommu = amd_iommu_rlookup_table[dev_data->devid];
1100 ret = iommu_flush_dte(iommu, dev_data->devid);
1104 if (dev_data->ats.enabled)
1105 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1111 * TLB invalidation function which is called from the mapping functions.
1112 * It invalidates a single PTE if the range to flush is within a single
1113 * page. Otherwise it flushes the whole TLB of the IOMMU.
1115 static void __domain_flush_pages(struct protection_domain *domain,
1116 u64 address, size_t size, int pde)
1118 struct iommu_dev_data *dev_data;
1119 struct iommu_cmd cmd;
1122 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1124 for (i = 0; i < amd_iommus_present; ++i) {
1125 if (!domain->dev_iommu[i])
1129 * Devices of this domain are behind this IOMMU
1130 * We need a TLB flush
1132 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1135 list_for_each_entry(dev_data, &domain->dev_list, list) {
1137 if (!dev_data->ats.enabled)
1140 ret |= device_flush_iotlb(dev_data, address, size);
1146 static void domain_flush_pages(struct protection_domain *domain,
1147 u64 address, size_t size)
1149 __domain_flush_pages(domain, address, size, 0);
1152 /* Flush the whole IO/TLB for a given protection domain */
1153 static void domain_flush_tlb(struct protection_domain *domain)
1155 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1158 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1159 static void domain_flush_tlb_pde(struct protection_domain *domain)
1161 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1164 static void domain_flush_complete(struct protection_domain *domain)
1168 for (i = 0; i < amd_iommus_present; ++i) {
1169 if (!domain->dev_iommu[i])
1173 * Devices of this domain are behind this IOMMU
1174 * We need to wait for completion of all commands.
1176 iommu_completion_wait(amd_iommus[i]);
1182 * This function flushes the DTEs for all devices in domain
1184 static void domain_flush_devices(struct protection_domain *domain)
1186 struct iommu_dev_data *dev_data;
1188 list_for_each_entry(dev_data, &domain->dev_list, list)
1189 device_flush_dte(dev_data);
1192 /****************************************************************************
1194 * The functions below are used the create the page table mappings for
1195 * unity mapped regions.
1197 ****************************************************************************/
1200 * This function is used to add another level to an IO page table. Adding
1201 * another level increases the size of the address space by 9 bits to a size up
1204 static bool increase_address_space(struct protection_domain *domain,
1209 if (domain->mode == PAGE_MODE_6_LEVEL)
1210 /* address space already 64 bit large */
1213 pte = (void *)get_zeroed_page(gfp);
1217 *pte = PM_LEVEL_PDE(domain->mode,
1218 virt_to_phys(domain->pt_root));
1219 domain->pt_root = pte;
1221 domain->updated = true;
1226 static u64 *alloc_pte(struct protection_domain *domain,
1227 unsigned long address,
1228 unsigned long page_size,
1235 BUG_ON(!is_power_of_2(page_size));
1237 while (address > PM_LEVEL_SIZE(domain->mode))
1238 increase_address_space(domain, gfp);
1240 level = domain->mode - 1;
1241 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1242 address = PAGE_SIZE_ALIGN(address, page_size);
1243 end_lvl = PAGE_SIZE_LEVEL(page_size);
1245 while (level > end_lvl) {
1246 if (!IOMMU_PTE_PRESENT(*pte)) {
1247 page = (u64 *)get_zeroed_page(gfp);
1250 *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1253 /* No level skipping support yet */
1254 if (PM_PTE_LEVEL(*pte) != level)
1259 pte = IOMMU_PTE_PAGE(*pte);
1261 if (pte_page && level == end_lvl)
1264 pte = &pte[PM_LEVEL_INDEX(level, address)];
1271 * This function checks if there is a PTE for a given dma address. If
1272 * there is one, it returns the pointer to it.
1274 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
1279 if (address > PM_LEVEL_SIZE(domain->mode))
1282 level = domain->mode - 1;
1283 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1288 if (!IOMMU_PTE_PRESENT(*pte))
1292 if (PM_PTE_LEVEL(*pte) == 0x07) {
1293 unsigned long pte_mask, __pte;
1296 * If we have a series of large PTEs, make
1297 * sure to return a pointer to the first one.
1299 pte_mask = PTE_PAGE_SIZE(*pte);
1300 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1301 __pte = ((unsigned long)pte) & pte_mask;
1303 return (u64 *)__pte;
1306 /* No level skipping support yet */
1307 if (PM_PTE_LEVEL(*pte) != level)
1312 /* Walk to the next level */
1313 pte = IOMMU_PTE_PAGE(*pte);
1314 pte = &pte[PM_LEVEL_INDEX(level, address)];
1321 * Generic mapping functions. It maps a physical address into a DMA
1322 * address space. It allocates the page table pages if necessary.
1323 * In the future it can be extended to a generic mapping function
1324 * supporting all features of AMD IOMMU page tables like level skipping
1325 * and full 64 bit address spaces.
1327 static int iommu_map_page(struct protection_domain *dom,
1328 unsigned long bus_addr,
1329 unsigned long phys_addr,
1331 unsigned long page_size)
1336 if (!(prot & IOMMU_PROT_MASK))
1339 bus_addr = PAGE_ALIGN(bus_addr);
1340 phys_addr = PAGE_ALIGN(phys_addr);
1341 count = PAGE_SIZE_PTE_COUNT(page_size);
1342 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1344 for (i = 0; i < count; ++i)
1345 if (IOMMU_PTE_PRESENT(pte[i]))
1348 if (page_size > PAGE_SIZE) {
1349 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1350 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1352 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1354 if (prot & IOMMU_PROT_IR)
1355 __pte |= IOMMU_PTE_IR;
1356 if (prot & IOMMU_PROT_IW)
1357 __pte |= IOMMU_PTE_IW;
1359 for (i = 0; i < count; ++i)
1367 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1368 unsigned long bus_addr,
1369 unsigned long page_size)
1371 unsigned long long unmap_size, unmapped;
1374 BUG_ON(!is_power_of_2(page_size));
1378 while (unmapped < page_size) {
1380 pte = fetch_pte(dom, bus_addr);
1384 * No PTE for this address
1385 * move forward in 4kb steps
1387 unmap_size = PAGE_SIZE;
1388 } else if (PM_PTE_LEVEL(*pte) == 0) {
1389 /* 4kb PTE found for this address */
1390 unmap_size = PAGE_SIZE;
1395 /* Large PTE found which maps this address */
1396 unmap_size = PTE_PAGE_SIZE(*pte);
1397 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1398 for (i = 0; i < count; i++)
1402 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1403 unmapped += unmap_size;
1406 BUG_ON(!is_power_of_2(unmapped));
1412 * This function checks if a specific unity mapping entry is needed for
1413 * this specific IOMMU.
1415 static int iommu_for_unity_map(struct amd_iommu *iommu,
1416 struct unity_map_entry *entry)
1420 for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1421 bdf = amd_iommu_alias_table[i];
1422 if (amd_iommu_rlookup_table[bdf] == iommu)
1430 * This function actually applies the mapping to the page table of the
1433 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1434 struct unity_map_entry *e)
1439 for (addr = e->address_start; addr < e->address_end;
1440 addr += PAGE_SIZE) {
1441 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1446 * if unity mapping is in aperture range mark the page
1447 * as allocated in the aperture
1449 if (addr < dma_dom->aperture_size)
1450 __set_bit(addr >> PAGE_SHIFT,
1451 dma_dom->aperture[0]->bitmap);
1458 * Init the unity mappings for a specific IOMMU in the system
1460 * Basically iterates over all unity mapping entries and applies them to
1461 * the default domain DMA of that IOMMU if necessary.
1463 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1465 struct unity_map_entry *entry;
1468 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1469 if (!iommu_for_unity_map(iommu, entry))
1471 ret = dma_ops_unity_map(iommu->default_dom, entry);
1480 * Inits the unity mappings required for a specific device
1482 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1485 struct unity_map_entry *e;
1488 list_for_each_entry(e, &amd_iommu_unity_map, list) {
1489 if (!(devid >= e->devid_start && devid <= e->devid_end))
1491 ret = dma_ops_unity_map(dma_dom, e);
1499 /****************************************************************************
1501 * The next functions belong to the address allocator for the dma_ops
1502 * interface functions. They work like the allocators in the other IOMMU
1503 * drivers. Its basically a bitmap which marks the allocated pages in
1504 * the aperture. Maybe it could be enhanced in the future to a more
1505 * efficient allocator.
1507 ****************************************************************************/
1510 * The address allocator core functions.
1512 * called with domain->lock held
1516 * Used to reserve address ranges in the aperture (e.g. for exclusion
1519 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1520 unsigned long start_page,
1523 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1525 if (start_page + pages > last_page)
1526 pages = last_page - start_page;
1528 for (i = start_page; i < start_page + pages; ++i) {
1529 int index = i / APERTURE_RANGE_PAGES;
1530 int page = i % APERTURE_RANGE_PAGES;
1531 __set_bit(page, dom->aperture[index]->bitmap);
1536 * This function is used to add a new aperture range to an existing
1537 * aperture in case of dma_ops domain allocation or address allocation
1540 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1541 bool populate, gfp_t gfp)
1543 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1544 struct amd_iommu *iommu;
1545 unsigned long i, old_size;
1547 #ifdef CONFIG_IOMMU_STRESS
1551 if (index >= APERTURE_MAX_RANGES)
1554 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1555 if (!dma_dom->aperture[index])
1558 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1559 if (!dma_dom->aperture[index]->bitmap)
1562 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1565 unsigned long address = dma_dom->aperture_size;
1566 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1567 u64 *pte, *pte_page;
1569 for (i = 0; i < num_ptes; ++i) {
1570 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1575 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1577 address += APERTURE_RANGE_SIZE / 64;
1581 old_size = dma_dom->aperture_size;
1582 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1584 /* Reserve address range used for MSI messages */
1585 if (old_size < MSI_ADDR_BASE_LO &&
1586 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1587 unsigned long spage;
1590 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1591 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1593 dma_ops_reserve_addresses(dma_dom, spage, pages);
1596 /* Initialize the exclusion range if necessary */
1597 for_each_iommu(iommu) {
1598 if (iommu->exclusion_start &&
1599 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1600 && iommu->exclusion_start < dma_dom->aperture_size) {
1601 unsigned long startpage;
1602 int pages = iommu_num_pages(iommu->exclusion_start,
1603 iommu->exclusion_length,
1605 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1606 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1611 * Check for areas already mapped as present in the new aperture
1612 * range and mark those pages as reserved in the allocator. Such
1613 * mappings may already exist as a result of requested unity
1614 * mappings for devices.
1616 for (i = dma_dom->aperture[index]->offset;
1617 i < dma_dom->aperture_size;
1619 u64 *pte = fetch_pte(&dma_dom->domain, i);
1620 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1623 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1626 update_domain(&dma_dom->domain);
1631 update_domain(&dma_dom->domain);
1633 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1635 kfree(dma_dom->aperture[index]);
1636 dma_dom->aperture[index] = NULL;
1641 static unsigned long dma_ops_area_alloc(struct device *dev,
1642 struct dma_ops_domain *dom,
1644 unsigned long align_mask,
1646 unsigned long start)
1648 unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1649 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1650 int i = start >> APERTURE_RANGE_SHIFT;
1651 unsigned long boundary_size;
1652 unsigned long address = -1;
1653 unsigned long limit;
1655 next_bit >>= PAGE_SHIFT;
1657 boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1658 PAGE_SIZE) >> PAGE_SHIFT;
1660 for (;i < max_index; ++i) {
1661 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1663 if (dom->aperture[i]->offset >= dma_mask)
1666 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1667 dma_mask >> PAGE_SHIFT);
1669 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1670 limit, next_bit, pages, 0,
1671 boundary_size, align_mask);
1672 if (address != -1) {
1673 address = dom->aperture[i]->offset +
1674 (address << PAGE_SHIFT);
1675 dom->next_address = address + (pages << PAGE_SHIFT);
1685 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1686 struct dma_ops_domain *dom,
1688 unsigned long align_mask,
1691 unsigned long address;
1693 #ifdef CONFIG_IOMMU_STRESS
1694 dom->next_address = 0;
1695 dom->need_flush = true;
1698 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1699 dma_mask, dom->next_address);
1701 if (address == -1) {
1702 dom->next_address = 0;
1703 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1705 dom->need_flush = true;
1708 if (unlikely(address == -1))
1709 address = DMA_ERROR_CODE;
1711 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1717 * The address free function.
1719 * called with domain->lock held
1721 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1722 unsigned long address,
1725 unsigned i = address >> APERTURE_RANGE_SHIFT;
1726 struct aperture_range *range = dom->aperture[i];
1728 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1730 #ifdef CONFIG_IOMMU_STRESS
1735 if (address >= dom->next_address)
1736 dom->need_flush = true;
1738 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1740 bitmap_clear(range->bitmap, address, pages);
1744 /****************************************************************************
1746 * The next functions belong to the domain allocation. A domain is
1747 * allocated for every IOMMU as the default domain. If device isolation
1748 * is enabled, every device get its own domain. The most important thing
1749 * about domains is the page table mapping the DMA address space they
1752 ****************************************************************************/
1755 * This function adds a protection domain to the global protection domain list
1757 static void add_domain_to_list(struct protection_domain *domain)
1759 unsigned long flags;
1761 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1762 list_add(&domain->list, &amd_iommu_pd_list);
1763 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1767 * This function removes a protection domain to the global
1768 * protection domain list
1770 static void del_domain_from_list(struct protection_domain *domain)
1772 unsigned long flags;
1774 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1775 list_del(&domain->list);
1776 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1779 static u16 domain_id_alloc(void)
1781 unsigned long flags;
1784 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1785 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1787 if (id > 0 && id < MAX_DOMAIN_ID)
1788 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1791 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1796 static void domain_id_free(int id)
1798 unsigned long flags;
1800 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1801 if (id > 0 && id < MAX_DOMAIN_ID)
1802 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1803 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1806 static void free_pagetable(struct protection_domain *domain)
1811 p1 = domain->pt_root;
1816 for (i = 0; i < 512; ++i) {
1817 if (!IOMMU_PTE_PRESENT(p1[i]))
1820 p2 = IOMMU_PTE_PAGE(p1[i]);
1821 for (j = 0; j < 512; ++j) {
1822 if (!IOMMU_PTE_PRESENT(p2[j]))
1824 p3 = IOMMU_PTE_PAGE(p2[j]);
1825 free_page((unsigned long)p3);
1828 free_page((unsigned long)p2);
1831 free_page((unsigned long)p1);
1833 domain->pt_root = NULL;
1836 static void free_gcr3_tbl_level1(u64 *tbl)
1841 for (i = 0; i < 512; ++i) {
1842 if (!(tbl[i] & GCR3_VALID))
1845 ptr = __va(tbl[i] & PAGE_MASK);
1847 free_page((unsigned long)ptr);
1851 static void free_gcr3_tbl_level2(u64 *tbl)
1856 for (i = 0; i < 512; ++i) {
1857 if (!(tbl[i] & GCR3_VALID))
1860 ptr = __va(tbl[i] & PAGE_MASK);
1862 free_gcr3_tbl_level1(ptr);
1866 static void free_gcr3_table(struct protection_domain *domain)
1868 if (domain->glx == 2)
1869 free_gcr3_tbl_level2(domain->gcr3_tbl);
1870 else if (domain->glx == 1)
1871 free_gcr3_tbl_level1(domain->gcr3_tbl);
1872 else if (domain->glx != 0)
1875 free_page((unsigned long)domain->gcr3_tbl);
1879 * Free a domain, only used if something went wrong in the
1880 * allocation path and we need to free an already allocated page table
1882 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1889 del_domain_from_list(&dom->domain);
1891 free_pagetable(&dom->domain);
1893 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1894 if (!dom->aperture[i])
1896 free_page((unsigned long)dom->aperture[i]->bitmap);
1897 kfree(dom->aperture[i]);
1904 * Allocates a new protection domain usable for the dma_ops functions.
1905 * It also initializes the page table and the address allocator data
1906 * structures required for the dma_ops interface
1908 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1910 struct dma_ops_domain *dma_dom;
1912 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1916 spin_lock_init(&dma_dom->domain.lock);
1918 dma_dom->domain.id = domain_id_alloc();
1919 if (dma_dom->domain.id == 0)
1921 INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1922 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1923 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1924 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1925 dma_dom->domain.priv = dma_dom;
1926 if (!dma_dom->domain.pt_root)
1929 dma_dom->need_flush = false;
1930 dma_dom->target_dev = 0xffff;
1932 add_domain_to_list(&dma_dom->domain);
1934 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1938 * mark the first page as allocated so we never return 0 as
1939 * a valid dma-address. So we can use 0 as error value
1941 dma_dom->aperture[0]->bitmap[0] = 1;
1942 dma_dom->next_address = 0;
1948 dma_ops_domain_free(dma_dom);
1954 * little helper function to check whether a given protection domain is a
1957 static bool dma_ops_domain(struct protection_domain *domain)
1959 return domain->flags & PD_DMA_OPS_MASK;
1962 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1967 if (domain->mode != PAGE_MODE_NONE)
1968 pte_root = virt_to_phys(domain->pt_root);
1970 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1971 << DEV_ENTRY_MODE_SHIFT;
1972 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1974 flags = amd_iommu_dev_table[devid].data[1];
1977 flags |= DTE_FLAG_IOTLB;
1979 if (domain->flags & PD_IOMMUV2_MASK) {
1980 u64 gcr3 = __pa(domain->gcr3_tbl);
1981 u64 glx = domain->glx;
1984 pte_root |= DTE_FLAG_GV;
1985 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1987 /* First mask out possible old values for GCR3 table */
1988 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1991 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1994 /* Encode GCR3 table into DTE */
1995 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1998 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
2001 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
2005 flags &= ~(0xffffUL);
2006 flags |= domain->id;
2008 amd_iommu_dev_table[devid].data[1] = flags;
2009 amd_iommu_dev_table[devid].data[0] = pte_root;
2012 static void clear_dte_entry(u16 devid)
2014 /* remove entry from the device table seen by the hardware */
2015 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
2016 amd_iommu_dev_table[devid].data[1] = 0;
2018 amd_iommu_apply_erratum_63(devid);
2021 static void do_attach(struct iommu_dev_data *dev_data,
2022 struct protection_domain *domain)
2024 struct amd_iommu *iommu;
2027 iommu = amd_iommu_rlookup_table[dev_data->devid];
2028 ats = dev_data->ats.enabled;
2030 /* Update data structures */
2031 dev_data->domain = domain;
2032 list_add(&dev_data->list, &domain->dev_list);
2033 set_dte_entry(dev_data->devid, domain, ats);
2035 /* Do reference counting */
2036 domain->dev_iommu[iommu->index] += 1;
2037 domain->dev_cnt += 1;
2039 /* Flush the DTE entry */
2040 device_flush_dte(dev_data);
2043 static void do_detach(struct iommu_dev_data *dev_data)
2045 struct amd_iommu *iommu;
2047 iommu = amd_iommu_rlookup_table[dev_data->devid];
2049 /* decrease reference counters */
2050 dev_data->domain->dev_iommu[iommu->index] -= 1;
2051 dev_data->domain->dev_cnt -= 1;
2053 /* Update data structures */
2054 dev_data->domain = NULL;
2055 list_del(&dev_data->list);
2056 clear_dte_entry(dev_data->devid);
2058 /* Flush the DTE entry */
2059 device_flush_dte(dev_data);
2063 * If a device is not yet associated with a domain, this function does
2064 * assigns it visible for the hardware
2066 static int __attach_device(struct iommu_dev_data *dev_data,
2067 struct protection_domain *domain)
2072 spin_lock(&domain->lock);
2074 if (dev_data->alias_data != NULL) {
2075 struct iommu_dev_data *alias_data = dev_data->alias_data;
2077 /* Some sanity checks */
2079 if (alias_data->domain != NULL &&
2080 alias_data->domain != domain)
2083 if (dev_data->domain != NULL &&
2084 dev_data->domain != domain)
2087 /* Do real assignment */
2088 if (alias_data->domain == NULL)
2089 do_attach(alias_data, domain);
2091 atomic_inc(&alias_data->bind);
2094 if (dev_data->domain == NULL)
2095 do_attach(dev_data, domain);
2097 atomic_inc(&dev_data->bind);
2104 spin_unlock(&domain->lock);
2110 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2112 pci_disable_ats(pdev);
2113 pci_disable_pri(pdev);
2114 pci_disable_pasid(pdev);
2117 /* FIXME: Change generic reset-function to do the same */
2118 static int pri_reset_while_enabled(struct pci_dev *pdev)
2123 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2127 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2128 control |= PCI_PRI_CTRL_RESET;
2129 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2134 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2139 /* FIXME: Hardcode number of outstanding requests for now */
2141 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2143 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2145 /* Only allow access to user-accessible pages */
2146 ret = pci_enable_pasid(pdev, 0);
2150 /* First reset the PRI state of the device */
2151 ret = pci_reset_pri(pdev);
2156 ret = pci_enable_pri(pdev, reqs);
2161 ret = pri_reset_while_enabled(pdev);
2166 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2173 pci_disable_pri(pdev);
2174 pci_disable_pasid(pdev);
2179 /* FIXME: Move this to PCI code */
2180 #define PCI_PRI_TLP_OFF (1 << 15)
2182 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2187 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2191 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2193 return (status & PCI_PRI_TLP_OFF) ? true : false;
2197 * If a device is not yet associated with a domain, this function
2198 * assigns it visible for the hardware
2200 static int attach_device(struct device *dev,
2201 struct protection_domain *domain)
2203 struct pci_dev *pdev = to_pci_dev(dev);
2204 struct iommu_dev_data *dev_data;
2205 unsigned long flags;
2208 dev_data = get_dev_data(dev);
2210 if (domain->flags & PD_IOMMUV2_MASK) {
2211 if (!dev_data->iommu_v2 || !dev_data->passthrough)
2214 if (pdev_iommuv2_enable(pdev) != 0)
2217 dev_data->ats.enabled = true;
2218 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2219 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2220 } else if (amd_iommu_iotlb_sup &&
2221 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2222 dev_data->ats.enabled = true;
2223 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2226 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2227 ret = __attach_device(dev_data, domain);
2228 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2231 * We might boot into a crash-kernel here. The crashed kernel
2232 * left the caches in the IOMMU dirty. So we have to flush
2233 * here to evict all dirty stuff.
2235 domain_flush_tlb_pde(domain);
2241 * Removes a device from a protection domain (unlocked)
2243 static void __detach_device(struct iommu_dev_data *dev_data)
2245 struct protection_domain *domain;
2246 unsigned long flags;
2248 BUG_ON(!dev_data->domain);
2250 domain = dev_data->domain;
2252 spin_lock_irqsave(&domain->lock, flags);
2254 if (dev_data->alias_data != NULL) {
2255 struct iommu_dev_data *alias_data = dev_data->alias_data;
2257 if (atomic_dec_and_test(&alias_data->bind))
2258 do_detach(alias_data);
2261 if (atomic_dec_and_test(&dev_data->bind))
2262 do_detach(dev_data);
2264 spin_unlock_irqrestore(&domain->lock, flags);
2267 * If we run in passthrough mode the device must be assigned to the
2268 * passthrough domain if it is detached from any other domain.
2269 * Make sure we can deassign from the pt_domain itself.
2271 if (dev_data->passthrough &&
2272 (dev_data->domain == NULL && domain != pt_domain))
2273 __attach_device(dev_data, pt_domain);
2277 * Removes a device from a protection domain (with devtable_lock held)
2279 static void detach_device(struct device *dev)
2281 struct protection_domain *domain;
2282 struct iommu_dev_data *dev_data;
2283 unsigned long flags;
2285 dev_data = get_dev_data(dev);
2286 domain = dev_data->domain;
2288 /* lock device table */
2289 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2290 __detach_device(dev_data);
2291 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2293 if (domain->flags & PD_IOMMUV2_MASK)
2294 pdev_iommuv2_disable(to_pci_dev(dev));
2295 else if (dev_data->ats.enabled)
2296 pci_disable_ats(to_pci_dev(dev));
2298 dev_data->ats.enabled = false;
2302 * Find out the protection domain structure for a given PCI device. This
2303 * will give us the pointer to the page table root for example.
2305 static struct protection_domain *domain_for_device(struct device *dev)
2307 struct iommu_dev_data *dev_data;
2308 struct protection_domain *dom = NULL;
2309 unsigned long flags;
2311 dev_data = get_dev_data(dev);
2313 if (dev_data->domain)
2314 return dev_data->domain;
2316 if (dev_data->alias_data != NULL) {
2317 struct iommu_dev_data *alias_data = dev_data->alias_data;
2319 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
2320 if (alias_data->domain != NULL) {
2321 __attach_device(dev_data, alias_data->domain);
2322 dom = alias_data->domain;
2324 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2330 static int device_change_notifier(struct notifier_block *nb,
2331 unsigned long action, void *data)
2333 struct dma_ops_domain *dma_domain;
2334 struct protection_domain *domain;
2335 struct iommu_dev_data *dev_data;
2336 struct device *dev = data;
2337 struct amd_iommu *iommu;
2338 unsigned long flags;
2341 if (!check_device(dev))
2344 devid = get_device_id(dev);
2345 iommu = amd_iommu_rlookup_table[devid];
2346 dev_data = get_dev_data(dev);
2349 case BUS_NOTIFY_UNBOUND_DRIVER:
2351 domain = domain_for_device(dev);
2355 if (dev_data->passthrough)
2359 case BUS_NOTIFY_ADD_DEVICE:
2361 iommu_init_device(dev);
2364 * dev_data is still NULL and
2365 * got initialized in iommu_init_device
2367 dev_data = get_dev_data(dev);
2369 if (iommu_pass_through || dev_data->iommu_v2) {
2370 dev_data->passthrough = true;
2371 attach_device(dev, pt_domain);
2375 domain = domain_for_device(dev);
2377 /* allocate a protection domain if a device is added */
2378 dma_domain = find_protection_domain(devid);
2381 dma_domain = dma_ops_domain_alloc();
2384 dma_domain->target_dev = devid;
2386 spin_lock_irqsave(&iommu_pd_list_lock, flags);
2387 list_add_tail(&dma_domain->list, &iommu_pd_list);
2388 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
2390 dev_data = get_dev_data(dev);
2392 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2395 case BUS_NOTIFY_DEL_DEVICE:
2397 iommu_uninit_device(dev);
2403 iommu_completion_wait(iommu);
2409 static struct notifier_block device_nb = {
2410 .notifier_call = device_change_notifier,
2413 void amd_iommu_init_notifier(void)
2415 bus_register_notifier(&pci_bus_type, &device_nb);
2418 /*****************************************************************************
2420 * The next functions belong to the dma_ops mapping/unmapping code.
2422 *****************************************************************************/
2425 * In the dma_ops path we only have the struct device. This function
2426 * finds the corresponding IOMMU, the protection domain and the
2427 * requestor id for a given device.
2428 * If the device is not yet associated with a domain this is also done
2431 static struct protection_domain *get_domain(struct device *dev)
2433 struct protection_domain *domain;
2434 struct dma_ops_domain *dma_dom;
2435 u16 devid = get_device_id(dev);
2437 if (!check_device(dev))
2438 return ERR_PTR(-EINVAL);
2440 domain = domain_for_device(dev);
2441 if (domain != NULL && !dma_ops_domain(domain))
2442 return ERR_PTR(-EBUSY);
2447 /* Device not bound yet - bind it */
2448 dma_dom = find_protection_domain(devid);
2450 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
2451 attach_device(dev, &dma_dom->domain);
2452 DUMP_printk("Using protection domain %d for device %s\n",
2453 dma_dom->domain.id, dev_name(dev));
2455 return &dma_dom->domain;
2458 static void update_device_table(struct protection_domain *domain)
2460 struct iommu_dev_data *dev_data;
2462 list_for_each_entry(dev_data, &domain->dev_list, list)
2463 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2466 static void update_domain(struct protection_domain *domain)
2468 if (!domain->updated)
2471 update_device_table(domain);
2473 domain_flush_devices(domain);
2474 domain_flush_tlb_pde(domain);
2476 domain->updated = false;
2480 * This function fetches the PTE for a given address in the aperture
2482 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2483 unsigned long address)
2485 struct aperture_range *aperture;
2486 u64 *pte, *pte_page;
2488 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2492 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2494 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2496 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2498 pte += PM_LEVEL_INDEX(0, address);
2500 update_domain(&dom->domain);
2506 * This is the generic map function. It maps one 4kb page at paddr to
2507 * the given address in the DMA address space for the domain.
2509 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2510 unsigned long address,
2516 WARN_ON(address > dom->aperture_size);
2520 pte = dma_ops_get_pte(dom, address);
2522 return DMA_ERROR_CODE;
2524 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2526 if (direction == DMA_TO_DEVICE)
2527 __pte |= IOMMU_PTE_IR;
2528 else if (direction == DMA_FROM_DEVICE)
2529 __pte |= IOMMU_PTE_IW;
2530 else if (direction == DMA_BIDIRECTIONAL)
2531 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2537 return (dma_addr_t)address;
2541 * The generic unmapping function for on page in the DMA address space.
2543 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2544 unsigned long address)
2546 struct aperture_range *aperture;
2549 if (address >= dom->aperture_size)
2552 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2556 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2560 pte += PM_LEVEL_INDEX(0, address);
2568 * This function contains common code for mapping of a physically
2569 * contiguous memory region into DMA address space. It is used by all
2570 * mapping functions provided with this IOMMU driver.
2571 * Must be called with the domain lock held.
2573 static dma_addr_t __map_single(struct device *dev,
2574 struct dma_ops_domain *dma_dom,
2581 dma_addr_t offset = paddr & ~PAGE_MASK;
2582 dma_addr_t address, start, ret;
2584 unsigned long align_mask = 0;
2587 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2590 INC_STATS_COUNTER(total_map_requests);
2593 INC_STATS_COUNTER(cross_page);
2596 align_mask = (1UL << get_order(size)) - 1;
2599 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2601 if (unlikely(address == DMA_ERROR_CODE)) {
2603 * setting next_address here will let the address
2604 * allocator only scan the new allocated range in the
2605 * first run. This is a small optimization.
2607 dma_dom->next_address = dma_dom->aperture_size;
2609 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2613 * aperture was successfully enlarged by 128 MB, try
2620 for (i = 0; i < pages; ++i) {
2621 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2622 if (ret == DMA_ERROR_CODE)
2630 ADD_STATS_COUNTER(alloced_io_mem, size);
2632 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2633 domain_flush_tlb(&dma_dom->domain);
2634 dma_dom->need_flush = false;
2635 } else if (unlikely(amd_iommu_np_cache))
2636 domain_flush_pages(&dma_dom->domain, address, size);
2643 for (--i; i >= 0; --i) {
2645 dma_ops_domain_unmap(dma_dom, start);
2648 dma_ops_free_addresses(dma_dom, address, pages);
2650 return DMA_ERROR_CODE;
2654 * Does the reverse of the __map_single function. Must be called with
2655 * the domain lock held too
2657 static void __unmap_single(struct dma_ops_domain *dma_dom,
2658 dma_addr_t dma_addr,
2662 dma_addr_t flush_addr;
2663 dma_addr_t i, start;
2666 if ((dma_addr == DMA_ERROR_CODE) ||
2667 (dma_addr + size > dma_dom->aperture_size))
2670 flush_addr = dma_addr;
2671 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2672 dma_addr &= PAGE_MASK;
2675 for (i = 0; i < pages; ++i) {
2676 dma_ops_domain_unmap(dma_dom, start);
2680 SUB_STATS_COUNTER(alloced_io_mem, size);
2682 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2684 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2685 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2686 dma_dom->need_flush = false;
2691 * The exported map_single function for dma_ops.
2693 static dma_addr_t map_page(struct device *dev, struct page *page,
2694 unsigned long offset, size_t size,
2695 enum dma_data_direction dir,
2696 struct dma_attrs *attrs)
2698 unsigned long flags;
2699 struct protection_domain *domain;
2702 phys_addr_t paddr = page_to_phys(page) + offset;
2704 INC_STATS_COUNTER(cnt_map_single);
2706 domain = get_domain(dev);
2707 if (PTR_ERR(domain) == -EINVAL)
2708 return (dma_addr_t)paddr;
2709 else if (IS_ERR(domain))
2710 return DMA_ERROR_CODE;
2712 dma_mask = *dev->dma_mask;
2714 spin_lock_irqsave(&domain->lock, flags);
2716 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2718 if (addr == DMA_ERROR_CODE)
2721 domain_flush_complete(domain);
2724 spin_unlock_irqrestore(&domain->lock, flags);
2730 * The exported unmap_single function for dma_ops.
2732 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2733 enum dma_data_direction dir, struct dma_attrs *attrs)
2735 unsigned long flags;
2736 struct protection_domain *domain;
2738 INC_STATS_COUNTER(cnt_unmap_single);
2740 domain = get_domain(dev);
2744 spin_lock_irqsave(&domain->lock, flags);
2746 __unmap_single(domain->priv, dma_addr, size, dir);
2748 domain_flush_complete(domain);
2750 spin_unlock_irqrestore(&domain->lock, flags);
2754 * This is a special map_sg function which is used if we should map a
2755 * device which is not handled by an AMD IOMMU in the system.
2757 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2758 int nelems, int dir)
2760 struct scatterlist *s;
2763 for_each_sg(sglist, s, nelems, i) {
2764 s->dma_address = (dma_addr_t)sg_phys(s);
2765 s->dma_length = s->length;
2772 * The exported map_sg function for dma_ops (handles scatter-gather
2775 static int map_sg(struct device *dev, struct scatterlist *sglist,
2776 int nelems, enum dma_data_direction dir,
2777 struct dma_attrs *attrs)
2779 unsigned long flags;
2780 struct protection_domain *domain;
2782 struct scatterlist *s;
2784 int mapped_elems = 0;
2787 INC_STATS_COUNTER(cnt_map_sg);
2789 domain = get_domain(dev);
2790 if (PTR_ERR(domain) == -EINVAL)
2791 return map_sg_no_iommu(dev, sglist, nelems, dir);
2792 else if (IS_ERR(domain))
2795 dma_mask = *dev->dma_mask;
2797 spin_lock_irqsave(&domain->lock, flags);
2799 for_each_sg(sglist, s, nelems, i) {
2802 s->dma_address = __map_single(dev, domain->priv,
2803 paddr, s->length, dir, false,
2806 if (s->dma_address) {
2807 s->dma_length = s->length;
2813 domain_flush_complete(domain);
2816 spin_unlock_irqrestore(&domain->lock, flags);
2818 return mapped_elems;
2820 for_each_sg(sglist, s, mapped_elems, i) {
2822 __unmap_single(domain->priv, s->dma_address,
2823 s->dma_length, dir);
2824 s->dma_address = s->dma_length = 0;
2833 * The exported map_sg function for dma_ops (handles scatter-gather
2836 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2837 int nelems, enum dma_data_direction dir,
2838 struct dma_attrs *attrs)
2840 unsigned long flags;
2841 struct protection_domain *domain;
2842 struct scatterlist *s;
2845 INC_STATS_COUNTER(cnt_unmap_sg);
2847 domain = get_domain(dev);
2851 spin_lock_irqsave(&domain->lock, flags);
2853 for_each_sg(sglist, s, nelems, i) {
2854 __unmap_single(domain->priv, s->dma_address,
2855 s->dma_length, dir);
2856 s->dma_address = s->dma_length = 0;
2859 domain_flush_complete(domain);
2861 spin_unlock_irqrestore(&domain->lock, flags);
2865 * The exported alloc_coherent function for dma_ops.
2867 static void *alloc_coherent(struct device *dev, size_t size,
2868 dma_addr_t *dma_addr, gfp_t flag,
2869 struct dma_attrs *attrs)
2871 unsigned long flags;
2873 struct protection_domain *domain;
2875 u64 dma_mask = dev->coherent_dma_mask;
2877 INC_STATS_COUNTER(cnt_alloc_coherent);
2879 domain = get_domain(dev);
2880 if (PTR_ERR(domain) == -EINVAL) {
2881 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2882 *dma_addr = __pa(virt_addr);
2884 } else if (IS_ERR(domain))
2887 dma_mask = dev->coherent_dma_mask;
2888 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2891 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2895 paddr = virt_to_phys(virt_addr);
2898 dma_mask = *dev->dma_mask;
2900 spin_lock_irqsave(&domain->lock, flags);
2902 *dma_addr = __map_single(dev, domain->priv, paddr,
2903 size, DMA_BIDIRECTIONAL, true, dma_mask);
2905 if (*dma_addr == DMA_ERROR_CODE) {
2906 spin_unlock_irqrestore(&domain->lock, flags);
2910 domain_flush_complete(domain);
2912 spin_unlock_irqrestore(&domain->lock, flags);
2918 free_pages((unsigned long)virt_addr, get_order(size));
2924 * The exported free_coherent function for dma_ops.
2926 static void free_coherent(struct device *dev, size_t size,
2927 void *virt_addr, dma_addr_t dma_addr,
2928 struct dma_attrs *attrs)
2930 unsigned long flags;
2931 struct protection_domain *domain;
2933 INC_STATS_COUNTER(cnt_free_coherent);
2935 domain = get_domain(dev);
2939 spin_lock_irqsave(&domain->lock, flags);
2941 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2943 domain_flush_complete(domain);
2945 spin_unlock_irqrestore(&domain->lock, flags);
2948 free_pages((unsigned long)virt_addr, get_order(size));
2952 * This function is called by the DMA layer to find out if we can handle a
2953 * particular device. It is part of the dma_ops.
2955 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2957 return check_device(dev);
2961 * The function for pre-allocating protection domains.
2963 * If the driver core informs the DMA layer if a driver grabs a device
2964 * we don't need to preallocate the protection domains anymore.
2965 * For now we have to.
2967 static void __init prealloc_protection_domains(void)
2969 struct iommu_dev_data *dev_data;
2970 struct dma_ops_domain *dma_dom;
2971 struct pci_dev *dev = NULL;
2974 for_each_pci_dev(dev) {
2976 /* Do we handle this device? */
2977 if (!check_device(&dev->dev))
2980 dev_data = get_dev_data(&dev->dev);
2981 if (!amd_iommu_force_isolation && dev_data->iommu_v2) {
2982 /* Make sure passthrough domain is allocated */
2983 alloc_passthrough_domain();
2984 dev_data->passthrough = true;
2985 attach_device(&dev->dev, pt_domain);
2986 pr_info("AMD-Vi: Using passthrough domain for device %s\n",
2987 dev_name(&dev->dev));
2990 /* Is there already any domain for it? */
2991 if (domain_for_device(&dev->dev))
2994 devid = get_device_id(&dev->dev);
2996 dma_dom = dma_ops_domain_alloc();
2999 init_unity_mappings_for_device(dma_dom, devid);
3000 dma_dom->target_dev = devid;
3002 attach_device(&dev->dev, &dma_dom->domain);
3004 list_add_tail(&dma_dom->list, &iommu_pd_list);
3008 static struct dma_map_ops amd_iommu_dma_ops = {
3009 .alloc = alloc_coherent,
3010 .free = free_coherent,
3011 .map_page = map_page,
3012 .unmap_page = unmap_page,
3014 .unmap_sg = unmap_sg,
3015 .dma_supported = amd_iommu_dma_supported,
3018 static unsigned device_dma_ops_init(void)
3020 struct iommu_dev_data *dev_data;
3021 struct pci_dev *pdev = NULL;
3022 unsigned unhandled = 0;
3024 for_each_pci_dev(pdev) {
3025 if (!check_device(&pdev->dev)) {
3027 iommu_ignore_device(&pdev->dev);
3033 dev_data = get_dev_data(&pdev->dev);
3035 if (!dev_data->passthrough)
3036 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
3038 pdev->dev.archdata.dma_ops = &nommu_dma_ops;
3045 * The function which clues the AMD IOMMU driver into dma_ops.
3048 void __init amd_iommu_init_api(void)
3050 bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
3053 int __init amd_iommu_init_dma_ops(void)
3055 struct amd_iommu *iommu;
3059 * first allocate a default protection domain for every IOMMU we
3060 * found in the system. Devices not assigned to any other
3061 * protection domain will be assigned to the default one.
3063 for_each_iommu(iommu) {
3064 iommu->default_dom = dma_ops_domain_alloc();
3065 if (iommu->default_dom == NULL)
3067 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
3068 ret = iommu_init_unity_mappings(iommu);
3074 * Pre-allocate the protection domains for each device.
3076 prealloc_protection_domains();
3081 /* Make the driver finally visible to the drivers */
3082 unhandled = device_dma_ops_init();
3083 if (unhandled && max_pfn > MAX_DMA32_PFN) {
3084 /* There are unhandled devices - initialize swiotlb for them */
3088 amd_iommu_stats_init();
3090 if (amd_iommu_unmap_flush)
3091 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
3093 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
3099 for_each_iommu(iommu) {
3100 if (iommu->default_dom)
3101 dma_ops_domain_free(iommu->default_dom);
3107 /*****************************************************************************
3109 * The following functions belong to the exported interface of AMD IOMMU
3111 * This interface allows access to lower level functions of the IOMMU
3112 * like protection domain handling and assignement of devices to domains
3113 * which is not possible with the dma_ops interface.
3115 *****************************************************************************/
3117 static void cleanup_domain(struct protection_domain *domain)
3119 struct iommu_dev_data *dev_data, *next;
3120 unsigned long flags;
3122 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3124 list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
3125 __detach_device(dev_data);
3126 atomic_set(&dev_data->bind, 0);
3129 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3132 static void protection_domain_free(struct protection_domain *domain)
3137 del_domain_from_list(domain);
3140 domain_id_free(domain->id);
3145 static struct protection_domain *protection_domain_alloc(void)
3147 struct protection_domain *domain;
3149 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
3153 spin_lock_init(&domain->lock);
3154 mutex_init(&domain->api_lock);
3155 domain->id = domain_id_alloc();
3158 INIT_LIST_HEAD(&domain->dev_list);
3160 add_domain_to_list(domain);
3170 static int __init alloc_passthrough_domain(void)
3172 if (pt_domain != NULL)
3175 /* allocate passthrough domain */
3176 pt_domain = protection_domain_alloc();
3180 pt_domain->mode = PAGE_MODE_NONE;
3184 static int amd_iommu_domain_init(struct iommu_domain *dom)
3186 struct protection_domain *domain;
3188 domain = protection_domain_alloc();
3192 domain->mode = PAGE_MODE_3_LEVEL;
3193 domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
3194 if (!domain->pt_root)
3197 domain->iommu_domain = dom;
3201 dom->geometry.aperture_start = 0;
3202 dom->geometry.aperture_end = ~0ULL;
3203 dom->geometry.force_aperture = true;
3208 protection_domain_free(domain);
3213 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
3215 struct protection_domain *domain = dom->priv;
3220 if (domain->dev_cnt > 0)
3221 cleanup_domain(domain);
3223 BUG_ON(domain->dev_cnt != 0);
3225 if (domain->mode != PAGE_MODE_NONE)
3226 free_pagetable(domain);
3228 if (domain->flags & PD_IOMMUV2_MASK)
3229 free_gcr3_table(domain);
3231 protection_domain_free(domain);
3236 static void amd_iommu_detach_device(struct iommu_domain *dom,
3239 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3240 struct amd_iommu *iommu;
3243 if (!check_device(dev))
3246 devid = get_device_id(dev);
3248 if (dev_data->domain != NULL)
3251 iommu = amd_iommu_rlookup_table[devid];
3255 iommu_completion_wait(iommu);
3258 static int amd_iommu_attach_device(struct iommu_domain *dom,
3261 struct protection_domain *domain = dom->priv;
3262 struct iommu_dev_data *dev_data;
3263 struct amd_iommu *iommu;
3266 if (!check_device(dev))
3269 dev_data = dev->archdata.iommu;
3271 iommu = amd_iommu_rlookup_table[dev_data->devid];
3275 if (dev_data->domain)
3278 ret = attach_device(dev, domain);
3280 iommu_completion_wait(iommu);
3285 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3286 phys_addr_t paddr, size_t page_size, int iommu_prot)
3288 struct protection_domain *domain = dom->priv;
3292 if (domain->mode == PAGE_MODE_NONE)
3295 if (iommu_prot & IOMMU_READ)
3296 prot |= IOMMU_PROT_IR;
3297 if (iommu_prot & IOMMU_WRITE)
3298 prot |= IOMMU_PROT_IW;
3300 mutex_lock(&domain->api_lock);
3301 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3302 mutex_unlock(&domain->api_lock);
3307 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3310 struct protection_domain *domain = dom->priv;
3313 if (domain->mode == PAGE_MODE_NONE)
3316 mutex_lock(&domain->api_lock);
3317 unmap_size = iommu_unmap_page(domain, iova, page_size);
3318 mutex_unlock(&domain->api_lock);
3320 domain_flush_tlb_pde(domain);
3325 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3328 struct protection_domain *domain = dom->priv;
3329 unsigned long offset_mask;
3333 if (domain->mode == PAGE_MODE_NONE)
3336 pte = fetch_pte(domain, iova);
3338 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3341 if (PM_PTE_LEVEL(*pte) == 0)
3342 offset_mask = PAGE_SIZE - 1;
3344 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
3346 __pte = *pte & PM_ADDR_MASK;
3347 paddr = (__pte & ~offset_mask) | (iova & offset_mask);
3352 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
3356 case IOMMU_CAP_CACHE_COHERENCY:
3358 case IOMMU_CAP_INTR_REMAP:
3359 return irq_remapping_enabled;
3365 static struct iommu_ops amd_iommu_ops = {
3366 .domain_init = amd_iommu_domain_init,
3367 .domain_destroy = amd_iommu_domain_destroy,
3368 .attach_dev = amd_iommu_attach_device,
3369 .detach_dev = amd_iommu_detach_device,
3370 .map = amd_iommu_map,
3371 .unmap = amd_iommu_unmap,
3372 .iova_to_phys = amd_iommu_iova_to_phys,
3373 .domain_has_cap = amd_iommu_domain_has_cap,
3374 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3377 /*****************************************************************************
3379 * The next functions do a basic initialization of IOMMU for pass through
3382 * In passthrough mode the IOMMU is initialized and enabled but not used for
3383 * DMA-API translation.
3385 *****************************************************************************/
3387 int __init amd_iommu_init_passthrough(void)
3389 struct iommu_dev_data *dev_data;
3390 struct pci_dev *dev = NULL;
3391 struct amd_iommu *iommu;
3395 ret = alloc_passthrough_domain();
3399 for_each_pci_dev(dev) {
3400 if (!check_device(&dev->dev))
3403 dev_data = get_dev_data(&dev->dev);
3404 dev_data->passthrough = true;
3406 devid = get_device_id(&dev->dev);
3408 iommu = amd_iommu_rlookup_table[devid];
3412 attach_device(&dev->dev, pt_domain);
3415 amd_iommu_stats_init();
3417 pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
3422 /* IOMMUv2 specific functions */
3423 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3425 return atomic_notifier_chain_register(&ppr_notifier, nb);
3427 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3429 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3431 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3433 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3435 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3437 struct protection_domain *domain = dom->priv;
3438 unsigned long flags;
3440 spin_lock_irqsave(&domain->lock, flags);
3442 /* Update data structure */
3443 domain->mode = PAGE_MODE_NONE;
3444 domain->updated = true;
3446 /* Make changes visible to IOMMUs */
3447 update_domain(domain);
3449 /* Page-table is not visible to IOMMU anymore, so free it */
3450 free_pagetable(domain);
3452 spin_unlock_irqrestore(&domain->lock, flags);
3454 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3456 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3458 struct protection_domain *domain = dom->priv;
3459 unsigned long flags;
3462 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3465 /* Number of GCR3 table levels required */
3466 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3469 if (levels > amd_iommu_max_glx_val)
3472 spin_lock_irqsave(&domain->lock, flags);
3475 * Save us all sanity checks whether devices already in the
3476 * domain support IOMMUv2. Just force that the domain has no
3477 * devices attached when it is switched into IOMMUv2 mode.
3480 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3484 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3485 if (domain->gcr3_tbl == NULL)
3488 domain->glx = levels;
3489 domain->flags |= PD_IOMMUV2_MASK;
3490 domain->updated = true;
3492 update_domain(domain);
3497 spin_unlock_irqrestore(&domain->lock, flags);
3501 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3503 static int __flush_pasid(struct protection_domain *domain, int pasid,
3504 u64 address, bool size)
3506 struct iommu_dev_data *dev_data;
3507 struct iommu_cmd cmd;
3510 if (!(domain->flags & PD_IOMMUV2_MASK))
3513 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3516 * IOMMU TLB needs to be flushed before Device TLB to
3517 * prevent device TLB refill from IOMMU TLB
3519 for (i = 0; i < amd_iommus_present; ++i) {
3520 if (domain->dev_iommu[i] == 0)
3523 ret = iommu_queue_command(amd_iommus[i], &cmd);
3528 /* Wait until IOMMU TLB flushes are complete */
3529 domain_flush_complete(domain);
3531 /* Now flush device TLBs */
3532 list_for_each_entry(dev_data, &domain->dev_list, list) {
3533 struct amd_iommu *iommu;
3536 BUG_ON(!dev_data->ats.enabled);
3538 qdep = dev_data->ats.qdep;
3539 iommu = amd_iommu_rlookup_table[dev_data->devid];
3541 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3542 qdep, address, size);
3544 ret = iommu_queue_command(iommu, &cmd);
3549 /* Wait until all device TLBs are flushed */
3550 domain_flush_complete(domain);
3559 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3562 INC_STATS_COUNTER(invalidate_iotlb);
3564 return __flush_pasid(domain, pasid, address, false);
3567 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3570 struct protection_domain *domain = dom->priv;
3571 unsigned long flags;
3574 spin_lock_irqsave(&domain->lock, flags);
3575 ret = __amd_iommu_flush_page(domain, pasid, address);
3576 spin_unlock_irqrestore(&domain->lock, flags);
3580 EXPORT_SYMBOL(amd_iommu_flush_page);
3582 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3584 INC_STATS_COUNTER(invalidate_iotlb_all);
3586 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3590 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3592 struct protection_domain *domain = dom->priv;
3593 unsigned long flags;
3596 spin_lock_irqsave(&domain->lock, flags);
3597 ret = __amd_iommu_flush_tlb(domain, pasid);
3598 spin_unlock_irqrestore(&domain->lock, flags);
3602 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3604 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3611 index = (pasid >> (9 * level)) & 0x1ff;
3617 if (!(*pte & GCR3_VALID)) {
3621 root = (void *)get_zeroed_page(GFP_ATOMIC);
3625 *pte = __pa(root) | GCR3_VALID;
3628 root = __va(*pte & PAGE_MASK);
3636 static int __set_gcr3(struct protection_domain *domain, int pasid,
3641 if (domain->mode != PAGE_MODE_NONE)
3644 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3648 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3650 return __amd_iommu_flush_tlb(domain, pasid);
3653 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3657 if (domain->mode != PAGE_MODE_NONE)
3660 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3666 return __amd_iommu_flush_tlb(domain, pasid);
3669 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3672 struct protection_domain *domain = dom->priv;
3673 unsigned long flags;
3676 spin_lock_irqsave(&domain->lock, flags);
3677 ret = __set_gcr3(domain, pasid, cr3);
3678 spin_unlock_irqrestore(&domain->lock, flags);
3682 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3684 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3686 struct protection_domain *domain = dom->priv;
3687 unsigned long flags;
3690 spin_lock_irqsave(&domain->lock, flags);
3691 ret = __clear_gcr3(domain, pasid);
3692 spin_unlock_irqrestore(&domain->lock, flags);
3696 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3698 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3699 int status, int tag)
3701 struct iommu_dev_data *dev_data;
3702 struct amd_iommu *iommu;
3703 struct iommu_cmd cmd;
3705 INC_STATS_COUNTER(complete_ppr);
3707 dev_data = get_dev_data(&pdev->dev);
3708 iommu = amd_iommu_rlookup_table[dev_data->devid];
3710 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3711 tag, dev_data->pri_tlp);
3713 return iommu_queue_command(iommu, &cmd);
3715 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3717 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3719 struct protection_domain *domain;
3721 domain = get_domain(&pdev->dev);
3725 /* Only return IOMMUv2 domains */
3726 if (!(domain->flags & PD_IOMMUV2_MASK))
3729 return domain->iommu_domain;
3731 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3733 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3735 struct iommu_dev_data *dev_data;
3737 if (!amd_iommu_v2_supported())
3740 dev_data = get_dev_data(&pdev->dev);
3741 dev_data->errata |= (1 << erratum);
3743 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3745 int amd_iommu_device_info(struct pci_dev *pdev,
3746 struct amd_iommu_device_info *info)
3751 if (pdev == NULL || info == NULL)
3754 if (!amd_iommu_v2_supported())
3757 memset(info, 0, sizeof(*info));
3759 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3761 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3763 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3765 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3767 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3771 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3772 max_pasids = min(max_pasids, (1 << 20));
3774 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3775 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3777 features = pci_pasid_features(pdev);
3778 if (features & PCI_PASID_CAP_EXEC)
3779 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3780 if (features & PCI_PASID_CAP_PRIV)
3781 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3786 EXPORT_SYMBOL(amd_iommu_device_info);
3788 #ifdef CONFIG_IRQ_REMAP
3790 /*****************************************************************************
3792 * Interrupt Remapping Implementation
3794 *****************************************************************************/
3811 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3812 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3813 #define DTE_IRQ_TABLE_LEN (8ULL << 1)
3814 #define DTE_IRQ_REMAP_ENABLE 1ULL
3816 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3820 dte = amd_iommu_dev_table[devid].data[2];
3821 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3822 dte |= virt_to_phys(table->table);
3823 dte |= DTE_IRQ_REMAP_INTCTL;
3824 dte |= DTE_IRQ_TABLE_LEN;
3825 dte |= DTE_IRQ_REMAP_ENABLE;
3827 amd_iommu_dev_table[devid].data[2] = dte;
3830 #define IRTE_ALLOCATED (~1U)
3832 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3834 struct irq_remap_table *table = NULL;
3835 struct amd_iommu *iommu;
3836 unsigned long flags;
3839 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3841 iommu = amd_iommu_rlookup_table[devid];
3845 table = irq_lookup_table[devid];
3849 alias = amd_iommu_alias_table[devid];
3850 table = irq_lookup_table[alias];
3852 irq_lookup_table[devid] = table;
3853 set_dte_irq_entry(devid, table);
3854 iommu_flush_dte(iommu, devid);
3858 /* Nothing there yet, allocate new irq remapping table */
3859 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3864 /* Keep the first 32 indexes free for IOAPIC interrupts */
3865 table->min_index = 32;
3867 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3868 if (!table->table) {
3874 memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3879 for (i = 0; i < 32; ++i)
3880 table->table[i] = IRTE_ALLOCATED;
3883 irq_lookup_table[devid] = table;
3884 set_dte_irq_entry(devid, table);
3885 iommu_flush_dte(iommu, devid);
3886 if (devid != alias) {
3887 irq_lookup_table[alias] = table;
3888 set_dte_irq_entry(devid, table);
3889 iommu_flush_dte(iommu, alias);
3893 iommu_completion_wait(iommu);
3896 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3901 static int alloc_irq_index(struct irq_cfg *cfg, u16 devid, int count)
3903 struct irq_remap_table *table;
3904 unsigned long flags;
3907 table = get_irq_table(devid, false);
3911 spin_lock_irqsave(&table->lock, flags);
3913 /* Scan table for free entries */
3914 for (c = 0, index = table->min_index;
3915 index < MAX_IRQS_PER_TABLE;
3917 if (table->table[index] == 0)
3923 struct irq_2_iommu *irte_info;
3926 table->table[index - c + 1] = IRTE_ALLOCATED;
3930 irte_info = &cfg->irq_2_iommu;
3931 irte_info->sub_handle = devid;
3932 irte_info->irte_index = index;
3933 irte_info->iommu = (void *)cfg;
3942 spin_unlock_irqrestore(&table->lock, flags);
3947 static int get_irte(u16 devid, int index, union irte *irte)
3949 struct irq_remap_table *table;
3950 unsigned long flags;
3952 table = get_irq_table(devid, false);
3956 spin_lock_irqsave(&table->lock, flags);
3957 irte->val = table->table[index];
3958 spin_unlock_irqrestore(&table->lock, flags);
3963 static int modify_irte(u16 devid, int index, union irte irte)
3965 struct irq_remap_table *table;
3966 struct amd_iommu *iommu;
3967 unsigned long flags;
3969 iommu = amd_iommu_rlookup_table[devid];
3973 table = get_irq_table(devid, false);
3977 spin_lock_irqsave(&table->lock, flags);
3978 table->table[index] = irte.val;
3979 spin_unlock_irqrestore(&table->lock, flags);
3981 iommu_flush_irt(iommu, devid);
3982 iommu_completion_wait(iommu);
3987 static void free_irte(u16 devid, int index)
3989 struct irq_remap_table *table;
3990 struct amd_iommu *iommu;
3991 unsigned long flags;
3993 iommu = amd_iommu_rlookup_table[devid];
3997 table = get_irq_table(devid, false);
4001 spin_lock_irqsave(&table->lock, flags);
4002 table->table[index] = 0;
4003 spin_unlock_irqrestore(&table->lock, flags);
4005 iommu_flush_irt(iommu, devid);
4006 iommu_completion_wait(iommu);
4009 static int setup_ioapic_entry(int irq, struct IO_APIC_route_entry *entry,
4010 unsigned int destination, int vector,
4011 struct io_apic_irq_attr *attr)
4013 struct irq_remap_table *table;
4014 struct irq_2_iommu *irte_info;
4015 struct irq_cfg *cfg;
4022 cfg = irq_get_chip_data(irq);
4026 irte_info = &cfg->irq_2_iommu;
4027 ioapic_id = mpc_ioapic_id(attr->ioapic);
4028 devid = get_ioapic_devid(ioapic_id);
4033 table = get_irq_table(devid, true);
4037 index = attr->ioapic_pin;
4039 /* Setup IRQ remapping info */
4040 irte_info->sub_handle = devid;
4041 irte_info->irte_index = index;
4042 irte_info->iommu = (void *)cfg;
4044 /* Setup IRTE for IOMMU */
4046 irte.fields.vector = vector;
4047 irte.fields.int_type = apic->irq_delivery_mode;
4048 irte.fields.destination = destination;
4049 irte.fields.dm = apic->irq_dest_mode;
4050 irte.fields.valid = 1;
4052 ret = modify_irte(devid, index, irte);
4056 /* Setup IOAPIC entry */
4057 memset(entry, 0, sizeof(*entry));
4059 entry->vector = index;
4061 entry->trigger = attr->trigger;
4062 entry->polarity = attr->polarity;
4065 * Mask level triggered irqs.
4073 static int set_affinity(struct irq_data *data, const struct cpumask *mask,
4076 struct irq_2_iommu *irte_info;
4077 unsigned int dest, irq;
4078 struct irq_cfg *cfg;
4082 if (!config_enabled(CONFIG_SMP))
4085 cfg = data->chip_data;
4087 irte_info = &cfg->irq_2_iommu;
4089 if (!cpumask_intersects(mask, cpu_online_mask))
4092 if (get_irte(irte_info->sub_handle, irte_info->irte_index, &irte))
4095 if (assign_irq_vector(irq, cfg, mask))
4098 err = apic->cpu_mask_to_apicid_and(cfg->domain, mask, &dest);
4100 if (assign_irq_vector(irq, cfg, data->affinity))
4101 pr_err("AMD-Vi: Failed to recover vector for irq %d\n", irq);
4105 irte.fields.vector = cfg->vector;
4106 irte.fields.destination = dest;
4108 modify_irte(irte_info->sub_handle, irte_info->irte_index, irte);
4110 if (cfg->move_in_progress)
4111 send_cleanup_vector(cfg);
4113 cpumask_copy(data->affinity, mask);
4118 static int free_irq(int irq)
4120 struct irq_2_iommu *irte_info;
4121 struct irq_cfg *cfg;
4123 cfg = irq_get_chip_data(irq);
4127 irte_info = &cfg->irq_2_iommu;
4129 free_irte(irte_info->sub_handle, irte_info->irte_index);
4134 static void compose_msi_msg(struct pci_dev *pdev,
4135 unsigned int irq, unsigned int dest,
4136 struct msi_msg *msg, u8 hpet_id)
4138 struct irq_2_iommu *irte_info;
4139 struct irq_cfg *cfg;
4142 cfg = irq_get_chip_data(irq);
4146 irte_info = &cfg->irq_2_iommu;
4149 irte.fields.vector = cfg->vector;
4150 irte.fields.int_type = apic->irq_delivery_mode;
4151 irte.fields.destination = dest;
4152 irte.fields.dm = apic->irq_dest_mode;
4153 irte.fields.valid = 1;
4155 modify_irte(irte_info->sub_handle, irte_info->irte_index, irte);
4157 msg->address_hi = MSI_ADDR_BASE_HI;
4158 msg->address_lo = MSI_ADDR_BASE_LO;
4159 msg->data = irte_info->irte_index;
4162 static int msi_alloc_irq(struct pci_dev *pdev, int irq, int nvec)
4164 struct irq_cfg *cfg;
4171 cfg = irq_get_chip_data(irq);
4175 devid = get_device_id(&pdev->dev);
4176 index = alloc_irq_index(cfg, devid, nvec);
4178 return index < 0 ? MAX_IRQS_PER_TABLE : index;
4181 static int msi_setup_irq(struct pci_dev *pdev, unsigned int irq,
4182 int index, int offset)
4184 struct irq_2_iommu *irte_info;
4185 struct irq_cfg *cfg;
4191 cfg = irq_get_chip_data(irq);
4195 if (index >= MAX_IRQS_PER_TABLE)
4198 devid = get_device_id(&pdev->dev);
4199 irte_info = &cfg->irq_2_iommu;
4201 irte_info->sub_handle = devid;
4202 irte_info->irte_index = index + offset;
4203 irte_info->iommu = (void *)cfg;
4208 static int setup_hpet_msi(unsigned int irq, unsigned int id)
4210 struct irq_2_iommu *irte_info;
4211 struct irq_cfg *cfg;
4214 cfg = irq_get_chip_data(irq);
4218 irte_info = &cfg->irq_2_iommu;
4219 devid = get_hpet_devid(id);
4223 index = alloc_irq_index(cfg, devid, 1);
4227 irte_info->sub_handle = devid;
4228 irte_info->irte_index = index;
4229 irte_info->iommu = (void *)cfg;
4234 struct irq_remap_ops amd_iommu_irq_ops = {
4235 .supported = amd_iommu_supported,
4236 .prepare = amd_iommu_prepare,
4237 .enable = amd_iommu_enable,
4238 .disable = amd_iommu_disable,
4239 .reenable = amd_iommu_reenable,
4240 .enable_faulting = amd_iommu_enable_faulting,
4241 .setup_ioapic_entry = setup_ioapic_entry,
4242 .set_affinity = set_affinity,
4243 .free_irq = free_irq,
4244 .compose_msi_msg = compose_msi_msg,
4245 .msi_alloc_irq = msi_alloc_irq,
4246 .msi_setup_irq = msi_setup_irq,
4247 .setup_hpet_msi = setup_hpet_msi,