x86/speculation/mds: Fix documentation typo
[linux/fpc-iii.git] / drivers / iommu / amd_iommu.c
blob684f7cdd814b64350b01632a0aa77a2427e8879e
1 /*
2 * Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
3 * Author: Joerg Roedel <jroedel@suse.de>
4 * Leo Duran <leo.duran@amd.com>
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 as published
8 * by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 #include <linux/ratelimit.h>
21 #include <linux/pci.h>
22 #include <linux/acpi.h>
23 #include <linux/amba/bus.h>
24 #include <linux/platform_device.h>
25 #include <linux/pci-ats.h>
26 #include <linux/bitmap.h>
27 #include <linux/slab.h>
28 #include <linux/debugfs.h>
29 #include <linux/scatterlist.h>
30 #include <linux/dma-mapping.h>
31 #include <linux/iommu-helper.h>
32 #include <linux/iommu.h>
33 #include <linux/delay.h>
34 #include <linux/amd-iommu.h>
35 #include <linux/notifier.h>
36 #include <linux/export.h>
37 #include <linux/irq.h>
38 #include <linux/msi.h>
39 #include <linux/dma-contiguous.h>
40 #include <linux/irqdomain.h>
41 #include <linux/percpu.h>
42 #include <linux/iova.h>
43 #include <asm/irq_remapping.h>
44 #include <asm/io_apic.h>
45 #include <asm/apic.h>
46 #include <asm/hw_irq.h>
47 #include <asm/msidef.h>
48 #include <asm/proto.h>
49 #include <asm/iommu.h>
50 #include <asm/gart.h>
51 #include <asm/dma.h>
53 #include "amd_iommu_proto.h"
54 #include "amd_iommu_types.h"
55 #include "irq_remapping.h"
57 #define AMD_IOMMU_MAPPING_ERROR 0
59 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
61 #define LOOP_TIMEOUT 100000
63 /* IO virtual address start page frame number */
64 #define IOVA_START_PFN (1)
65 #define IOVA_PFN(addr) ((addr) >> PAGE_SHIFT)
66 #define DMA_32BIT_PFN IOVA_PFN(DMA_BIT_MASK(32))
68 /* Reserved IOVA ranges */
69 #define MSI_RANGE_START (0xfee00000)
70 #define MSI_RANGE_END (0xfeefffff)
71 #define HT_RANGE_START (0xfd00000000ULL)
72 #define HT_RANGE_END (0xffffffffffULL)
75 * This bitmap is used to advertise the page sizes our hardware support
76 * to the IOMMU core, which will then use this information to split
77 * physically contiguous memory regions it is mapping into page sizes
78 * that we support.
80 * 512GB Pages are not supported due to a hardware bug
82 #define AMD_IOMMU_PGSIZES ((~0xFFFUL) & ~(2ULL << 38))
84 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
86 /* List of all available dev_data structures */
87 static LIST_HEAD(dev_data_list);
88 static DEFINE_SPINLOCK(dev_data_list_lock);
90 LIST_HEAD(ioapic_map);
91 LIST_HEAD(hpet_map);
92 LIST_HEAD(acpihid_map);
95 * Domain for untranslated devices - only allocated
96 * if iommu=pt passed on kernel cmd line.
98 const struct iommu_ops amd_iommu_ops;
100 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
101 int amd_iommu_max_glx_val = -1;
103 static const struct dma_map_ops amd_iommu_dma_ops;
106 * general struct to manage commands send to an IOMMU
108 struct iommu_cmd {
109 u32 data[4];
112 struct kmem_cache *amd_iommu_irq_cache;
114 static void update_domain(struct protection_domain *domain);
115 static int protection_domain_init(struct protection_domain *domain);
116 static void detach_device(struct device *dev);
117 static void iova_domain_flush_tlb(struct iova_domain *iovad);
120 * Data container for a dma_ops specific protection domain
122 struct dma_ops_domain {
123 /* generic protection domain information */
124 struct protection_domain domain;
126 /* IOVA RB-Tree */
127 struct iova_domain iovad;
130 static struct iova_domain reserved_iova_ranges;
131 static struct lock_class_key reserved_rbtree_key;
133 /****************************************************************************
135 * Helper functions
137 ****************************************************************************/
139 static inline int match_hid_uid(struct device *dev,
140 struct acpihid_map_entry *entry)
142 const char *hid, *uid;
144 hid = acpi_device_hid(ACPI_COMPANION(dev));
145 uid = acpi_device_uid(ACPI_COMPANION(dev));
147 if (!hid || !(*hid))
148 return -ENODEV;
150 if (!uid || !(*uid))
151 return strcmp(hid, entry->hid);
153 if (!(*entry->uid))
154 return strcmp(hid, entry->hid);
156 return (strcmp(hid, entry->hid) || strcmp(uid, entry->uid));
159 static inline u16 get_pci_device_id(struct device *dev)
161 struct pci_dev *pdev = to_pci_dev(dev);
163 return PCI_DEVID(pdev->bus->number, pdev->devfn);
166 static inline int get_acpihid_device_id(struct device *dev,
167 struct acpihid_map_entry **entry)
169 struct acpihid_map_entry *p;
171 list_for_each_entry(p, &acpihid_map, list) {
172 if (!match_hid_uid(dev, p)) {
173 if (entry)
174 *entry = p;
175 return p->devid;
178 return -EINVAL;
181 static inline int get_device_id(struct device *dev)
183 int devid;
185 if (dev_is_pci(dev))
186 devid = get_pci_device_id(dev);
187 else
188 devid = get_acpihid_device_id(dev, NULL);
190 return devid;
193 static struct protection_domain *to_pdomain(struct iommu_domain *dom)
195 return container_of(dom, struct protection_domain, domain);
198 static struct dma_ops_domain* to_dma_ops_domain(struct protection_domain *domain)
200 BUG_ON(domain->flags != PD_DMA_OPS_MASK);
201 return container_of(domain, struct dma_ops_domain, domain);
204 static struct iommu_dev_data *alloc_dev_data(u16 devid)
206 struct iommu_dev_data *dev_data;
207 unsigned long flags;
209 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
210 if (!dev_data)
211 return NULL;
213 dev_data->devid = devid;
215 spin_lock_irqsave(&dev_data_list_lock, flags);
216 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
217 spin_unlock_irqrestore(&dev_data_list_lock, flags);
219 ratelimit_default_init(&dev_data->rs);
221 return dev_data;
224 static struct iommu_dev_data *search_dev_data(u16 devid)
226 struct iommu_dev_data *dev_data;
227 unsigned long flags;
229 spin_lock_irqsave(&dev_data_list_lock, flags);
230 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
231 if (dev_data->devid == devid)
232 goto out_unlock;
235 dev_data = NULL;
237 out_unlock:
238 spin_unlock_irqrestore(&dev_data_list_lock, flags);
240 return dev_data;
243 static int __last_alias(struct pci_dev *pdev, u16 alias, void *data)
245 *(u16 *)data = alias;
246 return 0;
249 static u16 get_alias(struct device *dev)
251 struct pci_dev *pdev = to_pci_dev(dev);
252 u16 devid, ivrs_alias, pci_alias;
254 /* The callers make sure that get_device_id() does not fail here */
255 devid = get_device_id(dev);
257 /* For ACPI HID devices, we simply return the devid as such */
258 if (!dev_is_pci(dev))
259 return devid;
261 ivrs_alias = amd_iommu_alias_table[devid];
263 pci_for_each_dma_alias(pdev, __last_alias, &pci_alias);
265 if (ivrs_alias == pci_alias)
266 return ivrs_alias;
269 * DMA alias showdown
271 * The IVRS is fairly reliable in telling us about aliases, but it
272 * can't know about every screwy device. If we don't have an IVRS
273 * reported alias, use the PCI reported alias. In that case we may
274 * still need to initialize the rlookup and dev_table entries if the
275 * alias is to a non-existent device.
277 if (ivrs_alias == devid) {
278 if (!amd_iommu_rlookup_table[pci_alias]) {
279 amd_iommu_rlookup_table[pci_alias] =
280 amd_iommu_rlookup_table[devid];
281 memcpy(amd_iommu_dev_table[pci_alias].data,
282 amd_iommu_dev_table[devid].data,
283 sizeof(amd_iommu_dev_table[pci_alias].data));
286 return pci_alias;
289 pr_info("AMD-Vi: Using IVRS reported alias %02x:%02x.%d "
290 "for device %s[%04x:%04x], kernel reported alias "
291 "%02x:%02x.%d\n", PCI_BUS_NUM(ivrs_alias), PCI_SLOT(ivrs_alias),
292 PCI_FUNC(ivrs_alias), dev_name(dev), pdev->vendor, pdev->device,
293 PCI_BUS_NUM(pci_alias), PCI_SLOT(pci_alias),
294 PCI_FUNC(pci_alias));
297 * If we don't have a PCI DMA alias and the IVRS alias is on the same
298 * bus, then the IVRS table may know about a quirk that we don't.
300 if (pci_alias == devid &&
301 PCI_BUS_NUM(ivrs_alias) == pdev->bus->number) {
302 pci_add_dma_alias(pdev, ivrs_alias & 0xff);
303 pr_info("AMD-Vi: Added PCI DMA alias %02x.%d for %s\n",
304 PCI_SLOT(ivrs_alias), PCI_FUNC(ivrs_alias),
305 dev_name(dev));
308 return ivrs_alias;
311 static struct iommu_dev_data *find_dev_data(u16 devid)
313 struct iommu_dev_data *dev_data;
314 struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
316 dev_data = search_dev_data(devid);
318 if (dev_data == NULL) {
319 dev_data = alloc_dev_data(devid);
320 if (!dev_data)
321 return NULL;
323 if (translation_pre_enabled(iommu))
324 dev_data->defer_attach = true;
327 return dev_data;
330 struct iommu_dev_data *get_dev_data(struct device *dev)
332 return dev->archdata.iommu;
334 EXPORT_SYMBOL(get_dev_data);
337 * Find or create an IOMMU group for a acpihid device.
339 static struct iommu_group *acpihid_device_group(struct device *dev)
341 struct acpihid_map_entry *p, *entry = NULL;
342 int devid;
344 devid = get_acpihid_device_id(dev, &entry);
345 if (devid < 0)
346 return ERR_PTR(devid);
348 list_for_each_entry(p, &acpihid_map, list) {
349 if ((devid == p->devid) && p->group)
350 entry->group = p->group;
353 if (!entry->group)
354 entry->group = generic_device_group(dev);
355 else
356 iommu_group_ref_get(entry->group);
358 return entry->group;
361 static bool pci_iommuv2_capable(struct pci_dev *pdev)
363 static const int caps[] = {
364 PCI_EXT_CAP_ID_ATS,
365 PCI_EXT_CAP_ID_PRI,
366 PCI_EXT_CAP_ID_PASID,
368 int i, pos;
370 for (i = 0; i < 3; ++i) {
371 pos = pci_find_ext_capability(pdev, caps[i]);
372 if (pos == 0)
373 return false;
376 return true;
379 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
381 struct iommu_dev_data *dev_data;
383 dev_data = get_dev_data(&pdev->dev);
385 return dev_data->errata & (1 << erratum) ? true : false;
389 * This function checks if the driver got a valid device from the caller to
390 * avoid dereferencing invalid pointers.
392 static bool check_device(struct device *dev)
394 int devid;
396 if (!dev || !dev->dma_mask)
397 return false;
399 devid = get_device_id(dev);
400 if (devid < 0)
401 return false;
403 /* Out of our scope? */
404 if (devid > amd_iommu_last_bdf)
405 return false;
407 if (amd_iommu_rlookup_table[devid] == NULL)
408 return false;
410 return true;
413 static void init_iommu_group(struct device *dev)
415 struct iommu_group *group;
417 group = iommu_group_get_for_dev(dev);
418 if (IS_ERR(group))
419 return;
421 iommu_group_put(group);
424 static int iommu_init_device(struct device *dev)
426 struct iommu_dev_data *dev_data;
427 struct amd_iommu *iommu;
428 int devid;
430 if (dev->archdata.iommu)
431 return 0;
433 devid = get_device_id(dev);
434 if (devid < 0)
435 return devid;
437 iommu = amd_iommu_rlookup_table[devid];
439 dev_data = find_dev_data(devid);
440 if (!dev_data)
441 return -ENOMEM;
443 dev_data->alias = get_alias(dev);
446 * By default we use passthrough mode for IOMMUv2 capable device.
447 * But if amd_iommu=force_isolation is set (e.g. to debug DMA to
448 * invalid address), we ignore the capability for the device so
449 * it'll be forced to go into translation mode.
451 if ((iommu_pass_through || !amd_iommu_force_isolation) &&
452 dev_is_pci(dev) && pci_iommuv2_capable(to_pci_dev(dev))) {
453 struct amd_iommu *iommu;
455 iommu = amd_iommu_rlookup_table[dev_data->devid];
456 dev_data->iommu_v2 = iommu->is_iommu_v2;
459 dev->archdata.iommu = dev_data;
461 iommu_device_link(&iommu->iommu, dev);
463 return 0;
466 static void iommu_ignore_device(struct device *dev)
468 u16 alias;
469 int devid;
471 devid = get_device_id(dev);
472 if (devid < 0)
473 return;
475 alias = get_alias(dev);
477 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
478 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
480 amd_iommu_rlookup_table[devid] = NULL;
481 amd_iommu_rlookup_table[alias] = NULL;
484 static void iommu_uninit_device(struct device *dev)
486 struct iommu_dev_data *dev_data;
487 struct amd_iommu *iommu;
488 int devid;
490 devid = get_device_id(dev);
491 if (devid < 0)
492 return;
494 iommu = amd_iommu_rlookup_table[devid];
496 dev_data = search_dev_data(devid);
497 if (!dev_data)
498 return;
500 if (dev_data->domain)
501 detach_device(dev);
503 iommu_device_unlink(&iommu->iommu, dev);
505 iommu_group_remove_device(dev);
507 /* Remove dma-ops */
508 dev->dma_ops = NULL;
511 * We keep dev_data around for unplugged devices and reuse it when the
512 * device is re-plugged - not doing so would introduce a ton of races.
516 /****************************************************************************
518 * Interrupt handling functions
520 ****************************************************************************/
522 static void dump_dte_entry(u16 devid)
524 int i;
526 for (i = 0; i < 4; ++i)
527 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
528 amd_iommu_dev_table[devid].data[i]);
531 static void dump_command(unsigned long phys_addr)
533 struct iommu_cmd *cmd = iommu_phys_to_virt(phys_addr);
534 int i;
536 for (i = 0; i < 4; ++i)
537 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
540 static void amd_iommu_report_page_fault(u16 devid, u16 domain_id,
541 u64 address, int flags)
543 struct iommu_dev_data *dev_data = NULL;
544 struct pci_dev *pdev;
546 pdev = pci_get_bus_and_slot(PCI_BUS_NUM(devid), devid & 0xff);
547 if (pdev)
548 dev_data = get_dev_data(&pdev->dev);
550 if (dev_data && __ratelimit(&dev_data->rs)) {
551 dev_err(&pdev->dev, "AMD-Vi: Event logged [IO_PAGE_FAULT domain=0x%04x address=0x%016llx flags=0x%04x]\n",
552 domain_id, address, flags);
553 } else if (printk_ratelimit()) {
554 pr_err("AMD-Vi: Event logged [IO_PAGE_FAULT device=%02x:%02x.%x domain=0x%04x address=0x%016llx flags=0x%04x]\n",
555 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
556 domain_id, address, flags);
559 if (pdev)
560 pci_dev_put(pdev);
563 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
565 int type, devid, domid, flags;
566 volatile u32 *event = __evt;
567 int count = 0;
568 u64 address;
570 retry:
571 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
572 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
573 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
574 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
575 address = (u64)(((u64)event[3]) << 32) | event[2];
577 if (type == 0) {
578 /* Did we hit the erratum? */
579 if (++count == LOOP_TIMEOUT) {
580 pr_err("AMD-Vi: No event written to event log\n");
581 return;
583 udelay(1);
584 goto retry;
587 if (type == EVENT_TYPE_IO_FAULT) {
588 amd_iommu_report_page_fault(devid, domid, address, flags);
589 return;
590 } else {
591 printk(KERN_ERR "AMD-Vi: Event logged [");
594 switch (type) {
595 case EVENT_TYPE_ILL_DEV:
596 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
597 "address=0x%016llx flags=0x%04x]\n",
598 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
599 address, flags);
600 dump_dte_entry(devid);
601 break;
602 case EVENT_TYPE_DEV_TAB_ERR:
603 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
604 "address=0x%016llx flags=0x%04x]\n",
605 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
606 address, flags);
607 break;
608 case EVENT_TYPE_PAGE_TAB_ERR:
609 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
610 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
611 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
612 domid, address, flags);
613 break;
614 case EVENT_TYPE_ILL_CMD:
615 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
616 dump_command(address);
617 break;
618 case EVENT_TYPE_CMD_HARD_ERR:
619 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
620 "flags=0x%04x]\n", address, flags);
621 break;
622 case EVENT_TYPE_IOTLB_INV_TO:
623 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
624 "address=0x%016llx]\n",
625 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
626 address);
627 break;
628 case EVENT_TYPE_INV_DEV_REQ:
629 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
630 "address=0x%016llx flags=0x%04x]\n",
631 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
632 address, flags);
633 break;
634 default:
635 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
638 memset(__evt, 0, 4 * sizeof(u32));
641 static void iommu_poll_events(struct amd_iommu *iommu)
643 u32 head, tail;
645 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
646 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
648 while (head != tail) {
649 iommu_print_event(iommu, iommu->evt_buf + head);
650 head = (head + EVENT_ENTRY_SIZE) % EVT_BUFFER_SIZE;
653 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
656 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
658 struct amd_iommu_fault fault;
660 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
661 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
662 return;
665 fault.address = raw[1];
666 fault.pasid = PPR_PASID(raw[0]);
667 fault.device_id = PPR_DEVID(raw[0]);
668 fault.tag = PPR_TAG(raw[0]);
669 fault.flags = PPR_FLAGS(raw[0]);
671 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
674 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
676 u32 head, tail;
678 if (iommu->ppr_log == NULL)
679 return;
681 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
682 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
684 while (head != tail) {
685 volatile u64 *raw;
686 u64 entry[2];
687 int i;
689 raw = (u64 *)(iommu->ppr_log + head);
692 * Hardware bug: Interrupt may arrive before the entry is
693 * written to memory. If this happens we need to wait for the
694 * entry to arrive.
696 for (i = 0; i < LOOP_TIMEOUT; ++i) {
697 if (PPR_REQ_TYPE(raw[0]) != 0)
698 break;
699 udelay(1);
702 /* Avoid memcpy function-call overhead */
703 entry[0] = raw[0];
704 entry[1] = raw[1];
707 * To detect the hardware bug we need to clear the entry
708 * back to zero.
710 raw[0] = raw[1] = 0UL;
712 /* Update head pointer of hardware ring-buffer */
713 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
714 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
716 /* Handle PPR entry */
717 iommu_handle_ppr_entry(iommu, entry);
719 /* Refresh ring-buffer information */
720 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
721 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
725 #ifdef CONFIG_IRQ_REMAP
726 static int (*iommu_ga_log_notifier)(u32);
728 int amd_iommu_register_ga_log_notifier(int (*notifier)(u32))
730 iommu_ga_log_notifier = notifier;
732 return 0;
734 EXPORT_SYMBOL(amd_iommu_register_ga_log_notifier);
736 static void iommu_poll_ga_log(struct amd_iommu *iommu)
738 u32 head, tail, cnt = 0;
740 if (iommu->ga_log == NULL)
741 return;
743 head = readl(iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
744 tail = readl(iommu->mmio_base + MMIO_GA_TAIL_OFFSET);
746 while (head != tail) {
747 volatile u64 *raw;
748 u64 log_entry;
750 raw = (u64 *)(iommu->ga_log + head);
751 cnt++;
753 /* Avoid memcpy function-call overhead */
754 log_entry = *raw;
756 /* Update head pointer of hardware ring-buffer */
757 head = (head + GA_ENTRY_SIZE) % GA_LOG_SIZE;
758 writel(head, iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
760 /* Handle GA entry */
761 switch (GA_REQ_TYPE(log_entry)) {
762 case GA_GUEST_NR:
763 if (!iommu_ga_log_notifier)
764 break;
766 pr_debug("AMD-Vi: %s: devid=%#x, ga_tag=%#x\n",
767 __func__, GA_DEVID(log_entry),
768 GA_TAG(log_entry));
770 if (iommu_ga_log_notifier(GA_TAG(log_entry)) != 0)
771 pr_err("AMD-Vi: GA log notifier failed.\n");
772 break;
773 default:
774 break;
778 #endif /* CONFIG_IRQ_REMAP */
780 #define AMD_IOMMU_INT_MASK \
781 (MMIO_STATUS_EVT_INT_MASK | \
782 MMIO_STATUS_PPR_INT_MASK | \
783 MMIO_STATUS_GALOG_INT_MASK)
785 irqreturn_t amd_iommu_int_thread(int irq, void *data)
787 struct amd_iommu *iommu = (struct amd_iommu *) data;
788 u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
790 while (status & AMD_IOMMU_INT_MASK) {
791 /* Enable EVT and PPR and GA interrupts again */
792 writel(AMD_IOMMU_INT_MASK,
793 iommu->mmio_base + MMIO_STATUS_OFFSET);
795 if (status & MMIO_STATUS_EVT_INT_MASK) {
796 pr_devel("AMD-Vi: Processing IOMMU Event Log\n");
797 iommu_poll_events(iommu);
800 if (status & MMIO_STATUS_PPR_INT_MASK) {
801 pr_devel("AMD-Vi: Processing IOMMU PPR Log\n");
802 iommu_poll_ppr_log(iommu);
805 #ifdef CONFIG_IRQ_REMAP
806 if (status & MMIO_STATUS_GALOG_INT_MASK) {
807 pr_devel("AMD-Vi: Processing IOMMU GA Log\n");
808 iommu_poll_ga_log(iommu);
810 #endif
813 * Hardware bug: ERBT1312
814 * When re-enabling interrupt (by writing 1
815 * to clear the bit), the hardware might also try to set
816 * the interrupt bit in the event status register.
817 * In this scenario, the bit will be set, and disable
818 * subsequent interrupts.
820 * Workaround: The IOMMU driver should read back the
821 * status register and check if the interrupt bits are cleared.
822 * If not, driver will need to go through the interrupt handler
823 * again and re-clear the bits
825 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
827 return IRQ_HANDLED;
830 irqreturn_t amd_iommu_int_handler(int irq, void *data)
832 return IRQ_WAKE_THREAD;
835 /****************************************************************************
837 * IOMMU command queuing functions
839 ****************************************************************************/
841 static int wait_on_sem(volatile u64 *sem)
843 int i = 0;
845 while (*sem == 0 && i < LOOP_TIMEOUT) {
846 udelay(1);
847 i += 1;
850 if (i == LOOP_TIMEOUT) {
851 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
852 return -EIO;
855 return 0;
858 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
859 struct iommu_cmd *cmd)
861 u8 *target;
863 target = iommu->cmd_buf + iommu->cmd_buf_tail;
865 iommu->cmd_buf_tail += sizeof(*cmd);
866 iommu->cmd_buf_tail %= CMD_BUFFER_SIZE;
868 /* Copy command to buffer */
869 memcpy(target, cmd, sizeof(*cmd));
871 /* Tell the IOMMU about it */
872 writel(iommu->cmd_buf_tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
875 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
877 u64 paddr = iommu_virt_to_phys((void *)address);
879 WARN_ON(address & 0x7ULL);
881 memset(cmd, 0, sizeof(*cmd));
882 cmd->data[0] = lower_32_bits(paddr) | CMD_COMPL_WAIT_STORE_MASK;
883 cmd->data[1] = upper_32_bits(paddr);
884 cmd->data[2] = 1;
885 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
888 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
890 memset(cmd, 0, sizeof(*cmd));
891 cmd->data[0] = devid;
892 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
895 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
896 size_t size, u16 domid, int pde)
898 u64 pages;
899 bool s;
901 pages = iommu_num_pages(address, size, PAGE_SIZE);
902 s = false;
904 if (pages > 1) {
906 * If we have to flush more than one page, flush all
907 * TLB entries for this domain
909 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
910 s = true;
913 address &= PAGE_MASK;
915 memset(cmd, 0, sizeof(*cmd));
916 cmd->data[1] |= domid;
917 cmd->data[2] = lower_32_bits(address);
918 cmd->data[3] = upper_32_bits(address);
919 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
920 if (s) /* size bit - we flush more than one 4kb page */
921 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
922 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
923 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
926 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
927 u64 address, size_t size)
929 u64 pages;
930 bool s;
932 pages = iommu_num_pages(address, size, PAGE_SIZE);
933 s = false;
935 if (pages > 1) {
937 * If we have to flush more than one page, flush all
938 * TLB entries for this domain
940 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
941 s = true;
944 address &= PAGE_MASK;
946 memset(cmd, 0, sizeof(*cmd));
947 cmd->data[0] = devid;
948 cmd->data[0] |= (qdep & 0xff) << 24;
949 cmd->data[1] = devid;
950 cmd->data[2] = lower_32_bits(address);
951 cmd->data[3] = upper_32_bits(address);
952 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
953 if (s)
954 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
957 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
958 u64 address, bool size)
960 memset(cmd, 0, sizeof(*cmd));
962 address &= ~(0xfffULL);
964 cmd->data[0] = pasid;
965 cmd->data[1] = domid;
966 cmd->data[2] = lower_32_bits(address);
967 cmd->data[3] = upper_32_bits(address);
968 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
969 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
970 if (size)
971 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
972 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
975 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
976 int qdep, u64 address, bool size)
978 memset(cmd, 0, sizeof(*cmd));
980 address &= ~(0xfffULL);
982 cmd->data[0] = devid;
983 cmd->data[0] |= ((pasid >> 8) & 0xff) << 16;
984 cmd->data[0] |= (qdep & 0xff) << 24;
985 cmd->data[1] = devid;
986 cmd->data[1] |= (pasid & 0xff) << 16;
987 cmd->data[2] = lower_32_bits(address);
988 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
989 cmd->data[3] = upper_32_bits(address);
990 if (size)
991 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
992 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
995 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
996 int status, int tag, bool gn)
998 memset(cmd, 0, sizeof(*cmd));
1000 cmd->data[0] = devid;
1001 if (gn) {
1002 cmd->data[1] = pasid;
1003 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
1005 cmd->data[3] = tag & 0x1ff;
1006 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
1008 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
1011 static void build_inv_all(struct iommu_cmd *cmd)
1013 memset(cmd, 0, sizeof(*cmd));
1014 CMD_SET_TYPE(cmd, CMD_INV_ALL);
1017 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
1019 memset(cmd, 0, sizeof(*cmd));
1020 cmd->data[0] = devid;
1021 CMD_SET_TYPE(cmd, CMD_INV_IRT);
1025 * Writes the command to the IOMMUs command buffer and informs the
1026 * hardware about the new command.
1028 static int __iommu_queue_command_sync(struct amd_iommu *iommu,
1029 struct iommu_cmd *cmd,
1030 bool sync)
1032 unsigned int count = 0;
1033 u32 left, next_tail;
1035 next_tail = (iommu->cmd_buf_tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
1036 again:
1037 left = (iommu->cmd_buf_head - next_tail) % CMD_BUFFER_SIZE;
1039 if (left <= 0x20) {
1040 /* Skip udelay() the first time around */
1041 if (count++) {
1042 if (count == LOOP_TIMEOUT) {
1043 pr_err("AMD-Vi: Command buffer timeout\n");
1044 return -EIO;
1047 udelay(1);
1050 /* Update head and recheck remaining space */
1051 iommu->cmd_buf_head = readl(iommu->mmio_base +
1052 MMIO_CMD_HEAD_OFFSET);
1054 goto again;
1057 copy_cmd_to_buffer(iommu, cmd);
1059 /* Do we need to make sure all commands are processed? */
1060 iommu->need_sync = sync;
1062 return 0;
1065 static int iommu_queue_command_sync(struct amd_iommu *iommu,
1066 struct iommu_cmd *cmd,
1067 bool sync)
1069 unsigned long flags;
1070 int ret;
1072 spin_lock_irqsave(&iommu->lock, flags);
1073 ret = __iommu_queue_command_sync(iommu, cmd, sync);
1074 spin_unlock_irqrestore(&iommu->lock, flags);
1076 return ret;
1079 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
1081 return iommu_queue_command_sync(iommu, cmd, true);
1085 * This function queues a completion wait command into the command
1086 * buffer of an IOMMU
1088 static int iommu_completion_wait(struct amd_iommu *iommu)
1090 struct iommu_cmd cmd;
1091 unsigned long flags;
1092 int ret;
1094 if (!iommu->need_sync)
1095 return 0;
1098 build_completion_wait(&cmd, (u64)&iommu->cmd_sem);
1100 spin_lock_irqsave(&iommu->lock, flags);
1102 iommu->cmd_sem = 0;
1104 ret = __iommu_queue_command_sync(iommu, &cmd, false);
1105 if (ret)
1106 goto out_unlock;
1108 ret = wait_on_sem(&iommu->cmd_sem);
1110 out_unlock:
1111 spin_unlock_irqrestore(&iommu->lock, flags);
1113 return ret;
1116 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1118 struct iommu_cmd cmd;
1120 build_inv_dte(&cmd, devid);
1122 return iommu_queue_command(iommu, &cmd);
1125 static void amd_iommu_flush_dte_all(struct amd_iommu *iommu)
1127 u32 devid;
1129 for (devid = 0; devid <= 0xffff; ++devid)
1130 iommu_flush_dte(iommu, devid);
1132 iommu_completion_wait(iommu);
1136 * This function uses heavy locking and may disable irqs for some time. But
1137 * this is no issue because it is only called during resume.
1139 static void amd_iommu_flush_tlb_all(struct amd_iommu *iommu)
1141 u32 dom_id;
1143 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1144 struct iommu_cmd cmd;
1145 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1146 dom_id, 1);
1147 iommu_queue_command(iommu, &cmd);
1150 iommu_completion_wait(iommu);
1153 static void amd_iommu_flush_all(struct amd_iommu *iommu)
1155 struct iommu_cmd cmd;
1157 build_inv_all(&cmd);
1159 iommu_queue_command(iommu, &cmd);
1160 iommu_completion_wait(iommu);
1163 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1165 struct iommu_cmd cmd;
1167 build_inv_irt(&cmd, devid);
1169 iommu_queue_command(iommu, &cmd);
1172 static void amd_iommu_flush_irt_all(struct amd_iommu *iommu)
1174 u32 devid;
1176 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1177 iommu_flush_irt(iommu, devid);
1179 iommu_completion_wait(iommu);
1182 void iommu_flush_all_caches(struct amd_iommu *iommu)
1184 if (iommu_feature(iommu, FEATURE_IA)) {
1185 amd_iommu_flush_all(iommu);
1186 } else {
1187 amd_iommu_flush_dte_all(iommu);
1188 amd_iommu_flush_irt_all(iommu);
1189 amd_iommu_flush_tlb_all(iommu);
1194 * Command send function for flushing on-device TLB
1196 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1197 u64 address, size_t size)
1199 struct amd_iommu *iommu;
1200 struct iommu_cmd cmd;
1201 int qdep;
1203 qdep = dev_data->ats.qdep;
1204 iommu = amd_iommu_rlookup_table[dev_data->devid];
1206 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1208 return iommu_queue_command(iommu, &cmd);
1212 * Command send function for invalidating a device table entry
1214 static int device_flush_dte(struct iommu_dev_data *dev_data)
1216 struct amd_iommu *iommu;
1217 u16 alias;
1218 int ret;
1220 iommu = amd_iommu_rlookup_table[dev_data->devid];
1221 alias = dev_data->alias;
1223 ret = iommu_flush_dte(iommu, dev_data->devid);
1224 if (!ret && alias != dev_data->devid)
1225 ret = iommu_flush_dte(iommu, alias);
1226 if (ret)
1227 return ret;
1229 if (dev_data->ats.enabled)
1230 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1232 return ret;
1236 * TLB invalidation function which is called from the mapping functions.
1237 * It invalidates a single PTE if the range to flush is within a single
1238 * page. Otherwise it flushes the whole TLB of the IOMMU.
1240 static void __domain_flush_pages(struct protection_domain *domain,
1241 u64 address, size_t size, int pde)
1243 struct iommu_dev_data *dev_data;
1244 struct iommu_cmd cmd;
1245 int ret = 0, i;
1247 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1249 for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
1250 if (!domain->dev_iommu[i])
1251 continue;
1254 * Devices of this domain are behind this IOMMU
1255 * We need a TLB flush
1257 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1260 list_for_each_entry(dev_data, &domain->dev_list, list) {
1262 if (!dev_data->ats.enabled)
1263 continue;
1265 ret |= device_flush_iotlb(dev_data, address, size);
1268 WARN_ON(ret);
1271 static void domain_flush_pages(struct protection_domain *domain,
1272 u64 address, size_t size)
1274 __domain_flush_pages(domain, address, size, 0);
1277 /* Flush the whole IO/TLB for a given protection domain */
1278 static void domain_flush_tlb(struct protection_domain *domain)
1280 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1283 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1284 static void domain_flush_tlb_pde(struct protection_domain *domain)
1286 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1289 static void domain_flush_complete(struct protection_domain *domain)
1291 int i;
1293 for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
1294 if (domain && !domain->dev_iommu[i])
1295 continue;
1298 * Devices of this domain are behind this IOMMU
1299 * We need to wait for completion of all commands.
1301 iommu_completion_wait(amd_iommus[i]);
1307 * This function flushes the DTEs for all devices in domain
1309 static void domain_flush_devices(struct protection_domain *domain)
1311 struct iommu_dev_data *dev_data;
1313 list_for_each_entry(dev_data, &domain->dev_list, list)
1314 device_flush_dte(dev_data);
1317 /****************************************************************************
1319 * The functions below are used the create the page table mappings for
1320 * unity mapped regions.
1322 ****************************************************************************/
1325 * This function is used to add another level to an IO page table. Adding
1326 * another level increases the size of the address space by 9 bits to a size up
1327 * to 64 bits.
1329 static bool increase_address_space(struct protection_domain *domain,
1330 gfp_t gfp)
1332 u64 *pte;
1334 if (domain->mode == PAGE_MODE_6_LEVEL)
1335 /* address space already 64 bit large */
1336 return false;
1338 pte = (void *)get_zeroed_page(gfp);
1339 if (!pte)
1340 return false;
1342 *pte = PM_LEVEL_PDE(domain->mode,
1343 iommu_virt_to_phys(domain->pt_root));
1344 domain->pt_root = pte;
1345 domain->mode += 1;
1346 domain->updated = true;
1348 return true;
1351 static u64 *alloc_pte(struct protection_domain *domain,
1352 unsigned long address,
1353 unsigned long page_size,
1354 u64 **pte_page,
1355 gfp_t gfp)
1357 int level, end_lvl;
1358 u64 *pte, *page;
1360 BUG_ON(!is_power_of_2(page_size));
1362 while (address > PM_LEVEL_SIZE(domain->mode))
1363 increase_address_space(domain, gfp);
1365 level = domain->mode - 1;
1366 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1367 address = PAGE_SIZE_ALIGN(address, page_size);
1368 end_lvl = PAGE_SIZE_LEVEL(page_size);
1370 while (level > end_lvl) {
1371 u64 __pte, __npte;
1373 __pte = *pte;
1375 if (!IOMMU_PTE_PRESENT(__pte)) {
1376 page = (u64 *)get_zeroed_page(gfp);
1377 if (!page)
1378 return NULL;
1380 __npte = PM_LEVEL_PDE(level, iommu_virt_to_phys(page));
1382 /* pte could have been changed somewhere. */
1383 if (cmpxchg64(pte, __pte, __npte) != __pte) {
1384 free_page((unsigned long)page);
1385 continue;
1389 /* No level skipping support yet */
1390 if (PM_PTE_LEVEL(*pte) != level)
1391 return NULL;
1393 level -= 1;
1395 pte = IOMMU_PTE_PAGE(*pte);
1397 if (pte_page && level == end_lvl)
1398 *pte_page = pte;
1400 pte = &pte[PM_LEVEL_INDEX(level, address)];
1403 return pte;
1407 * This function checks if there is a PTE for a given dma address. If
1408 * there is one, it returns the pointer to it.
1410 static u64 *fetch_pte(struct protection_domain *domain,
1411 unsigned long address,
1412 unsigned long *page_size)
1414 int level;
1415 u64 *pte;
1417 if (address > PM_LEVEL_SIZE(domain->mode))
1418 return NULL;
1420 level = domain->mode - 1;
1421 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1422 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1424 while (level > 0) {
1426 /* Not Present */
1427 if (!IOMMU_PTE_PRESENT(*pte))
1428 return NULL;
1430 /* Large PTE */
1431 if (PM_PTE_LEVEL(*pte) == 7 ||
1432 PM_PTE_LEVEL(*pte) == 0)
1433 break;
1435 /* No level skipping support yet */
1436 if (PM_PTE_LEVEL(*pte) != level)
1437 return NULL;
1439 level -= 1;
1441 /* Walk to the next level */
1442 pte = IOMMU_PTE_PAGE(*pte);
1443 pte = &pte[PM_LEVEL_INDEX(level, address)];
1444 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1447 if (PM_PTE_LEVEL(*pte) == 0x07) {
1448 unsigned long pte_mask;
1451 * If we have a series of large PTEs, make
1452 * sure to return a pointer to the first one.
1454 *page_size = pte_mask = PTE_PAGE_SIZE(*pte);
1455 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1456 pte = (u64 *)(((unsigned long)pte) & pte_mask);
1459 return pte;
1463 * Generic mapping functions. It maps a physical address into a DMA
1464 * address space. It allocates the page table pages if necessary.
1465 * In the future it can be extended to a generic mapping function
1466 * supporting all features of AMD IOMMU page tables like level skipping
1467 * and full 64 bit address spaces.
1469 static int iommu_map_page(struct protection_domain *dom,
1470 unsigned long bus_addr,
1471 unsigned long phys_addr,
1472 unsigned long page_size,
1473 int prot,
1474 gfp_t gfp)
1476 u64 __pte, *pte;
1477 int i, count;
1479 BUG_ON(!IS_ALIGNED(bus_addr, page_size));
1480 BUG_ON(!IS_ALIGNED(phys_addr, page_size));
1482 if (!(prot & IOMMU_PROT_MASK))
1483 return -EINVAL;
1485 count = PAGE_SIZE_PTE_COUNT(page_size);
1486 pte = alloc_pte(dom, bus_addr, page_size, NULL, gfp);
1488 if (!pte)
1489 return -ENOMEM;
1491 for (i = 0; i < count; ++i)
1492 if (IOMMU_PTE_PRESENT(pte[i]))
1493 return -EBUSY;
1495 if (count > 1) {
1496 __pte = PAGE_SIZE_PTE(__sme_set(phys_addr), page_size);
1497 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_PR | IOMMU_PTE_FC;
1498 } else
1499 __pte = __sme_set(phys_addr) | IOMMU_PTE_PR | IOMMU_PTE_FC;
1501 if (prot & IOMMU_PROT_IR)
1502 __pte |= IOMMU_PTE_IR;
1503 if (prot & IOMMU_PROT_IW)
1504 __pte |= IOMMU_PTE_IW;
1506 for (i = 0; i < count; ++i)
1507 pte[i] = __pte;
1509 update_domain(dom);
1511 return 0;
1514 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1515 unsigned long bus_addr,
1516 unsigned long page_size)
1518 unsigned long long unmapped;
1519 unsigned long unmap_size;
1520 u64 *pte;
1522 BUG_ON(!is_power_of_2(page_size));
1524 unmapped = 0;
1526 while (unmapped < page_size) {
1528 pte = fetch_pte(dom, bus_addr, &unmap_size);
1530 if (pte) {
1531 int i, count;
1533 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1534 for (i = 0; i < count; i++)
1535 pte[i] = 0ULL;
1538 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1539 unmapped += unmap_size;
1542 BUG_ON(unmapped && !is_power_of_2(unmapped));
1544 return unmapped;
1547 /****************************************************************************
1549 * The next functions belong to the address allocator for the dma_ops
1550 * interface functions.
1552 ****************************************************************************/
1555 static unsigned long dma_ops_alloc_iova(struct device *dev,
1556 struct dma_ops_domain *dma_dom,
1557 unsigned int pages, u64 dma_mask)
1559 unsigned long pfn = 0;
1561 pages = __roundup_pow_of_two(pages);
1563 if (dma_mask > DMA_BIT_MASK(32))
1564 pfn = alloc_iova_fast(&dma_dom->iovad, pages,
1565 IOVA_PFN(DMA_BIT_MASK(32)));
1567 if (!pfn)
1568 pfn = alloc_iova_fast(&dma_dom->iovad, pages, IOVA_PFN(dma_mask));
1570 return (pfn << PAGE_SHIFT);
1573 static void dma_ops_free_iova(struct dma_ops_domain *dma_dom,
1574 unsigned long address,
1575 unsigned int pages)
1577 pages = __roundup_pow_of_two(pages);
1578 address >>= PAGE_SHIFT;
1580 free_iova_fast(&dma_dom->iovad, address, pages);
1583 /****************************************************************************
1585 * The next functions belong to the domain allocation. A domain is
1586 * allocated for every IOMMU as the default domain. If device isolation
1587 * is enabled, every device get its own domain. The most important thing
1588 * about domains is the page table mapping the DMA address space they
1589 * contain.
1591 ****************************************************************************/
1594 * This function adds a protection domain to the global protection domain list
1596 static void add_domain_to_list(struct protection_domain *domain)
1598 unsigned long flags;
1600 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1601 list_add(&domain->list, &amd_iommu_pd_list);
1602 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1606 * This function removes a protection domain to the global
1607 * protection domain list
1609 static void del_domain_from_list(struct protection_domain *domain)
1611 unsigned long flags;
1613 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1614 list_del(&domain->list);
1615 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1618 static u16 domain_id_alloc(void)
1620 unsigned long flags;
1621 int id;
1623 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1624 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1625 BUG_ON(id == 0);
1626 if (id > 0 && id < MAX_DOMAIN_ID)
1627 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1628 else
1629 id = 0;
1630 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1632 return id;
1635 static void domain_id_free(int id)
1637 unsigned long flags;
1639 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1640 if (id > 0 && id < MAX_DOMAIN_ID)
1641 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1642 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1645 #define DEFINE_FREE_PT_FN(LVL, FN) \
1646 static void free_pt_##LVL (unsigned long __pt) \
1648 unsigned long p; \
1649 u64 *pt; \
1650 int i; \
1652 pt = (u64 *)__pt; \
1654 for (i = 0; i < 512; ++i) { \
1655 /* PTE present? */ \
1656 if (!IOMMU_PTE_PRESENT(pt[i])) \
1657 continue; \
1659 /* Large PTE? */ \
1660 if (PM_PTE_LEVEL(pt[i]) == 0 || \
1661 PM_PTE_LEVEL(pt[i]) == 7) \
1662 continue; \
1664 p = (unsigned long)IOMMU_PTE_PAGE(pt[i]); \
1665 FN(p); \
1667 free_page((unsigned long)pt); \
1670 DEFINE_FREE_PT_FN(l2, free_page)
1671 DEFINE_FREE_PT_FN(l3, free_pt_l2)
1672 DEFINE_FREE_PT_FN(l4, free_pt_l3)
1673 DEFINE_FREE_PT_FN(l5, free_pt_l4)
1674 DEFINE_FREE_PT_FN(l6, free_pt_l5)
1676 static void free_pagetable(struct protection_domain *domain)
1678 unsigned long root = (unsigned long)domain->pt_root;
1680 switch (domain->mode) {
1681 case PAGE_MODE_NONE:
1682 break;
1683 case PAGE_MODE_1_LEVEL:
1684 free_page(root);
1685 break;
1686 case PAGE_MODE_2_LEVEL:
1687 free_pt_l2(root);
1688 break;
1689 case PAGE_MODE_3_LEVEL:
1690 free_pt_l3(root);
1691 break;
1692 case PAGE_MODE_4_LEVEL:
1693 free_pt_l4(root);
1694 break;
1695 case PAGE_MODE_5_LEVEL:
1696 free_pt_l5(root);
1697 break;
1698 case PAGE_MODE_6_LEVEL:
1699 free_pt_l6(root);
1700 break;
1701 default:
1702 BUG();
1706 static void free_gcr3_tbl_level1(u64 *tbl)
1708 u64 *ptr;
1709 int i;
1711 for (i = 0; i < 512; ++i) {
1712 if (!(tbl[i] & GCR3_VALID))
1713 continue;
1715 ptr = iommu_phys_to_virt(tbl[i] & PAGE_MASK);
1717 free_page((unsigned long)ptr);
1721 static void free_gcr3_tbl_level2(u64 *tbl)
1723 u64 *ptr;
1724 int i;
1726 for (i = 0; i < 512; ++i) {
1727 if (!(tbl[i] & GCR3_VALID))
1728 continue;
1730 ptr = iommu_phys_to_virt(tbl[i] & PAGE_MASK);
1732 free_gcr3_tbl_level1(ptr);
1736 static void free_gcr3_table(struct protection_domain *domain)
1738 if (domain->glx == 2)
1739 free_gcr3_tbl_level2(domain->gcr3_tbl);
1740 else if (domain->glx == 1)
1741 free_gcr3_tbl_level1(domain->gcr3_tbl);
1742 else
1743 BUG_ON(domain->glx != 0);
1745 free_page((unsigned long)domain->gcr3_tbl);
1748 static void dma_ops_domain_flush_tlb(struct dma_ops_domain *dom)
1750 domain_flush_tlb(&dom->domain);
1751 domain_flush_complete(&dom->domain);
1754 static void iova_domain_flush_tlb(struct iova_domain *iovad)
1756 struct dma_ops_domain *dom;
1758 dom = container_of(iovad, struct dma_ops_domain, iovad);
1760 dma_ops_domain_flush_tlb(dom);
1764 * Free a domain, only used if something went wrong in the
1765 * allocation path and we need to free an already allocated page table
1767 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1769 if (!dom)
1770 return;
1772 del_domain_from_list(&dom->domain);
1774 put_iova_domain(&dom->iovad);
1776 free_pagetable(&dom->domain);
1778 if (dom->domain.id)
1779 domain_id_free(dom->domain.id);
1781 kfree(dom);
1785 * Allocates a new protection domain usable for the dma_ops functions.
1786 * It also initializes the page table and the address allocator data
1787 * structures required for the dma_ops interface
1789 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1791 struct dma_ops_domain *dma_dom;
1793 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1794 if (!dma_dom)
1795 return NULL;
1797 if (protection_domain_init(&dma_dom->domain))
1798 goto free_dma_dom;
1800 dma_dom->domain.mode = PAGE_MODE_3_LEVEL;
1801 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1802 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1803 if (!dma_dom->domain.pt_root)
1804 goto free_dma_dom;
1806 init_iova_domain(&dma_dom->iovad, PAGE_SIZE,
1807 IOVA_START_PFN, DMA_32BIT_PFN);
1809 if (init_iova_flush_queue(&dma_dom->iovad, iova_domain_flush_tlb, NULL))
1810 goto free_dma_dom;
1812 /* Initialize reserved ranges */
1813 copy_reserved_iova(&reserved_iova_ranges, &dma_dom->iovad);
1815 add_domain_to_list(&dma_dom->domain);
1817 return dma_dom;
1819 free_dma_dom:
1820 dma_ops_domain_free(dma_dom);
1822 return NULL;
1826 * little helper function to check whether a given protection domain is a
1827 * dma_ops domain
1829 static bool dma_ops_domain(struct protection_domain *domain)
1831 return domain->flags & PD_DMA_OPS_MASK;
1834 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1836 u64 pte_root = 0;
1837 u64 flags = 0;
1839 if (domain->mode != PAGE_MODE_NONE)
1840 pte_root = iommu_virt_to_phys(domain->pt_root);
1842 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1843 << DEV_ENTRY_MODE_SHIFT;
1844 pte_root |= DTE_FLAG_IR | DTE_FLAG_IW | DTE_FLAG_V | DTE_FLAG_TV;
1846 flags = amd_iommu_dev_table[devid].data[1];
1848 if (ats)
1849 flags |= DTE_FLAG_IOTLB;
1851 if (domain->flags & PD_IOMMUV2_MASK) {
1852 u64 gcr3 = iommu_virt_to_phys(domain->gcr3_tbl);
1853 u64 glx = domain->glx;
1854 u64 tmp;
1856 pte_root |= DTE_FLAG_GV;
1857 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1859 /* First mask out possible old values for GCR3 table */
1860 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1861 flags &= ~tmp;
1863 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1864 flags &= ~tmp;
1866 /* Encode GCR3 table into DTE */
1867 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1868 pte_root |= tmp;
1870 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1871 flags |= tmp;
1873 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
1874 flags |= tmp;
1877 flags &= ~DEV_DOMID_MASK;
1878 flags |= domain->id;
1880 amd_iommu_dev_table[devid].data[1] = flags;
1881 amd_iommu_dev_table[devid].data[0] = pte_root;
1884 static void clear_dte_entry(u16 devid)
1886 /* remove entry from the device table seen by the hardware */
1887 amd_iommu_dev_table[devid].data[0] = DTE_FLAG_V | DTE_FLAG_TV;
1888 amd_iommu_dev_table[devid].data[1] &= DTE_FLAG_MASK;
1890 amd_iommu_apply_erratum_63(devid);
1893 static void do_attach(struct iommu_dev_data *dev_data,
1894 struct protection_domain *domain)
1896 struct amd_iommu *iommu;
1897 u16 alias;
1898 bool ats;
1900 iommu = amd_iommu_rlookup_table[dev_data->devid];
1901 alias = dev_data->alias;
1902 ats = dev_data->ats.enabled;
1904 /* Update data structures */
1905 dev_data->domain = domain;
1906 list_add(&dev_data->list, &domain->dev_list);
1908 /* Do reference counting */
1909 domain->dev_iommu[iommu->index] += 1;
1910 domain->dev_cnt += 1;
1912 /* Update device table */
1913 set_dte_entry(dev_data->devid, domain, ats);
1914 if (alias != dev_data->devid)
1915 set_dte_entry(alias, domain, ats);
1917 device_flush_dte(dev_data);
1920 static void do_detach(struct iommu_dev_data *dev_data)
1922 struct protection_domain *domain = dev_data->domain;
1923 struct amd_iommu *iommu;
1924 u16 alias;
1927 * First check if the device is still attached. It might already
1928 * be detached from its domain because the generic
1929 * iommu_detach_group code detached it and we try again here in
1930 * our alias handling.
1932 if (!dev_data->domain)
1933 return;
1935 iommu = amd_iommu_rlookup_table[dev_data->devid];
1936 alias = dev_data->alias;
1938 /* Update data structures */
1939 dev_data->domain = NULL;
1940 list_del(&dev_data->list);
1941 clear_dte_entry(dev_data->devid);
1942 if (alias != dev_data->devid)
1943 clear_dte_entry(alias);
1945 /* Flush the DTE entry */
1946 device_flush_dte(dev_data);
1948 /* Flush IOTLB */
1949 domain_flush_tlb_pde(domain);
1951 /* Wait for the flushes to finish */
1952 domain_flush_complete(domain);
1954 /* decrease reference counters - needs to happen after the flushes */
1955 domain->dev_iommu[iommu->index] -= 1;
1956 domain->dev_cnt -= 1;
1960 * If a device is not yet associated with a domain, this function does
1961 * assigns it visible for the hardware
1963 static int __attach_device(struct iommu_dev_data *dev_data,
1964 struct protection_domain *domain)
1966 int ret;
1969 * Must be called with IRQs disabled. Warn here to detect early
1970 * when its not.
1972 WARN_ON(!irqs_disabled());
1974 /* lock domain */
1975 spin_lock(&domain->lock);
1977 ret = -EBUSY;
1978 if (dev_data->domain != NULL)
1979 goto out_unlock;
1981 /* Attach alias group root */
1982 do_attach(dev_data, domain);
1984 ret = 0;
1986 out_unlock:
1988 /* ready */
1989 spin_unlock(&domain->lock);
1991 return ret;
1995 static void pdev_iommuv2_disable(struct pci_dev *pdev)
1997 pci_disable_ats(pdev);
1998 pci_disable_pri(pdev);
1999 pci_disable_pasid(pdev);
2002 /* FIXME: Change generic reset-function to do the same */
2003 static int pri_reset_while_enabled(struct pci_dev *pdev)
2005 u16 control;
2006 int pos;
2008 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2009 if (!pos)
2010 return -EINVAL;
2012 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2013 control |= PCI_PRI_CTRL_RESET;
2014 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2016 return 0;
2019 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2021 bool reset_enable;
2022 int reqs, ret;
2024 /* FIXME: Hardcode number of outstanding requests for now */
2025 reqs = 32;
2026 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2027 reqs = 1;
2028 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2030 /* Only allow access to user-accessible pages */
2031 ret = pci_enable_pasid(pdev, 0);
2032 if (ret)
2033 goto out_err;
2035 /* First reset the PRI state of the device */
2036 ret = pci_reset_pri(pdev);
2037 if (ret)
2038 goto out_err;
2040 /* Enable PRI */
2041 ret = pci_enable_pri(pdev, reqs);
2042 if (ret)
2043 goto out_err;
2045 if (reset_enable) {
2046 ret = pri_reset_while_enabled(pdev);
2047 if (ret)
2048 goto out_err;
2051 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2052 if (ret)
2053 goto out_err;
2055 return 0;
2057 out_err:
2058 pci_disable_pri(pdev);
2059 pci_disable_pasid(pdev);
2061 return ret;
2064 /* FIXME: Move this to PCI code */
2065 #define PCI_PRI_TLP_OFF (1 << 15)
2067 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2069 u16 status;
2070 int pos;
2072 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2073 if (!pos)
2074 return false;
2076 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2078 return (status & PCI_PRI_TLP_OFF) ? true : false;
2082 * If a device is not yet associated with a domain, this function
2083 * assigns it visible for the hardware
2085 static int attach_device(struct device *dev,
2086 struct protection_domain *domain)
2088 struct pci_dev *pdev;
2089 struct iommu_dev_data *dev_data;
2090 unsigned long flags;
2091 int ret;
2093 dev_data = get_dev_data(dev);
2095 if (!dev_is_pci(dev))
2096 goto skip_ats_check;
2098 pdev = to_pci_dev(dev);
2099 if (domain->flags & PD_IOMMUV2_MASK) {
2100 if (!dev_data->passthrough)
2101 return -EINVAL;
2103 if (dev_data->iommu_v2) {
2104 if (pdev_iommuv2_enable(pdev) != 0)
2105 return -EINVAL;
2107 dev_data->ats.enabled = true;
2108 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2109 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2111 } else if (amd_iommu_iotlb_sup &&
2112 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2113 dev_data->ats.enabled = true;
2114 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2117 skip_ats_check:
2118 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2119 ret = __attach_device(dev_data, domain);
2120 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2123 * We might boot into a crash-kernel here. The crashed kernel
2124 * left the caches in the IOMMU dirty. So we have to flush
2125 * here to evict all dirty stuff.
2127 domain_flush_tlb_pde(domain);
2129 return ret;
2133 * Removes a device from a protection domain (unlocked)
2135 static void __detach_device(struct iommu_dev_data *dev_data)
2137 struct protection_domain *domain;
2140 * Must be called with IRQs disabled. Warn here to detect early
2141 * when its not.
2143 WARN_ON(!irqs_disabled());
2145 if (WARN_ON(!dev_data->domain))
2146 return;
2148 domain = dev_data->domain;
2150 spin_lock(&domain->lock);
2152 do_detach(dev_data);
2154 spin_unlock(&domain->lock);
2158 * Removes a device from a protection domain (with devtable_lock held)
2160 static void detach_device(struct device *dev)
2162 struct protection_domain *domain;
2163 struct iommu_dev_data *dev_data;
2164 unsigned long flags;
2166 dev_data = get_dev_data(dev);
2167 domain = dev_data->domain;
2169 /* lock device table */
2170 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2171 __detach_device(dev_data);
2172 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2174 if (!dev_is_pci(dev))
2175 return;
2177 if (domain->flags & PD_IOMMUV2_MASK && dev_data->iommu_v2)
2178 pdev_iommuv2_disable(to_pci_dev(dev));
2179 else if (dev_data->ats.enabled)
2180 pci_disable_ats(to_pci_dev(dev));
2182 dev_data->ats.enabled = false;
2185 static int amd_iommu_add_device(struct device *dev)
2187 struct iommu_dev_data *dev_data;
2188 struct iommu_domain *domain;
2189 struct amd_iommu *iommu;
2190 int ret, devid;
2192 if (!check_device(dev) || get_dev_data(dev))
2193 return 0;
2195 devid = get_device_id(dev);
2196 if (devid < 0)
2197 return devid;
2199 iommu = amd_iommu_rlookup_table[devid];
2201 ret = iommu_init_device(dev);
2202 if (ret) {
2203 if (ret != -ENOTSUPP)
2204 pr_err("Failed to initialize device %s - trying to proceed anyway\n",
2205 dev_name(dev));
2207 iommu_ignore_device(dev);
2208 dev->dma_ops = &nommu_dma_ops;
2209 goto out;
2211 init_iommu_group(dev);
2213 dev_data = get_dev_data(dev);
2215 BUG_ON(!dev_data);
2217 if (iommu_pass_through || dev_data->iommu_v2)
2218 iommu_request_dm_for_dev(dev);
2220 /* Domains are initialized for this device - have a look what we ended up with */
2221 domain = iommu_get_domain_for_dev(dev);
2222 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2223 dev_data->passthrough = true;
2224 else
2225 dev->dma_ops = &amd_iommu_dma_ops;
2227 out:
2228 iommu_completion_wait(iommu);
2230 return 0;
2233 static void amd_iommu_remove_device(struct device *dev)
2235 struct amd_iommu *iommu;
2236 int devid;
2238 if (!check_device(dev))
2239 return;
2241 devid = get_device_id(dev);
2242 if (devid < 0)
2243 return;
2245 iommu = amd_iommu_rlookup_table[devid];
2247 iommu_uninit_device(dev);
2248 iommu_completion_wait(iommu);
2251 static struct iommu_group *amd_iommu_device_group(struct device *dev)
2253 if (dev_is_pci(dev))
2254 return pci_device_group(dev);
2256 return acpihid_device_group(dev);
2259 /*****************************************************************************
2261 * The next functions belong to the dma_ops mapping/unmapping code.
2263 *****************************************************************************/
2266 * In the dma_ops path we only have the struct device. This function
2267 * finds the corresponding IOMMU, the protection domain and the
2268 * requestor id for a given device.
2269 * If the device is not yet associated with a domain this is also done
2270 * in this function.
2272 static struct protection_domain *get_domain(struct device *dev)
2274 struct protection_domain *domain;
2275 struct iommu_domain *io_domain;
2277 if (!check_device(dev))
2278 return ERR_PTR(-EINVAL);
2280 domain = get_dev_data(dev)->domain;
2281 if (domain == NULL && get_dev_data(dev)->defer_attach) {
2282 get_dev_data(dev)->defer_attach = false;
2283 io_domain = iommu_get_domain_for_dev(dev);
2284 domain = to_pdomain(io_domain);
2285 attach_device(dev, domain);
2287 if (domain == NULL)
2288 return ERR_PTR(-EBUSY);
2290 if (!dma_ops_domain(domain))
2291 return ERR_PTR(-EBUSY);
2293 return domain;
2296 static void update_device_table(struct protection_domain *domain)
2298 struct iommu_dev_data *dev_data;
2300 list_for_each_entry(dev_data, &domain->dev_list, list) {
2301 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2303 if (dev_data->devid == dev_data->alias)
2304 continue;
2306 /* There is an alias, update device table entry for it */
2307 set_dte_entry(dev_data->alias, domain, dev_data->ats.enabled);
2311 static void update_domain(struct protection_domain *domain)
2313 if (!domain->updated)
2314 return;
2316 update_device_table(domain);
2318 domain_flush_devices(domain);
2319 domain_flush_tlb_pde(domain);
2321 domain->updated = false;
2324 static int dir2prot(enum dma_data_direction direction)
2326 if (direction == DMA_TO_DEVICE)
2327 return IOMMU_PROT_IR;
2328 else if (direction == DMA_FROM_DEVICE)
2329 return IOMMU_PROT_IW;
2330 else if (direction == DMA_BIDIRECTIONAL)
2331 return IOMMU_PROT_IW | IOMMU_PROT_IR;
2332 else
2333 return 0;
2337 * This function contains common code for mapping of a physically
2338 * contiguous memory region into DMA address space. It is used by all
2339 * mapping functions provided with this IOMMU driver.
2340 * Must be called with the domain lock held.
2342 static dma_addr_t __map_single(struct device *dev,
2343 struct dma_ops_domain *dma_dom,
2344 phys_addr_t paddr,
2345 size_t size,
2346 enum dma_data_direction direction,
2347 u64 dma_mask)
2349 dma_addr_t offset = paddr & ~PAGE_MASK;
2350 dma_addr_t address, start, ret;
2351 unsigned int pages;
2352 int prot = 0;
2353 int i;
2355 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2356 paddr &= PAGE_MASK;
2358 address = dma_ops_alloc_iova(dev, dma_dom, pages, dma_mask);
2359 if (address == AMD_IOMMU_MAPPING_ERROR)
2360 goto out;
2362 prot = dir2prot(direction);
2364 start = address;
2365 for (i = 0; i < pages; ++i) {
2366 ret = iommu_map_page(&dma_dom->domain, start, paddr,
2367 PAGE_SIZE, prot, GFP_ATOMIC);
2368 if (ret)
2369 goto out_unmap;
2371 paddr += PAGE_SIZE;
2372 start += PAGE_SIZE;
2374 address += offset;
2376 if (unlikely(amd_iommu_np_cache)) {
2377 domain_flush_pages(&dma_dom->domain, address, size);
2378 domain_flush_complete(&dma_dom->domain);
2381 out:
2382 return address;
2384 out_unmap:
2386 for (--i; i >= 0; --i) {
2387 start -= PAGE_SIZE;
2388 iommu_unmap_page(&dma_dom->domain, start, PAGE_SIZE);
2391 domain_flush_tlb(&dma_dom->domain);
2392 domain_flush_complete(&dma_dom->domain);
2394 dma_ops_free_iova(dma_dom, address, pages);
2396 return AMD_IOMMU_MAPPING_ERROR;
2400 * Does the reverse of the __map_single function. Must be called with
2401 * the domain lock held too
2403 static void __unmap_single(struct dma_ops_domain *dma_dom,
2404 dma_addr_t dma_addr,
2405 size_t size,
2406 int dir)
2408 dma_addr_t flush_addr;
2409 dma_addr_t i, start;
2410 unsigned int pages;
2412 flush_addr = dma_addr;
2413 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2414 dma_addr &= PAGE_MASK;
2415 start = dma_addr;
2417 for (i = 0; i < pages; ++i) {
2418 iommu_unmap_page(&dma_dom->domain, start, PAGE_SIZE);
2419 start += PAGE_SIZE;
2422 if (amd_iommu_unmap_flush) {
2423 domain_flush_tlb(&dma_dom->domain);
2424 domain_flush_complete(&dma_dom->domain);
2425 dma_ops_free_iova(dma_dom, dma_addr, pages);
2426 } else {
2427 pages = __roundup_pow_of_two(pages);
2428 queue_iova(&dma_dom->iovad, dma_addr >> PAGE_SHIFT, pages, 0);
2433 * The exported map_single function for dma_ops.
2435 static dma_addr_t map_page(struct device *dev, struct page *page,
2436 unsigned long offset, size_t size,
2437 enum dma_data_direction dir,
2438 unsigned long attrs)
2440 phys_addr_t paddr = page_to_phys(page) + offset;
2441 struct protection_domain *domain;
2442 struct dma_ops_domain *dma_dom;
2443 u64 dma_mask;
2445 domain = get_domain(dev);
2446 if (PTR_ERR(domain) == -EINVAL)
2447 return (dma_addr_t)paddr;
2448 else if (IS_ERR(domain))
2449 return AMD_IOMMU_MAPPING_ERROR;
2451 dma_mask = *dev->dma_mask;
2452 dma_dom = to_dma_ops_domain(domain);
2454 return __map_single(dev, dma_dom, paddr, size, dir, dma_mask);
2458 * The exported unmap_single function for dma_ops.
2460 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2461 enum dma_data_direction dir, unsigned long attrs)
2463 struct protection_domain *domain;
2464 struct dma_ops_domain *dma_dom;
2466 domain = get_domain(dev);
2467 if (IS_ERR(domain))
2468 return;
2470 dma_dom = to_dma_ops_domain(domain);
2472 __unmap_single(dma_dom, dma_addr, size, dir);
2475 static int sg_num_pages(struct device *dev,
2476 struct scatterlist *sglist,
2477 int nelems)
2479 unsigned long mask, boundary_size;
2480 struct scatterlist *s;
2481 int i, npages = 0;
2483 mask = dma_get_seg_boundary(dev);
2484 boundary_size = mask + 1 ? ALIGN(mask + 1, PAGE_SIZE) >> PAGE_SHIFT :
2485 1UL << (BITS_PER_LONG - PAGE_SHIFT);
2487 for_each_sg(sglist, s, nelems, i) {
2488 int p, n;
2490 s->dma_address = npages << PAGE_SHIFT;
2491 p = npages % boundary_size;
2492 n = iommu_num_pages(sg_phys(s), s->length, PAGE_SIZE);
2493 if (p + n > boundary_size)
2494 npages += boundary_size - p;
2495 npages += n;
2498 return npages;
2502 * The exported map_sg function for dma_ops (handles scatter-gather
2503 * lists).
2505 static int map_sg(struct device *dev, struct scatterlist *sglist,
2506 int nelems, enum dma_data_direction direction,
2507 unsigned long attrs)
2509 int mapped_pages = 0, npages = 0, prot = 0, i;
2510 struct protection_domain *domain;
2511 struct dma_ops_domain *dma_dom;
2512 struct scatterlist *s;
2513 unsigned long address;
2514 u64 dma_mask;
2516 domain = get_domain(dev);
2517 if (IS_ERR(domain))
2518 return 0;
2520 dma_dom = to_dma_ops_domain(domain);
2521 dma_mask = *dev->dma_mask;
2523 npages = sg_num_pages(dev, sglist, nelems);
2525 address = dma_ops_alloc_iova(dev, dma_dom, npages, dma_mask);
2526 if (address == AMD_IOMMU_MAPPING_ERROR)
2527 goto out_err;
2529 prot = dir2prot(direction);
2531 /* Map all sg entries */
2532 for_each_sg(sglist, s, nelems, i) {
2533 int j, pages = iommu_num_pages(sg_phys(s), s->length, PAGE_SIZE);
2535 for (j = 0; j < pages; ++j) {
2536 unsigned long bus_addr, phys_addr;
2537 int ret;
2539 bus_addr = address + s->dma_address + (j << PAGE_SHIFT);
2540 phys_addr = (sg_phys(s) & PAGE_MASK) + (j << PAGE_SHIFT);
2541 ret = iommu_map_page(domain, bus_addr, phys_addr, PAGE_SIZE, prot, GFP_ATOMIC);
2542 if (ret)
2543 goto out_unmap;
2545 mapped_pages += 1;
2549 /* Everything is mapped - write the right values into s->dma_address */
2550 for_each_sg(sglist, s, nelems, i) {
2552 * Add in the remaining piece of the scatter-gather offset that
2553 * was masked out when we were determining the physical address
2554 * via (sg_phys(s) & PAGE_MASK) earlier.
2556 s->dma_address += address + (s->offset & ~PAGE_MASK);
2557 s->dma_length = s->length;
2560 return nelems;
2562 out_unmap:
2563 pr_err("%s: IOMMU mapping error in map_sg (io-pages: %d)\n",
2564 dev_name(dev), npages);
2566 for_each_sg(sglist, s, nelems, i) {
2567 int j, pages = iommu_num_pages(sg_phys(s), s->length, PAGE_SIZE);
2569 for (j = 0; j < pages; ++j) {
2570 unsigned long bus_addr;
2572 bus_addr = address + s->dma_address + (j << PAGE_SHIFT);
2573 iommu_unmap_page(domain, bus_addr, PAGE_SIZE);
2575 if (--mapped_pages == 0)
2576 goto out_free_iova;
2580 out_free_iova:
2581 free_iova_fast(&dma_dom->iovad, address >> PAGE_SHIFT, npages);
2583 out_err:
2584 return 0;
2588 * The exported map_sg function for dma_ops (handles scatter-gather
2589 * lists).
2591 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2592 int nelems, enum dma_data_direction dir,
2593 unsigned long attrs)
2595 struct protection_domain *domain;
2596 struct dma_ops_domain *dma_dom;
2597 unsigned long startaddr;
2598 int npages = 2;
2600 domain = get_domain(dev);
2601 if (IS_ERR(domain))
2602 return;
2604 startaddr = sg_dma_address(sglist) & PAGE_MASK;
2605 dma_dom = to_dma_ops_domain(domain);
2606 npages = sg_num_pages(dev, sglist, nelems);
2608 __unmap_single(dma_dom, startaddr, npages << PAGE_SHIFT, dir);
2612 * The exported alloc_coherent function for dma_ops.
2614 static void *alloc_coherent(struct device *dev, size_t size,
2615 dma_addr_t *dma_addr, gfp_t flag,
2616 unsigned long attrs)
2618 u64 dma_mask = dev->coherent_dma_mask;
2619 struct protection_domain *domain;
2620 struct dma_ops_domain *dma_dom;
2621 struct page *page;
2623 domain = get_domain(dev);
2624 if (PTR_ERR(domain) == -EINVAL) {
2625 page = alloc_pages(flag, get_order(size));
2626 *dma_addr = page_to_phys(page);
2627 return page_address(page);
2628 } else if (IS_ERR(domain))
2629 return NULL;
2631 dma_dom = to_dma_ops_domain(domain);
2632 size = PAGE_ALIGN(size);
2633 dma_mask = dev->coherent_dma_mask;
2634 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2635 flag |= __GFP_ZERO;
2637 page = alloc_pages(flag | __GFP_NOWARN, get_order(size));
2638 if (!page) {
2639 if (!gfpflags_allow_blocking(flag))
2640 return NULL;
2642 page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
2643 get_order(size), flag);
2644 if (!page)
2645 return NULL;
2648 if (!dma_mask)
2649 dma_mask = *dev->dma_mask;
2651 *dma_addr = __map_single(dev, dma_dom, page_to_phys(page),
2652 size, DMA_BIDIRECTIONAL, dma_mask);
2654 if (*dma_addr == AMD_IOMMU_MAPPING_ERROR)
2655 goto out_free;
2657 return page_address(page);
2659 out_free:
2661 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2662 __free_pages(page, get_order(size));
2664 return NULL;
2668 * The exported free_coherent function for dma_ops.
2670 static void free_coherent(struct device *dev, size_t size,
2671 void *virt_addr, dma_addr_t dma_addr,
2672 unsigned long attrs)
2674 struct protection_domain *domain;
2675 struct dma_ops_domain *dma_dom;
2676 struct page *page;
2678 page = virt_to_page(virt_addr);
2679 size = PAGE_ALIGN(size);
2681 domain = get_domain(dev);
2682 if (IS_ERR(domain))
2683 goto free_mem;
2685 dma_dom = to_dma_ops_domain(domain);
2687 __unmap_single(dma_dom, dma_addr, size, DMA_BIDIRECTIONAL);
2689 free_mem:
2690 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2691 __free_pages(page, get_order(size));
2695 * This function is called by the DMA layer to find out if we can handle a
2696 * particular device. It is part of the dma_ops.
2698 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2700 if (!x86_dma_supported(dev, mask))
2701 return 0;
2702 return check_device(dev);
2705 static int amd_iommu_mapping_error(struct device *dev, dma_addr_t dma_addr)
2707 return dma_addr == AMD_IOMMU_MAPPING_ERROR;
2710 static const struct dma_map_ops amd_iommu_dma_ops = {
2711 .alloc = alloc_coherent,
2712 .free = free_coherent,
2713 .map_page = map_page,
2714 .unmap_page = unmap_page,
2715 .map_sg = map_sg,
2716 .unmap_sg = unmap_sg,
2717 .dma_supported = amd_iommu_dma_supported,
2718 .mapping_error = amd_iommu_mapping_error,
2721 static int init_reserved_iova_ranges(void)
2723 struct pci_dev *pdev = NULL;
2724 struct iova *val;
2726 init_iova_domain(&reserved_iova_ranges, PAGE_SIZE,
2727 IOVA_START_PFN, DMA_32BIT_PFN);
2729 lockdep_set_class(&reserved_iova_ranges.iova_rbtree_lock,
2730 &reserved_rbtree_key);
2732 /* MSI memory range */
2733 val = reserve_iova(&reserved_iova_ranges,
2734 IOVA_PFN(MSI_RANGE_START), IOVA_PFN(MSI_RANGE_END));
2735 if (!val) {
2736 pr_err("Reserving MSI range failed\n");
2737 return -ENOMEM;
2740 /* HT memory range */
2741 val = reserve_iova(&reserved_iova_ranges,
2742 IOVA_PFN(HT_RANGE_START), IOVA_PFN(HT_RANGE_END));
2743 if (!val) {
2744 pr_err("Reserving HT range failed\n");
2745 return -ENOMEM;
2749 * Memory used for PCI resources
2750 * FIXME: Check whether we can reserve the PCI-hole completly
2752 for_each_pci_dev(pdev) {
2753 int i;
2755 for (i = 0; i < PCI_NUM_RESOURCES; ++i) {
2756 struct resource *r = &pdev->resource[i];
2758 if (!(r->flags & IORESOURCE_MEM))
2759 continue;
2761 val = reserve_iova(&reserved_iova_ranges,
2762 IOVA_PFN(r->start),
2763 IOVA_PFN(r->end));
2764 if (!val) {
2765 pr_err("Reserve pci-resource range failed\n");
2766 return -ENOMEM;
2771 return 0;
2774 int __init amd_iommu_init_api(void)
2776 int ret, err = 0;
2778 ret = iova_cache_get();
2779 if (ret)
2780 return ret;
2782 ret = init_reserved_iova_ranges();
2783 if (ret)
2784 return ret;
2786 err = bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2787 if (err)
2788 return err;
2789 #ifdef CONFIG_ARM_AMBA
2790 err = bus_set_iommu(&amba_bustype, &amd_iommu_ops);
2791 if (err)
2792 return err;
2793 #endif
2794 err = bus_set_iommu(&platform_bus_type, &amd_iommu_ops);
2795 if (err)
2796 return err;
2798 return 0;
2801 int __init amd_iommu_init_dma_ops(void)
2803 swiotlb = (iommu_pass_through || sme_me_mask) ? 1 : 0;
2804 iommu_detected = 1;
2807 * In case we don't initialize SWIOTLB (actually the common case
2808 * when AMD IOMMU is enabled and SME is not active), make sure there
2809 * are global dma_ops set as a fall-back for devices not handled by
2810 * this driver (for example non-PCI devices). When SME is active,
2811 * make sure that swiotlb variable remains set so the global dma_ops
2812 * continue to be SWIOTLB.
2814 if (!swiotlb)
2815 dma_ops = &nommu_dma_ops;
2817 if (amd_iommu_unmap_flush)
2818 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
2819 else
2820 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
2822 return 0;
2826 /*****************************************************************************
2828 * The following functions belong to the exported interface of AMD IOMMU
2830 * This interface allows access to lower level functions of the IOMMU
2831 * like protection domain handling and assignement of devices to domains
2832 * which is not possible with the dma_ops interface.
2834 *****************************************************************************/
2836 static void cleanup_domain(struct protection_domain *domain)
2838 struct iommu_dev_data *entry;
2839 unsigned long flags;
2841 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2843 while (!list_empty(&domain->dev_list)) {
2844 entry = list_first_entry(&domain->dev_list,
2845 struct iommu_dev_data, list);
2846 __detach_device(entry);
2849 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2852 static void protection_domain_free(struct protection_domain *domain)
2854 if (!domain)
2855 return;
2857 del_domain_from_list(domain);
2859 if (domain->id)
2860 domain_id_free(domain->id);
2862 kfree(domain);
2865 static int protection_domain_init(struct protection_domain *domain)
2867 spin_lock_init(&domain->lock);
2868 mutex_init(&domain->api_lock);
2869 domain->id = domain_id_alloc();
2870 if (!domain->id)
2871 return -ENOMEM;
2872 INIT_LIST_HEAD(&domain->dev_list);
2874 return 0;
2877 static struct protection_domain *protection_domain_alloc(void)
2879 struct protection_domain *domain;
2881 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2882 if (!domain)
2883 return NULL;
2885 if (protection_domain_init(domain))
2886 goto out_err;
2888 add_domain_to_list(domain);
2890 return domain;
2892 out_err:
2893 kfree(domain);
2895 return NULL;
2898 static struct iommu_domain *amd_iommu_domain_alloc(unsigned type)
2900 struct protection_domain *pdomain;
2901 struct dma_ops_domain *dma_domain;
2903 switch (type) {
2904 case IOMMU_DOMAIN_UNMANAGED:
2905 pdomain = protection_domain_alloc();
2906 if (!pdomain)
2907 return NULL;
2909 pdomain->mode = PAGE_MODE_3_LEVEL;
2910 pdomain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2911 if (!pdomain->pt_root) {
2912 protection_domain_free(pdomain);
2913 return NULL;
2916 pdomain->domain.geometry.aperture_start = 0;
2917 pdomain->domain.geometry.aperture_end = ~0ULL;
2918 pdomain->domain.geometry.force_aperture = true;
2920 break;
2921 case IOMMU_DOMAIN_DMA:
2922 dma_domain = dma_ops_domain_alloc();
2923 if (!dma_domain) {
2924 pr_err("AMD-Vi: Failed to allocate\n");
2925 return NULL;
2927 pdomain = &dma_domain->domain;
2928 break;
2929 case IOMMU_DOMAIN_IDENTITY:
2930 pdomain = protection_domain_alloc();
2931 if (!pdomain)
2932 return NULL;
2934 pdomain->mode = PAGE_MODE_NONE;
2935 break;
2936 default:
2937 return NULL;
2940 return &pdomain->domain;
2943 static void amd_iommu_domain_free(struct iommu_domain *dom)
2945 struct protection_domain *domain;
2946 struct dma_ops_domain *dma_dom;
2948 domain = to_pdomain(dom);
2950 if (domain->dev_cnt > 0)
2951 cleanup_domain(domain);
2953 BUG_ON(domain->dev_cnt != 0);
2955 if (!dom)
2956 return;
2958 switch (dom->type) {
2959 case IOMMU_DOMAIN_DMA:
2960 /* Now release the domain */
2961 dma_dom = to_dma_ops_domain(domain);
2962 dma_ops_domain_free(dma_dom);
2963 break;
2964 default:
2965 if (domain->mode != PAGE_MODE_NONE)
2966 free_pagetable(domain);
2968 if (domain->flags & PD_IOMMUV2_MASK)
2969 free_gcr3_table(domain);
2971 protection_domain_free(domain);
2972 break;
2976 static void amd_iommu_detach_device(struct iommu_domain *dom,
2977 struct device *dev)
2979 struct iommu_dev_data *dev_data = dev->archdata.iommu;
2980 struct amd_iommu *iommu;
2981 int devid;
2983 if (!check_device(dev))
2984 return;
2986 devid = get_device_id(dev);
2987 if (devid < 0)
2988 return;
2990 if (dev_data->domain != NULL)
2991 detach_device(dev);
2993 iommu = amd_iommu_rlookup_table[devid];
2994 if (!iommu)
2995 return;
2997 #ifdef CONFIG_IRQ_REMAP
2998 if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) &&
2999 (dom->type == IOMMU_DOMAIN_UNMANAGED))
3000 dev_data->use_vapic = 0;
3001 #endif
3003 iommu_completion_wait(iommu);
3006 static int amd_iommu_attach_device(struct iommu_domain *dom,
3007 struct device *dev)
3009 struct protection_domain *domain = to_pdomain(dom);
3010 struct iommu_dev_data *dev_data;
3011 struct amd_iommu *iommu;
3012 int ret;
3014 if (!check_device(dev))
3015 return -EINVAL;
3017 dev_data = dev->archdata.iommu;
3019 iommu = amd_iommu_rlookup_table[dev_data->devid];
3020 if (!iommu)
3021 return -EINVAL;
3023 if (dev_data->domain)
3024 detach_device(dev);
3026 ret = attach_device(dev, domain);
3028 #ifdef CONFIG_IRQ_REMAP
3029 if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
3030 if (dom->type == IOMMU_DOMAIN_UNMANAGED)
3031 dev_data->use_vapic = 1;
3032 else
3033 dev_data->use_vapic = 0;
3035 #endif
3037 iommu_completion_wait(iommu);
3039 return ret;
3042 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3043 phys_addr_t paddr, size_t page_size, int iommu_prot)
3045 struct protection_domain *domain = to_pdomain(dom);
3046 int prot = 0;
3047 int ret;
3049 if (domain->mode == PAGE_MODE_NONE)
3050 return -EINVAL;
3052 if (iommu_prot & IOMMU_READ)
3053 prot |= IOMMU_PROT_IR;
3054 if (iommu_prot & IOMMU_WRITE)
3055 prot |= IOMMU_PROT_IW;
3057 mutex_lock(&domain->api_lock);
3058 ret = iommu_map_page(domain, iova, paddr, page_size, prot, GFP_KERNEL);
3059 mutex_unlock(&domain->api_lock);
3061 return ret;
3064 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3065 size_t page_size)
3067 struct protection_domain *domain = to_pdomain(dom);
3068 size_t unmap_size;
3070 if (domain->mode == PAGE_MODE_NONE)
3071 return -EINVAL;
3073 mutex_lock(&domain->api_lock);
3074 unmap_size = iommu_unmap_page(domain, iova, page_size);
3075 mutex_unlock(&domain->api_lock);
3077 domain_flush_tlb_pde(domain);
3078 domain_flush_complete(domain);
3080 return unmap_size;
3083 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3084 dma_addr_t iova)
3086 struct protection_domain *domain = to_pdomain(dom);
3087 unsigned long offset_mask, pte_pgsize;
3088 u64 *pte, __pte;
3090 if (domain->mode == PAGE_MODE_NONE)
3091 return iova;
3093 pte = fetch_pte(domain, iova, &pte_pgsize);
3095 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3096 return 0;
3098 offset_mask = pte_pgsize - 1;
3099 __pte = __sme_clr(*pte & PM_ADDR_MASK);
3101 return (__pte & ~offset_mask) | (iova & offset_mask);
3104 static bool amd_iommu_capable(enum iommu_cap cap)
3106 switch (cap) {
3107 case IOMMU_CAP_CACHE_COHERENCY:
3108 return true;
3109 case IOMMU_CAP_INTR_REMAP:
3110 return (irq_remapping_enabled == 1);
3111 case IOMMU_CAP_NOEXEC:
3112 return false;
3115 return false;
3118 static void amd_iommu_get_resv_regions(struct device *dev,
3119 struct list_head *head)
3121 struct iommu_resv_region *region;
3122 struct unity_map_entry *entry;
3123 int devid;
3125 devid = get_device_id(dev);
3126 if (devid < 0)
3127 return;
3129 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
3130 int type, prot = 0;
3131 size_t length;
3133 if (devid < entry->devid_start || devid > entry->devid_end)
3134 continue;
3136 type = IOMMU_RESV_DIRECT;
3137 length = entry->address_end - entry->address_start;
3138 if (entry->prot & IOMMU_PROT_IR)
3139 prot |= IOMMU_READ;
3140 if (entry->prot & IOMMU_PROT_IW)
3141 prot |= IOMMU_WRITE;
3142 if (entry->prot & IOMMU_UNITY_MAP_FLAG_EXCL_RANGE)
3143 /* Exclusion range */
3144 type = IOMMU_RESV_RESERVED;
3146 region = iommu_alloc_resv_region(entry->address_start,
3147 length, prot, type);
3148 if (!region) {
3149 pr_err("Out of memory allocating dm-regions for %s\n",
3150 dev_name(dev));
3151 return;
3153 list_add_tail(&region->list, head);
3156 region = iommu_alloc_resv_region(MSI_RANGE_START,
3157 MSI_RANGE_END - MSI_RANGE_START + 1,
3158 0, IOMMU_RESV_MSI);
3159 if (!region)
3160 return;
3161 list_add_tail(&region->list, head);
3163 region = iommu_alloc_resv_region(HT_RANGE_START,
3164 HT_RANGE_END - HT_RANGE_START + 1,
3165 0, IOMMU_RESV_RESERVED);
3166 if (!region)
3167 return;
3168 list_add_tail(&region->list, head);
3171 static void amd_iommu_put_resv_regions(struct device *dev,
3172 struct list_head *head)
3174 struct iommu_resv_region *entry, *next;
3176 list_for_each_entry_safe(entry, next, head, list)
3177 kfree(entry);
3180 static void amd_iommu_apply_resv_region(struct device *dev,
3181 struct iommu_domain *domain,
3182 struct iommu_resv_region *region)
3184 struct dma_ops_domain *dma_dom = to_dma_ops_domain(to_pdomain(domain));
3185 unsigned long start, end;
3187 start = IOVA_PFN(region->start);
3188 end = IOVA_PFN(region->start + region->length - 1);
3190 WARN_ON_ONCE(reserve_iova(&dma_dom->iovad, start, end) == NULL);
3193 static bool amd_iommu_is_attach_deferred(struct iommu_domain *domain,
3194 struct device *dev)
3196 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3197 return dev_data->defer_attach;
3200 const struct iommu_ops amd_iommu_ops = {
3201 .capable = amd_iommu_capable,
3202 .domain_alloc = amd_iommu_domain_alloc,
3203 .domain_free = amd_iommu_domain_free,
3204 .attach_dev = amd_iommu_attach_device,
3205 .detach_dev = amd_iommu_detach_device,
3206 .map = amd_iommu_map,
3207 .unmap = amd_iommu_unmap,
3208 .map_sg = default_iommu_map_sg,
3209 .iova_to_phys = amd_iommu_iova_to_phys,
3210 .add_device = amd_iommu_add_device,
3211 .remove_device = amd_iommu_remove_device,
3212 .device_group = amd_iommu_device_group,
3213 .get_resv_regions = amd_iommu_get_resv_regions,
3214 .put_resv_regions = amd_iommu_put_resv_regions,
3215 .apply_resv_region = amd_iommu_apply_resv_region,
3216 .is_attach_deferred = amd_iommu_is_attach_deferred,
3217 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3220 /*****************************************************************************
3222 * The next functions do a basic initialization of IOMMU for pass through
3223 * mode
3225 * In passthrough mode the IOMMU is initialized and enabled but not used for
3226 * DMA-API translation.
3228 *****************************************************************************/
3230 /* IOMMUv2 specific functions */
3231 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3233 return atomic_notifier_chain_register(&ppr_notifier, nb);
3235 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3237 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3239 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3241 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3243 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3245 struct protection_domain *domain = to_pdomain(dom);
3246 unsigned long flags;
3248 spin_lock_irqsave(&domain->lock, flags);
3250 /* Update data structure */
3251 domain->mode = PAGE_MODE_NONE;
3252 domain->updated = true;
3254 /* Make changes visible to IOMMUs */
3255 update_domain(domain);
3257 /* Page-table is not visible to IOMMU anymore, so free it */
3258 free_pagetable(domain);
3260 spin_unlock_irqrestore(&domain->lock, flags);
3262 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3264 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3266 struct protection_domain *domain = to_pdomain(dom);
3267 unsigned long flags;
3268 int levels, ret;
3270 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3271 return -EINVAL;
3273 /* Number of GCR3 table levels required */
3274 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3275 levels += 1;
3277 if (levels > amd_iommu_max_glx_val)
3278 return -EINVAL;
3280 spin_lock_irqsave(&domain->lock, flags);
3283 * Save us all sanity checks whether devices already in the
3284 * domain support IOMMUv2. Just force that the domain has no
3285 * devices attached when it is switched into IOMMUv2 mode.
3287 ret = -EBUSY;
3288 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3289 goto out;
3291 ret = -ENOMEM;
3292 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3293 if (domain->gcr3_tbl == NULL)
3294 goto out;
3296 domain->glx = levels;
3297 domain->flags |= PD_IOMMUV2_MASK;
3298 domain->updated = true;
3300 update_domain(domain);
3302 ret = 0;
3304 out:
3305 spin_unlock_irqrestore(&domain->lock, flags);
3307 return ret;
3309 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3311 static int __flush_pasid(struct protection_domain *domain, int pasid,
3312 u64 address, bool size)
3314 struct iommu_dev_data *dev_data;
3315 struct iommu_cmd cmd;
3316 int i, ret;
3318 if (!(domain->flags & PD_IOMMUV2_MASK))
3319 return -EINVAL;
3321 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3324 * IOMMU TLB needs to be flushed before Device TLB to
3325 * prevent device TLB refill from IOMMU TLB
3327 for (i = 0; i < amd_iommu_get_num_iommus(); ++i) {
3328 if (domain->dev_iommu[i] == 0)
3329 continue;
3331 ret = iommu_queue_command(amd_iommus[i], &cmd);
3332 if (ret != 0)
3333 goto out;
3336 /* Wait until IOMMU TLB flushes are complete */
3337 domain_flush_complete(domain);
3339 /* Now flush device TLBs */
3340 list_for_each_entry(dev_data, &domain->dev_list, list) {
3341 struct amd_iommu *iommu;
3342 int qdep;
3345 There might be non-IOMMUv2 capable devices in an IOMMUv2
3346 * domain.
3348 if (!dev_data->ats.enabled)
3349 continue;
3351 qdep = dev_data->ats.qdep;
3352 iommu = amd_iommu_rlookup_table[dev_data->devid];
3354 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3355 qdep, address, size);
3357 ret = iommu_queue_command(iommu, &cmd);
3358 if (ret != 0)
3359 goto out;
3362 /* Wait until all device TLBs are flushed */
3363 domain_flush_complete(domain);
3365 ret = 0;
3367 out:
3369 return ret;
3372 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3373 u64 address)
3375 return __flush_pasid(domain, pasid, address, false);
3378 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3379 u64 address)
3381 struct protection_domain *domain = to_pdomain(dom);
3382 unsigned long flags;
3383 int ret;
3385 spin_lock_irqsave(&domain->lock, flags);
3386 ret = __amd_iommu_flush_page(domain, pasid, address);
3387 spin_unlock_irqrestore(&domain->lock, flags);
3389 return ret;
3391 EXPORT_SYMBOL(amd_iommu_flush_page);
3393 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3395 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3396 true);
3399 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3401 struct protection_domain *domain = to_pdomain(dom);
3402 unsigned long flags;
3403 int ret;
3405 spin_lock_irqsave(&domain->lock, flags);
3406 ret = __amd_iommu_flush_tlb(domain, pasid);
3407 spin_unlock_irqrestore(&domain->lock, flags);
3409 return ret;
3411 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3413 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3415 int index;
3416 u64 *pte;
3418 while (true) {
3420 index = (pasid >> (9 * level)) & 0x1ff;
3421 pte = &root[index];
3423 if (level == 0)
3424 break;
3426 if (!(*pte & GCR3_VALID)) {
3427 if (!alloc)
3428 return NULL;
3430 root = (void *)get_zeroed_page(GFP_ATOMIC);
3431 if (root == NULL)
3432 return NULL;
3434 *pte = iommu_virt_to_phys(root) | GCR3_VALID;
3437 root = iommu_phys_to_virt(*pte & PAGE_MASK);
3439 level -= 1;
3442 return pte;
3445 static int __set_gcr3(struct protection_domain *domain, int pasid,
3446 unsigned long cr3)
3448 u64 *pte;
3450 if (domain->mode != PAGE_MODE_NONE)
3451 return -EINVAL;
3453 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3454 if (pte == NULL)
3455 return -ENOMEM;
3457 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3459 return __amd_iommu_flush_tlb(domain, pasid);
3462 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3464 u64 *pte;
3466 if (domain->mode != PAGE_MODE_NONE)
3467 return -EINVAL;
3469 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3470 if (pte == NULL)
3471 return 0;
3473 *pte = 0;
3475 return __amd_iommu_flush_tlb(domain, pasid);
3478 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3479 unsigned long cr3)
3481 struct protection_domain *domain = to_pdomain(dom);
3482 unsigned long flags;
3483 int ret;
3485 spin_lock_irqsave(&domain->lock, flags);
3486 ret = __set_gcr3(domain, pasid, cr3);
3487 spin_unlock_irqrestore(&domain->lock, flags);
3489 return ret;
3491 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3493 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3495 struct protection_domain *domain = to_pdomain(dom);
3496 unsigned long flags;
3497 int ret;
3499 spin_lock_irqsave(&domain->lock, flags);
3500 ret = __clear_gcr3(domain, pasid);
3501 spin_unlock_irqrestore(&domain->lock, flags);
3503 return ret;
3505 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3507 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3508 int status, int tag)
3510 struct iommu_dev_data *dev_data;
3511 struct amd_iommu *iommu;
3512 struct iommu_cmd cmd;
3514 dev_data = get_dev_data(&pdev->dev);
3515 iommu = amd_iommu_rlookup_table[dev_data->devid];
3517 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3518 tag, dev_data->pri_tlp);
3520 return iommu_queue_command(iommu, &cmd);
3522 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3524 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3526 struct protection_domain *pdomain;
3528 pdomain = get_domain(&pdev->dev);
3529 if (IS_ERR(pdomain))
3530 return NULL;
3532 /* Only return IOMMUv2 domains */
3533 if (!(pdomain->flags & PD_IOMMUV2_MASK))
3534 return NULL;
3536 return &pdomain->domain;
3538 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3540 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3542 struct iommu_dev_data *dev_data;
3544 if (!amd_iommu_v2_supported())
3545 return;
3547 dev_data = get_dev_data(&pdev->dev);
3548 dev_data->errata |= (1 << erratum);
3550 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3552 int amd_iommu_device_info(struct pci_dev *pdev,
3553 struct amd_iommu_device_info *info)
3555 int max_pasids;
3556 int pos;
3558 if (pdev == NULL || info == NULL)
3559 return -EINVAL;
3561 if (!amd_iommu_v2_supported())
3562 return -EINVAL;
3564 memset(info, 0, sizeof(*info));
3566 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3567 if (pos)
3568 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3570 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3571 if (pos)
3572 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3574 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3575 if (pos) {
3576 int features;
3578 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3579 max_pasids = min(max_pasids, (1 << 20));
3581 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3582 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3584 features = pci_pasid_features(pdev);
3585 if (features & PCI_PASID_CAP_EXEC)
3586 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3587 if (features & PCI_PASID_CAP_PRIV)
3588 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3591 return 0;
3593 EXPORT_SYMBOL(amd_iommu_device_info);
3595 #ifdef CONFIG_IRQ_REMAP
3597 /*****************************************************************************
3599 * Interrupt Remapping Implementation
3601 *****************************************************************************/
3603 static struct irq_chip amd_ir_chip;
3605 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3607 u64 dte;
3609 dte = amd_iommu_dev_table[devid].data[2];
3610 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3611 dte |= iommu_virt_to_phys(table->table);
3612 dte |= DTE_IRQ_REMAP_INTCTL;
3613 dte |= DTE_IRQ_TABLE_LEN;
3614 dte |= DTE_IRQ_REMAP_ENABLE;
3616 amd_iommu_dev_table[devid].data[2] = dte;
3619 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3621 struct irq_remap_table *table = NULL;
3622 struct amd_iommu *iommu;
3623 unsigned long flags;
3624 u16 alias;
3626 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3628 iommu = amd_iommu_rlookup_table[devid];
3629 if (!iommu)
3630 goto out_unlock;
3632 table = irq_lookup_table[devid];
3633 if (table)
3634 goto out_unlock;
3636 alias = amd_iommu_alias_table[devid];
3637 table = irq_lookup_table[alias];
3638 if (table) {
3639 irq_lookup_table[devid] = table;
3640 set_dte_irq_entry(devid, table);
3641 iommu_flush_dte(iommu, devid);
3642 goto out;
3645 /* Nothing there yet, allocate new irq remapping table */
3646 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3647 if (!table)
3648 goto out_unlock;
3650 /* Initialize table spin-lock */
3651 spin_lock_init(&table->lock);
3653 if (ioapic)
3654 /* Keep the first 32 indexes free for IOAPIC interrupts */
3655 table->min_index = 32;
3657 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3658 if (!table->table) {
3659 kfree(table);
3660 table = NULL;
3661 goto out_unlock;
3664 if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
3665 memset(table->table, 0,
3666 MAX_IRQS_PER_TABLE * sizeof(u32));
3667 else
3668 memset(table->table, 0,
3669 (MAX_IRQS_PER_TABLE * (sizeof(u64) * 2)));
3671 if (ioapic) {
3672 int i;
3674 for (i = 0; i < 32; ++i)
3675 iommu->irte_ops->set_allocated(table, i);
3678 irq_lookup_table[devid] = table;
3679 set_dte_irq_entry(devid, table);
3680 iommu_flush_dte(iommu, devid);
3681 if (devid != alias) {
3682 irq_lookup_table[alias] = table;
3683 set_dte_irq_entry(alias, table);
3684 iommu_flush_dte(iommu, alias);
3687 out:
3688 iommu_completion_wait(iommu);
3690 out_unlock:
3691 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3693 return table;
3696 static int alloc_irq_index(u16 devid, int count)
3698 struct irq_remap_table *table;
3699 unsigned long flags;
3700 int index, c;
3701 struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
3703 if (!iommu)
3704 return -ENODEV;
3706 table = get_irq_table(devid, false);
3707 if (!table)
3708 return -ENODEV;
3710 spin_lock_irqsave(&table->lock, flags);
3712 /* Scan table for free entries */
3713 for (c = 0, index = table->min_index;
3714 index < MAX_IRQS_PER_TABLE;
3715 ++index) {
3716 if (!iommu->irte_ops->is_allocated(table, index))
3717 c += 1;
3718 else
3719 c = 0;
3721 if (c == count) {
3722 for (; c != 0; --c)
3723 iommu->irte_ops->set_allocated(table, index - c + 1);
3725 index -= count - 1;
3726 goto out;
3730 index = -ENOSPC;
3732 out:
3733 spin_unlock_irqrestore(&table->lock, flags);
3735 return index;
3738 static int modify_irte_ga(u16 devid, int index, struct irte_ga *irte,
3739 struct amd_ir_data *data)
3741 struct irq_remap_table *table;
3742 struct amd_iommu *iommu;
3743 unsigned long flags;
3744 struct irte_ga *entry;
3746 iommu = amd_iommu_rlookup_table[devid];
3747 if (iommu == NULL)
3748 return -EINVAL;
3750 table = get_irq_table(devid, false);
3751 if (!table)
3752 return -ENOMEM;
3754 spin_lock_irqsave(&table->lock, flags);
3756 entry = (struct irte_ga *)table->table;
3757 entry = &entry[index];
3758 entry->lo.fields_remap.valid = 0;
3759 entry->hi.val = irte->hi.val;
3760 entry->lo.val = irte->lo.val;
3761 entry->lo.fields_remap.valid = 1;
3762 if (data)
3763 data->ref = entry;
3765 spin_unlock_irqrestore(&table->lock, flags);
3767 iommu_flush_irt(iommu, devid);
3768 iommu_completion_wait(iommu);
3770 return 0;
3773 static int modify_irte(u16 devid, int index, union irte *irte)
3775 struct irq_remap_table *table;
3776 struct amd_iommu *iommu;
3777 unsigned long flags;
3779 iommu = amd_iommu_rlookup_table[devid];
3780 if (iommu == NULL)
3781 return -EINVAL;
3783 table = get_irq_table(devid, false);
3784 if (!table)
3785 return -ENOMEM;
3787 spin_lock_irqsave(&table->lock, flags);
3788 table->table[index] = irte->val;
3789 spin_unlock_irqrestore(&table->lock, flags);
3791 iommu_flush_irt(iommu, devid);
3792 iommu_completion_wait(iommu);
3794 return 0;
3797 static void free_irte(u16 devid, int index)
3799 struct irq_remap_table *table;
3800 struct amd_iommu *iommu;
3801 unsigned long flags;
3803 iommu = amd_iommu_rlookup_table[devid];
3804 if (iommu == NULL)
3805 return;
3807 table = get_irq_table(devid, false);
3808 if (!table)
3809 return;
3811 spin_lock_irqsave(&table->lock, flags);
3812 iommu->irte_ops->clear_allocated(table, index);
3813 spin_unlock_irqrestore(&table->lock, flags);
3815 iommu_flush_irt(iommu, devid);
3816 iommu_completion_wait(iommu);
3819 static void irte_prepare(void *entry,
3820 u32 delivery_mode, u32 dest_mode,
3821 u8 vector, u32 dest_apicid, int devid)
3823 union irte *irte = (union irte *) entry;
3825 irte->val = 0;
3826 irte->fields.vector = vector;
3827 irte->fields.int_type = delivery_mode;
3828 irte->fields.destination = dest_apicid;
3829 irte->fields.dm = dest_mode;
3830 irte->fields.valid = 1;
3833 static void irte_ga_prepare(void *entry,
3834 u32 delivery_mode, u32 dest_mode,
3835 u8 vector, u32 dest_apicid, int devid)
3837 struct irte_ga *irte = (struct irte_ga *) entry;
3839 irte->lo.val = 0;
3840 irte->hi.val = 0;
3841 irte->lo.fields_remap.int_type = delivery_mode;
3842 irte->lo.fields_remap.dm = dest_mode;
3843 irte->hi.fields.vector = vector;
3844 irte->lo.fields_remap.destination = dest_apicid;
3845 irte->lo.fields_remap.valid = 1;
3848 static void irte_activate(void *entry, u16 devid, u16 index)
3850 union irte *irte = (union irte *) entry;
3852 irte->fields.valid = 1;
3853 modify_irte(devid, index, irte);
3856 static void irte_ga_activate(void *entry, u16 devid, u16 index)
3858 struct irte_ga *irte = (struct irte_ga *) entry;
3860 irte->lo.fields_remap.valid = 1;
3861 modify_irte_ga(devid, index, irte, NULL);
3864 static void irte_deactivate(void *entry, u16 devid, u16 index)
3866 union irte *irte = (union irte *) entry;
3868 irte->fields.valid = 0;
3869 modify_irte(devid, index, irte);
3872 static void irte_ga_deactivate(void *entry, u16 devid, u16 index)
3874 struct irte_ga *irte = (struct irte_ga *) entry;
3876 irte->lo.fields_remap.valid = 0;
3877 modify_irte_ga(devid, index, irte, NULL);
3880 static void irte_set_affinity(void *entry, u16 devid, u16 index,
3881 u8 vector, u32 dest_apicid)
3883 union irte *irte = (union irte *) entry;
3885 irte->fields.vector = vector;
3886 irte->fields.destination = dest_apicid;
3887 modify_irte(devid, index, irte);
3890 static void irte_ga_set_affinity(void *entry, u16 devid, u16 index,
3891 u8 vector, u32 dest_apicid)
3893 struct irte_ga *irte = (struct irte_ga *) entry;
3894 struct iommu_dev_data *dev_data = search_dev_data(devid);
3896 if (!dev_data || !dev_data->use_vapic ||
3897 !irte->lo.fields_remap.guest_mode) {
3898 irte->hi.fields.vector = vector;
3899 irte->lo.fields_remap.destination = dest_apicid;
3900 modify_irte_ga(devid, index, irte, NULL);
3904 #define IRTE_ALLOCATED (~1U)
3905 static void irte_set_allocated(struct irq_remap_table *table, int index)
3907 table->table[index] = IRTE_ALLOCATED;
3910 static void irte_ga_set_allocated(struct irq_remap_table *table, int index)
3912 struct irte_ga *ptr = (struct irte_ga *)table->table;
3913 struct irte_ga *irte = &ptr[index];
3915 memset(&irte->lo.val, 0, sizeof(u64));
3916 memset(&irte->hi.val, 0, sizeof(u64));
3917 irte->hi.fields.vector = 0xff;
3920 static bool irte_is_allocated(struct irq_remap_table *table, int index)
3922 union irte *ptr = (union irte *)table->table;
3923 union irte *irte = &ptr[index];
3925 return irte->val != 0;
3928 static bool irte_ga_is_allocated(struct irq_remap_table *table, int index)
3930 struct irte_ga *ptr = (struct irte_ga *)table->table;
3931 struct irte_ga *irte = &ptr[index];
3933 return irte->hi.fields.vector != 0;
3936 static void irte_clear_allocated(struct irq_remap_table *table, int index)
3938 table->table[index] = 0;
3941 static void irte_ga_clear_allocated(struct irq_remap_table *table, int index)
3943 struct irte_ga *ptr = (struct irte_ga *)table->table;
3944 struct irte_ga *irte = &ptr[index];
3946 memset(&irte->lo.val, 0, sizeof(u64));
3947 memset(&irte->hi.val, 0, sizeof(u64));
3950 static int get_devid(struct irq_alloc_info *info)
3952 int devid = -1;
3954 switch (info->type) {
3955 case X86_IRQ_ALLOC_TYPE_IOAPIC:
3956 devid = get_ioapic_devid(info->ioapic_id);
3957 break;
3958 case X86_IRQ_ALLOC_TYPE_HPET:
3959 devid = get_hpet_devid(info->hpet_id);
3960 break;
3961 case X86_IRQ_ALLOC_TYPE_MSI:
3962 case X86_IRQ_ALLOC_TYPE_MSIX:
3963 devid = get_device_id(&info->msi_dev->dev);
3964 break;
3965 default:
3966 BUG_ON(1);
3967 break;
3970 return devid;
3973 static struct irq_domain *get_ir_irq_domain(struct irq_alloc_info *info)
3975 struct amd_iommu *iommu;
3976 int devid;
3978 if (!info)
3979 return NULL;
3981 devid = get_devid(info);
3982 if (devid >= 0) {
3983 iommu = amd_iommu_rlookup_table[devid];
3984 if (iommu)
3985 return iommu->ir_domain;
3988 return NULL;
3991 static struct irq_domain *get_irq_domain(struct irq_alloc_info *info)
3993 struct amd_iommu *iommu;
3994 int devid;
3996 if (!info)
3997 return NULL;
3999 switch (info->type) {
4000 case X86_IRQ_ALLOC_TYPE_MSI:
4001 case X86_IRQ_ALLOC_TYPE_MSIX:
4002 devid = get_device_id(&info->msi_dev->dev);
4003 if (devid < 0)
4004 return NULL;
4006 iommu = amd_iommu_rlookup_table[devid];
4007 if (iommu)
4008 return iommu->msi_domain;
4009 break;
4010 default:
4011 break;
4014 return NULL;
4017 struct irq_remap_ops amd_iommu_irq_ops = {
4018 .prepare = amd_iommu_prepare,
4019 .enable = amd_iommu_enable,
4020 .disable = amd_iommu_disable,
4021 .reenable = amd_iommu_reenable,
4022 .enable_faulting = amd_iommu_enable_faulting,
4023 .get_ir_irq_domain = get_ir_irq_domain,
4024 .get_irq_domain = get_irq_domain,
4027 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
4028 struct irq_cfg *irq_cfg,
4029 struct irq_alloc_info *info,
4030 int devid, int index, int sub_handle)
4032 struct irq_2_irte *irte_info = &data->irq_2_irte;
4033 struct msi_msg *msg = &data->msi_entry;
4034 struct IO_APIC_route_entry *entry;
4035 struct amd_iommu *iommu = amd_iommu_rlookup_table[devid];
4037 if (!iommu)
4038 return;
4040 data->irq_2_irte.devid = devid;
4041 data->irq_2_irte.index = index + sub_handle;
4042 iommu->irte_ops->prepare(data->entry, apic->irq_delivery_mode,
4043 apic->irq_dest_mode, irq_cfg->vector,
4044 irq_cfg->dest_apicid, devid);
4046 switch (info->type) {
4047 case X86_IRQ_ALLOC_TYPE_IOAPIC:
4048 /* Setup IOAPIC entry */
4049 entry = info->ioapic_entry;
4050 info->ioapic_entry = NULL;
4051 memset(entry, 0, sizeof(*entry));
4052 entry->vector = index;
4053 entry->mask = 0;
4054 entry->trigger = info->ioapic_trigger;
4055 entry->polarity = info->ioapic_polarity;
4056 /* Mask level triggered irqs. */
4057 if (info->ioapic_trigger)
4058 entry->mask = 1;
4059 break;
4061 case X86_IRQ_ALLOC_TYPE_HPET:
4062 case X86_IRQ_ALLOC_TYPE_MSI:
4063 case X86_IRQ_ALLOC_TYPE_MSIX:
4064 msg->address_hi = MSI_ADDR_BASE_HI;
4065 msg->address_lo = MSI_ADDR_BASE_LO;
4066 msg->data = irte_info->index;
4067 break;
4069 default:
4070 BUG_ON(1);
4071 break;
4075 struct amd_irte_ops irte_32_ops = {
4076 .prepare = irte_prepare,
4077 .activate = irte_activate,
4078 .deactivate = irte_deactivate,
4079 .set_affinity = irte_set_affinity,
4080 .set_allocated = irte_set_allocated,
4081 .is_allocated = irte_is_allocated,
4082 .clear_allocated = irte_clear_allocated,
4085 struct amd_irte_ops irte_128_ops = {
4086 .prepare = irte_ga_prepare,
4087 .activate = irte_ga_activate,
4088 .deactivate = irte_ga_deactivate,
4089 .set_affinity = irte_ga_set_affinity,
4090 .set_allocated = irte_ga_set_allocated,
4091 .is_allocated = irte_ga_is_allocated,
4092 .clear_allocated = irte_ga_clear_allocated,
4095 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
4096 unsigned int nr_irqs, void *arg)
4098 struct irq_alloc_info *info = arg;
4099 struct irq_data *irq_data;
4100 struct amd_ir_data *data = NULL;
4101 struct irq_cfg *cfg;
4102 int i, ret, devid;
4103 int index = -1;
4105 if (!info)
4106 return -EINVAL;
4107 if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_MSI &&
4108 info->type != X86_IRQ_ALLOC_TYPE_MSIX)
4109 return -EINVAL;
4112 * With IRQ remapping enabled, don't need contiguous CPU vectors
4113 * to support multiple MSI interrupts.
4115 if (info->type == X86_IRQ_ALLOC_TYPE_MSI)
4116 info->flags &= ~X86_IRQ_ALLOC_CONTIGUOUS_VECTORS;
4118 devid = get_devid(info);
4119 if (devid < 0)
4120 return -EINVAL;
4122 ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
4123 if (ret < 0)
4124 return ret;
4126 if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
4127 if (get_irq_table(devid, true))
4128 index = info->ioapic_pin;
4129 else
4130 ret = -ENOMEM;
4131 } else {
4132 index = alloc_irq_index(devid, nr_irqs);
4134 if (index < 0) {
4135 pr_warn("Failed to allocate IRTE\n");
4136 ret = index;
4137 goto out_free_parent;
4140 for (i = 0; i < nr_irqs; i++) {
4141 irq_data = irq_domain_get_irq_data(domain, virq + i);
4142 cfg = irqd_cfg(irq_data);
4143 if (!irq_data || !cfg) {
4144 ret = -EINVAL;
4145 goto out_free_data;
4148 ret = -ENOMEM;
4149 data = kzalloc(sizeof(*data), GFP_KERNEL);
4150 if (!data)
4151 goto out_free_data;
4153 if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
4154 data->entry = kzalloc(sizeof(union irte), GFP_KERNEL);
4155 else
4156 data->entry = kzalloc(sizeof(struct irte_ga),
4157 GFP_KERNEL);
4158 if (!data->entry) {
4159 kfree(data);
4160 goto out_free_data;
4163 irq_data->hwirq = (devid << 16) + i;
4164 irq_data->chip_data = data;
4165 irq_data->chip = &amd_ir_chip;
4166 irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
4167 irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
4170 return 0;
4172 out_free_data:
4173 for (i--; i >= 0; i--) {
4174 irq_data = irq_domain_get_irq_data(domain, virq + i);
4175 if (irq_data)
4176 kfree(irq_data->chip_data);
4178 for (i = 0; i < nr_irqs; i++)
4179 free_irte(devid, index + i);
4180 out_free_parent:
4181 irq_domain_free_irqs_common(domain, virq, nr_irqs);
4182 return ret;
4185 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
4186 unsigned int nr_irqs)
4188 struct irq_2_irte *irte_info;
4189 struct irq_data *irq_data;
4190 struct amd_ir_data *data;
4191 int i;
4193 for (i = 0; i < nr_irqs; i++) {
4194 irq_data = irq_domain_get_irq_data(domain, virq + i);
4195 if (irq_data && irq_data->chip_data) {
4196 data = irq_data->chip_data;
4197 irte_info = &data->irq_2_irte;
4198 free_irte(irte_info->devid, irte_info->index);
4199 kfree(data->entry);
4200 kfree(data);
4203 irq_domain_free_irqs_common(domain, virq, nr_irqs);
4206 static void irq_remapping_activate(struct irq_domain *domain,
4207 struct irq_data *irq_data)
4209 struct amd_ir_data *data = irq_data->chip_data;
4210 struct irq_2_irte *irte_info = &data->irq_2_irte;
4211 struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
4213 if (iommu)
4214 iommu->irte_ops->activate(data->entry, irte_info->devid,
4215 irte_info->index);
4218 static void irq_remapping_deactivate(struct irq_domain *domain,
4219 struct irq_data *irq_data)
4221 struct amd_ir_data *data = irq_data->chip_data;
4222 struct irq_2_irte *irte_info = &data->irq_2_irte;
4223 struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
4225 if (iommu)
4226 iommu->irte_ops->deactivate(data->entry, irte_info->devid,
4227 irte_info->index);
4230 static const struct irq_domain_ops amd_ir_domain_ops = {
4231 .alloc = irq_remapping_alloc,
4232 .free = irq_remapping_free,
4233 .activate = irq_remapping_activate,
4234 .deactivate = irq_remapping_deactivate,
4237 static int amd_ir_set_vcpu_affinity(struct irq_data *data, void *vcpu_info)
4239 struct amd_iommu *iommu;
4240 struct amd_iommu_pi_data *pi_data = vcpu_info;
4241 struct vcpu_data *vcpu_pi_info = pi_data->vcpu_data;
4242 struct amd_ir_data *ir_data = data->chip_data;
4243 struct irte_ga *irte = (struct irte_ga *) ir_data->entry;
4244 struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4245 struct iommu_dev_data *dev_data = search_dev_data(irte_info->devid);
4247 /* Note:
4248 * This device has never been set up for guest mode.
4249 * we should not modify the IRTE
4251 if (!dev_data || !dev_data->use_vapic)
4252 return 0;
4254 pi_data->ir_data = ir_data;
4256 /* Note:
4257 * SVM tries to set up for VAPIC mode, but we are in
4258 * legacy mode. So, we force legacy mode instead.
4260 if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
4261 pr_debug("AMD-Vi: %s: Fall back to using intr legacy remap\n",
4262 __func__);
4263 pi_data->is_guest_mode = false;
4266 iommu = amd_iommu_rlookup_table[irte_info->devid];
4267 if (iommu == NULL)
4268 return -EINVAL;
4270 pi_data->prev_ga_tag = ir_data->cached_ga_tag;
4271 if (pi_data->is_guest_mode) {
4272 /* Setting */
4273 irte->hi.fields.ga_root_ptr = (pi_data->base >> 12);
4274 irte->hi.fields.vector = vcpu_pi_info->vector;
4275 irte->lo.fields_vapic.ga_log_intr = 1;
4276 irte->lo.fields_vapic.guest_mode = 1;
4277 irte->lo.fields_vapic.ga_tag = pi_data->ga_tag;
4279 ir_data->cached_ga_tag = pi_data->ga_tag;
4280 } else {
4281 /* Un-Setting */
4282 struct irq_cfg *cfg = irqd_cfg(data);
4284 irte->hi.val = 0;
4285 irte->lo.val = 0;
4286 irte->hi.fields.vector = cfg->vector;
4287 irte->lo.fields_remap.guest_mode = 0;
4288 irte->lo.fields_remap.destination = cfg->dest_apicid;
4289 irte->lo.fields_remap.int_type = apic->irq_delivery_mode;
4290 irte->lo.fields_remap.dm = apic->irq_dest_mode;
4293 * This communicates the ga_tag back to the caller
4294 * so that it can do all the necessary clean up.
4296 ir_data->cached_ga_tag = 0;
4299 return modify_irte_ga(irte_info->devid, irte_info->index, irte, ir_data);
4302 static int amd_ir_set_affinity(struct irq_data *data,
4303 const struct cpumask *mask, bool force)
4305 struct amd_ir_data *ir_data = data->chip_data;
4306 struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4307 struct irq_cfg *cfg = irqd_cfg(data);
4308 struct irq_data *parent = data->parent_data;
4309 struct amd_iommu *iommu = amd_iommu_rlookup_table[irte_info->devid];
4310 int ret;
4312 if (!iommu)
4313 return -ENODEV;
4315 ret = parent->chip->irq_set_affinity(parent, mask, force);
4316 if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
4317 return ret;
4320 * Atomically updates the IRTE with the new destination, vector
4321 * and flushes the interrupt entry cache.
4323 iommu->irte_ops->set_affinity(ir_data->entry, irte_info->devid,
4324 irte_info->index, cfg->vector, cfg->dest_apicid);
4327 * After this point, all the interrupts will start arriving
4328 * at the new destination. So, time to cleanup the previous
4329 * vector allocation.
4331 send_cleanup_vector(cfg);
4333 return IRQ_SET_MASK_OK_DONE;
4336 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
4338 struct amd_ir_data *ir_data = irq_data->chip_data;
4340 *msg = ir_data->msi_entry;
4343 static struct irq_chip amd_ir_chip = {
4344 .name = "AMD-IR",
4345 .irq_ack = ir_ack_apic_edge,
4346 .irq_set_affinity = amd_ir_set_affinity,
4347 .irq_set_vcpu_affinity = amd_ir_set_vcpu_affinity,
4348 .irq_compose_msi_msg = ir_compose_msi_msg,
4351 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
4353 struct fwnode_handle *fn;
4355 fn = irq_domain_alloc_named_id_fwnode("AMD-IR", iommu->index);
4356 if (!fn)
4357 return -ENOMEM;
4358 iommu->ir_domain = irq_domain_create_tree(fn, &amd_ir_domain_ops, iommu);
4359 irq_domain_free_fwnode(fn);
4360 if (!iommu->ir_domain)
4361 return -ENOMEM;
4363 iommu->ir_domain->parent = arch_get_ir_parent_domain();
4364 iommu->msi_domain = arch_create_remap_msi_irq_domain(iommu->ir_domain,
4365 "AMD-IR-MSI",
4366 iommu->index);
4367 return 0;
4370 int amd_iommu_update_ga(int cpu, bool is_run, void *data)
4372 unsigned long flags;
4373 struct amd_iommu *iommu;
4374 struct irq_remap_table *irt;
4375 struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
4376 int devid = ir_data->irq_2_irte.devid;
4377 struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
4378 struct irte_ga *ref = (struct irte_ga *) ir_data->ref;
4380 if (!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir) ||
4381 !ref || !entry || !entry->lo.fields_vapic.guest_mode)
4382 return 0;
4384 iommu = amd_iommu_rlookup_table[devid];
4385 if (!iommu)
4386 return -ENODEV;
4388 irt = get_irq_table(devid, false);
4389 if (!irt)
4390 return -ENODEV;
4392 spin_lock_irqsave(&irt->lock, flags);
4394 if (ref->lo.fields_vapic.guest_mode) {
4395 if (cpu >= 0)
4396 ref->lo.fields_vapic.destination = cpu;
4397 ref->lo.fields_vapic.is_run = is_run;
4398 barrier();
4401 spin_unlock_irqrestore(&irt->lock, flags);
4403 iommu_flush_irt(iommu, devid);
4404 iommu_completion_wait(iommu);
4405 return 0;
4407 EXPORT_SYMBOL(amd_iommu_update_ga);
4408 #endif