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"
51 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
53 #define LOOP_TIMEOUT 100000
56 * This bitmap is used to advertise the page sizes our hardware support
57 * to the IOMMU core, which will then use this information to split
58 * physically contiguous memory regions it is mapping into page sizes
61 * 512GB Pages are not supported due to a hardware bug
63 #define AMD_IOMMU_PGSIZES ((~0xFFFUL) & ~(2ULL << 38))
65 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
67 /* A list of preallocated protection domains */
68 static LIST_HEAD(iommu_pd_list);
69 static DEFINE_SPINLOCK(iommu_pd_list_lock);
71 /* List of all available dev_data structures */
72 static LIST_HEAD(dev_data_list);
73 static DEFINE_SPINLOCK(dev_data_list_lock);
75 LIST_HEAD(ioapic_map);
79 * Domain for untranslated devices - only allocated
80 * if iommu=pt passed on kernel cmd line.
82 static struct protection_domain *pt_domain;
84 static struct iommu_ops amd_iommu_ops;
86 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
87 int amd_iommu_max_glx_val = -1;
89 static struct dma_map_ops amd_iommu_dma_ops;
92 * general struct to manage commands send to an IOMMU
98 struct kmem_cache *amd_iommu_irq_cache;
100 static void update_domain(struct protection_domain *domain);
101 static int __init alloc_passthrough_domain(void);
103 /****************************************************************************
107 ****************************************************************************/
109 static struct iommu_dev_data *alloc_dev_data(u16 devid)
111 struct iommu_dev_data *dev_data;
114 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
118 dev_data->devid = devid;
119 atomic_set(&dev_data->bind, 0);
121 spin_lock_irqsave(&dev_data_list_lock, flags);
122 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
123 spin_unlock_irqrestore(&dev_data_list_lock, flags);
128 static void free_dev_data(struct iommu_dev_data *dev_data)
132 spin_lock_irqsave(&dev_data_list_lock, flags);
133 list_del(&dev_data->dev_data_list);
134 spin_unlock_irqrestore(&dev_data_list_lock, flags);
137 iommu_group_put(dev_data->group);
142 static struct iommu_dev_data *search_dev_data(u16 devid)
144 struct iommu_dev_data *dev_data;
147 spin_lock_irqsave(&dev_data_list_lock, flags);
148 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
149 if (dev_data->devid == devid)
156 spin_unlock_irqrestore(&dev_data_list_lock, flags);
161 static struct iommu_dev_data *find_dev_data(u16 devid)
163 struct iommu_dev_data *dev_data;
165 dev_data = search_dev_data(devid);
167 if (dev_data == NULL)
168 dev_data = alloc_dev_data(devid);
173 static inline u16 get_device_id(struct device *dev)
175 struct pci_dev *pdev = to_pci_dev(dev);
177 return PCI_DEVID(pdev->bus->number, pdev->devfn);
180 static struct iommu_dev_data *get_dev_data(struct device *dev)
182 return dev->archdata.iommu;
185 static bool pci_iommuv2_capable(struct pci_dev *pdev)
187 static const int caps[] = {
190 PCI_EXT_CAP_ID_PASID,
194 for (i = 0; i < 3; ++i) {
195 pos = pci_find_ext_capability(pdev, caps[i]);
203 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
205 struct iommu_dev_data *dev_data;
207 dev_data = get_dev_data(&pdev->dev);
209 return dev_data->errata & (1 << erratum) ? true : false;
213 * In this function the list of preallocated protection domains is traversed to
214 * find the domain for a specific device
216 static struct dma_ops_domain *find_protection_domain(u16 devid)
218 struct dma_ops_domain *entry, *ret = NULL;
220 u16 alias = amd_iommu_alias_table[devid];
222 if (list_empty(&iommu_pd_list))
225 spin_lock_irqsave(&iommu_pd_list_lock, flags);
227 list_for_each_entry(entry, &iommu_pd_list, list) {
228 if (entry->target_dev == devid ||
229 entry->target_dev == alias) {
235 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
241 * This function checks if the driver got a valid device from the caller to
242 * avoid dereferencing invalid pointers.
244 static bool check_device(struct device *dev)
248 if (!dev || !dev->dma_mask)
251 /* No device or no PCI device */
252 if (dev->bus != &pci_bus_type)
255 devid = get_device_id(dev);
257 /* Out of our scope? */
258 if (devid > amd_iommu_last_bdf)
261 if (amd_iommu_rlookup_table[devid] == NULL)
267 static struct pci_bus *find_hosted_bus(struct pci_bus *bus)
270 if (!pci_is_root_bus(bus))
273 return ERR_PTR(-ENODEV);
279 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
281 static struct pci_dev *get_isolation_root(struct pci_dev *pdev)
283 struct pci_dev *dma_pdev = pdev;
285 /* Account for quirked devices */
286 swap_pci_ref(&dma_pdev, pci_get_dma_source(dma_pdev));
289 * If it's a multifunction device that does not support our
290 * required ACS flags, add to the same group as function 0.
292 if (dma_pdev->multifunction &&
293 !pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS))
294 swap_pci_ref(&dma_pdev,
295 pci_get_slot(dma_pdev->bus,
296 PCI_DEVFN(PCI_SLOT(dma_pdev->devfn),
300 * Devices on the root bus go through the iommu. If that's not us,
301 * find the next upstream device and test ACS up to the root bus.
302 * Finding the next device may require skipping virtual buses.
304 while (!pci_is_root_bus(dma_pdev->bus)) {
305 struct pci_bus *bus = find_hosted_bus(dma_pdev->bus);
309 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
312 swap_pci_ref(&dma_pdev, pci_dev_get(bus->self));
318 static int use_pdev_iommu_group(struct pci_dev *pdev, struct device *dev)
320 struct iommu_group *group = iommu_group_get(&pdev->dev);
324 group = iommu_group_alloc();
326 return PTR_ERR(group);
328 WARN_ON(&pdev->dev != dev);
331 ret = iommu_group_add_device(group, dev);
332 iommu_group_put(group);
336 static int use_dev_data_iommu_group(struct iommu_dev_data *dev_data,
339 if (!dev_data->group) {
340 struct iommu_group *group = iommu_group_alloc();
342 return PTR_ERR(group);
344 dev_data->group = group;
347 return iommu_group_add_device(dev_data->group, dev);
350 static int init_iommu_group(struct device *dev)
352 struct iommu_dev_data *dev_data;
353 struct iommu_group *group;
354 struct pci_dev *dma_pdev;
357 group = iommu_group_get(dev);
359 iommu_group_put(group);
363 dev_data = find_dev_data(get_device_id(dev));
367 if (dev_data->alias_data) {
371 if (dev_data->alias_data->group)
375 * If the alias device exists, it's effectively just a first
376 * level quirk for finding the DMA source.
378 alias = amd_iommu_alias_table[dev_data->devid];
379 dma_pdev = pci_get_bus_and_slot(alias >> 8, alias & 0xff);
381 dma_pdev = get_isolation_root(dma_pdev);
386 * If the alias is virtual, try to find a parent device
387 * and test whether the IOMMU group is actualy rooted above
388 * the alias. Be careful to also test the parent device if
389 * we think the alias is the root of the group.
391 bus = pci_find_bus(0, alias >> 8);
395 bus = find_hosted_bus(bus);
396 if (IS_ERR(bus) || !bus->self)
399 dma_pdev = get_isolation_root(pci_dev_get(bus->self));
400 if (dma_pdev != bus->self || (dma_pdev->multifunction &&
401 !pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS)))
404 pci_dev_put(dma_pdev);
408 dma_pdev = get_isolation_root(pci_dev_get(to_pci_dev(dev)));
410 ret = use_pdev_iommu_group(dma_pdev, dev);
411 pci_dev_put(dma_pdev);
414 return use_dev_data_iommu_group(dev_data->alias_data, dev);
417 static int iommu_init_device(struct device *dev)
419 struct pci_dev *pdev = to_pci_dev(dev);
420 struct iommu_dev_data *dev_data;
424 if (dev->archdata.iommu)
427 dev_data = find_dev_data(get_device_id(dev));
431 alias = amd_iommu_alias_table[dev_data->devid];
432 if (alias != dev_data->devid) {
433 struct iommu_dev_data *alias_data;
435 alias_data = find_dev_data(alias);
436 if (alias_data == NULL) {
437 pr_err("AMD-Vi: Warning: Unhandled device %s\n",
439 free_dev_data(dev_data);
442 dev_data->alias_data = alias_data;
445 ret = init_iommu_group(dev);
449 if (pci_iommuv2_capable(pdev)) {
450 struct amd_iommu *iommu;
452 iommu = amd_iommu_rlookup_table[dev_data->devid];
453 dev_data->iommu_v2 = iommu->is_iommu_v2;
456 dev->archdata.iommu = dev_data;
461 static void iommu_ignore_device(struct device *dev)
465 devid = get_device_id(dev);
466 alias = amd_iommu_alias_table[devid];
468 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
469 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
471 amd_iommu_rlookup_table[devid] = NULL;
472 amd_iommu_rlookup_table[alias] = NULL;
475 static void iommu_uninit_device(struct device *dev)
477 iommu_group_remove_device(dev);
480 * Nothing to do here - we keep dev_data around for unplugged devices
481 * and reuse it when the device is re-plugged - not doing so would
482 * introduce a ton of races.
486 void __init amd_iommu_uninit_devices(void)
488 struct iommu_dev_data *dev_data, *n;
489 struct pci_dev *pdev = NULL;
491 for_each_pci_dev(pdev) {
493 if (!check_device(&pdev->dev))
496 iommu_uninit_device(&pdev->dev);
499 /* Free all of our dev_data structures */
500 list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
501 free_dev_data(dev_data);
504 int __init amd_iommu_init_devices(void)
506 struct pci_dev *pdev = NULL;
509 for_each_pci_dev(pdev) {
511 if (!check_device(&pdev->dev))
514 ret = iommu_init_device(&pdev->dev);
515 if (ret == -ENOTSUPP)
516 iommu_ignore_device(&pdev->dev);
525 amd_iommu_uninit_devices();
529 #ifdef CONFIG_AMD_IOMMU_STATS
532 * Initialization code for statistics collection
535 DECLARE_STATS_COUNTER(compl_wait);
536 DECLARE_STATS_COUNTER(cnt_map_single);
537 DECLARE_STATS_COUNTER(cnt_unmap_single);
538 DECLARE_STATS_COUNTER(cnt_map_sg);
539 DECLARE_STATS_COUNTER(cnt_unmap_sg);
540 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
541 DECLARE_STATS_COUNTER(cnt_free_coherent);
542 DECLARE_STATS_COUNTER(cross_page);
543 DECLARE_STATS_COUNTER(domain_flush_single);
544 DECLARE_STATS_COUNTER(domain_flush_all);
545 DECLARE_STATS_COUNTER(alloced_io_mem);
546 DECLARE_STATS_COUNTER(total_map_requests);
547 DECLARE_STATS_COUNTER(complete_ppr);
548 DECLARE_STATS_COUNTER(invalidate_iotlb);
549 DECLARE_STATS_COUNTER(invalidate_iotlb_all);
550 DECLARE_STATS_COUNTER(pri_requests);
552 static struct dentry *stats_dir;
553 static struct dentry *de_fflush;
555 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
557 if (stats_dir == NULL)
560 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
564 static void amd_iommu_stats_init(void)
566 stats_dir = debugfs_create_dir("amd-iommu", NULL);
567 if (stats_dir == NULL)
570 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
571 &amd_iommu_unmap_flush);
573 amd_iommu_stats_add(&compl_wait);
574 amd_iommu_stats_add(&cnt_map_single);
575 amd_iommu_stats_add(&cnt_unmap_single);
576 amd_iommu_stats_add(&cnt_map_sg);
577 amd_iommu_stats_add(&cnt_unmap_sg);
578 amd_iommu_stats_add(&cnt_alloc_coherent);
579 amd_iommu_stats_add(&cnt_free_coherent);
580 amd_iommu_stats_add(&cross_page);
581 amd_iommu_stats_add(&domain_flush_single);
582 amd_iommu_stats_add(&domain_flush_all);
583 amd_iommu_stats_add(&alloced_io_mem);
584 amd_iommu_stats_add(&total_map_requests);
585 amd_iommu_stats_add(&complete_ppr);
586 amd_iommu_stats_add(&invalidate_iotlb);
587 amd_iommu_stats_add(&invalidate_iotlb_all);
588 amd_iommu_stats_add(&pri_requests);
593 /****************************************************************************
595 * Interrupt handling functions
597 ****************************************************************************/
599 static void dump_dte_entry(u16 devid)
603 for (i = 0; i < 4; ++i)
604 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
605 amd_iommu_dev_table[devid].data[i]);
608 static void dump_command(unsigned long phys_addr)
610 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
613 for (i = 0; i < 4; ++i)
614 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
617 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
619 int type, devid, domid, flags;
620 volatile u32 *event = __evt;
625 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
626 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
627 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
628 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
629 address = (u64)(((u64)event[3]) << 32) | event[2];
632 /* Did we hit the erratum? */
633 if (++count == LOOP_TIMEOUT) {
634 pr_err("AMD-Vi: No event written to event log\n");
641 printk(KERN_ERR "AMD-Vi: Event logged [");
644 case EVENT_TYPE_ILL_DEV:
645 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
646 "address=0x%016llx flags=0x%04x]\n",
647 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
649 dump_dte_entry(devid);
651 case EVENT_TYPE_IO_FAULT:
652 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
653 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
654 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
655 domid, address, flags);
657 case EVENT_TYPE_DEV_TAB_ERR:
658 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
659 "address=0x%016llx flags=0x%04x]\n",
660 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
663 case EVENT_TYPE_PAGE_TAB_ERR:
664 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
665 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
666 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
667 domid, address, flags);
669 case EVENT_TYPE_ILL_CMD:
670 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
671 dump_command(address);
673 case EVENT_TYPE_CMD_HARD_ERR:
674 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
675 "flags=0x%04x]\n", address, flags);
677 case EVENT_TYPE_IOTLB_INV_TO:
678 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
679 "address=0x%016llx]\n",
680 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
683 case EVENT_TYPE_INV_DEV_REQ:
684 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
685 "address=0x%016llx flags=0x%04x]\n",
686 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
690 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
693 memset(__evt, 0, 4 * sizeof(u32));
696 static void iommu_poll_events(struct amd_iommu *iommu)
700 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
701 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
703 while (head != tail) {
704 iommu_print_event(iommu, iommu->evt_buf + head);
705 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
708 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
711 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
713 struct amd_iommu_fault fault;
715 INC_STATS_COUNTER(pri_requests);
717 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
718 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
722 fault.address = raw[1];
723 fault.pasid = PPR_PASID(raw[0]);
724 fault.device_id = PPR_DEVID(raw[0]);
725 fault.tag = PPR_TAG(raw[0]);
726 fault.flags = PPR_FLAGS(raw[0]);
728 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
731 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
735 if (iommu->ppr_log == NULL)
738 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
739 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
741 while (head != tail) {
746 raw = (u64 *)(iommu->ppr_log + head);
749 * Hardware bug: Interrupt may arrive before the entry is
750 * written to memory. If this happens we need to wait for the
753 for (i = 0; i < LOOP_TIMEOUT; ++i) {
754 if (PPR_REQ_TYPE(raw[0]) != 0)
759 /* Avoid memcpy function-call overhead */
764 * To detect the hardware bug we need to clear the entry
767 raw[0] = raw[1] = 0UL;
769 /* Update head pointer of hardware ring-buffer */
770 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
771 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
773 /* Handle PPR entry */
774 iommu_handle_ppr_entry(iommu, entry);
776 /* Refresh ring-buffer information */
777 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
778 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
782 irqreturn_t amd_iommu_int_thread(int irq, void *data)
784 struct amd_iommu *iommu = (struct amd_iommu *) data;
785 u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
787 while (status & (MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK)) {
788 /* Enable EVT and PPR interrupts again */
789 writel((MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK),
790 iommu->mmio_base + MMIO_STATUS_OFFSET);
792 if (status & MMIO_STATUS_EVT_INT_MASK) {
793 pr_devel("AMD-Vi: Processing IOMMU Event Log\n");
794 iommu_poll_events(iommu);
797 if (status & MMIO_STATUS_PPR_INT_MASK) {
798 pr_devel("AMD-Vi: Processing IOMMU PPR Log\n");
799 iommu_poll_ppr_log(iommu);
803 * Hardware bug: ERBT1312
804 * When re-enabling interrupt (by writing 1
805 * to clear the bit), the hardware might also try to set
806 * the interrupt bit in the event status register.
807 * In this scenario, the bit will be set, and disable
808 * subsequent interrupts.
810 * Workaround: The IOMMU driver should read back the
811 * status register and check if the interrupt bits are cleared.
812 * If not, driver will need to go through the interrupt handler
813 * again and re-clear the bits
815 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
820 irqreturn_t amd_iommu_int_handler(int irq, void *data)
822 return IRQ_WAKE_THREAD;
825 /****************************************************************************
827 * IOMMU command queuing functions
829 ****************************************************************************/
831 static int wait_on_sem(volatile u64 *sem)
835 while (*sem == 0 && i < LOOP_TIMEOUT) {
840 if (i == LOOP_TIMEOUT) {
841 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
848 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
849 struct iommu_cmd *cmd,
854 target = iommu->cmd_buf + tail;
855 tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
857 /* Copy command to buffer */
858 memcpy(target, cmd, sizeof(*cmd));
860 /* Tell the IOMMU about it */
861 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
864 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
866 WARN_ON(address & 0x7ULL);
868 memset(cmd, 0, sizeof(*cmd));
869 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
870 cmd->data[1] = upper_32_bits(__pa(address));
872 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
875 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
877 memset(cmd, 0, sizeof(*cmd));
878 cmd->data[0] = devid;
879 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
882 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
883 size_t size, u16 domid, int pde)
888 pages = iommu_num_pages(address, size, PAGE_SIZE);
893 * If we have to flush more than one page, flush all
894 * TLB entries for this domain
896 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
900 address &= PAGE_MASK;
902 memset(cmd, 0, sizeof(*cmd));
903 cmd->data[1] |= domid;
904 cmd->data[2] = lower_32_bits(address);
905 cmd->data[3] = upper_32_bits(address);
906 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
907 if (s) /* size bit - we flush more than one 4kb page */
908 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
909 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
910 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
913 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
914 u64 address, size_t size)
919 pages = iommu_num_pages(address, size, PAGE_SIZE);
924 * If we have to flush more than one page, flush all
925 * TLB entries for this domain
927 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
931 address &= PAGE_MASK;
933 memset(cmd, 0, sizeof(*cmd));
934 cmd->data[0] = devid;
935 cmd->data[0] |= (qdep & 0xff) << 24;
936 cmd->data[1] = devid;
937 cmd->data[2] = lower_32_bits(address);
938 cmd->data[3] = upper_32_bits(address);
939 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
941 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
944 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
945 u64 address, bool size)
947 memset(cmd, 0, sizeof(*cmd));
949 address &= ~(0xfffULL);
951 cmd->data[0] = pasid & PASID_MASK;
952 cmd->data[1] = domid;
953 cmd->data[2] = lower_32_bits(address);
954 cmd->data[3] = upper_32_bits(address);
955 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
956 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
958 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
959 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
962 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
963 int qdep, u64 address, bool size)
965 memset(cmd, 0, sizeof(*cmd));
967 address &= ~(0xfffULL);
969 cmd->data[0] = devid;
970 cmd->data[0] |= (pasid & 0xff) << 16;
971 cmd->data[0] |= (qdep & 0xff) << 24;
972 cmd->data[1] = devid;
973 cmd->data[1] |= ((pasid >> 8) & 0xfff) << 16;
974 cmd->data[2] = lower_32_bits(address);
975 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
976 cmd->data[3] = upper_32_bits(address);
978 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
979 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
982 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
983 int status, int tag, bool gn)
985 memset(cmd, 0, sizeof(*cmd));
987 cmd->data[0] = devid;
989 cmd->data[1] = pasid & PASID_MASK;
990 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
992 cmd->data[3] = tag & 0x1ff;
993 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
995 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
998 static void build_inv_all(struct iommu_cmd *cmd)
1000 memset(cmd, 0, sizeof(*cmd));
1001 CMD_SET_TYPE(cmd, CMD_INV_ALL);
1004 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
1006 memset(cmd, 0, sizeof(*cmd));
1007 cmd->data[0] = devid;
1008 CMD_SET_TYPE(cmd, CMD_INV_IRT);
1012 * Writes the command to the IOMMUs command buffer and informs the
1013 * hardware about the new command.
1015 static int iommu_queue_command_sync(struct amd_iommu *iommu,
1016 struct iommu_cmd *cmd,
1019 u32 left, tail, head, next_tail;
1020 unsigned long flags;
1022 WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
1025 spin_lock_irqsave(&iommu->lock, flags);
1027 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
1028 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
1029 next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
1030 left = (head - next_tail) % iommu->cmd_buf_size;
1033 struct iommu_cmd sync_cmd;
1034 volatile u64 sem = 0;
1037 build_completion_wait(&sync_cmd, (u64)&sem);
1038 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
1040 spin_unlock_irqrestore(&iommu->lock, flags);
1042 if ((ret = wait_on_sem(&sem)) != 0)
1048 copy_cmd_to_buffer(iommu, cmd, tail);
1050 /* We need to sync now to make sure all commands are processed */
1051 iommu->need_sync = sync;
1053 spin_unlock_irqrestore(&iommu->lock, flags);
1058 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
1060 return iommu_queue_command_sync(iommu, cmd, true);
1064 * This function queues a completion wait command into the command
1065 * buffer of an IOMMU
1067 static int iommu_completion_wait(struct amd_iommu *iommu)
1069 struct iommu_cmd cmd;
1070 volatile u64 sem = 0;
1073 if (!iommu->need_sync)
1076 build_completion_wait(&cmd, (u64)&sem);
1078 ret = iommu_queue_command_sync(iommu, &cmd, false);
1082 return wait_on_sem(&sem);
1085 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1087 struct iommu_cmd cmd;
1089 build_inv_dte(&cmd, devid);
1091 return iommu_queue_command(iommu, &cmd);
1094 static void iommu_flush_dte_all(struct amd_iommu *iommu)
1098 for (devid = 0; devid <= 0xffff; ++devid)
1099 iommu_flush_dte(iommu, devid);
1101 iommu_completion_wait(iommu);
1105 * This function uses heavy locking and may disable irqs for some time. But
1106 * this is no issue because it is only called during resume.
1108 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1112 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1113 struct iommu_cmd cmd;
1114 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1116 iommu_queue_command(iommu, &cmd);
1119 iommu_completion_wait(iommu);
1122 static void iommu_flush_all(struct amd_iommu *iommu)
1124 struct iommu_cmd cmd;
1126 build_inv_all(&cmd);
1128 iommu_queue_command(iommu, &cmd);
1129 iommu_completion_wait(iommu);
1132 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1134 struct iommu_cmd cmd;
1136 build_inv_irt(&cmd, devid);
1138 iommu_queue_command(iommu, &cmd);
1141 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1145 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1146 iommu_flush_irt(iommu, devid);
1148 iommu_completion_wait(iommu);
1151 void iommu_flush_all_caches(struct amd_iommu *iommu)
1153 if (iommu_feature(iommu, FEATURE_IA)) {
1154 iommu_flush_all(iommu);
1156 iommu_flush_dte_all(iommu);
1157 iommu_flush_irt_all(iommu);
1158 iommu_flush_tlb_all(iommu);
1163 * Command send function for flushing on-device TLB
1165 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1166 u64 address, size_t size)
1168 struct amd_iommu *iommu;
1169 struct iommu_cmd cmd;
1172 qdep = dev_data->ats.qdep;
1173 iommu = amd_iommu_rlookup_table[dev_data->devid];
1175 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1177 return iommu_queue_command(iommu, &cmd);
1181 * Command send function for invalidating a device table entry
1183 static int device_flush_dte(struct iommu_dev_data *dev_data)
1185 struct amd_iommu *iommu;
1188 iommu = amd_iommu_rlookup_table[dev_data->devid];
1190 ret = iommu_flush_dte(iommu, dev_data->devid);
1194 if (dev_data->ats.enabled)
1195 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1201 * TLB invalidation function which is called from the mapping functions.
1202 * It invalidates a single PTE if the range to flush is within a single
1203 * page. Otherwise it flushes the whole TLB of the IOMMU.
1205 static void __domain_flush_pages(struct protection_domain *domain,
1206 u64 address, size_t size, int pde)
1208 struct iommu_dev_data *dev_data;
1209 struct iommu_cmd cmd;
1212 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1214 for (i = 0; i < amd_iommus_present; ++i) {
1215 if (!domain->dev_iommu[i])
1219 * Devices of this domain are behind this IOMMU
1220 * We need a TLB flush
1222 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1225 list_for_each_entry(dev_data, &domain->dev_list, list) {
1227 if (!dev_data->ats.enabled)
1230 ret |= device_flush_iotlb(dev_data, address, size);
1236 static void domain_flush_pages(struct protection_domain *domain,
1237 u64 address, size_t size)
1239 __domain_flush_pages(domain, address, size, 0);
1242 /* Flush the whole IO/TLB for a given protection domain */
1243 static void domain_flush_tlb(struct protection_domain *domain)
1245 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1248 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1249 static void domain_flush_tlb_pde(struct protection_domain *domain)
1251 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1254 static void domain_flush_complete(struct protection_domain *domain)
1258 for (i = 0; i < amd_iommus_present; ++i) {
1259 if (!domain->dev_iommu[i])
1263 * Devices of this domain are behind this IOMMU
1264 * We need to wait for completion of all commands.
1266 iommu_completion_wait(amd_iommus[i]);
1272 * This function flushes the DTEs for all devices in domain
1274 static void domain_flush_devices(struct protection_domain *domain)
1276 struct iommu_dev_data *dev_data;
1278 list_for_each_entry(dev_data, &domain->dev_list, list)
1279 device_flush_dte(dev_data);
1282 /****************************************************************************
1284 * The functions below are used the create the page table mappings for
1285 * unity mapped regions.
1287 ****************************************************************************/
1290 * This function is used to add another level to an IO page table. Adding
1291 * another level increases the size of the address space by 9 bits to a size up
1294 static bool increase_address_space(struct protection_domain *domain,
1299 if (domain->mode == PAGE_MODE_6_LEVEL)
1300 /* address space already 64 bit large */
1303 pte = (void *)get_zeroed_page(gfp);
1307 *pte = PM_LEVEL_PDE(domain->mode,
1308 virt_to_phys(domain->pt_root));
1309 domain->pt_root = pte;
1311 domain->updated = true;
1316 static u64 *alloc_pte(struct protection_domain *domain,
1317 unsigned long address,
1318 unsigned long page_size,
1325 BUG_ON(!is_power_of_2(page_size));
1327 while (address > PM_LEVEL_SIZE(domain->mode))
1328 increase_address_space(domain, gfp);
1330 level = domain->mode - 1;
1331 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1332 address = PAGE_SIZE_ALIGN(address, page_size);
1333 end_lvl = PAGE_SIZE_LEVEL(page_size);
1335 while (level > end_lvl) {
1336 if (!IOMMU_PTE_PRESENT(*pte)) {
1337 page = (u64 *)get_zeroed_page(gfp);
1340 *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1343 /* No level skipping support yet */
1344 if (PM_PTE_LEVEL(*pte) != level)
1349 pte = IOMMU_PTE_PAGE(*pte);
1351 if (pte_page && level == end_lvl)
1354 pte = &pte[PM_LEVEL_INDEX(level, address)];
1361 * This function checks if there is a PTE for a given dma address. If
1362 * there is one, it returns the pointer to it.
1364 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
1369 if (address > PM_LEVEL_SIZE(domain->mode))
1372 level = domain->mode - 1;
1373 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1378 if (!IOMMU_PTE_PRESENT(*pte))
1382 if (PM_PTE_LEVEL(*pte) == 0x07) {
1383 unsigned long pte_mask, __pte;
1386 * If we have a series of large PTEs, make
1387 * sure to return a pointer to the first one.
1389 pte_mask = PTE_PAGE_SIZE(*pte);
1390 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1391 __pte = ((unsigned long)pte) & pte_mask;
1393 return (u64 *)__pte;
1396 /* No level skipping support yet */
1397 if (PM_PTE_LEVEL(*pte) != level)
1402 /* Walk to the next level */
1403 pte = IOMMU_PTE_PAGE(*pte);
1404 pte = &pte[PM_LEVEL_INDEX(level, address)];
1411 * Generic mapping functions. It maps a physical address into a DMA
1412 * address space. It allocates the page table pages if necessary.
1413 * In the future it can be extended to a generic mapping function
1414 * supporting all features of AMD IOMMU page tables like level skipping
1415 * and full 64 bit address spaces.
1417 static int iommu_map_page(struct protection_domain *dom,
1418 unsigned long bus_addr,
1419 unsigned long phys_addr,
1421 unsigned long page_size)
1426 if (!(prot & IOMMU_PROT_MASK))
1429 bus_addr = PAGE_ALIGN(bus_addr);
1430 phys_addr = PAGE_ALIGN(phys_addr);
1431 count = PAGE_SIZE_PTE_COUNT(page_size);
1432 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1434 for (i = 0; i < count; ++i)
1435 if (IOMMU_PTE_PRESENT(pte[i]))
1438 if (page_size > PAGE_SIZE) {
1439 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1440 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1442 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1444 if (prot & IOMMU_PROT_IR)
1445 __pte |= IOMMU_PTE_IR;
1446 if (prot & IOMMU_PROT_IW)
1447 __pte |= IOMMU_PTE_IW;
1449 for (i = 0; i < count; ++i)
1457 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1458 unsigned long bus_addr,
1459 unsigned long page_size)
1461 unsigned long long unmap_size, unmapped;
1464 BUG_ON(!is_power_of_2(page_size));
1468 while (unmapped < page_size) {
1470 pte = fetch_pte(dom, bus_addr);
1474 * No PTE for this address
1475 * move forward in 4kb steps
1477 unmap_size = PAGE_SIZE;
1478 } else if (PM_PTE_LEVEL(*pte) == 0) {
1479 /* 4kb PTE found for this address */
1480 unmap_size = PAGE_SIZE;
1485 /* Large PTE found which maps this address */
1486 unmap_size = PTE_PAGE_SIZE(*pte);
1488 /* Only unmap from the first pte in the page */
1489 if ((unmap_size - 1) & bus_addr)
1491 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1492 for (i = 0; i < count; i++)
1496 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1497 unmapped += unmap_size;
1500 BUG_ON(unmapped && !is_power_of_2(unmapped));
1506 * This function checks if a specific unity mapping entry is needed for
1507 * this specific IOMMU.
1509 static int iommu_for_unity_map(struct amd_iommu *iommu,
1510 struct unity_map_entry *entry)
1514 for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1515 bdf = amd_iommu_alias_table[i];
1516 if (amd_iommu_rlookup_table[bdf] == iommu)
1524 * This function actually applies the mapping to the page table of the
1527 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1528 struct unity_map_entry *e)
1533 for (addr = e->address_start; addr < e->address_end;
1534 addr += PAGE_SIZE) {
1535 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1540 * if unity mapping is in aperture range mark the page
1541 * as allocated in the aperture
1543 if (addr < dma_dom->aperture_size)
1544 __set_bit(addr >> PAGE_SHIFT,
1545 dma_dom->aperture[0]->bitmap);
1552 * Init the unity mappings for a specific IOMMU in the system
1554 * Basically iterates over all unity mapping entries and applies them to
1555 * the default domain DMA of that IOMMU if necessary.
1557 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1559 struct unity_map_entry *entry;
1562 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1563 if (!iommu_for_unity_map(iommu, entry))
1565 ret = dma_ops_unity_map(iommu->default_dom, entry);
1574 * Inits the unity mappings required for a specific device
1576 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1579 struct unity_map_entry *e;
1582 list_for_each_entry(e, &amd_iommu_unity_map, list) {
1583 if (!(devid >= e->devid_start && devid <= e->devid_end))
1585 ret = dma_ops_unity_map(dma_dom, e);
1593 /****************************************************************************
1595 * The next functions belong to the address allocator for the dma_ops
1596 * interface functions. They work like the allocators in the other IOMMU
1597 * drivers. Its basically a bitmap which marks the allocated pages in
1598 * the aperture. Maybe it could be enhanced in the future to a more
1599 * efficient allocator.
1601 ****************************************************************************/
1604 * The address allocator core functions.
1606 * called with domain->lock held
1610 * Used to reserve address ranges in the aperture (e.g. for exclusion
1613 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1614 unsigned long start_page,
1617 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1619 if (start_page + pages > last_page)
1620 pages = last_page - start_page;
1622 for (i = start_page; i < start_page + pages; ++i) {
1623 int index = i / APERTURE_RANGE_PAGES;
1624 int page = i % APERTURE_RANGE_PAGES;
1625 __set_bit(page, dom->aperture[index]->bitmap);
1630 * This function is used to add a new aperture range to an existing
1631 * aperture in case of dma_ops domain allocation or address allocation
1634 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1635 bool populate, gfp_t gfp)
1637 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1638 struct amd_iommu *iommu;
1639 unsigned long i, old_size;
1641 #ifdef CONFIG_IOMMU_STRESS
1645 if (index >= APERTURE_MAX_RANGES)
1648 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1649 if (!dma_dom->aperture[index])
1652 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1653 if (!dma_dom->aperture[index]->bitmap)
1656 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1659 unsigned long address = dma_dom->aperture_size;
1660 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1661 u64 *pte, *pte_page;
1663 for (i = 0; i < num_ptes; ++i) {
1664 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1669 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1671 address += APERTURE_RANGE_SIZE / 64;
1675 old_size = dma_dom->aperture_size;
1676 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1678 /* Reserve address range used for MSI messages */
1679 if (old_size < MSI_ADDR_BASE_LO &&
1680 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1681 unsigned long spage;
1684 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1685 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1687 dma_ops_reserve_addresses(dma_dom, spage, pages);
1690 /* Initialize the exclusion range if necessary */
1691 for_each_iommu(iommu) {
1692 if (iommu->exclusion_start &&
1693 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1694 && iommu->exclusion_start < dma_dom->aperture_size) {
1695 unsigned long startpage;
1696 int pages = iommu_num_pages(iommu->exclusion_start,
1697 iommu->exclusion_length,
1699 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1700 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1705 * Check for areas already mapped as present in the new aperture
1706 * range and mark those pages as reserved in the allocator. Such
1707 * mappings may already exist as a result of requested unity
1708 * mappings for devices.
1710 for (i = dma_dom->aperture[index]->offset;
1711 i < dma_dom->aperture_size;
1713 u64 *pte = fetch_pte(&dma_dom->domain, i);
1714 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1717 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1720 update_domain(&dma_dom->domain);
1725 update_domain(&dma_dom->domain);
1727 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1729 kfree(dma_dom->aperture[index]);
1730 dma_dom->aperture[index] = NULL;
1735 static unsigned long dma_ops_area_alloc(struct device *dev,
1736 struct dma_ops_domain *dom,
1738 unsigned long align_mask,
1740 unsigned long start)
1742 unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1743 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1744 int i = start >> APERTURE_RANGE_SHIFT;
1745 unsigned long boundary_size;
1746 unsigned long address = -1;
1747 unsigned long limit;
1749 next_bit >>= PAGE_SHIFT;
1751 boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1752 PAGE_SIZE) >> PAGE_SHIFT;
1754 for (;i < max_index; ++i) {
1755 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1757 if (dom->aperture[i]->offset >= dma_mask)
1760 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1761 dma_mask >> PAGE_SHIFT);
1763 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1764 limit, next_bit, pages, 0,
1765 boundary_size, align_mask);
1766 if (address != -1) {
1767 address = dom->aperture[i]->offset +
1768 (address << PAGE_SHIFT);
1769 dom->next_address = address + (pages << PAGE_SHIFT);
1779 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1780 struct dma_ops_domain *dom,
1782 unsigned long align_mask,
1785 unsigned long address;
1787 #ifdef CONFIG_IOMMU_STRESS
1788 dom->next_address = 0;
1789 dom->need_flush = true;
1792 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1793 dma_mask, dom->next_address);
1795 if (address == -1) {
1796 dom->next_address = 0;
1797 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1799 dom->need_flush = true;
1802 if (unlikely(address == -1))
1803 address = DMA_ERROR_CODE;
1805 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1811 * The address free function.
1813 * called with domain->lock held
1815 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1816 unsigned long address,
1819 unsigned i = address >> APERTURE_RANGE_SHIFT;
1820 struct aperture_range *range = dom->aperture[i];
1822 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1824 #ifdef CONFIG_IOMMU_STRESS
1829 if (address >= dom->next_address)
1830 dom->need_flush = true;
1832 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1834 bitmap_clear(range->bitmap, address, pages);
1838 /****************************************************************************
1840 * The next functions belong to the domain allocation. A domain is
1841 * allocated for every IOMMU as the default domain. If device isolation
1842 * is enabled, every device get its own domain. The most important thing
1843 * about domains is the page table mapping the DMA address space they
1846 ****************************************************************************/
1849 * This function adds a protection domain to the global protection domain list
1851 static void add_domain_to_list(struct protection_domain *domain)
1853 unsigned long flags;
1855 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1856 list_add(&domain->list, &amd_iommu_pd_list);
1857 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1861 * This function removes a protection domain to the global
1862 * protection domain list
1864 static void del_domain_from_list(struct protection_domain *domain)
1866 unsigned long flags;
1868 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1869 list_del(&domain->list);
1870 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1873 static u16 domain_id_alloc(void)
1875 unsigned long flags;
1878 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1879 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1881 if (id > 0 && id < MAX_DOMAIN_ID)
1882 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1885 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1890 static void domain_id_free(int id)
1892 unsigned long flags;
1894 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1895 if (id > 0 && id < MAX_DOMAIN_ID)
1896 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1897 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1900 static void free_pagetable(struct protection_domain *domain)
1905 p1 = domain->pt_root;
1910 for (i = 0; i < 512; ++i) {
1911 if (!IOMMU_PTE_PRESENT(p1[i]))
1914 p2 = IOMMU_PTE_PAGE(p1[i]);
1915 for (j = 0; j < 512; ++j) {
1916 if (!IOMMU_PTE_PRESENT(p2[j]))
1918 p3 = IOMMU_PTE_PAGE(p2[j]);
1919 free_page((unsigned long)p3);
1922 free_page((unsigned long)p2);
1925 free_page((unsigned long)p1);
1927 domain->pt_root = NULL;
1930 static void free_gcr3_tbl_level1(u64 *tbl)
1935 for (i = 0; i < 512; ++i) {
1936 if (!(tbl[i] & GCR3_VALID))
1939 ptr = __va(tbl[i] & PAGE_MASK);
1941 free_page((unsigned long)ptr);
1945 static void free_gcr3_tbl_level2(u64 *tbl)
1950 for (i = 0; i < 512; ++i) {
1951 if (!(tbl[i] & GCR3_VALID))
1954 ptr = __va(tbl[i] & PAGE_MASK);
1956 free_gcr3_tbl_level1(ptr);
1960 static void free_gcr3_table(struct protection_domain *domain)
1962 if (domain->glx == 2)
1963 free_gcr3_tbl_level2(domain->gcr3_tbl);
1964 else if (domain->glx == 1)
1965 free_gcr3_tbl_level1(domain->gcr3_tbl);
1966 else if (domain->glx != 0)
1969 free_page((unsigned long)domain->gcr3_tbl);
1973 * Free a domain, only used if something went wrong in the
1974 * allocation path and we need to free an already allocated page table
1976 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1983 del_domain_from_list(&dom->domain);
1985 free_pagetable(&dom->domain);
1987 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1988 if (!dom->aperture[i])
1990 free_page((unsigned long)dom->aperture[i]->bitmap);
1991 kfree(dom->aperture[i]);
1998 * Allocates a new protection domain usable for the dma_ops functions.
1999 * It also initializes the page table and the address allocator data
2000 * structures required for the dma_ops interface
2002 static struct dma_ops_domain *dma_ops_domain_alloc(void)
2004 struct dma_ops_domain *dma_dom;
2006 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
2010 spin_lock_init(&dma_dom->domain.lock);
2012 dma_dom->domain.id = domain_id_alloc();
2013 if (dma_dom->domain.id == 0)
2015 INIT_LIST_HEAD(&dma_dom->domain.dev_list);
2016 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
2017 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2018 dma_dom->domain.flags = PD_DMA_OPS_MASK;
2019 dma_dom->domain.priv = dma_dom;
2020 if (!dma_dom->domain.pt_root)
2023 dma_dom->need_flush = false;
2024 dma_dom->target_dev = 0xffff;
2026 add_domain_to_list(&dma_dom->domain);
2028 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
2032 * mark the first page as allocated so we never return 0 as
2033 * a valid dma-address. So we can use 0 as error value
2035 dma_dom->aperture[0]->bitmap[0] = 1;
2036 dma_dom->next_address = 0;
2042 dma_ops_domain_free(dma_dom);
2048 * little helper function to check whether a given protection domain is a
2051 static bool dma_ops_domain(struct protection_domain *domain)
2053 return domain->flags & PD_DMA_OPS_MASK;
2056 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
2061 if (domain->mode != PAGE_MODE_NONE)
2062 pte_root = virt_to_phys(domain->pt_root);
2064 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
2065 << DEV_ENTRY_MODE_SHIFT;
2066 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
2068 flags = amd_iommu_dev_table[devid].data[1];
2071 flags |= DTE_FLAG_IOTLB;
2073 if (domain->flags & PD_IOMMUV2_MASK) {
2074 u64 gcr3 = __pa(domain->gcr3_tbl);
2075 u64 glx = domain->glx;
2078 pte_root |= DTE_FLAG_GV;
2079 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
2081 /* First mask out possible old values for GCR3 table */
2082 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
2085 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
2088 /* Encode GCR3 table into DTE */
2089 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
2092 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
2095 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
2099 flags &= ~(0xffffUL);
2100 flags |= domain->id;
2102 amd_iommu_dev_table[devid].data[1] = flags;
2103 amd_iommu_dev_table[devid].data[0] = pte_root;
2106 static void clear_dte_entry(u16 devid)
2108 /* remove entry from the device table seen by the hardware */
2109 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
2110 amd_iommu_dev_table[devid].data[1] = 0;
2112 amd_iommu_apply_erratum_63(devid);
2115 static void do_attach(struct iommu_dev_data *dev_data,
2116 struct protection_domain *domain)
2118 struct amd_iommu *iommu;
2121 iommu = amd_iommu_rlookup_table[dev_data->devid];
2122 ats = dev_data->ats.enabled;
2124 /* Update data structures */
2125 dev_data->domain = domain;
2126 list_add(&dev_data->list, &domain->dev_list);
2127 set_dte_entry(dev_data->devid, domain, ats);
2129 /* Do reference counting */
2130 domain->dev_iommu[iommu->index] += 1;
2131 domain->dev_cnt += 1;
2133 /* Flush the DTE entry */
2134 device_flush_dte(dev_data);
2137 static void do_detach(struct iommu_dev_data *dev_data)
2139 struct amd_iommu *iommu;
2141 iommu = amd_iommu_rlookup_table[dev_data->devid];
2143 /* decrease reference counters */
2144 dev_data->domain->dev_iommu[iommu->index] -= 1;
2145 dev_data->domain->dev_cnt -= 1;
2147 /* Update data structures */
2148 dev_data->domain = NULL;
2149 list_del(&dev_data->list);
2150 clear_dte_entry(dev_data->devid);
2152 /* Flush the DTE entry */
2153 device_flush_dte(dev_data);
2157 * If a device is not yet associated with a domain, this function does
2158 * assigns it visible for the hardware
2160 static int __attach_device(struct iommu_dev_data *dev_data,
2161 struct protection_domain *domain)
2166 spin_lock(&domain->lock);
2168 if (dev_data->alias_data != NULL) {
2169 struct iommu_dev_data *alias_data = dev_data->alias_data;
2171 /* Some sanity checks */
2173 if (alias_data->domain != NULL &&
2174 alias_data->domain != domain)
2177 if (dev_data->domain != NULL &&
2178 dev_data->domain != domain)
2181 /* Do real assignment */
2182 if (alias_data->domain == NULL)
2183 do_attach(alias_data, domain);
2185 atomic_inc(&alias_data->bind);
2188 if (dev_data->domain == NULL)
2189 do_attach(dev_data, domain);
2191 atomic_inc(&dev_data->bind);
2198 spin_unlock(&domain->lock);
2204 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2206 pci_disable_ats(pdev);
2207 pci_disable_pri(pdev);
2208 pci_disable_pasid(pdev);
2211 /* FIXME: Change generic reset-function to do the same */
2212 static int pri_reset_while_enabled(struct pci_dev *pdev)
2217 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2221 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2222 control |= PCI_PRI_CTRL_RESET;
2223 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2228 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2233 /* FIXME: Hardcode number of outstanding requests for now */
2235 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2237 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2239 /* Only allow access to user-accessible pages */
2240 ret = pci_enable_pasid(pdev, 0);
2244 /* First reset the PRI state of the device */
2245 ret = pci_reset_pri(pdev);
2250 ret = pci_enable_pri(pdev, reqs);
2255 ret = pri_reset_while_enabled(pdev);
2260 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2267 pci_disable_pri(pdev);
2268 pci_disable_pasid(pdev);
2273 /* FIXME: Move this to PCI code */
2274 #define PCI_PRI_TLP_OFF (1 << 15)
2276 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2281 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2285 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2287 return (status & PCI_PRI_TLP_OFF) ? true : false;
2291 * If a device is not yet associated with a domain, this function
2292 * assigns it visible for the hardware
2294 static int attach_device(struct device *dev,
2295 struct protection_domain *domain)
2297 struct pci_dev *pdev = to_pci_dev(dev);
2298 struct iommu_dev_data *dev_data;
2299 unsigned long flags;
2302 dev_data = get_dev_data(dev);
2304 if (domain->flags & PD_IOMMUV2_MASK) {
2305 if (!dev_data->iommu_v2 || !dev_data->passthrough)
2308 if (pdev_iommuv2_enable(pdev) != 0)
2311 dev_data->ats.enabled = true;
2312 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2313 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2314 } else if (amd_iommu_iotlb_sup &&
2315 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2316 dev_data->ats.enabled = true;
2317 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2320 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2321 ret = __attach_device(dev_data, domain);
2322 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2325 * We might boot into a crash-kernel here. The crashed kernel
2326 * left the caches in the IOMMU dirty. So we have to flush
2327 * here to evict all dirty stuff.
2329 domain_flush_tlb_pde(domain);
2335 * Removes a device from a protection domain (unlocked)
2337 static void __detach_device(struct iommu_dev_data *dev_data)
2339 struct protection_domain *domain;
2340 unsigned long flags;
2342 BUG_ON(!dev_data->domain);
2344 domain = dev_data->domain;
2346 spin_lock_irqsave(&domain->lock, flags);
2348 if (dev_data->alias_data != NULL) {
2349 struct iommu_dev_data *alias_data = dev_data->alias_data;
2351 if (atomic_dec_and_test(&alias_data->bind))
2352 do_detach(alias_data);
2355 if (atomic_dec_and_test(&dev_data->bind))
2356 do_detach(dev_data);
2358 spin_unlock_irqrestore(&domain->lock, flags);
2361 * If we run in passthrough mode the device must be assigned to the
2362 * passthrough domain if it is detached from any other domain.
2363 * Make sure we can deassign from the pt_domain itself.
2365 if (dev_data->passthrough &&
2366 (dev_data->domain == NULL && domain != pt_domain))
2367 __attach_device(dev_data, pt_domain);
2371 * Removes a device from a protection domain (with devtable_lock held)
2373 static void detach_device(struct device *dev)
2375 struct protection_domain *domain;
2376 struct iommu_dev_data *dev_data;
2377 unsigned long flags;
2379 dev_data = get_dev_data(dev);
2380 domain = dev_data->domain;
2382 /* lock device table */
2383 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2384 __detach_device(dev_data);
2385 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2387 if (domain->flags & PD_IOMMUV2_MASK)
2388 pdev_iommuv2_disable(to_pci_dev(dev));
2389 else if (dev_data->ats.enabled)
2390 pci_disable_ats(to_pci_dev(dev));
2392 dev_data->ats.enabled = false;
2396 * Find out the protection domain structure for a given PCI device. This
2397 * will give us the pointer to the page table root for example.
2399 static struct protection_domain *domain_for_device(struct device *dev)
2401 struct iommu_dev_data *dev_data;
2402 struct protection_domain *dom = NULL;
2403 unsigned long flags;
2405 dev_data = get_dev_data(dev);
2407 if (dev_data->domain)
2408 return dev_data->domain;
2410 if (dev_data->alias_data != NULL) {
2411 struct iommu_dev_data *alias_data = dev_data->alias_data;
2413 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
2414 if (alias_data->domain != NULL) {
2415 __attach_device(dev_data, alias_data->domain);
2416 dom = alias_data->domain;
2418 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2424 static int device_change_notifier(struct notifier_block *nb,
2425 unsigned long action, void *data)
2427 struct dma_ops_domain *dma_domain;
2428 struct protection_domain *domain;
2429 struct iommu_dev_data *dev_data;
2430 struct device *dev = data;
2431 struct amd_iommu *iommu;
2432 unsigned long flags;
2435 if (!check_device(dev))
2438 devid = get_device_id(dev);
2439 iommu = amd_iommu_rlookup_table[devid];
2440 dev_data = get_dev_data(dev);
2443 case BUS_NOTIFY_UNBOUND_DRIVER:
2445 domain = domain_for_device(dev);
2449 if (dev_data->passthrough)
2453 case BUS_NOTIFY_ADD_DEVICE:
2455 iommu_init_device(dev);
2458 * dev_data is still NULL and
2459 * got initialized in iommu_init_device
2461 dev_data = get_dev_data(dev);
2463 if (iommu_pass_through || dev_data->iommu_v2) {
2464 dev_data->passthrough = true;
2465 attach_device(dev, pt_domain);
2469 domain = domain_for_device(dev);
2471 /* allocate a protection domain if a device is added */
2472 dma_domain = find_protection_domain(devid);
2474 dma_domain = dma_ops_domain_alloc();
2477 dma_domain->target_dev = devid;
2479 spin_lock_irqsave(&iommu_pd_list_lock, flags);
2480 list_add_tail(&dma_domain->list, &iommu_pd_list);
2481 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
2484 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2487 case BUS_NOTIFY_DEL_DEVICE:
2489 iommu_uninit_device(dev);
2495 iommu_completion_wait(iommu);
2501 static struct notifier_block device_nb = {
2502 .notifier_call = device_change_notifier,
2505 void amd_iommu_init_notifier(void)
2507 bus_register_notifier(&pci_bus_type, &device_nb);
2510 /*****************************************************************************
2512 * The next functions belong to the dma_ops mapping/unmapping code.
2514 *****************************************************************************/
2517 * In the dma_ops path we only have the struct device. This function
2518 * finds the corresponding IOMMU, the protection domain and the
2519 * requestor id for a given device.
2520 * If the device is not yet associated with a domain this is also done
2523 static struct protection_domain *get_domain(struct device *dev)
2525 struct protection_domain *domain;
2526 struct dma_ops_domain *dma_dom;
2527 u16 devid = get_device_id(dev);
2529 if (!check_device(dev))
2530 return ERR_PTR(-EINVAL);
2532 domain = domain_for_device(dev);
2533 if (domain != NULL && !dma_ops_domain(domain))
2534 return ERR_PTR(-EBUSY);
2539 /* Device not bound yet - bind it */
2540 dma_dom = find_protection_domain(devid);
2542 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
2543 attach_device(dev, &dma_dom->domain);
2544 DUMP_printk("Using protection domain %d for device %s\n",
2545 dma_dom->domain.id, dev_name(dev));
2547 return &dma_dom->domain;
2550 static void update_device_table(struct protection_domain *domain)
2552 struct iommu_dev_data *dev_data;
2554 list_for_each_entry(dev_data, &domain->dev_list, list)
2555 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2558 static void update_domain(struct protection_domain *domain)
2560 if (!domain->updated)
2563 update_device_table(domain);
2565 domain_flush_devices(domain);
2566 domain_flush_tlb_pde(domain);
2568 domain->updated = false;
2572 * This function fetches the PTE for a given address in the aperture
2574 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2575 unsigned long address)
2577 struct aperture_range *aperture;
2578 u64 *pte, *pte_page;
2580 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2584 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2586 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2588 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2590 pte += PM_LEVEL_INDEX(0, address);
2592 update_domain(&dom->domain);
2598 * This is the generic map function. It maps one 4kb page at paddr to
2599 * the given address in the DMA address space for the domain.
2601 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2602 unsigned long address,
2608 WARN_ON(address > dom->aperture_size);
2612 pte = dma_ops_get_pte(dom, address);
2614 return DMA_ERROR_CODE;
2616 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2618 if (direction == DMA_TO_DEVICE)
2619 __pte |= IOMMU_PTE_IR;
2620 else if (direction == DMA_FROM_DEVICE)
2621 __pte |= IOMMU_PTE_IW;
2622 else if (direction == DMA_BIDIRECTIONAL)
2623 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2629 return (dma_addr_t)address;
2633 * The generic unmapping function for on page in the DMA address space.
2635 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2636 unsigned long address)
2638 struct aperture_range *aperture;
2641 if (address >= dom->aperture_size)
2644 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2648 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2652 pte += PM_LEVEL_INDEX(0, address);
2660 * This function contains common code for mapping of a physically
2661 * contiguous memory region into DMA address space. It is used by all
2662 * mapping functions provided with this IOMMU driver.
2663 * Must be called with the domain lock held.
2665 static dma_addr_t __map_single(struct device *dev,
2666 struct dma_ops_domain *dma_dom,
2673 dma_addr_t offset = paddr & ~PAGE_MASK;
2674 dma_addr_t address, start, ret;
2676 unsigned long align_mask = 0;
2679 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2682 INC_STATS_COUNTER(total_map_requests);
2685 INC_STATS_COUNTER(cross_page);
2688 align_mask = (1UL << get_order(size)) - 1;
2691 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2693 if (unlikely(address == DMA_ERROR_CODE)) {
2695 * setting next_address here will let the address
2696 * allocator only scan the new allocated range in the
2697 * first run. This is a small optimization.
2699 dma_dom->next_address = dma_dom->aperture_size;
2701 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2705 * aperture was successfully enlarged by 128 MB, try
2712 for (i = 0; i < pages; ++i) {
2713 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2714 if (ret == DMA_ERROR_CODE)
2722 ADD_STATS_COUNTER(alloced_io_mem, size);
2724 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2725 domain_flush_tlb(&dma_dom->domain);
2726 dma_dom->need_flush = false;
2727 } else if (unlikely(amd_iommu_np_cache))
2728 domain_flush_pages(&dma_dom->domain, address, size);
2735 for (--i; i >= 0; --i) {
2737 dma_ops_domain_unmap(dma_dom, start);
2740 dma_ops_free_addresses(dma_dom, address, pages);
2742 return DMA_ERROR_CODE;
2746 * Does the reverse of the __map_single function. Must be called with
2747 * the domain lock held too
2749 static void __unmap_single(struct dma_ops_domain *dma_dom,
2750 dma_addr_t dma_addr,
2754 dma_addr_t flush_addr;
2755 dma_addr_t i, start;
2758 if ((dma_addr == DMA_ERROR_CODE) ||
2759 (dma_addr + size > dma_dom->aperture_size))
2762 flush_addr = dma_addr;
2763 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2764 dma_addr &= PAGE_MASK;
2767 for (i = 0; i < pages; ++i) {
2768 dma_ops_domain_unmap(dma_dom, start);
2772 SUB_STATS_COUNTER(alloced_io_mem, size);
2774 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2776 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2777 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2778 dma_dom->need_flush = false;
2783 * The exported map_single function for dma_ops.
2785 static dma_addr_t map_page(struct device *dev, struct page *page,
2786 unsigned long offset, size_t size,
2787 enum dma_data_direction dir,
2788 struct dma_attrs *attrs)
2790 unsigned long flags;
2791 struct protection_domain *domain;
2794 phys_addr_t paddr = page_to_phys(page) + offset;
2796 INC_STATS_COUNTER(cnt_map_single);
2798 domain = get_domain(dev);
2799 if (PTR_ERR(domain) == -EINVAL)
2800 return (dma_addr_t)paddr;
2801 else if (IS_ERR(domain))
2802 return DMA_ERROR_CODE;
2804 dma_mask = *dev->dma_mask;
2806 spin_lock_irqsave(&domain->lock, flags);
2808 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2810 if (addr == DMA_ERROR_CODE)
2813 domain_flush_complete(domain);
2816 spin_unlock_irqrestore(&domain->lock, flags);
2822 * The exported unmap_single function for dma_ops.
2824 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2825 enum dma_data_direction dir, struct dma_attrs *attrs)
2827 unsigned long flags;
2828 struct protection_domain *domain;
2830 INC_STATS_COUNTER(cnt_unmap_single);
2832 domain = get_domain(dev);
2836 spin_lock_irqsave(&domain->lock, flags);
2838 __unmap_single(domain->priv, dma_addr, size, dir);
2840 domain_flush_complete(domain);
2842 spin_unlock_irqrestore(&domain->lock, flags);
2846 * The exported map_sg function for dma_ops (handles scatter-gather
2849 static int map_sg(struct device *dev, struct scatterlist *sglist,
2850 int nelems, enum dma_data_direction dir,
2851 struct dma_attrs *attrs)
2853 unsigned long flags;
2854 struct protection_domain *domain;
2856 struct scatterlist *s;
2858 int mapped_elems = 0;
2861 INC_STATS_COUNTER(cnt_map_sg);
2863 domain = get_domain(dev);
2867 dma_mask = *dev->dma_mask;
2869 spin_lock_irqsave(&domain->lock, flags);
2871 for_each_sg(sglist, s, nelems, i) {
2874 s->dma_address = __map_single(dev, domain->priv,
2875 paddr, s->length, dir, false,
2878 if (s->dma_address) {
2879 s->dma_length = s->length;
2885 domain_flush_complete(domain);
2888 spin_unlock_irqrestore(&domain->lock, flags);
2890 return mapped_elems;
2892 for_each_sg(sglist, s, mapped_elems, i) {
2894 __unmap_single(domain->priv, s->dma_address,
2895 s->dma_length, dir);
2896 s->dma_address = s->dma_length = 0;
2905 * The exported map_sg function for dma_ops (handles scatter-gather
2908 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2909 int nelems, enum dma_data_direction dir,
2910 struct dma_attrs *attrs)
2912 unsigned long flags;
2913 struct protection_domain *domain;
2914 struct scatterlist *s;
2917 INC_STATS_COUNTER(cnt_unmap_sg);
2919 domain = get_domain(dev);
2923 spin_lock_irqsave(&domain->lock, flags);
2925 for_each_sg(sglist, s, nelems, i) {
2926 __unmap_single(domain->priv, s->dma_address,
2927 s->dma_length, dir);
2928 s->dma_address = s->dma_length = 0;
2931 domain_flush_complete(domain);
2933 spin_unlock_irqrestore(&domain->lock, flags);
2937 * The exported alloc_coherent function for dma_ops.
2939 static void *alloc_coherent(struct device *dev, size_t size,
2940 dma_addr_t *dma_addr, gfp_t flag,
2941 struct dma_attrs *attrs)
2943 unsigned long flags;
2945 struct protection_domain *domain;
2947 u64 dma_mask = dev->coherent_dma_mask;
2949 INC_STATS_COUNTER(cnt_alloc_coherent);
2951 domain = get_domain(dev);
2952 if (PTR_ERR(domain) == -EINVAL) {
2953 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2954 *dma_addr = __pa(virt_addr);
2956 } else if (IS_ERR(domain))
2959 dma_mask = dev->coherent_dma_mask;
2960 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2963 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2967 paddr = virt_to_phys(virt_addr);
2970 dma_mask = *dev->dma_mask;
2972 spin_lock_irqsave(&domain->lock, flags);
2974 *dma_addr = __map_single(dev, domain->priv, paddr,
2975 size, DMA_BIDIRECTIONAL, true, dma_mask);
2977 if (*dma_addr == DMA_ERROR_CODE) {
2978 spin_unlock_irqrestore(&domain->lock, flags);
2982 domain_flush_complete(domain);
2984 spin_unlock_irqrestore(&domain->lock, flags);
2990 free_pages((unsigned long)virt_addr, get_order(size));
2996 * The exported free_coherent function for dma_ops.
2998 static void free_coherent(struct device *dev, size_t size,
2999 void *virt_addr, dma_addr_t dma_addr,
3000 struct dma_attrs *attrs)
3002 unsigned long flags;
3003 struct protection_domain *domain;
3005 INC_STATS_COUNTER(cnt_free_coherent);
3007 domain = get_domain(dev);
3011 spin_lock_irqsave(&domain->lock, flags);
3013 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
3015 domain_flush_complete(domain);
3017 spin_unlock_irqrestore(&domain->lock, flags);
3020 free_pages((unsigned long)virt_addr, get_order(size));
3024 * This function is called by the DMA layer to find out if we can handle a
3025 * particular device. It is part of the dma_ops.
3027 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
3029 return check_device(dev);
3033 * The function for pre-allocating protection domains.
3035 * If the driver core informs the DMA layer if a driver grabs a device
3036 * we don't need to preallocate the protection domains anymore.
3037 * For now we have to.
3039 static void __init prealloc_protection_domains(void)
3041 struct iommu_dev_data *dev_data;
3042 struct dma_ops_domain *dma_dom;
3043 struct pci_dev *dev = NULL;
3046 for_each_pci_dev(dev) {
3048 /* Do we handle this device? */
3049 if (!check_device(&dev->dev))
3052 dev_data = get_dev_data(&dev->dev);
3053 if (!amd_iommu_force_isolation && dev_data->iommu_v2) {
3054 /* Make sure passthrough domain is allocated */
3055 alloc_passthrough_domain();
3056 dev_data->passthrough = true;
3057 attach_device(&dev->dev, pt_domain);
3058 pr_info("AMD-Vi: Using passthrough domain for device %s\n",
3059 dev_name(&dev->dev));
3062 /* Is there already any domain for it? */
3063 if (domain_for_device(&dev->dev))
3066 devid = get_device_id(&dev->dev);
3068 dma_dom = dma_ops_domain_alloc();
3071 init_unity_mappings_for_device(dma_dom, devid);
3072 dma_dom->target_dev = devid;
3074 attach_device(&dev->dev, &dma_dom->domain);
3076 list_add_tail(&dma_dom->list, &iommu_pd_list);
3080 static struct dma_map_ops amd_iommu_dma_ops = {
3081 .alloc = alloc_coherent,
3082 .free = free_coherent,
3083 .map_page = map_page,
3084 .unmap_page = unmap_page,
3086 .unmap_sg = unmap_sg,
3087 .dma_supported = amd_iommu_dma_supported,
3090 static unsigned device_dma_ops_init(void)
3092 struct iommu_dev_data *dev_data;
3093 struct pci_dev *pdev = NULL;
3094 unsigned unhandled = 0;
3096 for_each_pci_dev(pdev) {
3097 if (!check_device(&pdev->dev)) {
3099 iommu_ignore_device(&pdev->dev);
3105 dev_data = get_dev_data(&pdev->dev);
3107 if (!dev_data->passthrough)
3108 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
3110 pdev->dev.archdata.dma_ops = &nommu_dma_ops;
3117 * The function which clues the AMD IOMMU driver into dma_ops.
3120 void __init amd_iommu_init_api(void)
3122 bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
3125 int __init amd_iommu_init_dma_ops(void)
3127 struct amd_iommu *iommu;
3131 * first allocate a default protection domain for every IOMMU we
3132 * found in the system. Devices not assigned to any other
3133 * protection domain will be assigned to the default one.
3135 for_each_iommu(iommu) {
3136 iommu->default_dom = dma_ops_domain_alloc();
3137 if (iommu->default_dom == NULL)
3139 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
3140 ret = iommu_init_unity_mappings(iommu);
3146 * Pre-allocate the protection domains for each device.
3148 prealloc_protection_domains();
3153 /* Make the driver finally visible to the drivers */
3154 unhandled = device_dma_ops_init();
3155 if (unhandled && max_pfn > MAX_DMA32_PFN) {
3156 /* There are unhandled devices - initialize swiotlb for them */
3160 amd_iommu_stats_init();
3162 if (amd_iommu_unmap_flush)
3163 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
3165 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
3171 for_each_iommu(iommu) {
3172 dma_ops_domain_free(iommu->default_dom);
3178 /*****************************************************************************
3180 * The following functions belong to the exported interface of AMD IOMMU
3182 * This interface allows access to lower level functions of the IOMMU
3183 * like protection domain handling and assignement of devices to domains
3184 * which is not possible with the dma_ops interface.
3186 *****************************************************************************/
3188 static void cleanup_domain(struct protection_domain *domain)
3190 struct iommu_dev_data *dev_data, *next;
3191 unsigned long flags;
3193 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3195 list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
3196 __detach_device(dev_data);
3197 atomic_set(&dev_data->bind, 0);
3200 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3203 static void protection_domain_free(struct protection_domain *domain)
3208 del_domain_from_list(domain);
3211 domain_id_free(domain->id);
3216 static struct protection_domain *protection_domain_alloc(void)
3218 struct protection_domain *domain;
3220 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
3224 spin_lock_init(&domain->lock);
3225 mutex_init(&domain->api_lock);
3226 domain->id = domain_id_alloc();
3229 INIT_LIST_HEAD(&domain->dev_list);
3231 add_domain_to_list(domain);
3241 static int __init alloc_passthrough_domain(void)
3243 if (pt_domain != NULL)
3246 /* allocate passthrough domain */
3247 pt_domain = protection_domain_alloc();
3251 pt_domain->mode = PAGE_MODE_NONE;
3255 static int amd_iommu_domain_init(struct iommu_domain *dom)
3257 struct protection_domain *domain;
3259 domain = protection_domain_alloc();
3263 domain->mode = PAGE_MODE_3_LEVEL;
3264 domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
3265 if (!domain->pt_root)
3268 domain->iommu_domain = dom;
3272 dom->geometry.aperture_start = 0;
3273 dom->geometry.aperture_end = ~0ULL;
3274 dom->geometry.force_aperture = true;
3279 protection_domain_free(domain);
3284 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
3286 struct protection_domain *domain = dom->priv;
3291 if (domain->dev_cnt > 0)
3292 cleanup_domain(domain);
3294 BUG_ON(domain->dev_cnt != 0);
3296 if (domain->mode != PAGE_MODE_NONE)
3297 free_pagetable(domain);
3299 if (domain->flags & PD_IOMMUV2_MASK)
3300 free_gcr3_table(domain);
3302 protection_domain_free(domain);
3307 static void amd_iommu_detach_device(struct iommu_domain *dom,
3310 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3311 struct amd_iommu *iommu;
3314 if (!check_device(dev))
3317 devid = get_device_id(dev);
3319 if (dev_data->domain != NULL)
3322 iommu = amd_iommu_rlookup_table[devid];
3326 iommu_completion_wait(iommu);
3329 static int amd_iommu_attach_device(struct iommu_domain *dom,
3332 struct protection_domain *domain = dom->priv;
3333 struct iommu_dev_data *dev_data;
3334 struct amd_iommu *iommu;
3337 if (!check_device(dev))
3340 dev_data = dev->archdata.iommu;
3342 iommu = amd_iommu_rlookup_table[dev_data->devid];
3346 if (dev_data->domain)
3349 ret = attach_device(dev, domain);
3351 iommu_completion_wait(iommu);
3356 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3357 phys_addr_t paddr, size_t page_size, int iommu_prot)
3359 struct protection_domain *domain = dom->priv;
3363 if (domain->mode == PAGE_MODE_NONE)
3366 if (iommu_prot & IOMMU_READ)
3367 prot |= IOMMU_PROT_IR;
3368 if (iommu_prot & IOMMU_WRITE)
3369 prot |= IOMMU_PROT_IW;
3371 mutex_lock(&domain->api_lock);
3372 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3373 mutex_unlock(&domain->api_lock);
3378 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3381 struct protection_domain *domain = dom->priv;
3384 if (domain->mode == PAGE_MODE_NONE)
3387 mutex_lock(&domain->api_lock);
3388 unmap_size = iommu_unmap_page(domain, iova, page_size);
3389 mutex_unlock(&domain->api_lock);
3391 domain_flush_tlb_pde(domain);
3396 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3399 struct protection_domain *domain = dom->priv;
3400 unsigned long offset_mask;
3404 if (domain->mode == PAGE_MODE_NONE)
3407 pte = fetch_pte(domain, iova);
3409 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3412 if (PM_PTE_LEVEL(*pte) == 0)
3413 offset_mask = PAGE_SIZE - 1;
3415 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
3417 __pte = *pte & PM_ADDR_MASK;
3418 paddr = (__pte & ~offset_mask) | (iova & offset_mask);
3423 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
3427 case IOMMU_CAP_CACHE_COHERENCY:
3429 case IOMMU_CAP_INTR_REMAP:
3430 return irq_remapping_enabled;
3436 static struct iommu_ops amd_iommu_ops = {
3437 .domain_init = amd_iommu_domain_init,
3438 .domain_destroy = amd_iommu_domain_destroy,
3439 .attach_dev = amd_iommu_attach_device,
3440 .detach_dev = amd_iommu_detach_device,
3441 .map = amd_iommu_map,
3442 .unmap = amd_iommu_unmap,
3443 .iova_to_phys = amd_iommu_iova_to_phys,
3444 .domain_has_cap = amd_iommu_domain_has_cap,
3445 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3448 /*****************************************************************************
3450 * The next functions do a basic initialization of IOMMU for pass through
3453 * In passthrough mode the IOMMU is initialized and enabled but not used for
3454 * DMA-API translation.
3456 *****************************************************************************/
3458 int __init amd_iommu_init_passthrough(void)
3460 struct iommu_dev_data *dev_data;
3461 struct pci_dev *dev = NULL;
3462 struct amd_iommu *iommu;
3466 ret = alloc_passthrough_domain();
3470 for_each_pci_dev(dev) {
3471 if (!check_device(&dev->dev))
3474 dev_data = get_dev_data(&dev->dev);
3475 dev_data->passthrough = true;
3477 devid = get_device_id(&dev->dev);
3479 iommu = amd_iommu_rlookup_table[devid];
3483 attach_device(&dev->dev, pt_domain);
3486 amd_iommu_stats_init();
3488 pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
3493 /* IOMMUv2 specific functions */
3494 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3496 return atomic_notifier_chain_register(&ppr_notifier, nb);
3498 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3500 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3502 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3504 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3506 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3508 struct protection_domain *domain = dom->priv;
3509 unsigned long flags;
3511 spin_lock_irqsave(&domain->lock, flags);
3513 /* Update data structure */
3514 domain->mode = PAGE_MODE_NONE;
3515 domain->updated = true;
3517 /* Make changes visible to IOMMUs */
3518 update_domain(domain);
3520 /* Page-table is not visible to IOMMU anymore, so free it */
3521 free_pagetable(domain);
3523 spin_unlock_irqrestore(&domain->lock, flags);
3525 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3527 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3529 struct protection_domain *domain = dom->priv;
3530 unsigned long flags;
3533 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3536 /* Number of GCR3 table levels required */
3537 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3540 if (levels > amd_iommu_max_glx_val)
3543 spin_lock_irqsave(&domain->lock, flags);
3546 * Save us all sanity checks whether devices already in the
3547 * domain support IOMMUv2. Just force that the domain has no
3548 * devices attached when it is switched into IOMMUv2 mode.
3551 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3555 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3556 if (domain->gcr3_tbl == NULL)
3559 domain->glx = levels;
3560 domain->flags |= PD_IOMMUV2_MASK;
3561 domain->updated = true;
3563 update_domain(domain);
3568 spin_unlock_irqrestore(&domain->lock, flags);
3572 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3574 static int __flush_pasid(struct protection_domain *domain, int pasid,
3575 u64 address, bool size)
3577 struct iommu_dev_data *dev_data;
3578 struct iommu_cmd cmd;
3581 if (!(domain->flags & PD_IOMMUV2_MASK))
3584 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3587 * IOMMU TLB needs to be flushed before Device TLB to
3588 * prevent device TLB refill from IOMMU TLB
3590 for (i = 0; i < amd_iommus_present; ++i) {
3591 if (domain->dev_iommu[i] == 0)
3594 ret = iommu_queue_command(amd_iommus[i], &cmd);
3599 /* Wait until IOMMU TLB flushes are complete */
3600 domain_flush_complete(domain);
3602 /* Now flush device TLBs */
3603 list_for_each_entry(dev_data, &domain->dev_list, list) {
3604 struct amd_iommu *iommu;
3607 BUG_ON(!dev_data->ats.enabled);
3609 qdep = dev_data->ats.qdep;
3610 iommu = amd_iommu_rlookup_table[dev_data->devid];
3612 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3613 qdep, address, size);
3615 ret = iommu_queue_command(iommu, &cmd);
3620 /* Wait until all device TLBs are flushed */
3621 domain_flush_complete(domain);
3630 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3633 INC_STATS_COUNTER(invalidate_iotlb);
3635 return __flush_pasid(domain, pasid, address, false);
3638 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3641 struct protection_domain *domain = dom->priv;
3642 unsigned long flags;
3645 spin_lock_irqsave(&domain->lock, flags);
3646 ret = __amd_iommu_flush_page(domain, pasid, address);
3647 spin_unlock_irqrestore(&domain->lock, flags);
3651 EXPORT_SYMBOL(amd_iommu_flush_page);
3653 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3655 INC_STATS_COUNTER(invalidate_iotlb_all);
3657 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3661 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3663 struct protection_domain *domain = dom->priv;
3664 unsigned long flags;
3667 spin_lock_irqsave(&domain->lock, flags);
3668 ret = __amd_iommu_flush_tlb(domain, pasid);
3669 spin_unlock_irqrestore(&domain->lock, flags);
3673 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3675 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3682 index = (pasid >> (9 * level)) & 0x1ff;
3688 if (!(*pte & GCR3_VALID)) {
3692 root = (void *)get_zeroed_page(GFP_ATOMIC);
3696 *pte = __pa(root) | GCR3_VALID;
3699 root = __va(*pte & PAGE_MASK);
3707 static int __set_gcr3(struct protection_domain *domain, int pasid,
3712 if (domain->mode != PAGE_MODE_NONE)
3715 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3719 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3721 return __amd_iommu_flush_tlb(domain, pasid);
3724 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3728 if (domain->mode != PAGE_MODE_NONE)
3731 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3737 return __amd_iommu_flush_tlb(domain, pasid);
3740 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3743 struct protection_domain *domain = dom->priv;
3744 unsigned long flags;
3747 spin_lock_irqsave(&domain->lock, flags);
3748 ret = __set_gcr3(domain, pasid, cr3);
3749 spin_unlock_irqrestore(&domain->lock, flags);
3753 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3755 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3757 struct protection_domain *domain = dom->priv;
3758 unsigned long flags;
3761 spin_lock_irqsave(&domain->lock, flags);
3762 ret = __clear_gcr3(domain, pasid);
3763 spin_unlock_irqrestore(&domain->lock, flags);
3767 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3769 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3770 int status, int tag)
3772 struct iommu_dev_data *dev_data;
3773 struct amd_iommu *iommu;
3774 struct iommu_cmd cmd;
3776 INC_STATS_COUNTER(complete_ppr);
3778 dev_data = get_dev_data(&pdev->dev);
3779 iommu = amd_iommu_rlookup_table[dev_data->devid];
3781 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3782 tag, dev_data->pri_tlp);
3784 return iommu_queue_command(iommu, &cmd);
3786 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3788 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3790 struct protection_domain *domain;
3792 domain = get_domain(&pdev->dev);
3796 /* Only return IOMMUv2 domains */
3797 if (!(domain->flags & PD_IOMMUV2_MASK))
3800 return domain->iommu_domain;
3802 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3804 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3806 struct iommu_dev_data *dev_data;
3808 if (!amd_iommu_v2_supported())
3811 dev_data = get_dev_data(&pdev->dev);
3812 dev_data->errata |= (1 << erratum);
3814 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3816 int amd_iommu_device_info(struct pci_dev *pdev,
3817 struct amd_iommu_device_info *info)
3822 if (pdev == NULL || info == NULL)
3825 if (!amd_iommu_v2_supported())
3828 memset(info, 0, sizeof(*info));
3830 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3832 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3834 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3836 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3838 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3842 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3843 max_pasids = min(max_pasids, (1 << 20));
3845 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3846 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3848 features = pci_pasid_features(pdev);
3849 if (features & PCI_PASID_CAP_EXEC)
3850 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3851 if (features & PCI_PASID_CAP_PRIV)
3852 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3857 EXPORT_SYMBOL(amd_iommu_device_info);
3859 #ifdef CONFIG_IRQ_REMAP
3861 /*****************************************************************************
3863 * Interrupt Remapping Implementation
3865 *****************************************************************************/
3882 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3883 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3884 #define DTE_IRQ_TABLE_LEN (8ULL << 1)
3885 #define DTE_IRQ_REMAP_ENABLE 1ULL
3887 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3891 dte = amd_iommu_dev_table[devid].data[2];
3892 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3893 dte |= virt_to_phys(table->table);
3894 dte |= DTE_IRQ_REMAP_INTCTL;
3895 dte |= DTE_IRQ_TABLE_LEN;
3896 dte |= DTE_IRQ_REMAP_ENABLE;
3898 amd_iommu_dev_table[devid].data[2] = dte;
3901 #define IRTE_ALLOCATED (~1U)
3903 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3905 struct irq_remap_table *table = NULL;
3906 struct amd_iommu *iommu;
3907 unsigned long flags;
3910 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3912 iommu = amd_iommu_rlookup_table[devid];
3916 table = irq_lookup_table[devid];
3920 alias = amd_iommu_alias_table[devid];
3921 table = irq_lookup_table[alias];
3923 irq_lookup_table[devid] = table;
3924 set_dte_irq_entry(devid, table);
3925 iommu_flush_dte(iommu, devid);
3929 /* Nothing there yet, allocate new irq remapping table */
3930 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3934 /* Initialize table spin-lock */
3935 spin_lock_init(&table->lock);
3938 /* Keep the first 32 indexes free for IOAPIC interrupts */
3939 table->min_index = 32;
3941 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3942 if (!table->table) {
3948 memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3953 for (i = 0; i < 32; ++i)
3954 table->table[i] = IRTE_ALLOCATED;
3957 irq_lookup_table[devid] = table;
3958 set_dte_irq_entry(devid, table);
3959 iommu_flush_dte(iommu, devid);
3960 if (devid != alias) {
3961 irq_lookup_table[alias] = table;
3962 set_dte_irq_entry(alias, table);
3963 iommu_flush_dte(iommu, alias);
3967 iommu_completion_wait(iommu);
3970 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3975 static int alloc_irq_index(struct irq_cfg *cfg, u16 devid, int count)
3977 struct irq_remap_table *table;
3978 unsigned long flags;
3981 table = get_irq_table(devid, false);
3985 spin_lock_irqsave(&table->lock, flags);
3987 /* Scan table for free entries */
3988 for (c = 0, index = table->min_index;
3989 index < MAX_IRQS_PER_TABLE;
3991 if (table->table[index] == 0)
3997 struct irq_2_irte *irte_info;
4000 table->table[index - c + 1] = IRTE_ALLOCATED;
4005 irte_info = &cfg->irq_2_irte;
4006 irte_info->devid = devid;
4007 irte_info->index = index;
4016 spin_unlock_irqrestore(&table->lock, flags);
4021 static int get_irte(u16 devid, int index, union irte *irte)
4023 struct irq_remap_table *table;
4024 unsigned long flags;
4026 table = get_irq_table(devid, false);
4030 spin_lock_irqsave(&table->lock, flags);
4031 irte->val = table->table[index];
4032 spin_unlock_irqrestore(&table->lock, flags);
4037 static int modify_irte(u16 devid, int index, union irte irte)
4039 struct irq_remap_table *table;
4040 struct amd_iommu *iommu;
4041 unsigned long flags;
4043 iommu = amd_iommu_rlookup_table[devid];
4047 table = get_irq_table(devid, false);
4051 spin_lock_irqsave(&table->lock, flags);
4052 table->table[index] = irte.val;
4053 spin_unlock_irqrestore(&table->lock, flags);
4055 iommu_flush_irt(iommu, devid);
4056 iommu_completion_wait(iommu);
4061 static void free_irte(u16 devid, int index)
4063 struct irq_remap_table *table;
4064 struct amd_iommu *iommu;
4065 unsigned long flags;
4067 iommu = amd_iommu_rlookup_table[devid];
4071 table = get_irq_table(devid, false);
4075 spin_lock_irqsave(&table->lock, flags);
4076 table->table[index] = 0;
4077 spin_unlock_irqrestore(&table->lock, flags);
4079 iommu_flush_irt(iommu, devid);
4080 iommu_completion_wait(iommu);
4083 static int setup_ioapic_entry(int irq, struct IO_APIC_route_entry *entry,
4084 unsigned int destination, int vector,
4085 struct io_apic_irq_attr *attr)
4087 struct irq_remap_table *table;
4088 struct irq_2_irte *irte_info;
4089 struct irq_cfg *cfg;
4096 cfg = irq_get_chip_data(irq);
4100 irte_info = &cfg->irq_2_irte;
4101 ioapic_id = mpc_ioapic_id(attr->ioapic);
4102 devid = get_ioapic_devid(ioapic_id);
4107 table = get_irq_table(devid, true);
4111 index = attr->ioapic_pin;
4113 /* Setup IRQ remapping info */
4115 irte_info->devid = devid;
4116 irte_info->index = index;
4118 /* Setup IRTE for IOMMU */
4120 irte.fields.vector = vector;
4121 irte.fields.int_type = apic->irq_delivery_mode;
4122 irte.fields.destination = destination;
4123 irte.fields.dm = apic->irq_dest_mode;
4124 irte.fields.valid = 1;
4126 ret = modify_irte(devid, index, irte);
4130 /* Setup IOAPIC entry */
4131 memset(entry, 0, sizeof(*entry));
4133 entry->vector = index;
4135 entry->trigger = attr->trigger;
4136 entry->polarity = attr->polarity;
4139 * Mask level triggered irqs.
4147 static int set_affinity(struct irq_data *data, const struct cpumask *mask,
4150 struct irq_2_irte *irte_info;
4151 unsigned int dest, irq;
4152 struct irq_cfg *cfg;
4156 if (!config_enabled(CONFIG_SMP))
4159 cfg = data->chip_data;
4161 irte_info = &cfg->irq_2_irte;
4163 if (!cpumask_intersects(mask, cpu_online_mask))
4166 if (get_irte(irte_info->devid, irte_info->index, &irte))
4169 if (assign_irq_vector(irq, cfg, mask))
4172 err = apic->cpu_mask_to_apicid_and(cfg->domain, mask, &dest);
4174 if (assign_irq_vector(irq, cfg, data->affinity))
4175 pr_err("AMD-Vi: Failed to recover vector for irq %d\n", irq);
4179 irte.fields.vector = cfg->vector;
4180 irte.fields.destination = dest;
4182 modify_irte(irte_info->devid, irte_info->index, irte);
4184 if (cfg->move_in_progress)
4185 send_cleanup_vector(cfg);
4187 cpumask_copy(data->affinity, mask);
4192 static int free_irq(int irq)
4194 struct irq_2_irte *irte_info;
4195 struct irq_cfg *cfg;
4197 cfg = irq_get_chip_data(irq);
4201 irte_info = &cfg->irq_2_irte;
4203 free_irte(irte_info->devid, irte_info->index);
4208 static void compose_msi_msg(struct pci_dev *pdev,
4209 unsigned int irq, unsigned int dest,
4210 struct msi_msg *msg, u8 hpet_id)
4212 struct irq_2_irte *irte_info;
4213 struct irq_cfg *cfg;
4216 cfg = irq_get_chip_data(irq);
4220 irte_info = &cfg->irq_2_irte;
4223 irte.fields.vector = cfg->vector;
4224 irte.fields.int_type = apic->irq_delivery_mode;
4225 irte.fields.destination = dest;
4226 irte.fields.dm = apic->irq_dest_mode;
4227 irte.fields.valid = 1;
4229 modify_irte(irte_info->devid, irte_info->index, irte);
4231 msg->address_hi = MSI_ADDR_BASE_HI;
4232 msg->address_lo = MSI_ADDR_BASE_LO;
4233 msg->data = irte_info->index;
4236 static int msi_alloc_irq(struct pci_dev *pdev, int irq, int nvec)
4238 struct irq_cfg *cfg;
4245 cfg = irq_get_chip_data(irq);
4249 devid = get_device_id(&pdev->dev);
4250 index = alloc_irq_index(cfg, devid, nvec);
4252 return index < 0 ? MAX_IRQS_PER_TABLE : index;
4255 static int msi_setup_irq(struct pci_dev *pdev, unsigned int irq,
4256 int index, int offset)
4258 struct irq_2_irte *irte_info;
4259 struct irq_cfg *cfg;
4265 cfg = irq_get_chip_data(irq);
4269 if (index >= MAX_IRQS_PER_TABLE)
4272 devid = get_device_id(&pdev->dev);
4273 irte_info = &cfg->irq_2_irte;
4276 irte_info->devid = devid;
4277 irte_info->index = index + offset;
4282 static int setup_hpet_msi(unsigned int irq, unsigned int id)
4284 struct irq_2_irte *irte_info;
4285 struct irq_cfg *cfg;
4288 cfg = irq_get_chip_data(irq);
4292 irte_info = &cfg->irq_2_irte;
4293 devid = get_hpet_devid(id);
4297 index = alloc_irq_index(cfg, devid, 1);
4302 irte_info->devid = devid;
4303 irte_info->index = index;
4308 struct irq_remap_ops amd_iommu_irq_ops = {
4309 .supported = amd_iommu_supported,
4310 .prepare = amd_iommu_prepare,
4311 .enable = amd_iommu_enable,
4312 .disable = amd_iommu_disable,
4313 .reenable = amd_iommu_reenable,
4314 .enable_faulting = amd_iommu_enable_faulting,
4315 .setup_ioapic_entry = setup_ioapic_entry,
4316 .set_affinity = set_affinity,
4317 .free_irq = free_irq,
4318 .compose_msi_msg = compose_msi_msg,
4319 .msi_alloc_irq = msi_alloc_irq,
4320 .msi_setup_irq = msi_setup_irq,
4321 .setup_hpet_msi = setup_hpet_msi,