dm thin metadata: fix __udivdi3 undefined on 32-bit
[linux/fpc-iii.git] / drivers / iommu / amd_iommu.c
blob52c36394dba500db1526fa45e8c33a384e8ae142
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/pci-ats.h>
23 #include <linux/bitmap.h>
24 #include <linux/slab.h>
25 #include <linux/debugfs.h>
26 #include <linux/scatterlist.h>
27 #include <linux/dma-mapping.h>
28 #include <linux/iommu-helper.h>
29 #include <linux/iommu.h>
30 #include <linux/delay.h>
31 #include <linux/amd-iommu.h>
32 #include <linux/notifier.h>
33 #include <linux/export.h>
34 #include <linux/irq.h>
35 #include <linux/msi.h>
36 #include <linux/dma-contiguous.h>
37 #include <linux/irqdomain.h>
38 #include <asm/irq_remapping.h>
39 #include <asm/io_apic.h>
40 #include <asm/apic.h>
41 #include <asm/hw_irq.h>
42 #include <asm/msidef.h>
43 #include <asm/proto.h>
44 #include <asm/iommu.h>
45 #include <asm/gart.h>
46 #include <asm/dma.h>
48 #include "amd_iommu_proto.h"
49 #include "amd_iommu_types.h"
50 #include "irq_remapping.h"
52 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
54 #define LOOP_TIMEOUT 100000
57 * This bitmap is used to advertise the page sizes our hardware support
58 * to the IOMMU core, which will then use this information to split
59 * physically contiguous memory regions it is mapping into page sizes
60 * that we support.
62 * 512GB Pages are not supported due to a hardware bug
64 #define AMD_IOMMU_PGSIZES ((~0xFFFUL) & ~(2ULL << 38))
66 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
68 /* List of all available dev_data structures */
69 static LIST_HEAD(dev_data_list);
70 static DEFINE_SPINLOCK(dev_data_list_lock);
72 LIST_HEAD(ioapic_map);
73 LIST_HEAD(hpet_map);
76 * Domain for untranslated devices - only allocated
77 * if iommu=pt passed on kernel cmd line.
79 static const struct iommu_ops amd_iommu_ops;
81 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
82 int amd_iommu_max_glx_val = -1;
84 static struct dma_map_ops amd_iommu_dma_ops;
87 * This struct contains device specific data for the IOMMU
89 struct iommu_dev_data {
90 struct list_head list; /* For domain->dev_list */
91 struct list_head dev_data_list; /* For global dev_data_list */
92 struct protection_domain *domain; /* Domain the device is bound to */
93 u16 devid; /* PCI Device ID */
94 u16 alias; /* Alias Device ID */
95 bool iommu_v2; /* Device can make use of IOMMUv2 */
96 bool passthrough; /* Device is identity mapped */
97 struct {
98 bool enabled;
99 int qdep;
100 } ats; /* ATS state */
101 bool pri_tlp; /* PASID TLB required for
102 PPR completions */
103 u32 errata; /* Bitmap for errata to apply */
107 * general struct to manage commands send to an IOMMU
109 struct iommu_cmd {
110 u32 data[4];
113 struct kmem_cache *amd_iommu_irq_cache;
115 static void update_domain(struct protection_domain *domain);
116 static int protection_domain_init(struct protection_domain *domain);
118 /****************************************************************************
120 * Helper functions
122 ****************************************************************************/
124 static struct protection_domain *to_pdomain(struct iommu_domain *dom)
126 return container_of(dom, struct protection_domain, domain);
129 static inline u16 get_device_id(struct device *dev)
131 struct pci_dev *pdev = to_pci_dev(dev);
133 return PCI_DEVID(pdev->bus->number, pdev->devfn);
136 static struct iommu_dev_data *alloc_dev_data(u16 devid)
138 struct iommu_dev_data *dev_data;
139 unsigned long flags;
141 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
142 if (!dev_data)
143 return NULL;
145 dev_data->devid = devid;
147 spin_lock_irqsave(&dev_data_list_lock, flags);
148 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
149 spin_unlock_irqrestore(&dev_data_list_lock, flags);
151 return dev_data;
154 static struct iommu_dev_data *search_dev_data(u16 devid)
156 struct iommu_dev_data *dev_data;
157 unsigned long flags;
159 spin_lock_irqsave(&dev_data_list_lock, flags);
160 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
161 if (dev_data->devid == devid)
162 goto out_unlock;
165 dev_data = NULL;
167 out_unlock:
168 spin_unlock_irqrestore(&dev_data_list_lock, flags);
170 return dev_data;
173 static int __last_alias(struct pci_dev *pdev, u16 alias, void *data)
175 *(u16 *)data = alias;
176 return 0;
179 static u16 get_alias(struct device *dev)
181 struct pci_dev *pdev = to_pci_dev(dev);
182 u16 devid, ivrs_alias, pci_alias;
184 devid = get_device_id(dev);
185 ivrs_alias = amd_iommu_alias_table[devid];
186 pci_for_each_dma_alias(pdev, __last_alias, &pci_alias);
188 if (ivrs_alias == pci_alias)
189 return ivrs_alias;
192 * DMA alias showdown
194 * The IVRS is fairly reliable in telling us about aliases, but it
195 * can't know about every screwy device. If we don't have an IVRS
196 * reported alias, use the PCI reported alias. In that case we may
197 * still need to initialize the rlookup and dev_table entries if the
198 * alias is to a non-existent device.
200 if (ivrs_alias == devid) {
201 if (!amd_iommu_rlookup_table[pci_alias]) {
202 amd_iommu_rlookup_table[pci_alias] =
203 amd_iommu_rlookup_table[devid];
204 memcpy(amd_iommu_dev_table[pci_alias].data,
205 amd_iommu_dev_table[devid].data,
206 sizeof(amd_iommu_dev_table[pci_alias].data));
209 return pci_alias;
212 pr_info("AMD-Vi: Using IVRS reported alias %02x:%02x.%d "
213 "for device %s[%04x:%04x], kernel reported alias "
214 "%02x:%02x.%d\n", PCI_BUS_NUM(ivrs_alias), PCI_SLOT(ivrs_alias),
215 PCI_FUNC(ivrs_alias), dev_name(dev), pdev->vendor, pdev->device,
216 PCI_BUS_NUM(pci_alias), PCI_SLOT(pci_alias),
217 PCI_FUNC(pci_alias));
220 * If we don't have a PCI DMA alias and the IVRS alias is on the same
221 * bus, then the IVRS table may know about a quirk that we don't.
223 if (pci_alias == devid &&
224 PCI_BUS_NUM(ivrs_alias) == pdev->bus->number) {
225 pdev->dev_flags |= PCI_DEV_FLAGS_DMA_ALIAS_DEVFN;
226 pdev->dma_alias_devfn = ivrs_alias & 0xff;
227 pr_info("AMD-Vi: Added PCI DMA alias %02x.%d for %s\n",
228 PCI_SLOT(ivrs_alias), PCI_FUNC(ivrs_alias),
229 dev_name(dev));
232 return ivrs_alias;
235 static struct iommu_dev_data *find_dev_data(u16 devid)
237 struct iommu_dev_data *dev_data;
239 dev_data = search_dev_data(devid);
241 if (dev_data == NULL)
242 dev_data = alloc_dev_data(devid);
244 return dev_data;
247 static struct iommu_dev_data *get_dev_data(struct device *dev)
249 return dev->archdata.iommu;
252 static bool pci_iommuv2_capable(struct pci_dev *pdev)
254 static const int caps[] = {
255 PCI_EXT_CAP_ID_ATS,
256 PCI_EXT_CAP_ID_PRI,
257 PCI_EXT_CAP_ID_PASID,
259 int i, pos;
261 for (i = 0; i < 3; ++i) {
262 pos = pci_find_ext_capability(pdev, caps[i]);
263 if (pos == 0)
264 return false;
267 return true;
270 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
272 struct iommu_dev_data *dev_data;
274 dev_data = get_dev_data(&pdev->dev);
276 return dev_data->errata & (1 << erratum) ? true : false;
280 * This function actually applies the mapping to the page table of the
281 * dma_ops domain.
283 static void alloc_unity_mapping(struct dma_ops_domain *dma_dom,
284 struct unity_map_entry *e)
286 u64 addr;
288 for (addr = e->address_start; addr < e->address_end;
289 addr += PAGE_SIZE) {
290 if (addr < dma_dom->aperture_size)
291 __set_bit(addr >> PAGE_SHIFT,
292 dma_dom->aperture[0]->bitmap);
297 * Inits the unity mappings required for a specific device
299 static void init_unity_mappings_for_device(struct device *dev,
300 struct dma_ops_domain *dma_dom)
302 struct unity_map_entry *e;
303 u16 devid;
305 devid = get_device_id(dev);
307 list_for_each_entry(e, &amd_iommu_unity_map, list) {
308 if (!(devid >= e->devid_start && devid <= e->devid_end))
309 continue;
310 alloc_unity_mapping(dma_dom, e);
315 * This function checks if the driver got a valid device from the caller to
316 * avoid dereferencing invalid pointers.
318 static bool check_device(struct device *dev)
320 u16 devid;
322 if (!dev || !dev->dma_mask)
323 return false;
325 /* No PCI device */
326 if (!dev_is_pci(dev))
327 return false;
329 devid = get_device_id(dev);
331 /* Out of our scope? */
332 if (devid > amd_iommu_last_bdf)
333 return false;
335 if (amd_iommu_rlookup_table[devid] == NULL)
336 return false;
338 return true;
341 static void init_iommu_group(struct device *dev)
343 struct dma_ops_domain *dma_domain;
344 struct iommu_domain *domain;
345 struct iommu_group *group;
347 group = iommu_group_get_for_dev(dev);
348 if (IS_ERR(group))
349 return;
351 domain = iommu_group_default_domain(group);
352 if (!domain)
353 goto out;
355 if (to_pdomain(domain)->flags == PD_DMA_OPS_MASK) {
356 dma_domain = to_pdomain(domain)->priv;
357 init_unity_mappings_for_device(dev, dma_domain);
360 out:
361 iommu_group_put(group);
364 static int iommu_init_device(struct device *dev)
366 struct pci_dev *pdev = to_pci_dev(dev);
367 struct iommu_dev_data *dev_data;
369 if (dev->archdata.iommu)
370 return 0;
372 dev_data = find_dev_data(get_device_id(dev));
373 if (!dev_data)
374 return -ENOMEM;
376 dev_data->alias = get_alias(dev);
378 if (pci_iommuv2_capable(pdev)) {
379 struct amd_iommu *iommu;
381 iommu = amd_iommu_rlookup_table[dev_data->devid];
382 dev_data->iommu_v2 = iommu->is_iommu_v2;
385 dev->archdata.iommu = dev_data;
387 iommu_device_link(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
388 dev);
390 return 0;
393 static void iommu_ignore_device(struct device *dev)
395 u16 devid, alias;
397 devid = get_device_id(dev);
398 alias = get_alias(dev);
400 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
401 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
403 amd_iommu_rlookup_table[devid] = NULL;
404 amd_iommu_rlookup_table[alias] = NULL;
407 static void iommu_uninit_device(struct device *dev)
409 struct iommu_dev_data *dev_data = search_dev_data(get_device_id(dev));
411 if (!dev_data)
412 return;
414 iommu_device_unlink(amd_iommu_rlookup_table[dev_data->devid]->iommu_dev,
415 dev);
417 iommu_group_remove_device(dev);
419 /* Remove dma-ops */
420 dev->archdata.dma_ops = NULL;
423 * We keep dev_data around for unplugged devices and reuse it when the
424 * device is re-plugged - not doing so would introduce a ton of races.
428 #ifdef CONFIG_AMD_IOMMU_STATS
431 * Initialization code for statistics collection
434 DECLARE_STATS_COUNTER(compl_wait);
435 DECLARE_STATS_COUNTER(cnt_map_single);
436 DECLARE_STATS_COUNTER(cnt_unmap_single);
437 DECLARE_STATS_COUNTER(cnt_map_sg);
438 DECLARE_STATS_COUNTER(cnt_unmap_sg);
439 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
440 DECLARE_STATS_COUNTER(cnt_free_coherent);
441 DECLARE_STATS_COUNTER(cross_page);
442 DECLARE_STATS_COUNTER(domain_flush_single);
443 DECLARE_STATS_COUNTER(domain_flush_all);
444 DECLARE_STATS_COUNTER(alloced_io_mem);
445 DECLARE_STATS_COUNTER(total_map_requests);
446 DECLARE_STATS_COUNTER(complete_ppr);
447 DECLARE_STATS_COUNTER(invalidate_iotlb);
448 DECLARE_STATS_COUNTER(invalidate_iotlb_all);
449 DECLARE_STATS_COUNTER(pri_requests);
451 static struct dentry *stats_dir;
452 static struct dentry *de_fflush;
454 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
456 if (stats_dir == NULL)
457 return;
459 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
460 &cnt->value);
463 static void amd_iommu_stats_init(void)
465 stats_dir = debugfs_create_dir("amd-iommu", NULL);
466 if (stats_dir == NULL)
467 return;
469 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
470 &amd_iommu_unmap_flush);
472 amd_iommu_stats_add(&compl_wait);
473 amd_iommu_stats_add(&cnt_map_single);
474 amd_iommu_stats_add(&cnt_unmap_single);
475 amd_iommu_stats_add(&cnt_map_sg);
476 amd_iommu_stats_add(&cnt_unmap_sg);
477 amd_iommu_stats_add(&cnt_alloc_coherent);
478 amd_iommu_stats_add(&cnt_free_coherent);
479 amd_iommu_stats_add(&cross_page);
480 amd_iommu_stats_add(&domain_flush_single);
481 amd_iommu_stats_add(&domain_flush_all);
482 amd_iommu_stats_add(&alloced_io_mem);
483 amd_iommu_stats_add(&total_map_requests);
484 amd_iommu_stats_add(&complete_ppr);
485 amd_iommu_stats_add(&invalidate_iotlb);
486 amd_iommu_stats_add(&invalidate_iotlb_all);
487 amd_iommu_stats_add(&pri_requests);
490 #endif
492 /****************************************************************************
494 * Interrupt handling functions
496 ****************************************************************************/
498 static void dump_dte_entry(u16 devid)
500 int i;
502 for (i = 0; i < 4; ++i)
503 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
504 amd_iommu_dev_table[devid].data[i]);
507 static void dump_command(unsigned long phys_addr)
509 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
510 int i;
512 for (i = 0; i < 4; ++i)
513 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
516 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
518 int type, devid, domid, flags;
519 volatile u32 *event = __evt;
520 int count = 0;
521 u64 address;
523 retry:
524 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
525 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
526 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
527 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
528 address = (u64)(((u64)event[3]) << 32) | event[2];
530 if (type == 0) {
531 /* Did we hit the erratum? */
532 if (++count == LOOP_TIMEOUT) {
533 pr_err("AMD-Vi: No event written to event log\n");
534 return;
536 udelay(1);
537 goto retry;
540 printk(KERN_ERR "AMD-Vi: Event logged [");
542 switch (type) {
543 case EVENT_TYPE_ILL_DEV:
544 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
545 "address=0x%016llx flags=0x%04x]\n",
546 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
547 address, flags);
548 dump_dte_entry(devid);
549 break;
550 case EVENT_TYPE_IO_FAULT:
551 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
552 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
553 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
554 domid, address, flags);
555 break;
556 case EVENT_TYPE_DEV_TAB_ERR:
557 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
558 "address=0x%016llx flags=0x%04x]\n",
559 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
560 address, flags);
561 break;
562 case EVENT_TYPE_PAGE_TAB_ERR:
563 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
564 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
565 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
566 domid, address, flags);
567 break;
568 case EVENT_TYPE_ILL_CMD:
569 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
570 dump_command(address);
571 break;
572 case EVENT_TYPE_CMD_HARD_ERR:
573 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
574 "flags=0x%04x]\n", address, flags);
575 break;
576 case EVENT_TYPE_IOTLB_INV_TO:
577 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
578 "address=0x%016llx]\n",
579 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
580 address);
581 break;
582 case EVENT_TYPE_INV_DEV_REQ:
583 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
584 "address=0x%016llx flags=0x%04x]\n",
585 PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
586 address, flags);
587 break;
588 default:
589 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
592 memset(__evt, 0, 4 * sizeof(u32));
595 static void iommu_poll_events(struct amd_iommu *iommu)
597 u32 head, tail;
599 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
600 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
602 while (head != tail) {
603 iommu_print_event(iommu, iommu->evt_buf + head);
604 head = (head + EVENT_ENTRY_SIZE) % EVT_BUFFER_SIZE;
607 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
610 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
612 struct amd_iommu_fault fault;
614 INC_STATS_COUNTER(pri_requests);
616 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
617 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
618 return;
621 fault.address = raw[1];
622 fault.pasid = PPR_PASID(raw[0]);
623 fault.device_id = PPR_DEVID(raw[0]);
624 fault.tag = PPR_TAG(raw[0]);
625 fault.flags = PPR_FLAGS(raw[0]);
627 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
630 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
632 u32 head, tail;
634 if (iommu->ppr_log == NULL)
635 return;
637 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
638 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
640 while (head != tail) {
641 volatile u64 *raw;
642 u64 entry[2];
643 int i;
645 raw = (u64 *)(iommu->ppr_log + head);
648 * Hardware bug: Interrupt may arrive before the entry is
649 * written to memory. If this happens we need to wait for the
650 * entry to arrive.
652 for (i = 0; i < LOOP_TIMEOUT; ++i) {
653 if (PPR_REQ_TYPE(raw[0]) != 0)
654 break;
655 udelay(1);
658 /* Avoid memcpy function-call overhead */
659 entry[0] = raw[0];
660 entry[1] = raw[1];
663 * To detect the hardware bug we need to clear the entry
664 * back to zero.
666 raw[0] = raw[1] = 0UL;
668 /* Update head pointer of hardware ring-buffer */
669 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
670 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
672 /* Handle PPR entry */
673 iommu_handle_ppr_entry(iommu, entry);
675 /* Refresh ring-buffer information */
676 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
677 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
681 irqreturn_t amd_iommu_int_thread(int irq, void *data)
683 struct amd_iommu *iommu = (struct amd_iommu *) data;
684 u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
686 while (status & (MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK)) {
687 /* Enable EVT and PPR interrupts again */
688 writel((MMIO_STATUS_EVT_INT_MASK | MMIO_STATUS_PPR_INT_MASK),
689 iommu->mmio_base + MMIO_STATUS_OFFSET);
691 if (status & MMIO_STATUS_EVT_INT_MASK) {
692 pr_devel("AMD-Vi: Processing IOMMU Event Log\n");
693 iommu_poll_events(iommu);
696 if (status & MMIO_STATUS_PPR_INT_MASK) {
697 pr_devel("AMD-Vi: Processing IOMMU PPR Log\n");
698 iommu_poll_ppr_log(iommu);
702 * Hardware bug: ERBT1312
703 * When re-enabling interrupt (by writing 1
704 * to clear the bit), the hardware might also try to set
705 * the interrupt bit in the event status register.
706 * In this scenario, the bit will be set, and disable
707 * subsequent interrupts.
709 * Workaround: The IOMMU driver should read back the
710 * status register and check if the interrupt bits are cleared.
711 * If not, driver will need to go through the interrupt handler
712 * again and re-clear the bits
714 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
716 return IRQ_HANDLED;
719 irqreturn_t amd_iommu_int_handler(int irq, void *data)
721 return IRQ_WAKE_THREAD;
724 /****************************************************************************
726 * IOMMU command queuing functions
728 ****************************************************************************/
730 static int wait_on_sem(volatile u64 *sem)
732 int i = 0;
734 while (*sem == 0 && i < LOOP_TIMEOUT) {
735 udelay(1);
736 i += 1;
739 if (i == LOOP_TIMEOUT) {
740 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
741 return -EIO;
744 return 0;
747 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
748 struct iommu_cmd *cmd,
749 u32 tail)
751 u8 *target;
753 target = iommu->cmd_buf + tail;
754 tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
756 /* Copy command to buffer */
757 memcpy(target, cmd, sizeof(*cmd));
759 /* Tell the IOMMU about it */
760 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
763 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
765 WARN_ON(address & 0x7ULL);
767 memset(cmd, 0, sizeof(*cmd));
768 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
769 cmd->data[1] = upper_32_bits(__pa(address));
770 cmd->data[2] = 1;
771 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
774 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
776 memset(cmd, 0, sizeof(*cmd));
777 cmd->data[0] = devid;
778 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
781 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
782 size_t size, u16 domid, int pde)
784 u64 pages;
785 bool s;
787 pages = iommu_num_pages(address, size, PAGE_SIZE);
788 s = false;
790 if (pages > 1) {
792 * If we have to flush more than one page, flush all
793 * TLB entries for this domain
795 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
796 s = true;
799 address &= PAGE_MASK;
801 memset(cmd, 0, sizeof(*cmd));
802 cmd->data[1] |= domid;
803 cmd->data[2] = lower_32_bits(address);
804 cmd->data[3] = upper_32_bits(address);
805 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
806 if (s) /* size bit - we flush more than one 4kb page */
807 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
808 if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
809 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
812 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
813 u64 address, size_t size)
815 u64 pages;
816 bool s;
818 pages = iommu_num_pages(address, size, PAGE_SIZE);
819 s = false;
821 if (pages > 1) {
823 * If we have to flush more than one page, flush all
824 * TLB entries for this domain
826 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
827 s = true;
830 address &= PAGE_MASK;
832 memset(cmd, 0, sizeof(*cmd));
833 cmd->data[0] = devid;
834 cmd->data[0] |= (qdep & 0xff) << 24;
835 cmd->data[1] = devid;
836 cmd->data[2] = lower_32_bits(address);
837 cmd->data[3] = upper_32_bits(address);
838 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
839 if (s)
840 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
843 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
844 u64 address, bool size)
846 memset(cmd, 0, sizeof(*cmd));
848 address &= ~(0xfffULL);
850 cmd->data[0] = pasid;
851 cmd->data[1] = domid;
852 cmd->data[2] = lower_32_bits(address);
853 cmd->data[3] = upper_32_bits(address);
854 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
855 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
856 if (size)
857 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
858 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
861 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
862 int qdep, u64 address, bool size)
864 memset(cmd, 0, sizeof(*cmd));
866 address &= ~(0xfffULL);
868 cmd->data[0] = devid;
869 cmd->data[0] |= ((pasid >> 8) & 0xff) << 16;
870 cmd->data[0] |= (qdep & 0xff) << 24;
871 cmd->data[1] = devid;
872 cmd->data[1] |= (pasid & 0xff) << 16;
873 cmd->data[2] = lower_32_bits(address);
874 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
875 cmd->data[3] = upper_32_bits(address);
876 if (size)
877 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
878 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
881 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
882 int status, int tag, bool gn)
884 memset(cmd, 0, sizeof(*cmd));
886 cmd->data[0] = devid;
887 if (gn) {
888 cmd->data[1] = pasid;
889 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
891 cmd->data[3] = tag & 0x1ff;
892 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
894 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
897 static void build_inv_all(struct iommu_cmd *cmd)
899 memset(cmd, 0, sizeof(*cmd));
900 CMD_SET_TYPE(cmd, CMD_INV_ALL);
903 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
905 memset(cmd, 0, sizeof(*cmd));
906 cmd->data[0] = devid;
907 CMD_SET_TYPE(cmd, CMD_INV_IRT);
911 * Writes the command to the IOMMUs command buffer and informs the
912 * hardware about the new command.
914 static int iommu_queue_command_sync(struct amd_iommu *iommu,
915 struct iommu_cmd *cmd,
916 bool sync)
918 u32 left, tail, head, next_tail;
919 unsigned long flags;
921 again:
922 spin_lock_irqsave(&iommu->lock, flags);
924 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
925 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
926 next_tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
927 left = (head - next_tail) % CMD_BUFFER_SIZE;
929 if (left <= 0x20) {
930 struct iommu_cmd sync_cmd;
931 volatile u64 sem = 0;
932 int ret;
934 build_completion_wait(&sync_cmd, (u64)&sem);
935 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
937 spin_unlock_irqrestore(&iommu->lock, flags);
939 if ((ret = wait_on_sem(&sem)) != 0)
940 return ret;
942 goto again;
945 copy_cmd_to_buffer(iommu, cmd, tail);
947 /* We need to sync now to make sure all commands are processed */
948 iommu->need_sync = sync;
950 spin_unlock_irqrestore(&iommu->lock, flags);
952 return 0;
955 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
957 return iommu_queue_command_sync(iommu, cmd, true);
961 * This function queues a completion wait command into the command
962 * buffer of an IOMMU
964 static int iommu_completion_wait(struct amd_iommu *iommu)
966 struct iommu_cmd cmd;
967 volatile u64 sem = 0;
968 int ret;
970 if (!iommu->need_sync)
971 return 0;
973 build_completion_wait(&cmd, (u64)&sem);
975 ret = iommu_queue_command_sync(iommu, &cmd, false);
976 if (ret)
977 return ret;
979 return wait_on_sem(&sem);
982 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
984 struct iommu_cmd cmd;
986 build_inv_dte(&cmd, devid);
988 return iommu_queue_command(iommu, &cmd);
991 static void iommu_flush_dte_all(struct amd_iommu *iommu)
993 u32 devid;
995 for (devid = 0; devid <= 0xffff; ++devid)
996 iommu_flush_dte(iommu, devid);
998 iommu_completion_wait(iommu);
1002 * This function uses heavy locking and may disable irqs for some time. But
1003 * this is no issue because it is only called during resume.
1005 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1007 u32 dom_id;
1009 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1010 struct iommu_cmd cmd;
1011 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1012 dom_id, 1);
1013 iommu_queue_command(iommu, &cmd);
1016 iommu_completion_wait(iommu);
1019 static void iommu_flush_all(struct amd_iommu *iommu)
1021 struct iommu_cmd cmd;
1023 build_inv_all(&cmd);
1025 iommu_queue_command(iommu, &cmd);
1026 iommu_completion_wait(iommu);
1029 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1031 struct iommu_cmd cmd;
1033 build_inv_irt(&cmd, devid);
1035 iommu_queue_command(iommu, &cmd);
1038 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1040 u32 devid;
1042 for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1043 iommu_flush_irt(iommu, devid);
1045 iommu_completion_wait(iommu);
1048 void iommu_flush_all_caches(struct amd_iommu *iommu)
1050 if (iommu_feature(iommu, FEATURE_IA)) {
1051 iommu_flush_all(iommu);
1052 } else {
1053 iommu_flush_dte_all(iommu);
1054 iommu_flush_irt_all(iommu);
1055 iommu_flush_tlb_all(iommu);
1060 * Command send function for flushing on-device TLB
1062 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1063 u64 address, size_t size)
1065 struct amd_iommu *iommu;
1066 struct iommu_cmd cmd;
1067 int qdep;
1069 qdep = dev_data->ats.qdep;
1070 iommu = amd_iommu_rlookup_table[dev_data->devid];
1072 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1074 return iommu_queue_command(iommu, &cmd);
1078 * Command send function for invalidating a device table entry
1080 static int device_flush_dte(struct iommu_dev_data *dev_data)
1082 struct amd_iommu *iommu;
1083 u16 alias;
1084 int ret;
1086 iommu = amd_iommu_rlookup_table[dev_data->devid];
1087 alias = dev_data->alias;
1089 ret = iommu_flush_dte(iommu, dev_data->devid);
1090 if (!ret && alias != dev_data->devid)
1091 ret = iommu_flush_dte(iommu, alias);
1092 if (ret)
1093 return ret;
1095 if (dev_data->ats.enabled)
1096 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1098 return ret;
1102 * TLB invalidation function which is called from the mapping functions.
1103 * It invalidates a single PTE if the range to flush is within a single
1104 * page. Otherwise it flushes the whole TLB of the IOMMU.
1106 static void __domain_flush_pages(struct protection_domain *domain,
1107 u64 address, size_t size, int pde)
1109 struct iommu_dev_data *dev_data;
1110 struct iommu_cmd cmd;
1111 int ret = 0, i;
1113 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1115 for (i = 0; i < amd_iommus_present; ++i) {
1116 if (!domain->dev_iommu[i])
1117 continue;
1120 * Devices of this domain are behind this IOMMU
1121 * We need a TLB flush
1123 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1126 list_for_each_entry(dev_data, &domain->dev_list, list) {
1128 if (!dev_data->ats.enabled)
1129 continue;
1131 ret |= device_flush_iotlb(dev_data, address, size);
1134 WARN_ON(ret);
1137 static void domain_flush_pages(struct protection_domain *domain,
1138 u64 address, size_t size)
1140 __domain_flush_pages(domain, address, size, 0);
1143 /* Flush the whole IO/TLB for a given protection domain */
1144 static void domain_flush_tlb(struct protection_domain *domain)
1146 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1149 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1150 static void domain_flush_tlb_pde(struct protection_domain *domain)
1152 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1155 static void domain_flush_complete(struct protection_domain *domain)
1157 int i;
1159 for (i = 0; i < amd_iommus_present; ++i) {
1160 if (!domain->dev_iommu[i])
1161 continue;
1164 * Devices of this domain are behind this IOMMU
1165 * We need to wait for completion of all commands.
1167 iommu_completion_wait(amd_iommus[i]);
1173 * This function flushes the DTEs for all devices in domain
1175 static void domain_flush_devices(struct protection_domain *domain)
1177 struct iommu_dev_data *dev_data;
1179 list_for_each_entry(dev_data, &domain->dev_list, list)
1180 device_flush_dte(dev_data);
1183 /****************************************************************************
1185 * The functions below are used the create the page table mappings for
1186 * unity mapped regions.
1188 ****************************************************************************/
1191 * This function is used to add another level to an IO page table. Adding
1192 * another level increases the size of the address space by 9 bits to a size up
1193 * to 64 bits.
1195 static bool increase_address_space(struct protection_domain *domain,
1196 gfp_t gfp)
1198 u64 *pte;
1200 if (domain->mode == PAGE_MODE_6_LEVEL)
1201 /* address space already 64 bit large */
1202 return false;
1204 pte = (void *)get_zeroed_page(gfp);
1205 if (!pte)
1206 return false;
1208 *pte = PM_LEVEL_PDE(domain->mode,
1209 virt_to_phys(domain->pt_root));
1210 domain->pt_root = pte;
1211 domain->mode += 1;
1212 domain->updated = true;
1214 return true;
1217 static u64 *alloc_pte(struct protection_domain *domain,
1218 unsigned long address,
1219 unsigned long page_size,
1220 u64 **pte_page,
1221 gfp_t gfp)
1223 int level, end_lvl;
1224 u64 *pte, *page;
1226 BUG_ON(!is_power_of_2(page_size));
1228 while (address > PM_LEVEL_SIZE(domain->mode))
1229 increase_address_space(domain, gfp);
1231 level = domain->mode - 1;
1232 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1233 address = PAGE_SIZE_ALIGN(address, page_size);
1234 end_lvl = PAGE_SIZE_LEVEL(page_size);
1236 while (level > end_lvl) {
1237 if (!IOMMU_PTE_PRESENT(*pte)) {
1238 page = (u64 *)get_zeroed_page(gfp);
1239 if (!page)
1240 return NULL;
1241 *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1244 /* No level skipping support yet */
1245 if (PM_PTE_LEVEL(*pte) != level)
1246 return NULL;
1248 level -= 1;
1250 pte = IOMMU_PTE_PAGE(*pte);
1252 if (pte_page && level == end_lvl)
1253 *pte_page = pte;
1255 pte = &pte[PM_LEVEL_INDEX(level, address)];
1258 return pte;
1262 * This function checks if there is a PTE for a given dma address. If
1263 * there is one, it returns the pointer to it.
1265 static u64 *fetch_pte(struct protection_domain *domain,
1266 unsigned long address,
1267 unsigned long *page_size)
1269 int level;
1270 u64 *pte;
1272 if (address > PM_LEVEL_SIZE(domain->mode))
1273 return NULL;
1275 level = domain->mode - 1;
1276 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1277 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1279 while (level > 0) {
1281 /* Not Present */
1282 if (!IOMMU_PTE_PRESENT(*pte))
1283 return NULL;
1285 /* Large PTE */
1286 if (PM_PTE_LEVEL(*pte) == 7 ||
1287 PM_PTE_LEVEL(*pte) == 0)
1288 break;
1290 /* No level skipping support yet */
1291 if (PM_PTE_LEVEL(*pte) != level)
1292 return NULL;
1294 level -= 1;
1296 /* Walk to the next level */
1297 pte = IOMMU_PTE_PAGE(*pte);
1298 pte = &pte[PM_LEVEL_INDEX(level, address)];
1299 *page_size = PTE_LEVEL_PAGE_SIZE(level);
1302 if (PM_PTE_LEVEL(*pte) == 0x07) {
1303 unsigned long pte_mask;
1306 * If we have a series of large PTEs, make
1307 * sure to return a pointer to the first one.
1309 *page_size = pte_mask = PTE_PAGE_SIZE(*pte);
1310 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1311 pte = (u64 *)(((unsigned long)pte) & pte_mask);
1314 return pte;
1318 * Generic mapping functions. It maps a physical address into a DMA
1319 * address space. It allocates the page table pages if necessary.
1320 * In the future it can be extended to a generic mapping function
1321 * supporting all features of AMD IOMMU page tables like level skipping
1322 * and full 64 bit address spaces.
1324 static int iommu_map_page(struct protection_domain *dom,
1325 unsigned long bus_addr,
1326 unsigned long phys_addr,
1327 int prot,
1328 unsigned long page_size)
1330 u64 __pte, *pte;
1331 int i, count;
1333 BUG_ON(!IS_ALIGNED(bus_addr, page_size));
1334 BUG_ON(!IS_ALIGNED(phys_addr, page_size));
1336 if (!(prot & IOMMU_PROT_MASK))
1337 return -EINVAL;
1339 count = PAGE_SIZE_PTE_COUNT(page_size);
1340 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1342 if (!pte)
1343 return -ENOMEM;
1345 for (i = 0; i < count; ++i)
1346 if (IOMMU_PTE_PRESENT(pte[i]))
1347 return -EBUSY;
1349 if (count > 1) {
1350 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1351 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1352 } else
1353 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1355 if (prot & IOMMU_PROT_IR)
1356 __pte |= IOMMU_PTE_IR;
1357 if (prot & IOMMU_PROT_IW)
1358 __pte |= IOMMU_PTE_IW;
1360 for (i = 0; i < count; ++i)
1361 pte[i] = __pte;
1363 update_domain(dom);
1365 return 0;
1368 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1369 unsigned long bus_addr,
1370 unsigned long page_size)
1372 unsigned long long unmapped;
1373 unsigned long unmap_size;
1374 u64 *pte;
1376 BUG_ON(!is_power_of_2(page_size));
1378 unmapped = 0;
1380 while (unmapped < page_size) {
1382 pte = fetch_pte(dom, bus_addr, &unmap_size);
1384 if (pte) {
1385 int i, count;
1387 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1388 for (i = 0; i < count; i++)
1389 pte[i] = 0ULL;
1392 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1393 unmapped += unmap_size;
1396 BUG_ON(unmapped && !is_power_of_2(unmapped));
1398 return unmapped;
1401 /****************************************************************************
1403 * The next functions belong to the address allocator for the dma_ops
1404 * interface functions. They work like the allocators in the other IOMMU
1405 * drivers. Its basically a bitmap which marks the allocated pages in
1406 * the aperture. Maybe it could be enhanced in the future to a more
1407 * efficient allocator.
1409 ****************************************************************************/
1412 * The address allocator core functions.
1414 * called with domain->lock held
1418 * Used to reserve address ranges in the aperture (e.g. for exclusion
1419 * ranges.
1421 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1422 unsigned long start_page,
1423 unsigned int pages)
1425 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1427 if (start_page + pages > last_page)
1428 pages = last_page - start_page;
1430 for (i = start_page; i < start_page + pages; ++i) {
1431 int index = i / APERTURE_RANGE_PAGES;
1432 int page = i % APERTURE_RANGE_PAGES;
1433 __set_bit(page, dom->aperture[index]->bitmap);
1438 * This function is used to add a new aperture range to an existing
1439 * aperture in case of dma_ops domain allocation or address allocation
1440 * failure.
1442 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1443 bool populate, gfp_t gfp)
1445 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1446 struct amd_iommu *iommu;
1447 unsigned long i, old_size, pte_pgsize;
1449 #ifdef CONFIG_IOMMU_STRESS
1450 populate = false;
1451 #endif
1453 if (index >= APERTURE_MAX_RANGES)
1454 return -ENOMEM;
1456 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1457 if (!dma_dom->aperture[index])
1458 return -ENOMEM;
1460 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1461 if (!dma_dom->aperture[index]->bitmap)
1462 goto out_free;
1464 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1466 if (populate) {
1467 unsigned long address = dma_dom->aperture_size;
1468 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1469 u64 *pte, *pte_page;
1471 for (i = 0; i < num_ptes; ++i) {
1472 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1473 &pte_page, gfp);
1474 if (!pte)
1475 goto out_free;
1477 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1479 address += APERTURE_RANGE_SIZE / 64;
1483 old_size = dma_dom->aperture_size;
1484 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1486 /* Reserve address range used for MSI messages */
1487 if (old_size < MSI_ADDR_BASE_LO &&
1488 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1489 unsigned long spage;
1490 int pages;
1492 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1493 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1495 dma_ops_reserve_addresses(dma_dom, spage, pages);
1498 /* Initialize the exclusion range if necessary */
1499 for_each_iommu(iommu) {
1500 if (iommu->exclusion_start &&
1501 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1502 && iommu->exclusion_start < dma_dom->aperture_size) {
1503 unsigned long startpage;
1504 int pages = iommu_num_pages(iommu->exclusion_start,
1505 iommu->exclusion_length,
1506 PAGE_SIZE);
1507 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1508 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1513 * Check for areas already mapped as present in the new aperture
1514 * range and mark those pages as reserved in the allocator. Such
1515 * mappings may already exist as a result of requested unity
1516 * mappings for devices.
1518 for (i = dma_dom->aperture[index]->offset;
1519 i < dma_dom->aperture_size;
1520 i += pte_pgsize) {
1521 u64 *pte = fetch_pte(&dma_dom->domain, i, &pte_pgsize);
1522 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1523 continue;
1525 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT,
1526 pte_pgsize >> 12);
1529 update_domain(&dma_dom->domain);
1531 return 0;
1533 out_free:
1534 update_domain(&dma_dom->domain);
1536 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1538 kfree(dma_dom->aperture[index]);
1539 dma_dom->aperture[index] = NULL;
1541 return -ENOMEM;
1544 static unsigned long dma_ops_area_alloc(struct device *dev,
1545 struct dma_ops_domain *dom,
1546 unsigned int pages,
1547 unsigned long align_mask,
1548 u64 dma_mask,
1549 unsigned long start)
1551 unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1552 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1553 int i = start >> APERTURE_RANGE_SHIFT;
1554 unsigned long boundary_size, mask;
1555 unsigned long address = -1;
1556 unsigned long limit;
1558 next_bit >>= PAGE_SHIFT;
1560 mask = dma_get_seg_boundary(dev);
1562 boundary_size = mask + 1 ? ALIGN(mask + 1, PAGE_SIZE) >> PAGE_SHIFT :
1563 1UL << (BITS_PER_LONG - PAGE_SHIFT);
1565 for (;i < max_index; ++i) {
1566 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1568 if (dom->aperture[i]->offset >= dma_mask)
1569 break;
1571 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1572 dma_mask >> PAGE_SHIFT);
1574 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1575 limit, next_bit, pages, 0,
1576 boundary_size, align_mask);
1577 if (address != -1) {
1578 address = dom->aperture[i]->offset +
1579 (address << PAGE_SHIFT);
1580 dom->next_address = address + (pages << PAGE_SHIFT);
1581 break;
1584 next_bit = 0;
1587 return address;
1590 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1591 struct dma_ops_domain *dom,
1592 unsigned int pages,
1593 unsigned long align_mask,
1594 u64 dma_mask)
1596 unsigned long address;
1598 #ifdef CONFIG_IOMMU_STRESS
1599 dom->next_address = 0;
1600 dom->need_flush = true;
1601 #endif
1603 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1604 dma_mask, dom->next_address);
1606 if (address == -1) {
1607 dom->next_address = 0;
1608 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1609 dma_mask, 0);
1610 dom->need_flush = true;
1613 if (unlikely(address == -1))
1614 address = DMA_ERROR_CODE;
1616 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1618 return address;
1622 * The address free function.
1624 * called with domain->lock held
1626 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1627 unsigned long address,
1628 unsigned int pages)
1630 unsigned i = address >> APERTURE_RANGE_SHIFT;
1631 struct aperture_range *range = dom->aperture[i];
1633 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1635 #ifdef CONFIG_IOMMU_STRESS
1636 if (i < 4)
1637 return;
1638 #endif
1640 if (address >= dom->next_address)
1641 dom->need_flush = true;
1643 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1645 bitmap_clear(range->bitmap, address, pages);
1649 /****************************************************************************
1651 * The next functions belong to the domain allocation. A domain is
1652 * allocated for every IOMMU as the default domain. If device isolation
1653 * is enabled, every device get its own domain. The most important thing
1654 * about domains is the page table mapping the DMA address space they
1655 * contain.
1657 ****************************************************************************/
1660 * This function adds a protection domain to the global protection domain list
1662 static void add_domain_to_list(struct protection_domain *domain)
1664 unsigned long flags;
1666 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1667 list_add(&domain->list, &amd_iommu_pd_list);
1668 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1672 * This function removes a protection domain to the global
1673 * protection domain list
1675 static void del_domain_from_list(struct protection_domain *domain)
1677 unsigned long flags;
1679 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1680 list_del(&domain->list);
1681 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1684 static u16 domain_id_alloc(void)
1686 unsigned long flags;
1687 int id;
1689 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1690 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1691 BUG_ON(id == 0);
1692 if (id > 0 && id < MAX_DOMAIN_ID)
1693 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1694 else
1695 id = 0;
1696 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1698 return id;
1701 static void domain_id_free(int id)
1703 unsigned long flags;
1705 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1706 if (id > 0 && id < MAX_DOMAIN_ID)
1707 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1708 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1711 #define DEFINE_FREE_PT_FN(LVL, FN) \
1712 static void free_pt_##LVL (unsigned long __pt) \
1714 unsigned long p; \
1715 u64 *pt; \
1716 int i; \
1718 pt = (u64 *)__pt; \
1720 for (i = 0; i < 512; ++i) { \
1721 /* PTE present? */ \
1722 if (!IOMMU_PTE_PRESENT(pt[i])) \
1723 continue; \
1725 /* Large PTE? */ \
1726 if (PM_PTE_LEVEL(pt[i]) == 0 || \
1727 PM_PTE_LEVEL(pt[i]) == 7) \
1728 continue; \
1730 p = (unsigned long)IOMMU_PTE_PAGE(pt[i]); \
1731 FN(p); \
1733 free_page((unsigned long)pt); \
1736 DEFINE_FREE_PT_FN(l2, free_page)
1737 DEFINE_FREE_PT_FN(l3, free_pt_l2)
1738 DEFINE_FREE_PT_FN(l4, free_pt_l3)
1739 DEFINE_FREE_PT_FN(l5, free_pt_l4)
1740 DEFINE_FREE_PT_FN(l6, free_pt_l5)
1742 static void free_pagetable(struct protection_domain *domain)
1744 unsigned long root = (unsigned long)domain->pt_root;
1746 switch (domain->mode) {
1747 case PAGE_MODE_NONE:
1748 break;
1749 case PAGE_MODE_1_LEVEL:
1750 free_page(root);
1751 break;
1752 case PAGE_MODE_2_LEVEL:
1753 free_pt_l2(root);
1754 break;
1755 case PAGE_MODE_3_LEVEL:
1756 free_pt_l3(root);
1757 break;
1758 case PAGE_MODE_4_LEVEL:
1759 free_pt_l4(root);
1760 break;
1761 case PAGE_MODE_5_LEVEL:
1762 free_pt_l5(root);
1763 break;
1764 case PAGE_MODE_6_LEVEL:
1765 free_pt_l6(root);
1766 break;
1767 default:
1768 BUG();
1772 static void free_gcr3_tbl_level1(u64 *tbl)
1774 u64 *ptr;
1775 int i;
1777 for (i = 0; i < 512; ++i) {
1778 if (!(tbl[i] & GCR3_VALID))
1779 continue;
1781 ptr = __va(tbl[i] & PAGE_MASK);
1783 free_page((unsigned long)ptr);
1787 static void free_gcr3_tbl_level2(u64 *tbl)
1789 u64 *ptr;
1790 int i;
1792 for (i = 0; i < 512; ++i) {
1793 if (!(tbl[i] & GCR3_VALID))
1794 continue;
1796 ptr = __va(tbl[i] & PAGE_MASK);
1798 free_gcr3_tbl_level1(ptr);
1802 static void free_gcr3_table(struct protection_domain *domain)
1804 if (domain->glx == 2)
1805 free_gcr3_tbl_level2(domain->gcr3_tbl);
1806 else if (domain->glx == 1)
1807 free_gcr3_tbl_level1(domain->gcr3_tbl);
1808 else
1809 BUG_ON(domain->glx != 0);
1811 free_page((unsigned long)domain->gcr3_tbl);
1815 * Free a domain, only used if something went wrong in the
1816 * allocation path and we need to free an already allocated page table
1818 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1820 int i;
1822 if (!dom)
1823 return;
1825 del_domain_from_list(&dom->domain);
1827 free_pagetable(&dom->domain);
1829 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1830 if (!dom->aperture[i])
1831 continue;
1832 free_page((unsigned long)dom->aperture[i]->bitmap);
1833 kfree(dom->aperture[i]);
1836 if (dom->domain.id)
1837 domain_id_free(dom->domain.id);
1839 kfree(dom);
1843 * Allocates a new protection domain usable for the dma_ops functions.
1844 * It also initializes the page table and the address allocator data
1845 * structures required for the dma_ops interface
1847 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1849 struct dma_ops_domain *dma_dom;
1851 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1852 if (!dma_dom)
1853 return NULL;
1855 if (protection_domain_init(&dma_dom->domain))
1856 goto free_dma_dom;
1858 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1859 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1860 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1861 dma_dom->domain.priv = dma_dom;
1862 if (!dma_dom->domain.pt_root)
1863 goto free_dma_dom;
1865 dma_dom->need_flush = false;
1867 add_domain_to_list(&dma_dom->domain);
1869 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1870 goto free_dma_dom;
1873 * mark the first page as allocated so we never return 0 as
1874 * a valid dma-address. So we can use 0 as error value
1876 dma_dom->aperture[0]->bitmap[0] = 1;
1877 dma_dom->next_address = 0;
1880 return dma_dom;
1882 free_dma_dom:
1883 dma_ops_domain_free(dma_dom);
1885 return NULL;
1889 * little helper function to check whether a given protection domain is a
1890 * dma_ops domain
1892 static bool dma_ops_domain(struct protection_domain *domain)
1894 return domain->flags & PD_DMA_OPS_MASK;
1897 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1899 u64 pte_root = 0;
1900 u64 flags = 0;
1902 if (domain->mode != PAGE_MODE_NONE)
1903 pte_root = virt_to_phys(domain->pt_root);
1905 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1906 << DEV_ENTRY_MODE_SHIFT;
1907 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1909 flags = amd_iommu_dev_table[devid].data[1];
1911 if (ats)
1912 flags |= DTE_FLAG_IOTLB;
1914 if (domain->flags & PD_IOMMUV2_MASK) {
1915 u64 gcr3 = __pa(domain->gcr3_tbl);
1916 u64 glx = domain->glx;
1917 u64 tmp;
1919 pte_root |= DTE_FLAG_GV;
1920 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1922 /* First mask out possible old values for GCR3 table */
1923 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1924 flags &= ~tmp;
1926 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1927 flags &= ~tmp;
1929 /* Encode GCR3 table into DTE */
1930 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1931 pte_root |= tmp;
1933 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1934 flags |= tmp;
1936 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
1937 flags |= tmp;
1940 flags &= ~(0xffffUL);
1941 flags |= domain->id;
1943 amd_iommu_dev_table[devid].data[1] = flags;
1944 amd_iommu_dev_table[devid].data[0] = pte_root;
1947 static void clear_dte_entry(u16 devid)
1949 /* remove entry from the device table seen by the hardware */
1950 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1951 amd_iommu_dev_table[devid].data[1] &= DTE_FLAG_MASK;
1953 amd_iommu_apply_erratum_63(devid);
1956 static void do_attach(struct iommu_dev_data *dev_data,
1957 struct protection_domain *domain)
1959 struct amd_iommu *iommu;
1960 u16 alias;
1961 bool ats;
1963 iommu = amd_iommu_rlookup_table[dev_data->devid];
1964 alias = dev_data->alias;
1965 ats = dev_data->ats.enabled;
1967 /* Update data structures */
1968 dev_data->domain = domain;
1969 list_add(&dev_data->list, &domain->dev_list);
1971 /* Do reference counting */
1972 domain->dev_iommu[iommu->index] += 1;
1973 domain->dev_cnt += 1;
1975 /* Update device table */
1976 set_dte_entry(dev_data->devid, domain, ats);
1977 if (alias != dev_data->devid)
1978 set_dte_entry(alias, domain, ats);
1980 device_flush_dte(dev_data);
1983 static void do_detach(struct iommu_dev_data *dev_data)
1985 struct amd_iommu *iommu;
1986 u16 alias;
1989 * First check if the device is still attached. It might already
1990 * be detached from its domain because the generic
1991 * iommu_detach_group code detached it and we try again here in
1992 * our alias handling.
1994 if (!dev_data->domain)
1995 return;
1997 iommu = amd_iommu_rlookup_table[dev_data->devid];
1998 alias = dev_data->alias;
2000 /* decrease reference counters */
2001 dev_data->domain->dev_iommu[iommu->index] -= 1;
2002 dev_data->domain->dev_cnt -= 1;
2004 /* Update data structures */
2005 dev_data->domain = NULL;
2006 list_del(&dev_data->list);
2007 clear_dte_entry(dev_data->devid);
2008 if (alias != dev_data->devid)
2009 clear_dte_entry(alias);
2011 /* Flush the DTE entry */
2012 device_flush_dte(dev_data);
2016 * If a device is not yet associated with a domain, this function does
2017 * assigns it visible for the hardware
2019 static int __attach_device(struct iommu_dev_data *dev_data,
2020 struct protection_domain *domain)
2022 int ret;
2025 * Must be called with IRQs disabled. Warn here to detect early
2026 * when its not.
2028 WARN_ON(!irqs_disabled());
2030 /* lock domain */
2031 spin_lock(&domain->lock);
2033 ret = -EBUSY;
2034 if (dev_data->domain != NULL)
2035 goto out_unlock;
2037 /* Attach alias group root */
2038 do_attach(dev_data, domain);
2040 ret = 0;
2042 out_unlock:
2044 /* ready */
2045 spin_unlock(&domain->lock);
2047 return ret;
2051 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2053 pci_disable_ats(pdev);
2054 pci_disable_pri(pdev);
2055 pci_disable_pasid(pdev);
2058 /* FIXME: Change generic reset-function to do the same */
2059 static int pri_reset_while_enabled(struct pci_dev *pdev)
2061 u16 control;
2062 int pos;
2064 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2065 if (!pos)
2066 return -EINVAL;
2068 pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2069 control |= PCI_PRI_CTRL_RESET;
2070 pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2072 return 0;
2075 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2077 bool reset_enable;
2078 int reqs, ret;
2080 /* FIXME: Hardcode number of outstanding requests for now */
2081 reqs = 32;
2082 if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2083 reqs = 1;
2084 reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2086 /* Only allow access to user-accessible pages */
2087 ret = pci_enable_pasid(pdev, 0);
2088 if (ret)
2089 goto out_err;
2091 /* First reset the PRI state of the device */
2092 ret = pci_reset_pri(pdev);
2093 if (ret)
2094 goto out_err;
2096 /* Enable PRI */
2097 ret = pci_enable_pri(pdev, reqs);
2098 if (ret)
2099 goto out_err;
2101 if (reset_enable) {
2102 ret = pri_reset_while_enabled(pdev);
2103 if (ret)
2104 goto out_err;
2107 ret = pci_enable_ats(pdev, PAGE_SHIFT);
2108 if (ret)
2109 goto out_err;
2111 return 0;
2113 out_err:
2114 pci_disable_pri(pdev);
2115 pci_disable_pasid(pdev);
2117 return ret;
2120 /* FIXME: Move this to PCI code */
2121 #define PCI_PRI_TLP_OFF (1 << 15)
2123 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2125 u16 status;
2126 int pos;
2128 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2129 if (!pos)
2130 return false;
2132 pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2134 return (status & PCI_PRI_TLP_OFF) ? true : false;
2138 * If a device is not yet associated with a domain, this function
2139 * assigns it visible for the hardware
2141 static int attach_device(struct device *dev,
2142 struct protection_domain *domain)
2144 struct pci_dev *pdev = to_pci_dev(dev);
2145 struct iommu_dev_data *dev_data;
2146 unsigned long flags;
2147 int ret;
2149 dev_data = get_dev_data(dev);
2151 if (domain->flags & PD_IOMMUV2_MASK) {
2152 if (!dev_data->passthrough)
2153 return -EINVAL;
2155 if (dev_data->iommu_v2) {
2156 if (pdev_iommuv2_enable(pdev) != 0)
2157 return -EINVAL;
2159 dev_data->ats.enabled = true;
2160 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2161 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2163 } else if (amd_iommu_iotlb_sup &&
2164 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2165 dev_data->ats.enabled = true;
2166 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2169 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2170 ret = __attach_device(dev_data, domain);
2171 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2174 * We might boot into a crash-kernel here. The crashed kernel
2175 * left the caches in the IOMMU dirty. So we have to flush
2176 * here to evict all dirty stuff.
2178 domain_flush_tlb_pde(domain);
2180 return ret;
2184 * Removes a device from a protection domain (unlocked)
2186 static void __detach_device(struct iommu_dev_data *dev_data)
2188 struct protection_domain *domain;
2191 * Must be called with IRQs disabled. Warn here to detect early
2192 * when its not.
2194 WARN_ON(!irqs_disabled());
2196 if (WARN_ON(!dev_data->domain))
2197 return;
2199 domain = dev_data->domain;
2201 spin_lock(&domain->lock);
2203 do_detach(dev_data);
2205 spin_unlock(&domain->lock);
2209 * Removes a device from a protection domain (with devtable_lock held)
2211 static void detach_device(struct device *dev)
2213 struct protection_domain *domain;
2214 struct iommu_dev_data *dev_data;
2215 unsigned long flags;
2217 dev_data = get_dev_data(dev);
2218 domain = dev_data->domain;
2220 /* lock device table */
2221 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2222 __detach_device(dev_data);
2223 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2225 if (domain->flags & PD_IOMMUV2_MASK && dev_data->iommu_v2)
2226 pdev_iommuv2_disable(to_pci_dev(dev));
2227 else if (dev_data->ats.enabled)
2228 pci_disable_ats(to_pci_dev(dev));
2230 dev_data->ats.enabled = false;
2233 static int amd_iommu_add_device(struct device *dev)
2235 struct iommu_dev_data *dev_data;
2236 struct iommu_domain *domain;
2237 struct amd_iommu *iommu;
2238 u16 devid;
2239 int ret;
2241 if (!check_device(dev) || get_dev_data(dev))
2242 return 0;
2244 devid = get_device_id(dev);
2245 iommu = amd_iommu_rlookup_table[devid];
2247 ret = iommu_init_device(dev);
2248 if (ret) {
2249 if (ret != -ENOTSUPP)
2250 pr_err("Failed to initialize device %s - trying to proceed anyway\n",
2251 dev_name(dev));
2253 iommu_ignore_device(dev);
2254 dev->archdata.dma_ops = &nommu_dma_ops;
2255 goto out;
2257 init_iommu_group(dev);
2259 dev_data = get_dev_data(dev);
2261 BUG_ON(!dev_data);
2263 if (iommu_pass_through || dev_data->iommu_v2)
2264 iommu_request_dm_for_dev(dev);
2266 /* Domains are initialized for this device - have a look what we ended up with */
2267 domain = iommu_get_domain_for_dev(dev);
2268 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2269 dev_data->passthrough = true;
2270 else
2271 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2273 out:
2274 iommu_completion_wait(iommu);
2276 return 0;
2279 static void amd_iommu_remove_device(struct device *dev)
2281 struct amd_iommu *iommu;
2282 u16 devid;
2284 if (!check_device(dev))
2285 return;
2287 devid = get_device_id(dev);
2288 iommu = amd_iommu_rlookup_table[devid];
2290 iommu_uninit_device(dev);
2291 iommu_completion_wait(iommu);
2294 /*****************************************************************************
2296 * The next functions belong to the dma_ops mapping/unmapping code.
2298 *****************************************************************************/
2301 * In the dma_ops path we only have the struct device. This function
2302 * finds the corresponding IOMMU, the protection domain and the
2303 * requestor id for a given device.
2304 * If the device is not yet associated with a domain this is also done
2305 * in this function.
2307 static struct protection_domain *get_domain(struct device *dev)
2309 struct protection_domain *domain;
2310 struct iommu_domain *io_domain;
2312 if (!check_device(dev))
2313 return ERR_PTR(-EINVAL);
2315 io_domain = iommu_get_domain_for_dev(dev);
2316 if (!io_domain)
2317 return NULL;
2319 domain = to_pdomain(io_domain);
2320 if (!dma_ops_domain(domain))
2321 return ERR_PTR(-EBUSY);
2323 return domain;
2326 static void update_device_table(struct protection_domain *domain)
2328 struct iommu_dev_data *dev_data;
2330 list_for_each_entry(dev_data, &domain->dev_list, list) {
2331 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2333 if (dev_data->devid == dev_data->alias)
2334 continue;
2336 /* There is an alias, update device table entry for it */
2337 set_dte_entry(dev_data->alias, domain, dev_data->ats.enabled);
2341 static void update_domain(struct protection_domain *domain)
2343 if (!domain->updated)
2344 return;
2346 update_device_table(domain);
2348 domain_flush_devices(domain);
2349 domain_flush_tlb_pde(domain);
2351 domain->updated = false;
2355 * This function fetches the PTE for a given address in the aperture
2357 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2358 unsigned long address)
2360 struct aperture_range *aperture;
2361 u64 *pte, *pte_page;
2363 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2364 if (!aperture)
2365 return NULL;
2367 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2368 if (!pte) {
2369 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2370 GFP_ATOMIC);
2371 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2372 } else
2373 pte += PM_LEVEL_INDEX(0, address);
2375 update_domain(&dom->domain);
2377 return pte;
2381 * This is the generic map function. It maps one 4kb page at paddr to
2382 * the given address in the DMA address space for the domain.
2384 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2385 unsigned long address,
2386 phys_addr_t paddr,
2387 int direction)
2389 u64 *pte, __pte;
2391 WARN_ON(address > dom->aperture_size);
2393 paddr &= PAGE_MASK;
2395 pte = dma_ops_get_pte(dom, address);
2396 if (!pte)
2397 return DMA_ERROR_CODE;
2399 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2401 if (direction == DMA_TO_DEVICE)
2402 __pte |= IOMMU_PTE_IR;
2403 else if (direction == DMA_FROM_DEVICE)
2404 __pte |= IOMMU_PTE_IW;
2405 else if (direction == DMA_BIDIRECTIONAL)
2406 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2408 WARN_ON(*pte);
2410 *pte = __pte;
2412 return (dma_addr_t)address;
2416 * The generic unmapping function for on page in the DMA address space.
2418 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2419 unsigned long address)
2421 struct aperture_range *aperture;
2422 u64 *pte;
2424 if (address >= dom->aperture_size)
2425 return;
2427 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2428 if (!aperture)
2429 return;
2431 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2432 if (!pte)
2433 return;
2435 pte += PM_LEVEL_INDEX(0, address);
2437 WARN_ON(!*pte);
2439 *pte = 0ULL;
2443 * This function contains common code for mapping of a physically
2444 * contiguous memory region into DMA address space. It is used by all
2445 * mapping functions provided with this IOMMU driver.
2446 * Must be called with the domain lock held.
2448 static dma_addr_t __map_single(struct device *dev,
2449 struct dma_ops_domain *dma_dom,
2450 phys_addr_t paddr,
2451 size_t size,
2452 int dir,
2453 bool align,
2454 u64 dma_mask)
2456 dma_addr_t offset = paddr & ~PAGE_MASK;
2457 dma_addr_t address, start, ret;
2458 unsigned int pages;
2459 unsigned long align_mask = 0;
2460 int i;
2462 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2463 paddr &= PAGE_MASK;
2465 INC_STATS_COUNTER(total_map_requests);
2467 if (pages > 1)
2468 INC_STATS_COUNTER(cross_page);
2470 if (align)
2471 align_mask = (1UL << get_order(size)) - 1;
2473 retry:
2474 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2475 dma_mask);
2476 if (unlikely(address == DMA_ERROR_CODE)) {
2478 * setting next_address here will let the address
2479 * allocator only scan the new allocated range in the
2480 * first run. This is a small optimization.
2482 dma_dom->next_address = dma_dom->aperture_size;
2484 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2485 goto out;
2488 * aperture was successfully enlarged by 128 MB, try
2489 * allocation again
2491 goto retry;
2494 start = address;
2495 for (i = 0; i < pages; ++i) {
2496 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2497 if (ret == DMA_ERROR_CODE)
2498 goto out_unmap;
2500 paddr += PAGE_SIZE;
2501 start += PAGE_SIZE;
2503 address += offset;
2505 ADD_STATS_COUNTER(alloced_io_mem, size);
2507 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2508 domain_flush_tlb(&dma_dom->domain);
2509 dma_dom->need_flush = false;
2510 } else if (unlikely(amd_iommu_np_cache))
2511 domain_flush_pages(&dma_dom->domain, address, size);
2513 out:
2514 return address;
2516 out_unmap:
2518 for (--i; i >= 0; --i) {
2519 start -= PAGE_SIZE;
2520 dma_ops_domain_unmap(dma_dom, start);
2523 dma_ops_free_addresses(dma_dom, address, pages);
2525 return DMA_ERROR_CODE;
2529 * Does the reverse of the __map_single function. Must be called with
2530 * the domain lock held too
2532 static void __unmap_single(struct dma_ops_domain *dma_dom,
2533 dma_addr_t dma_addr,
2534 size_t size,
2535 int dir)
2537 dma_addr_t flush_addr;
2538 dma_addr_t i, start;
2539 unsigned int pages;
2541 if ((dma_addr == DMA_ERROR_CODE) ||
2542 (dma_addr + size > dma_dom->aperture_size))
2543 return;
2545 flush_addr = dma_addr;
2546 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2547 dma_addr &= PAGE_MASK;
2548 start = dma_addr;
2550 for (i = 0; i < pages; ++i) {
2551 dma_ops_domain_unmap(dma_dom, start);
2552 start += PAGE_SIZE;
2555 SUB_STATS_COUNTER(alloced_io_mem, size);
2557 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2559 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2560 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2561 dma_dom->need_flush = false;
2566 * The exported map_single function for dma_ops.
2568 static dma_addr_t map_page(struct device *dev, struct page *page,
2569 unsigned long offset, size_t size,
2570 enum dma_data_direction dir,
2571 struct dma_attrs *attrs)
2573 unsigned long flags;
2574 struct protection_domain *domain;
2575 dma_addr_t addr;
2576 u64 dma_mask;
2577 phys_addr_t paddr = page_to_phys(page) + offset;
2579 INC_STATS_COUNTER(cnt_map_single);
2581 domain = get_domain(dev);
2582 if (PTR_ERR(domain) == -EINVAL)
2583 return (dma_addr_t)paddr;
2584 else if (IS_ERR(domain))
2585 return DMA_ERROR_CODE;
2587 dma_mask = *dev->dma_mask;
2589 spin_lock_irqsave(&domain->lock, flags);
2591 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2592 dma_mask);
2593 if (addr == DMA_ERROR_CODE)
2594 goto out;
2596 domain_flush_complete(domain);
2598 out:
2599 spin_unlock_irqrestore(&domain->lock, flags);
2601 return addr;
2605 * The exported unmap_single function for dma_ops.
2607 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2608 enum dma_data_direction dir, struct dma_attrs *attrs)
2610 unsigned long flags;
2611 struct protection_domain *domain;
2613 INC_STATS_COUNTER(cnt_unmap_single);
2615 domain = get_domain(dev);
2616 if (IS_ERR(domain))
2617 return;
2619 spin_lock_irqsave(&domain->lock, flags);
2621 __unmap_single(domain->priv, dma_addr, size, dir);
2623 domain_flush_complete(domain);
2625 spin_unlock_irqrestore(&domain->lock, flags);
2629 * The exported map_sg function for dma_ops (handles scatter-gather
2630 * lists).
2632 static int map_sg(struct device *dev, struct scatterlist *sglist,
2633 int nelems, enum dma_data_direction dir,
2634 struct dma_attrs *attrs)
2636 unsigned long flags;
2637 struct protection_domain *domain;
2638 int i;
2639 struct scatterlist *s;
2640 phys_addr_t paddr;
2641 int mapped_elems = 0;
2642 u64 dma_mask;
2644 INC_STATS_COUNTER(cnt_map_sg);
2646 domain = get_domain(dev);
2647 if (IS_ERR(domain))
2648 return 0;
2650 dma_mask = *dev->dma_mask;
2652 spin_lock_irqsave(&domain->lock, flags);
2654 for_each_sg(sglist, s, nelems, i) {
2655 paddr = sg_phys(s);
2657 s->dma_address = __map_single(dev, domain->priv,
2658 paddr, s->length, dir, false,
2659 dma_mask);
2661 if (s->dma_address) {
2662 s->dma_length = s->length;
2663 mapped_elems++;
2664 } else
2665 goto unmap;
2668 domain_flush_complete(domain);
2670 out:
2671 spin_unlock_irqrestore(&domain->lock, flags);
2673 return mapped_elems;
2674 unmap:
2675 for_each_sg(sglist, s, mapped_elems, i) {
2676 if (s->dma_address)
2677 __unmap_single(domain->priv, s->dma_address,
2678 s->dma_length, dir);
2679 s->dma_address = s->dma_length = 0;
2682 mapped_elems = 0;
2684 goto out;
2688 * The exported map_sg function for dma_ops (handles scatter-gather
2689 * lists).
2691 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2692 int nelems, enum dma_data_direction dir,
2693 struct dma_attrs *attrs)
2695 unsigned long flags;
2696 struct protection_domain *domain;
2697 struct scatterlist *s;
2698 int i;
2700 INC_STATS_COUNTER(cnt_unmap_sg);
2702 domain = get_domain(dev);
2703 if (IS_ERR(domain))
2704 return;
2706 spin_lock_irqsave(&domain->lock, flags);
2708 for_each_sg(sglist, s, nelems, i) {
2709 __unmap_single(domain->priv, s->dma_address,
2710 s->dma_length, dir);
2711 s->dma_address = s->dma_length = 0;
2714 domain_flush_complete(domain);
2716 spin_unlock_irqrestore(&domain->lock, flags);
2720 * The exported alloc_coherent function for dma_ops.
2722 static void *alloc_coherent(struct device *dev, size_t size,
2723 dma_addr_t *dma_addr, gfp_t flag,
2724 struct dma_attrs *attrs)
2726 u64 dma_mask = dev->coherent_dma_mask;
2727 struct protection_domain *domain;
2728 unsigned long flags;
2729 struct page *page;
2731 INC_STATS_COUNTER(cnt_alloc_coherent);
2733 domain = get_domain(dev);
2734 if (PTR_ERR(domain) == -EINVAL) {
2735 page = alloc_pages(flag, get_order(size));
2736 *dma_addr = page_to_phys(page);
2737 return page_address(page);
2738 } else if (IS_ERR(domain))
2739 return NULL;
2741 size = PAGE_ALIGN(size);
2742 dma_mask = dev->coherent_dma_mask;
2743 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2744 flag |= __GFP_ZERO;
2746 page = alloc_pages(flag | __GFP_NOWARN, get_order(size));
2747 if (!page) {
2748 if (!gfpflags_allow_blocking(flag))
2749 return NULL;
2751 page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
2752 get_order(size));
2753 if (!page)
2754 return NULL;
2757 if (!dma_mask)
2758 dma_mask = *dev->dma_mask;
2760 spin_lock_irqsave(&domain->lock, flags);
2762 *dma_addr = __map_single(dev, domain->priv, page_to_phys(page),
2763 size, DMA_BIDIRECTIONAL, true, dma_mask);
2765 if (*dma_addr == DMA_ERROR_CODE) {
2766 spin_unlock_irqrestore(&domain->lock, flags);
2767 goto out_free;
2770 domain_flush_complete(domain);
2772 spin_unlock_irqrestore(&domain->lock, flags);
2774 return page_address(page);
2776 out_free:
2778 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2779 __free_pages(page, get_order(size));
2781 return NULL;
2785 * The exported free_coherent function for dma_ops.
2787 static void free_coherent(struct device *dev, size_t size,
2788 void *virt_addr, dma_addr_t dma_addr,
2789 struct dma_attrs *attrs)
2791 struct protection_domain *domain;
2792 unsigned long flags;
2793 struct page *page;
2795 INC_STATS_COUNTER(cnt_free_coherent);
2797 page = virt_to_page(virt_addr);
2798 size = PAGE_ALIGN(size);
2800 domain = get_domain(dev);
2801 if (IS_ERR(domain))
2802 goto free_mem;
2804 spin_lock_irqsave(&domain->lock, flags);
2806 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2808 domain_flush_complete(domain);
2810 spin_unlock_irqrestore(&domain->lock, flags);
2812 free_mem:
2813 if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2814 __free_pages(page, get_order(size));
2818 * This function is called by the DMA layer to find out if we can handle a
2819 * particular device. It is part of the dma_ops.
2821 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2823 return check_device(dev);
2826 static struct dma_map_ops amd_iommu_dma_ops = {
2827 .alloc = alloc_coherent,
2828 .free = free_coherent,
2829 .map_page = map_page,
2830 .unmap_page = unmap_page,
2831 .map_sg = map_sg,
2832 .unmap_sg = unmap_sg,
2833 .dma_supported = amd_iommu_dma_supported,
2836 int __init amd_iommu_init_api(void)
2838 return bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2841 int __init amd_iommu_init_dma_ops(void)
2843 swiotlb = iommu_pass_through ? 1 : 0;
2844 iommu_detected = 1;
2847 * In case we don't initialize SWIOTLB (actually the common case
2848 * when AMD IOMMU is enabled), make sure there are global
2849 * dma_ops set as a fall-back for devices not handled by this
2850 * driver (for example non-PCI devices).
2852 if (!swiotlb)
2853 dma_ops = &nommu_dma_ops;
2855 amd_iommu_stats_init();
2857 if (amd_iommu_unmap_flush)
2858 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
2859 else
2860 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
2862 return 0;
2865 /*****************************************************************************
2867 * The following functions belong to the exported interface of AMD IOMMU
2869 * This interface allows access to lower level functions of the IOMMU
2870 * like protection domain handling and assignement of devices to domains
2871 * which is not possible with the dma_ops interface.
2873 *****************************************************************************/
2875 static void cleanup_domain(struct protection_domain *domain)
2877 struct iommu_dev_data *entry;
2878 unsigned long flags;
2880 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2882 while (!list_empty(&domain->dev_list)) {
2883 entry = list_first_entry(&domain->dev_list,
2884 struct iommu_dev_data, list);
2885 __detach_device(entry);
2888 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2891 static void protection_domain_free(struct protection_domain *domain)
2893 if (!domain)
2894 return;
2896 del_domain_from_list(domain);
2898 if (domain->id)
2899 domain_id_free(domain->id);
2901 kfree(domain);
2904 static int protection_domain_init(struct protection_domain *domain)
2906 spin_lock_init(&domain->lock);
2907 mutex_init(&domain->api_lock);
2908 domain->id = domain_id_alloc();
2909 if (!domain->id)
2910 return -ENOMEM;
2911 INIT_LIST_HEAD(&domain->dev_list);
2913 return 0;
2916 static struct protection_domain *protection_domain_alloc(void)
2918 struct protection_domain *domain;
2920 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2921 if (!domain)
2922 return NULL;
2924 if (protection_domain_init(domain))
2925 goto out_err;
2927 add_domain_to_list(domain);
2929 return domain;
2931 out_err:
2932 kfree(domain);
2934 return NULL;
2937 static struct iommu_domain *amd_iommu_domain_alloc(unsigned type)
2939 struct protection_domain *pdomain;
2940 struct dma_ops_domain *dma_domain;
2942 switch (type) {
2943 case IOMMU_DOMAIN_UNMANAGED:
2944 pdomain = protection_domain_alloc();
2945 if (!pdomain)
2946 return NULL;
2948 pdomain->mode = PAGE_MODE_3_LEVEL;
2949 pdomain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2950 if (!pdomain->pt_root) {
2951 protection_domain_free(pdomain);
2952 return NULL;
2955 pdomain->domain.geometry.aperture_start = 0;
2956 pdomain->domain.geometry.aperture_end = ~0ULL;
2957 pdomain->domain.geometry.force_aperture = true;
2959 break;
2960 case IOMMU_DOMAIN_DMA:
2961 dma_domain = dma_ops_domain_alloc();
2962 if (!dma_domain) {
2963 pr_err("AMD-Vi: Failed to allocate\n");
2964 return NULL;
2966 pdomain = &dma_domain->domain;
2967 break;
2968 case IOMMU_DOMAIN_IDENTITY:
2969 pdomain = protection_domain_alloc();
2970 if (!pdomain)
2971 return NULL;
2973 pdomain->mode = PAGE_MODE_NONE;
2974 break;
2975 default:
2976 return NULL;
2979 return &pdomain->domain;
2982 static void amd_iommu_domain_free(struct iommu_domain *dom)
2984 struct protection_domain *domain;
2985 struct dma_ops_domain *dma_dom;
2987 domain = to_pdomain(dom);
2989 if (domain->dev_cnt > 0)
2990 cleanup_domain(domain);
2992 BUG_ON(domain->dev_cnt != 0);
2994 if (!dom)
2995 return;
2997 switch (dom->type) {
2998 case IOMMU_DOMAIN_DMA:
2999 dma_dom = domain->priv;
3000 dma_ops_domain_free(dma_dom);
3001 break;
3002 default:
3003 if (domain->mode != PAGE_MODE_NONE)
3004 free_pagetable(domain);
3006 if (domain->flags & PD_IOMMUV2_MASK)
3007 free_gcr3_table(domain);
3009 protection_domain_free(domain);
3010 break;
3014 static void amd_iommu_detach_device(struct iommu_domain *dom,
3015 struct device *dev)
3017 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3018 struct amd_iommu *iommu;
3019 u16 devid;
3021 if (!check_device(dev))
3022 return;
3024 devid = get_device_id(dev);
3026 if (dev_data->domain != NULL)
3027 detach_device(dev);
3029 iommu = amd_iommu_rlookup_table[devid];
3030 if (!iommu)
3031 return;
3033 iommu_completion_wait(iommu);
3036 static int amd_iommu_attach_device(struct iommu_domain *dom,
3037 struct device *dev)
3039 struct protection_domain *domain = to_pdomain(dom);
3040 struct iommu_dev_data *dev_data;
3041 struct amd_iommu *iommu;
3042 int ret;
3044 if (!check_device(dev))
3045 return -EINVAL;
3047 dev_data = dev->archdata.iommu;
3049 iommu = amd_iommu_rlookup_table[dev_data->devid];
3050 if (!iommu)
3051 return -EINVAL;
3053 if (dev_data->domain)
3054 detach_device(dev);
3056 ret = attach_device(dev, domain);
3058 iommu_completion_wait(iommu);
3060 return ret;
3063 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3064 phys_addr_t paddr, size_t page_size, int iommu_prot)
3066 struct protection_domain *domain = to_pdomain(dom);
3067 int prot = 0;
3068 int ret;
3070 if (domain->mode == PAGE_MODE_NONE)
3071 return -EINVAL;
3073 if (iommu_prot & IOMMU_READ)
3074 prot |= IOMMU_PROT_IR;
3075 if (iommu_prot & IOMMU_WRITE)
3076 prot |= IOMMU_PROT_IW;
3078 mutex_lock(&domain->api_lock);
3079 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3080 mutex_unlock(&domain->api_lock);
3082 return ret;
3085 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3086 size_t page_size)
3088 struct protection_domain *domain = to_pdomain(dom);
3089 size_t unmap_size;
3091 if (domain->mode == PAGE_MODE_NONE)
3092 return -EINVAL;
3094 mutex_lock(&domain->api_lock);
3095 unmap_size = iommu_unmap_page(domain, iova, page_size);
3096 mutex_unlock(&domain->api_lock);
3098 domain_flush_tlb_pde(domain);
3099 domain_flush_complete(domain);
3101 return unmap_size;
3104 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3105 dma_addr_t iova)
3107 struct protection_domain *domain = to_pdomain(dom);
3108 unsigned long offset_mask, pte_pgsize;
3109 u64 *pte, __pte;
3111 if (domain->mode == PAGE_MODE_NONE)
3112 return iova;
3114 pte = fetch_pte(domain, iova, &pte_pgsize);
3116 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3117 return 0;
3119 offset_mask = pte_pgsize - 1;
3120 __pte = *pte & PM_ADDR_MASK;
3122 return (__pte & ~offset_mask) | (iova & offset_mask);
3125 static bool amd_iommu_capable(enum iommu_cap cap)
3127 switch (cap) {
3128 case IOMMU_CAP_CACHE_COHERENCY:
3129 return true;
3130 case IOMMU_CAP_INTR_REMAP:
3131 return (irq_remapping_enabled == 1);
3132 case IOMMU_CAP_NOEXEC:
3133 return false;
3136 return false;
3139 static void amd_iommu_get_dm_regions(struct device *dev,
3140 struct list_head *head)
3142 struct unity_map_entry *entry;
3143 u16 devid;
3145 devid = get_device_id(dev);
3147 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
3148 struct iommu_dm_region *region;
3150 if (devid < entry->devid_start || devid > entry->devid_end)
3151 continue;
3153 region = kzalloc(sizeof(*region), GFP_KERNEL);
3154 if (!region) {
3155 pr_err("Out of memory allocating dm-regions for %s\n",
3156 dev_name(dev));
3157 return;
3160 region->start = entry->address_start;
3161 region->length = entry->address_end - entry->address_start;
3162 if (entry->prot & IOMMU_PROT_IR)
3163 region->prot |= IOMMU_READ;
3164 if (entry->prot & IOMMU_PROT_IW)
3165 region->prot |= IOMMU_WRITE;
3167 list_add_tail(&region->list, head);
3171 static void amd_iommu_put_dm_regions(struct device *dev,
3172 struct list_head *head)
3174 struct iommu_dm_region *entry, *next;
3176 list_for_each_entry_safe(entry, next, head, list)
3177 kfree(entry);
3180 static const struct iommu_ops amd_iommu_ops = {
3181 .capable = amd_iommu_capable,
3182 .domain_alloc = amd_iommu_domain_alloc,
3183 .domain_free = amd_iommu_domain_free,
3184 .attach_dev = amd_iommu_attach_device,
3185 .detach_dev = amd_iommu_detach_device,
3186 .map = amd_iommu_map,
3187 .unmap = amd_iommu_unmap,
3188 .map_sg = default_iommu_map_sg,
3189 .iova_to_phys = amd_iommu_iova_to_phys,
3190 .add_device = amd_iommu_add_device,
3191 .remove_device = amd_iommu_remove_device,
3192 .device_group = pci_device_group,
3193 .get_dm_regions = amd_iommu_get_dm_regions,
3194 .put_dm_regions = amd_iommu_put_dm_regions,
3195 .pgsize_bitmap = AMD_IOMMU_PGSIZES,
3198 /*****************************************************************************
3200 * The next functions do a basic initialization of IOMMU for pass through
3201 * mode
3203 * In passthrough mode the IOMMU is initialized and enabled but not used for
3204 * DMA-API translation.
3206 *****************************************************************************/
3208 /* IOMMUv2 specific functions */
3209 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3211 return atomic_notifier_chain_register(&ppr_notifier, nb);
3213 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3215 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3217 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3219 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3221 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3223 struct protection_domain *domain = to_pdomain(dom);
3224 unsigned long flags;
3226 spin_lock_irqsave(&domain->lock, flags);
3228 /* Update data structure */
3229 domain->mode = PAGE_MODE_NONE;
3230 domain->updated = true;
3232 /* Make changes visible to IOMMUs */
3233 update_domain(domain);
3235 /* Page-table is not visible to IOMMU anymore, so free it */
3236 free_pagetable(domain);
3238 spin_unlock_irqrestore(&domain->lock, flags);
3240 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3242 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3244 struct protection_domain *domain = to_pdomain(dom);
3245 unsigned long flags;
3246 int levels, ret;
3248 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3249 return -EINVAL;
3251 /* Number of GCR3 table levels required */
3252 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3253 levels += 1;
3255 if (levels > amd_iommu_max_glx_val)
3256 return -EINVAL;
3258 spin_lock_irqsave(&domain->lock, flags);
3261 * Save us all sanity checks whether devices already in the
3262 * domain support IOMMUv2. Just force that the domain has no
3263 * devices attached when it is switched into IOMMUv2 mode.
3265 ret = -EBUSY;
3266 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3267 goto out;
3269 ret = -ENOMEM;
3270 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3271 if (domain->gcr3_tbl == NULL)
3272 goto out;
3274 domain->glx = levels;
3275 domain->flags |= PD_IOMMUV2_MASK;
3276 domain->updated = true;
3278 update_domain(domain);
3280 ret = 0;
3282 out:
3283 spin_unlock_irqrestore(&domain->lock, flags);
3285 return ret;
3287 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3289 static int __flush_pasid(struct protection_domain *domain, int pasid,
3290 u64 address, bool size)
3292 struct iommu_dev_data *dev_data;
3293 struct iommu_cmd cmd;
3294 int i, ret;
3296 if (!(domain->flags & PD_IOMMUV2_MASK))
3297 return -EINVAL;
3299 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3302 * IOMMU TLB needs to be flushed before Device TLB to
3303 * prevent device TLB refill from IOMMU TLB
3305 for (i = 0; i < amd_iommus_present; ++i) {
3306 if (domain->dev_iommu[i] == 0)
3307 continue;
3309 ret = iommu_queue_command(amd_iommus[i], &cmd);
3310 if (ret != 0)
3311 goto out;
3314 /* Wait until IOMMU TLB flushes are complete */
3315 domain_flush_complete(domain);
3317 /* Now flush device TLBs */
3318 list_for_each_entry(dev_data, &domain->dev_list, list) {
3319 struct amd_iommu *iommu;
3320 int qdep;
3323 There might be non-IOMMUv2 capable devices in an IOMMUv2
3324 * domain.
3326 if (!dev_data->ats.enabled)
3327 continue;
3329 qdep = dev_data->ats.qdep;
3330 iommu = amd_iommu_rlookup_table[dev_data->devid];
3332 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3333 qdep, address, size);
3335 ret = iommu_queue_command(iommu, &cmd);
3336 if (ret != 0)
3337 goto out;
3340 /* Wait until all device TLBs are flushed */
3341 domain_flush_complete(domain);
3343 ret = 0;
3345 out:
3347 return ret;
3350 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3351 u64 address)
3353 INC_STATS_COUNTER(invalidate_iotlb);
3355 return __flush_pasid(domain, pasid, address, false);
3358 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3359 u64 address)
3361 struct protection_domain *domain = to_pdomain(dom);
3362 unsigned long flags;
3363 int ret;
3365 spin_lock_irqsave(&domain->lock, flags);
3366 ret = __amd_iommu_flush_page(domain, pasid, address);
3367 spin_unlock_irqrestore(&domain->lock, flags);
3369 return ret;
3371 EXPORT_SYMBOL(amd_iommu_flush_page);
3373 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3375 INC_STATS_COUNTER(invalidate_iotlb_all);
3377 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3378 true);
3381 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3383 struct protection_domain *domain = to_pdomain(dom);
3384 unsigned long flags;
3385 int ret;
3387 spin_lock_irqsave(&domain->lock, flags);
3388 ret = __amd_iommu_flush_tlb(domain, pasid);
3389 spin_unlock_irqrestore(&domain->lock, flags);
3391 return ret;
3393 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3395 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3397 int index;
3398 u64 *pte;
3400 while (true) {
3402 index = (pasid >> (9 * level)) & 0x1ff;
3403 pte = &root[index];
3405 if (level == 0)
3406 break;
3408 if (!(*pte & GCR3_VALID)) {
3409 if (!alloc)
3410 return NULL;
3412 root = (void *)get_zeroed_page(GFP_ATOMIC);
3413 if (root == NULL)
3414 return NULL;
3416 *pte = __pa(root) | GCR3_VALID;
3419 root = __va(*pte & PAGE_MASK);
3421 level -= 1;
3424 return pte;
3427 static int __set_gcr3(struct protection_domain *domain, int pasid,
3428 unsigned long cr3)
3430 u64 *pte;
3432 if (domain->mode != PAGE_MODE_NONE)
3433 return -EINVAL;
3435 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3436 if (pte == NULL)
3437 return -ENOMEM;
3439 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3441 return __amd_iommu_flush_tlb(domain, pasid);
3444 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3446 u64 *pte;
3448 if (domain->mode != PAGE_MODE_NONE)
3449 return -EINVAL;
3451 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3452 if (pte == NULL)
3453 return 0;
3455 *pte = 0;
3457 return __amd_iommu_flush_tlb(domain, pasid);
3460 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3461 unsigned long cr3)
3463 struct protection_domain *domain = to_pdomain(dom);
3464 unsigned long flags;
3465 int ret;
3467 spin_lock_irqsave(&domain->lock, flags);
3468 ret = __set_gcr3(domain, pasid, cr3);
3469 spin_unlock_irqrestore(&domain->lock, flags);
3471 return ret;
3473 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3475 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3477 struct protection_domain *domain = to_pdomain(dom);
3478 unsigned long flags;
3479 int ret;
3481 spin_lock_irqsave(&domain->lock, flags);
3482 ret = __clear_gcr3(domain, pasid);
3483 spin_unlock_irqrestore(&domain->lock, flags);
3485 return ret;
3487 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3489 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3490 int status, int tag)
3492 struct iommu_dev_data *dev_data;
3493 struct amd_iommu *iommu;
3494 struct iommu_cmd cmd;
3496 INC_STATS_COUNTER(complete_ppr);
3498 dev_data = get_dev_data(&pdev->dev);
3499 iommu = amd_iommu_rlookup_table[dev_data->devid];
3501 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3502 tag, dev_data->pri_tlp);
3504 return iommu_queue_command(iommu, &cmd);
3506 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3508 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3510 struct protection_domain *pdomain;
3512 pdomain = get_domain(&pdev->dev);
3513 if (IS_ERR(pdomain))
3514 return NULL;
3516 /* Only return IOMMUv2 domains */
3517 if (!(pdomain->flags & PD_IOMMUV2_MASK))
3518 return NULL;
3520 return &pdomain->domain;
3522 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3524 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3526 struct iommu_dev_data *dev_data;
3528 if (!amd_iommu_v2_supported())
3529 return;
3531 dev_data = get_dev_data(&pdev->dev);
3532 dev_data->errata |= (1 << erratum);
3534 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3536 int amd_iommu_device_info(struct pci_dev *pdev,
3537 struct amd_iommu_device_info *info)
3539 int max_pasids;
3540 int pos;
3542 if (pdev == NULL || info == NULL)
3543 return -EINVAL;
3545 if (!amd_iommu_v2_supported())
3546 return -EINVAL;
3548 memset(info, 0, sizeof(*info));
3550 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3551 if (pos)
3552 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3554 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3555 if (pos)
3556 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3558 pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3559 if (pos) {
3560 int features;
3562 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3563 max_pasids = min(max_pasids, (1 << 20));
3565 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3566 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3568 features = pci_pasid_features(pdev);
3569 if (features & PCI_PASID_CAP_EXEC)
3570 info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3571 if (features & PCI_PASID_CAP_PRIV)
3572 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3575 return 0;
3577 EXPORT_SYMBOL(amd_iommu_device_info);
3579 #ifdef CONFIG_IRQ_REMAP
3581 /*****************************************************************************
3583 * Interrupt Remapping Implementation
3585 *****************************************************************************/
3587 union irte {
3588 u32 val;
3589 struct {
3590 u32 valid : 1,
3591 no_fault : 1,
3592 int_type : 3,
3593 rq_eoi : 1,
3594 dm : 1,
3595 rsvd_1 : 1,
3596 destination : 8,
3597 vector : 8,
3598 rsvd_2 : 8;
3599 } fields;
3602 struct irq_2_irte {
3603 u16 devid; /* Device ID for IRTE table */
3604 u16 index; /* Index into IRTE table*/
3607 struct amd_ir_data {
3608 struct irq_2_irte irq_2_irte;
3609 union irte irte_entry;
3610 union {
3611 struct msi_msg msi_entry;
3615 static struct irq_chip amd_ir_chip;
3617 #define DTE_IRQ_PHYS_ADDR_MASK (((1ULL << 45)-1) << 6)
3618 #define DTE_IRQ_REMAP_INTCTL (2ULL << 60)
3619 #define DTE_IRQ_TABLE_LEN (8ULL << 1)
3620 #define DTE_IRQ_REMAP_ENABLE 1ULL
3622 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3624 u64 dte;
3626 dte = amd_iommu_dev_table[devid].data[2];
3627 dte &= ~DTE_IRQ_PHYS_ADDR_MASK;
3628 dte |= virt_to_phys(table->table);
3629 dte |= DTE_IRQ_REMAP_INTCTL;
3630 dte |= DTE_IRQ_TABLE_LEN;
3631 dte |= DTE_IRQ_REMAP_ENABLE;
3633 amd_iommu_dev_table[devid].data[2] = dte;
3636 #define IRTE_ALLOCATED (~1U)
3638 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3640 struct irq_remap_table *table = NULL;
3641 struct amd_iommu *iommu;
3642 unsigned long flags;
3643 u16 alias;
3645 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3647 iommu = amd_iommu_rlookup_table[devid];
3648 if (!iommu)
3649 goto out_unlock;
3651 table = irq_lookup_table[devid];
3652 if (table)
3653 goto out;
3655 alias = amd_iommu_alias_table[devid];
3656 table = irq_lookup_table[alias];
3657 if (table) {
3658 irq_lookup_table[devid] = table;
3659 set_dte_irq_entry(devid, table);
3660 iommu_flush_dte(iommu, devid);
3661 goto out;
3664 /* Nothing there yet, allocate new irq remapping table */
3665 table = kzalloc(sizeof(*table), GFP_ATOMIC);
3666 if (!table)
3667 goto out;
3669 /* Initialize table spin-lock */
3670 spin_lock_init(&table->lock);
3672 if (ioapic)
3673 /* Keep the first 32 indexes free for IOAPIC interrupts */
3674 table->min_index = 32;
3676 table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3677 if (!table->table) {
3678 kfree(table);
3679 table = NULL;
3680 goto out;
3683 memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3685 if (ioapic) {
3686 int i;
3688 for (i = 0; i < 32; ++i)
3689 table->table[i] = IRTE_ALLOCATED;
3692 irq_lookup_table[devid] = table;
3693 set_dte_irq_entry(devid, table);
3694 iommu_flush_dte(iommu, devid);
3695 if (devid != alias) {
3696 irq_lookup_table[alias] = table;
3697 set_dte_irq_entry(alias, table);
3698 iommu_flush_dte(iommu, alias);
3701 out:
3702 iommu_completion_wait(iommu);
3704 out_unlock:
3705 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3707 return table;
3710 static int alloc_irq_index(u16 devid, int count)
3712 struct irq_remap_table *table;
3713 unsigned long flags;
3714 int index, c;
3716 table = get_irq_table(devid, false);
3717 if (!table)
3718 return -ENODEV;
3720 spin_lock_irqsave(&table->lock, flags);
3722 /* Scan table for free entries */
3723 for (c = 0, index = table->min_index;
3724 index < MAX_IRQS_PER_TABLE;
3725 ++index) {
3726 if (table->table[index] == 0)
3727 c += 1;
3728 else
3729 c = 0;
3731 if (c == count) {
3732 for (; c != 0; --c)
3733 table->table[index - c + 1] = IRTE_ALLOCATED;
3735 index -= count - 1;
3736 goto out;
3740 index = -ENOSPC;
3742 out:
3743 spin_unlock_irqrestore(&table->lock, flags);
3745 return index;
3748 static int modify_irte(u16 devid, int index, union irte irte)
3750 struct irq_remap_table *table;
3751 struct amd_iommu *iommu;
3752 unsigned long flags;
3754 iommu = amd_iommu_rlookup_table[devid];
3755 if (iommu == NULL)
3756 return -EINVAL;
3758 table = get_irq_table(devid, false);
3759 if (!table)
3760 return -ENOMEM;
3762 spin_lock_irqsave(&table->lock, flags);
3763 table->table[index] = irte.val;
3764 spin_unlock_irqrestore(&table->lock, flags);
3766 iommu_flush_irt(iommu, devid);
3767 iommu_completion_wait(iommu);
3769 return 0;
3772 static void free_irte(u16 devid, int index)
3774 struct irq_remap_table *table;
3775 struct amd_iommu *iommu;
3776 unsigned long flags;
3778 iommu = amd_iommu_rlookup_table[devid];
3779 if (iommu == NULL)
3780 return;
3782 table = get_irq_table(devid, false);
3783 if (!table)
3784 return;
3786 spin_lock_irqsave(&table->lock, flags);
3787 table->table[index] = 0;
3788 spin_unlock_irqrestore(&table->lock, flags);
3790 iommu_flush_irt(iommu, devid);
3791 iommu_completion_wait(iommu);
3794 static int get_devid(struct irq_alloc_info *info)
3796 int devid = -1;
3798 switch (info->type) {
3799 case X86_IRQ_ALLOC_TYPE_IOAPIC:
3800 devid = get_ioapic_devid(info->ioapic_id);
3801 break;
3802 case X86_IRQ_ALLOC_TYPE_HPET:
3803 devid = get_hpet_devid(info->hpet_id);
3804 break;
3805 case X86_IRQ_ALLOC_TYPE_MSI:
3806 case X86_IRQ_ALLOC_TYPE_MSIX:
3807 devid = get_device_id(&info->msi_dev->dev);
3808 break;
3809 default:
3810 BUG_ON(1);
3811 break;
3814 return devid;
3817 static struct irq_domain *get_ir_irq_domain(struct irq_alloc_info *info)
3819 struct amd_iommu *iommu;
3820 int devid;
3822 if (!info)
3823 return NULL;
3825 devid = get_devid(info);
3826 if (devid >= 0) {
3827 iommu = amd_iommu_rlookup_table[devid];
3828 if (iommu)
3829 return iommu->ir_domain;
3832 return NULL;
3835 static struct irq_domain *get_irq_domain(struct irq_alloc_info *info)
3837 struct amd_iommu *iommu;
3838 int devid;
3840 if (!info)
3841 return NULL;
3843 switch (info->type) {
3844 case X86_IRQ_ALLOC_TYPE_MSI:
3845 case X86_IRQ_ALLOC_TYPE_MSIX:
3846 devid = get_device_id(&info->msi_dev->dev);
3847 if (devid >= 0) {
3848 iommu = amd_iommu_rlookup_table[devid];
3849 if (iommu)
3850 return iommu->msi_domain;
3852 break;
3853 default:
3854 break;
3857 return NULL;
3860 struct irq_remap_ops amd_iommu_irq_ops = {
3861 .prepare = amd_iommu_prepare,
3862 .enable = amd_iommu_enable,
3863 .disable = amd_iommu_disable,
3864 .reenable = amd_iommu_reenable,
3865 .enable_faulting = amd_iommu_enable_faulting,
3866 .get_ir_irq_domain = get_ir_irq_domain,
3867 .get_irq_domain = get_irq_domain,
3870 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
3871 struct irq_cfg *irq_cfg,
3872 struct irq_alloc_info *info,
3873 int devid, int index, int sub_handle)
3875 struct irq_2_irte *irte_info = &data->irq_2_irte;
3876 struct msi_msg *msg = &data->msi_entry;
3877 union irte *irte = &data->irte_entry;
3878 struct IO_APIC_route_entry *entry;
3880 data->irq_2_irte.devid = devid;
3881 data->irq_2_irte.index = index + sub_handle;
3883 /* Setup IRTE for IOMMU */
3884 irte->val = 0;
3885 irte->fields.vector = irq_cfg->vector;
3886 irte->fields.int_type = apic->irq_delivery_mode;
3887 irte->fields.destination = irq_cfg->dest_apicid;
3888 irte->fields.dm = apic->irq_dest_mode;
3889 irte->fields.valid = 1;
3891 switch (info->type) {
3892 case X86_IRQ_ALLOC_TYPE_IOAPIC:
3893 /* Setup IOAPIC entry */
3894 entry = info->ioapic_entry;
3895 info->ioapic_entry = NULL;
3896 memset(entry, 0, sizeof(*entry));
3897 entry->vector = index;
3898 entry->mask = 0;
3899 entry->trigger = info->ioapic_trigger;
3900 entry->polarity = info->ioapic_polarity;
3901 /* Mask level triggered irqs. */
3902 if (info->ioapic_trigger)
3903 entry->mask = 1;
3904 break;
3906 case X86_IRQ_ALLOC_TYPE_HPET:
3907 case X86_IRQ_ALLOC_TYPE_MSI:
3908 case X86_IRQ_ALLOC_TYPE_MSIX:
3909 msg->address_hi = MSI_ADDR_BASE_HI;
3910 msg->address_lo = MSI_ADDR_BASE_LO;
3911 msg->data = irte_info->index;
3912 break;
3914 default:
3915 BUG_ON(1);
3916 break;
3920 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
3921 unsigned int nr_irqs, void *arg)
3923 struct irq_alloc_info *info = arg;
3924 struct irq_data *irq_data;
3925 struct amd_ir_data *data;
3926 struct irq_cfg *cfg;
3927 int i, ret, devid;
3928 int index = -1;
3930 if (!info)
3931 return -EINVAL;
3932 if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_MSI &&
3933 info->type != X86_IRQ_ALLOC_TYPE_MSIX)
3934 return -EINVAL;
3937 * With IRQ remapping enabled, don't need contiguous CPU vectors
3938 * to support multiple MSI interrupts.
3940 if (info->type == X86_IRQ_ALLOC_TYPE_MSI)
3941 info->flags &= ~X86_IRQ_ALLOC_CONTIGUOUS_VECTORS;
3943 devid = get_devid(info);
3944 if (devid < 0)
3945 return -EINVAL;
3947 ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
3948 if (ret < 0)
3949 return ret;
3951 if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
3952 if (get_irq_table(devid, true))
3953 index = info->ioapic_pin;
3954 else
3955 ret = -ENOMEM;
3956 } else {
3957 index = alloc_irq_index(devid, nr_irqs);
3959 if (index < 0) {
3960 pr_warn("Failed to allocate IRTE\n");
3961 goto out_free_parent;
3964 for (i = 0; i < nr_irqs; i++) {
3965 irq_data = irq_domain_get_irq_data(domain, virq + i);
3966 cfg = irqd_cfg(irq_data);
3967 if (!irq_data || !cfg) {
3968 ret = -EINVAL;
3969 goto out_free_data;
3972 ret = -ENOMEM;
3973 data = kzalloc(sizeof(*data), GFP_KERNEL);
3974 if (!data)
3975 goto out_free_data;
3977 irq_data->hwirq = (devid << 16) + i;
3978 irq_data->chip_data = data;
3979 irq_data->chip = &amd_ir_chip;
3980 irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
3981 irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
3984 return 0;
3986 out_free_data:
3987 for (i--; i >= 0; i--) {
3988 irq_data = irq_domain_get_irq_data(domain, virq + i);
3989 if (irq_data)
3990 kfree(irq_data->chip_data);
3992 for (i = 0; i < nr_irqs; i++)
3993 free_irte(devid, index + i);
3994 out_free_parent:
3995 irq_domain_free_irqs_common(domain, virq, nr_irqs);
3996 return ret;
3999 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
4000 unsigned int nr_irqs)
4002 struct irq_2_irte *irte_info;
4003 struct irq_data *irq_data;
4004 struct amd_ir_data *data;
4005 int i;
4007 for (i = 0; i < nr_irqs; i++) {
4008 irq_data = irq_domain_get_irq_data(domain, virq + i);
4009 if (irq_data && irq_data->chip_data) {
4010 data = irq_data->chip_data;
4011 irte_info = &data->irq_2_irte;
4012 free_irte(irte_info->devid, irte_info->index);
4013 kfree(data);
4016 irq_domain_free_irqs_common(domain, virq, nr_irqs);
4019 static void irq_remapping_activate(struct irq_domain *domain,
4020 struct irq_data *irq_data)
4022 struct amd_ir_data *data = irq_data->chip_data;
4023 struct irq_2_irte *irte_info = &data->irq_2_irte;
4025 modify_irte(irte_info->devid, irte_info->index, data->irte_entry);
4028 static void irq_remapping_deactivate(struct irq_domain *domain,
4029 struct irq_data *irq_data)
4031 struct amd_ir_data *data = irq_data->chip_data;
4032 struct irq_2_irte *irte_info = &data->irq_2_irte;
4033 union irte entry;
4035 entry.val = 0;
4036 modify_irte(irte_info->devid, irte_info->index, data->irte_entry);
4039 static struct irq_domain_ops amd_ir_domain_ops = {
4040 .alloc = irq_remapping_alloc,
4041 .free = irq_remapping_free,
4042 .activate = irq_remapping_activate,
4043 .deactivate = irq_remapping_deactivate,
4046 static int amd_ir_set_affinity(struct irq_data *data,
4047 const struct cpumask *mask, bool force)
4049 struct amd_ir_data *ir_data = data->chip_data;
4050 struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4051 struct irq_cfg *cfg = irqd_cfg(data);
4052 struct irq_data *parent = data->parent_data;
4053 int ret;
4055 ret = parent->chip->irq_set_affinity(parent, mask, force);
4056 if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
4057 return ret;
4060 * Atomically updates the IRTE with the new destination, vector
4061 * and flushes the interrupt entry cache.
4063 ir_data->irte_entry.fields.vector = cfg->vector;
4064 ir_data->irte_entry.fields.destination = cfg->dest_apicid;
4065 modify_irte(irte_info->devid, irte_info->index, ir_data->irte_entry);
4068 * After this point, all the interrupts will start arriving
4069 * at the new destination. So, time to cleanup the previous
4070 * vector allocation.
4072 send_cleanup_vector(cfg);
4074 return IRQ_SET_MASK_OK_DONE;
4077 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
4079 struct amd_ir_data *ir_data = irq_data->chip_data;
4081 *msg = ir_data->msi_entry;
4084 static struct irq_chip amd_ir_chip = {
4085 .irq_ack = ir_ack_apic_edge,
4086 .irq_set_affinity = amd_ir_set_affinity,
4087 .irq_compose_msi_msg = ir_compose_msi_msg,
4090 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
4092 iommu->ir_domain = irq_domain_add_tree(NULL, &amd_ir_domain_ops, iommu);
4093 if (!iommu->ir_domain)
4094 return -ENOMEM;
4096 iommu->ir_domain->parent = arch_get_ir_parent_domain();
4097 iommu->msi_domain = arch_create_msi_irq_domain(iommu->ir_domain);
4099 return 0;
4101 #endif