2 * Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
3 * Author: Joerg Roedel <joerg.roedel@amd.com>
4 * Leo Duran <leo.duran@amd.com>
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 as published
8 * by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 #include <linux/ratelimit.h>
21 #include <linux/pci.h>
22 #include <linux/pci-ats.h>
23 #include <linux/bitmap.h>
24 #include <linux/slab.h>
25 #include <linux/debugfs.h>
26 #include <linux/scatterlist.h>
27 #include <linux/dma-mapping.h>
28 #include <linux/iommu-helper.h>
29 #include <linux/iommu.h>
30 #include <linux/delay.h>
31 #include <linux/amd-iommu.h>
32 #include <linux/notifier.h>
33 #include <linux/export.h>
34 #include <asm/msidef.h>
35 #include <asm/proto.h>
36 #include <asm/iommu.h>
40 #include "amd_iommu_proto.h"
41 #include "amd_iommu_types.h"
43 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
45 #define LOOP_TIMEOUT 100000
47 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
49 /* A list of preallocated protection domains */
50 static LIST_HEAD(iommu_pd_list);
51 static DEFINE_SPINLOCK(iommu_pd_list_lock);
53 /* List of all available dev_data structures */
54 static LIST_HEAD(dev_data_list);
55 static DEFINE_SPINLOCK(dev_data_list_lock);
58 * Domain for untranslated devices - only allocated
59 * if iommu=pt passed on kernel cmd line.
61 static struct protection_domain *pt_domain;
63 static struct iommu_ops amd_iommu_ops;
65 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
66 int amd_iommu_max_glx_val = -1;
69 * general struct to manage commands send to an IOMMU
75 static void update_domain(struct protection_domain *domain);
76 static int __init alloc_passthrough_domain(void);
78 /****************************************************************************
82 ****************************************************************************/
84 static struct iommu_dev_data *alloc_dev_data(u16 devid)
86 struct iommu_dev_data *dev_data;
89 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
93 dev_data->devid = devid;
94 atomic_set(&dev_data->bind, 0);
96 spin_lock_irqsave(&dev_data_list_lock, flags);
97 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
98 spin_unlock_irqrestore(&dev_data_list_lock, flags);
103 static void free_dev_data(struct iommu_dev_data *dev_data)
107 spin_lock_irqsave(&dev_data_list_lock, flags);
108 list_del(&dev_data->dev_data_list);
109 spin_unlock_irqrestore(&dev_data_list_lock, flags);
114 static struct iommu_dev_data *search_dev_data(u16 devid)
116 struct iommu_dev_data *dev_data;
119 spin_lock_irqsave(&dev_data_list_lock, flags);
120 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
121 if (dev_data->devid == devid)
128 spin_unlock_irqrestore(&dev_data_list_lock, flags);
133 static struct iommu_dev_data *find_dev_data(u16 devid)
135 struct iommu_dev_data *dev_data;
137 dev_data = search_dev_data(devid);
139 if (dev_data == NULL)
140 dev_data = alloc_dev_data(devid);
145 static inline u16 get_device_id(struct device *dev)
147 struct pci_dev *pdev = to_pci_dev(dev);
149 return calc_devid(pdev->bus->number, pdev->devfn);
152 static struct iommu_dev_data *get_dev_data(struct device *dev)
154 return dev->archdata.iommu;
157 static bool pci_iommuv2_capable(struct pci_dev *pdev)
159 static const int caps[] = {
166 for (i = 0; i < 3; ++i) {
167 pos = pci_find_ext_capability(pdev, caps[i]);
176 * In this function the list of preallocated protection domains is traversed to
177 * find the domain for a specific device
179 static struct dma_ops_domain *find_protection_domain(u16 devid)
181 struct dma_ops_domain *entry, *ret = NULL;
183 u16 alias = amd_iommu_alias_table[devid];
185 if (list_empty(&iommu_pd_list))
188 spin_lock_irqsave(&iommu_pd_list_lock, flags);
190 list_for_each_entry(entry, &iommu_pd_list, list) {
191 if (entry->target_dev == devid ||
192 entry->target_dev == alias) {
198 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
204 * This function checks if the driver got a valid device from the caller to
205 * avoid dereferencing invalid pointers.
207 static bool check_device(struct device *dev)
211 if (!dev || !dev->dma_mask)
214 /* No device or no PCI device */
215 if (dev->bus != &pci_bus_type)
218 devid = get_device_id(dev);
220 /* Out of our scope? */
221 if (devid > amd_iommu_last_bdf)
224 if (amd_iommu_rlookup_table[devid] == NULL)
230 static int iommu_init_device(struct device *dev)
232 struct pci_dev *pdev = to_pci_dev(dev);
233 struct iommu_dev_data *dev_data;
236 if (dev->archdata.iommu)
239 dev_data = find_dev_data(get_device_id(dev));
243 alias = amd_iommu_alias_table[dev_data->devid];
244 if (alias != dev_data->devid) {
245 struct iommu_dev_data *alias_data;
247 alias_data = find_dev_data(alias);
248 if (alias_data == NULL) {
249 pr_err("AMD-Vi: Warning: Unhandled device %s\n",
251 free_dev_data(dev_data);
254 dev_data->alias_data = alias_data;
257 if (pci_iommuv2_capable(pdev)) {
258 struct amd_iommu *iommu;
260 iommu = amd_iommu_rlookup_table[dev_data->devid];
261 dev_data->iommu_v2 = iommu->is_iommu_v2;
264 dev->archdata.iommu = dev_data;
269 static void iommu_ignore_device(struct device *dev)
273 devid = get_device_id(dev);
274 alias = amd_iommu_alias_table[devid];
276 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
277 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
279 amd_iommu_rlookup_table[devid] = NULL;
280 amd_iommu_rlookup_table[alias] = NULL;
283 static void iommu_uninit_device(struct device *dev)
286 * Nothing to do here - we keep dev_data around for unplugged devices
287 * and reuse it when the device is re-plugged - not doing so would
288 * introduce a ton of races.
292 void __init amd_iommu_uninit_devices(void)
294 struct iommu_dev_data *dev_data, *n;
295 struct pci_dev *pdev = NULL;
297 for_each_pci_dev(pdev) {
299 if (!check_device(&pdev->dev))
302 iommu_uninit_device(&pdev->dev);
305 /* Free all of our dev_data structures */
306 list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
307 free_dev_data(dev_data);
310 int __init amd_iommu_init_devices(void)
312 struct pci_dev *pdev = NULL;
315 for_each_pci_dev(pdev) {
317 if (!check_device(&pdev->dev))
320 ret = iommu_init_device(&pdev->dev);
321 if (ret == -ENOTSUPP)
322 iommu_ignore_device(&pdev->dev);
331 amd_iommu_uninit_devices();
335 #ifdef CONFIG_AMD_IOMMU_STATS
338 * Initialization code for statistics collection
341 DECLARE_STATS_COUNTER(compl_wait);
342 DECLARE_STATS_COUNTER(cnt_map_single);
343 DECLARE_STATS_COUNTER(cnt_unmap_single);
344 DECLARE_STATS_COUNTER(cnt_map_sg);
345 DECLARE_STATS_COUNTER(cnt_unmap_sg);
346 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
347 DECLARE_STATS_COUNTER(cnt_free_coherent);
348 DECLARE_STATS_COUNTER(cross_page);
349 DECLARE_STATS_COUNTER(domain_flush_single);
350 DECLARE_STATS_COUNTER(domain_flush_all);
351 DECLARE_STATS_COUNTER(alloced_io_mem);
352 DECLARE_STATS_COUNTER(total_map_requests);
354 static struct dentry *stats_dir;
355 static struct dentry *de_fflush;
357 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
359 if (stats_dir == NULL)
362 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
366 static void amd_iommu_stats_init(void)
368 stats_dir = debugfs_create_dir("amd-iommu", NULL);
369 if (stats_dir == NULL)
372 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
373 (u32 *)&amd_iommu_unmap_flush);
375 amd_iommu_stats_add(&compl_wait);
376 amd_iommu_stats_add(&cnt_map_single);
377 amd_iommu_stats_add(&cnt_unmap_single);
378 amd_iommu_stats_add(&cnt_map_sg);
379 amd_iommu_stats_add(&cnt_unmap_sg);
380 amd_iommu_stats_add(&cnt_alloc_coherent);
381 amd_iommu_stats_add(&cnt_free_coherent);
382 amd_iommu_stats_add(&cross_page);
383 amd_iommu_stats_add(&domain_flush_single);
384 amd_iommu_stats_add(&domain_flush_all);
385 amd_iommu_stats_add(&alloced_io_mem);
386 amd_iommu_stats_add(&total_map_requests);
391 /****************************************************************************
393 * Interrupt handling functions
395 ****************************************************************************/
397 static void dump_dte_entry(u16 devid)
401 for (i = 0; i < 4; ++i)
402 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
403 amd_iommu_dev_table[devid].data[i]);
406 static void dump_command(unsigned long phys_addr)
408 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
411 for (i = 0; i < 4; ++i)
412 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
415 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
418 int type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
419 int devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
420 int domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
421 int flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
422 u64 address = (u64)(((u64)event[3]) << 32) | event[2];
424 printk(KERN_ERR "AMD-Vi: Event logged [");
427 case EVENT_TYPE_ILL_DEV:
428 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
429 "address=0x%016llx flags=0x%04x]\n",
430 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
432 dump_dte_entry(devid);
434 case EVENT_TYPE_IO_FAULT:
435 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
436 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
437 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
438 domid, address, flags);
440 case EVENT_TYPE_DEV_TAB_ERR:
441 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
442 "address=0x%016llx flags=0x%04x]\n",
443 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
446 case EVENT_TYPE_PAGE_TAB_ERR:
447 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
448 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
449 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
450 domid, address, flags);
452 case EVENT_TYPE_ILL_CMD:
453 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
454 dump_command(address);
456 case EVENT_TYPE_CMD_HARD_ERR:
457 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
458 "flags=0x%04x]\n", address, flags);
460 case EVENT_TYPE_IOTLB_INV_TO:
461 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
462 "address=0x%016llx]\n",
463 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
466 case EVENT_TYPE_INV_DEV_REQ:
467 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
468 "address=0x%016llx flags=0x%04x]\n",
469 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
473 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
477 static void iommu_poll_events(struct amd_iommu *iommu)
482 spin_lock_irqsave(&iommu->lock, flags);
484 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
485 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
487 while (head != tail) {
488 iommu_print_event(iommu, iommu->evt_buf + head);
489 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
492 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
494 spin_unlock_irqrestore(&iommu->lock, flags);
497 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u32 head)
499 struct amd_iommu_fault fault;
503 raw = (u64 *)(iommu->ppr_log + head);
506 * Hardware bug: Interrupt may arrive before the entry is written to
507 * memory. If this happens we need to wait for the entry to arrive.
509 for (i = 0; i < LOOP_TIMEOUT; ++i) {
510 if (PPR_REQ_TYPE(raw[0]) != 0)
515 if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
516 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
520 fault.address = raw[1];
521 fault.pasid = PPR_PASID(raw[0]);
522 fault.device_id = PPR_DEVID(raw[0]);
523 fault.tag = PPR_TAG(raw[0]);
524 fault.flags = PPR_FLAGS(raw[0]);
527 * To detect the hardware bug we need to clear the entry
532 atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
535 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
540 if (iommu->ppr_log == NULL)
543 spin_lock_irqsave(&iommu->lock, flags);
545 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
546 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
548 while (head != tail) {
550 /* Handle PPR entry */
551 iommu_handle_ppr_entry(iommu, head);
553 /* Update and refresh ring-buffer state*/
554 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
555 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
556 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
559 /* enable ppr interrupts again */
560 writel(MMIO_STATUS_PPR_INT_MASK, iommu->mmio_base + MMIO_STATUS_OFFSET);
562 spin_unlock_irqrestore(&iommu->lock, flags);
565 irqreturn_t amd_iommu_int_thread(int irq, void *data)
567 struct amd_iommu *iommu;
569 for_each_iommu(iommu) {
570 iommu_poll_events(iommu);
571 iommu_poll_ppr_log(iommu);
577 irqreturn_t amd_iommu_int_handler(int irq, void *data)
579 return IRQ_WAKE_THREAD;
582 /****************************************************************************
584 * IOMMU command queuing functions
586 ****************************************************************************/
588 static int wait_on_sem(volatile u64 *sem)
592 while (*sem == 0 && i < LOOP_TIMEOUT) {
597 if (i == LOOP_TIMEOUT) {
598 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
605 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
606 struct iommu_cmd *cmd,
611 target = iommu->cmd_buf + tail;
612 tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
614 /* Copy command to buffer */
615 memcpy(target, cmd, sizeof(*cmd));
617 /* Tell the IOMMU about it */
618 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
621 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
623 WARN_ON(address & 0x7ULL);
625 memset(cmd, 0, sizeof(*cmd));
626 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
627 cmd->data[1] = upper_32_bits(__pa(address));
629 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
632 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
634 memset(cmd, 0, sizeof(*cmd));
635 cmd->data[0] = devid;
636 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
639 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
640 size_t size, u16 domid, int pde)
645 pages = iommu_num_pages(address, size, PAGE_SIZE);
650 * If we have to flush more than one page, flush all
651 * TLB entries for this domain
653 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
657 address &= PAGE_MASK;
659 memset(cmd, 0, sizeof(*cmd));
660 cmd->data[1] |= domid;
661 cmd->data[2] = lower_32_bits(address);
662 cmd->data[3] = upper_32_bits(address);
663 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
664 if (s) /* size bit - we flush more than one 4kb page */
665 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
666 if (pde) /* PDE bit - we wan't flush everything not only the PTEs */
667 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
670 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
671 u64 address, size_t size)
676 pages = iommu_num_pages(address, size, PAGE_SIZE);
681 * If we have to flush more than one page, flush all
682 * TLB entries for this domain
684 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
688 address &= PAGE_MASK;
690 memset(cmd, 0, sizeof(*cmd));
691 cmd->data[0] = devid;
692 cmd->data[0] |= (qdep & 0xff) << 24;
693 cmd->data[1] = devid;
694 cmd->data[2] = lower_32_bits(address);
695 cmd->data[3] = upper_32_bits(address);
696 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
698 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
701 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
702 u64 address, bool size)
704 memset(cmd, 0, sizeof(*cmd));
706 address &= ~(0xfffULL);
708 cmd->data[0] = pasid & PASID_MASK;
709 cmd->data[1] = domid;
710 cmd->data[2] = lower_32_bits(address);
711 cmd->data[3] = upper_32_bits(address);
712 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
713 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
715 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
716 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
719 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
720 int qdep, u64 address, bool size)
722 memset(cmd, 0, sizeof(*cmd));
724 address &= ~(0xfffULL);
726 cmd->data[0] = devid;
727 cmd->data[0] |= (pasid & 0xff) << 16;
728 cmd->data[0] |= (qdep & 0xff) << 24;
729 cmd->data[1] = devid;
730 cmd->data[1] |= ((pasid >> 8) & 0xfff) << 16;
731 cmd->data[2] = lower_32_bits(address);
732 cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
733 cmd->data[3] = upper_32_bits(address);
735 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
736 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
739 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
740 int status, int tag, bool gn)
742 memset(cmd, 0, sizeof(*cmd));
744 cmd->data[0] = devid;
746 cmd->data[1] = pasid & PASID_MASK;
747 cmd->data[2] = CMD_INV_IOMMU_PAGES_GN_MASK;
749 cmd->data[3] = tag & 0x1ff;
750 cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
752 CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
755 static void build_inv_all(struct iommu_cmd *cmd)
757 memset(cmd, 0, sizeof(*cmd));
758 CMD_SET_TYPE(cmd, CMD_INV_ALL);
762 * Writes the command to the IOMMUs command buffer and informs the
763 * hardware about the new command.
765 static int iommu_queue_command_sync(struct amd_iommu *iommu,
766 struct iommu_cmd *cmd,
769 u32 left, tail, head, next_tail;
772 WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
775 spin_lock_irqsave(&iommu->lock, flags);
777 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
778 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
779 next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
780 left = (head - next_tail) % iommu->cmd_buf_size;
783 struct iommu_cmd sync_cmd;
784 volatile u64 sem = 0;
787 build_completion_wait(&sync_cmd, (u64)&sem);
788 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
790 spin_unlock_irqrestore(&iommu->lock, flags);
792 if ((ret = wait_on_sem(&sem)) != 0)
798 copy_cmd_to_buffer(iommu, cmd, tail);
800 /* We need to sync now to make sure all commands are processed */
801 iommu->need_sync = sync;
803 spin_unlock_irqrestore(&iommu->lock, flags);
808 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
810 return iommu_queue_command_sync(iommu, cmd, true);
814 * This function queues a completion wait command into the command
817 static int iommu_completion_wait(struct amd_iommu *iommu)
819 struct iommu_cmd cmd;
820 volatile u64 sem = 0;
823 if (!iommu->need_sync)
826 build_completion_wait(&cmd, (u64)&sem);
828 ret = iommu_queue_command_sync(iommu, &cmd, false);
832 return wait_on_sem(&sem);
835 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
837 struct iommu_cmd cmd;
839 build_inv_dte(&cmd, devid);
841 return iommu_queue_command(iommu, &cmd);
844 static void iommu_flush_dte_all(struct amd_iommu *iommu)
848 for (devid = 0; devid <= 0xffff; ++devid)
849 iommu_flush_dte(iommu, devid);
851 iommu_completion_wait(iommu);
855 * This function uses heavy locking and may disable irqs for some time. But
856 * this is no issue because it is only called during resume.
858 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
862 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
863 struct iommu_cmd cmd;
864 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
866 iommu_queue_command(iommu, &cmd);
869 iommu_completion_wait(iommu);
872 static void iommu_flush_all(struct amd_iommu *iommu)
874 struct iommu_cmd cmd;
878 iommu_queue_command(iommu, &cmd);
879 iommu_completion_wait(iommu);
882 void iommu_flush_all_caches(struct amd_iommu *iommu)
884 if (iommu_feature(iommu, FEATURE_IA)) {
885 iommu_flush_all(iommu);
887 iommu_flush_dte_all(iommu);
888 iommu_flush_tlb_all(iommu);
893 * Command send function for flushing on-device TLB
895 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
896 u64 address, size_t size)
898 struct amd_iommu *iommu;
899 struct iommu_cmd cmd;
902 qdep = dev_data->ats.qdep;
903 iommu = amd_iommu_rlookup_table[dev_data->devid];
905 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
907 return iommu_queue_command(iommu, &cmd);
911 * Command send function for invalidating a device table entry
913 static int device_flush_dte(struct iommu_dev_data *dev_data)
915 struct amd_iommu *iommu;
918 iommu = amd_iommu_rlookup_table[dev_data->devid];
920 ret = iommu_flush_dte(iommu, dev_data->devid);
924 if (dev_data->ats.enabled)
925 ret = device_flush_iotlb(dev_data, 0, ~0UL);
931 * TLB invalidation function which is called from the mapping functions.
932 * It invalidates a single PTE if the range to flush is within a single
933 * page. Otherwise it flushes the whole TLB of the IOMMU.
935 static void __domain_flush_pages(struct protection_domain *domain,
936 u64 address, size_t size, int pde)
938 struct iommu_dev_data *dev_data;
939 struct iommu_cmd cmd;
942 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
944 for (i = 0; i < amd_iommus_present; ++i) {
945 if (!domain->dev_iommu[i])
949 * Devices of this domain are behind this IOMMU
950 * We need a TLB flush
952 ret |= iommu_queue_command(amd_iommus[i], &cmd);
955 list_for_each_entry(dev_data, &domain->dev_list, list) {
957 if (!dev_data->ats.enabled)
960 ret |= device_flush_iotlb(dev_data, address, size);
966 static void domain_flush_pages(struct protection_domain *domain,
967 u64 address, size_t size)
969 __domain_flush_pages(domain, address, size, 0);
972 /* Flush the whole IO/TLB for a given protection domain */
973 static void domain_flush_tlb(struct protection_domain *domain)
975 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
978 /* Flush the whole IO/TLB for a given protection domain - including PDE */
979 static void domain_flush_tlb_pde(struct protection_domain *domain)
981 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
984 static void domain_flush_complete(struct protection_domain *domain)
988 for (i = 0; i < amd_iommus_present; ++i) {
989 if (!domain->dev_iommu[i])
993 * Devices of this domain are behind this IOMMU
994 * We need to wait for completion of all commands.
996 iommu_completion_wait(amd_iommus[i]);
1002 * This function flushes the DTEs for all devices in domain
1004 static void domain_flush_devices(struct protection_domain *domain)
1006 struct iommu_dev_data *dev_data;
1008 list_for_each_entry(dev_data, &domain->dev_list, list)
1009 device_flush_dte(dev_data);
1012 /****************************************************************************
1014 * The functions below are used the create the page table mappings for
1015 * unity mapped regions.
1017 ****************************************************************************/
1020 * This function is used to add another level to an IO page table. Adding
1021 * another level increases the size of the address space by 9 bits to a size up
1024 static bool increase_address_space(struct protection_domain *domain,
1029 if (domain->mode == PAGE_MODE_6_LEVEL)
1030 /* address space already 64 bit large */
1033 pte = (void *)get_zeroed_page(gfp);
1037 *pte = PM_LEVEL_PDE(domain->mode,
1038 virt_to_phys(domain->pt_root));
1039 domain->pt_root = pte;
1041 domain->updated = true;
1046 static u64 *alloc_pte(struct protection_domain *domain,
1047 unsigned long address,
1048 unsigned long page_size,
1055 BUG_ON(!is_power_of_2(page_size));
1057 while (address > PM_LEVEL_SIZE(domain->mode))
1058 increase_address_space(domain, gfp);
1060 level = domain->mode - 1;
1061 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1062 address = PAGE_SIZE_ALIGN(address, page_size);
1063 end_lvl = PAGE_SIZE_LEVEL(page_size);
1065 while (level > end_lvl) {
1066 if (!IOMMU_PTE_PRESENT(*pte)) {
1067 page = (u64 *)get_zeroed_page(gfp);
1070 *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1073 /* No level skipping support yet */
1074 if (PM_PTE_LEVEL(*pte) != level)
1079 pte = IOMMU_PTE_PAGE(*pte);
1081 if (pte_page && level == end_lvl)
1084 pte = &pte[PM_LEVEL_INDEX(level, address)];
1091 * This function checks if there is a PTE for a given dma address. If
1092 * there is one, it returns the pointer to it.
1094 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
1099 if (address > PM_LEVEL_SIZE(domain->mode))
1102 level = domain->mode - 1;
1103 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1108 if (!IOMMU_PTE_PRESENT(*pte))
1112 if (PM_PTE_LEVEL(*pte) == 0x07) {
1113 unsigned long pte_mask, __pte;
1116 * If we have a series of large PTEs, make
1117 * sure to return a pointer to the first one.
1119 pte_mask = PTE_PAGE_SIZE(*pte);
1120 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1121 __pte = ((unsigned long)pte) & pte_mask;
1123 return (u64 *)__pte;
1126 /* No level skipping support yet */
1127 if (PM_PTE_LEVEL(*pte) != level)
1132 /* Walk to the next level */
1133 pte = IOMMU_PTE_PAGE(*pte);
1134 pte = &pte[PM_LEVEL_INDEX(level, address)];
1141 * Generic mapping functions. It maps a physical address into a DMA
1142 * address space. It allocates the page table pages if necessary.
1143 * In the future it can be extended to a generic mapping function
1144 * supporting all features of AMD IOMMU page tables like level skipping
1145 * and full 64 bit address spaces.
1147 static int iommu_map_page(struct protection_domain *dom,
1148 unsigned long bus_addr,
1149 unsigned long phys_addr,
1151 unsigned long page_size)
1156 if (!(prot & IOMMU_PROT_MASK))
1159 bus_addr = PAGE_ALIGN(bus_addr);
1160 phys_addr = PAGE_ALIGN(phys_addr);
1161 count = PAGE_SIZE_PTE_COUNT(page_size);
1162 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1164 for (i = 0; i < count; ++i)
1165 if (IOMMU_PTE_PRESENT(pte[i]))
1168 if (page_size > PAGE_SIZE) {
1169 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1170 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1172 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1174 if (prot & IOMMU_PROT_IR)
1175 __pte |= IOMMU_PTE_IR;
1176 if (prot & IOMMU_PROT_IW)
1177 __pte |= IOMMU_PTE_IW;
1179 for (i = 0; i < count; ++i)
1187 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1188 unsigned long bus_addr,
1189 unsigned long page_size)
1191 unsigned long long unmap_size, unmapped;
1194 BUG_ON(!is_power_of_2(page_size));
1198 while (unmapped < page_size) {
1200 pte = fetch_pte(dom, bus_addr);
1204 * No PTE for this address
1205 * move forward in 4kb steps
1207 unmap_size = PAGE_SIZE;
1208 } else if (PM_PTE_LEVEL(*pte) == 0) {
1209 /* 4kb PTE found for this address */
1210 unmap_size = PAGE_SIZE;
1215 /* Large PTE found which maps this address */
1216 unmap_size = PTE_PAGE_SIZE(*pte);
1217 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1218 for (i = 0; i < count; i++)
1222 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1223 unmapped += unmap_size;
1226 BUG_ON(!is_power_of_2(unmapped));
1232 * This function checks if a specific unity mapping entry is needed for
1233 * this specific IOMMU.
1235 static int iommu_for_unity_map(struct amd_iommu *iommu,
1236 struct unity_map_entry *entry)
1240 for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1241 bdf = amd_iommu_alias_table[i];
1242 if (amd_iommu_rlookup_table[bdf] == iommu)
1250 * This function actually applies the mapping to the page table of the
1253 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1254 struct unity_map_entry *e)
1259 for (addr = e->address_start; addr < e->address_end;
1260 addr += PAGE_SIZE) {
1261 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1266 * if unity mapping is in aperture range mark the page
1267 * as allocated in the aperture
1269 if (addr < dma_dom->aperture_size)
1270 __set_bit(addr >> PAGE_SHIFT,
1271 dma_dom->aperture[0]->bitmap);
1278 * Init the unity mappings for a specific IOMMU in the system
1280 * Basically iterates over all unity mapping entries and applies them to
1281 * the default domain DMA of that IOMMU if necessary.
1283 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1285 struct unity_map_entry *entry;
1288 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1289 if (!iommu_for_unity_map(iommu, entry))
1291 ret = dma_ops_unity_map(iommu->default_dom, entry);
1300 * Inits the unity mappings required for a specific device
1302 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1305 struct unity_map_entry *e;
1308 list_for_each_entry(e, &amd_iommu_unity_map, list) {
1309 if (!(devid >= e->devid_start && devid <= e->devid_end))
1311 ret = dma_ops_unity_map(dma_dom, e);
1319 /****************************************************************************
1321 * The next functions belong to the address allocator for the dma_ops
1322 * interface functions. They work like the allocators in the other IOMMU
1323 * drivers. Its basically a bitmap which marks the allocated pages in
1324 * the aperture. Maybe it could be enhanced in the future to a more
1325 * efficient allocator.
1327 ****************************************************************************/
1330 * The address allocator core functions.
1332 * called with domain->lock held
1336 * Used to reserve address ranges in the aperture (e.g. for exclusion
1339 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1340 unsigned long start_page,
1343 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1345 if (start_page + pages > last_page)
1346 pages = last_page - start_page;
1348 for (i = start_page; i < start_page + pages; ++i) {
1349 int index = i / APERTURE_RANGE_PAGES;
1350 int page = i % APERTURE_RANGE_PAGES;
1351 __set_bit(page, dom->aperture[index]->bitmap);
1356 * This function is used to add a new aperture range to an existing
1357 * aperture in case of dma_ops domain allocation or address allocation
1360 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1361 bool populate, gfp_t gfp)
1363 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1364 struct amd_iommu *iommu;
1365 unsigned long i, old_size;
1367 #ifdef CONFIG_IOMMU_STRESS
1371 if (index >= APERTURE_MAX_RANGES)
1374 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1375 if (!dma_dom->aperture[index])
1378 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1379 if (!dma_dom->aperture[index]->bitmap)
1382 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1385 unsigned long address = dma_dom->aperture_size;
1386 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1387 u64 *pte, *pte_page;
1389 for (i = 0; i < num_ptes; ++i) {
1390 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1395 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1397 address += APERTURE_RANGE_SIZE / 64;
1401 old_size = dma_dom->aperture_size;
1402 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1404 /* Reserve address range used for MSI messages */
1405 if (old_size < MSI_ADDR_BASE_LO &&
1406 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1407 unsigned long spage;
1410 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1411 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1413 dma_ops_reserve_addresses(dma_dom, spage, pages);
1416 /* Initialize the exclusion range if necessary */
1417 for_each_iommu(iommu) {
1418 if (iommu->exclusion_start &&
1419 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1420 && iommu->exclusion_start < dma_dom->aperture_size) {
1421 unsigned long startpage;
1422 int pages = iommu_num_pages(iommu->exclusion_start,
1423 iommu->exclusion_length,
1425 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1426 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1431 * Check for areas already mapped as present in the new aperture
1432 * range and mark those pages as reserved in the allocator. Such
1433 * mappings may already exist as a result of requested unity
1434 * mappings for devices.
1436 for (i = dma_dom->aperture[index]->offset;
1437 i < dma_dom->aperture_size;
1439 u64 *pte = fetch_pte(&dma_dom->domain, i);
1440 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1443 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1446 update_domain(&dma_dom->domain);
1451 update_domain(&dma_dom->domain);
1453 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1455 kfree(dma_dom->aperture[index]);
1456 dma_dom->aperture[index] = NULL;
1461 static unsigned long dma_ops_area_alloc(struct device *dev,
1462 struct dma_ops_domain *dom,
1464 unsigned long align_mask,
1466 unsigned long start)
1468 unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1469 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1470 int i = start >> APERTURE_RANGE_SHIFT;
1471 unsigned long boundary_size;
1472 unsigned long address = -1;
1473 unsigned long limit;
1475 next_bit >>= PAGE_SHIFT;
1477 boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1478 PAGE_SIZE) >> PAGE_SHIFT;
1480 for (;i < max_index; ++i) {
1481 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1483 if (dom->aperture[i]->offset >= dma_mask)
1486 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1487 dma_mask >> PAGE_SHIFT);
1489 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1490 limit, next_bit, pages, 0,
1491 boundary_size, align_mask);
1492 if (address != -1) {
1493 address = dom->aperture[i]->offset +
1494 (address << PAGE_SHIFT);
1495 dom->next_address = address + (pages << PAGE_SHIFT);
1505 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1506 struct dma_ops_domain *dom,
1508 unsigned long align_mask,
1511 unsigned long address;
1513 #ifdef CONFIG_IOMMU_STRESS
1514 dom->next_address = 0;
1515 dom->need_flush = true;
1518 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1519 dma_mask, dom->next_address);
1521 if (address == -1) {
1522 dom->next_address = 0;
1523 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1525 dom->need_flush = true;
1528 if (unlikely(address == -1))
1529 address = DMA_ERROR_CODE;
1531 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1537 * The address free function.
1539 * called with domain->lock held
1541 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1542 unsigned long address,
1545 unsigned i = address >> APERTURE_RANGE_SHIFT;
1546 struct aperture_range *range = dom->aperture[i];
1548 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1550 #ifdef CONFIG_IOMMU_STRESS
1555 if (address >= dom->next_address)
1556 dom->need_flush = true;
1558 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1560 bitmap_clear(range->bitmap, address, pages);
1564 /****************************************************************************
1566 * The next functions belong to the domain allocation. A domain is
1567 * allocated for every IOMMU as the default domain. If device isolation
1568 * is enabled, every device get its own domain. The most important thing
1569 * about domains is the page table mapping the DMA address space they
1572 ****************************************************************************/
1575 * This function adds a protection domain to the global protection domain list
1577 static void add_domain_to_list(struct protection_domain *domain)
1579 unsigned long flags;
1581 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1582 list_add(&domain->list, &amd_iommu_pd_list);
1583 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1587 * This function removes a protection domain to the global
1588 * protection domain list
1590 static void del_domain_from_list(struct protection_domain *domain)
1592 unsigned long flags;
1594 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1595 list_del(&domain->list);
1596 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1599 static u16 domain_id_alloc(void)
1601 unsigned long flags;
1604 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1605 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1607 if (id > 0 && id < MAX_DOMAIN_ID)
1608 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1611 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1616 static void domain_id_free(int id)
1618 unsigned long flags;
1620 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1621 if (id > 0 && id < MAX_DOMAIN_ID)
1622 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1623 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1626 static void free_pagetable(struct protection_domain *domain)
1631 p1 = domain->pt_root;
1636 for (i = 0; i < 512; ++i) {
1637 if (!IOMMU_PTE_PRESENT(p1[i]))
1640 p2 = IOMMU_PTE_PAGE(p1[i]);
1641 for (j = 0; j < 512; ++j) {
1642 if (!IOMMU_PTE_PRESENT(p2[j]))
1644 p3 = IOMMU_PTE_PAGE(p2[j]);
1645 free_page((unsigned long)p3);
1648 free_page((unsigned long)p2);
1651 free_page((unsigned long)p1);
1653 domain->pt_root = NULL;
1656 static void free_gcr3_tbl_level1(u64 *tbl)
1661 for (i = 0; i < 512; ++i) {
1662 if (!(tbl[i] & GCR3_VALID))
1665 ptr = __va(tbl[i] & PAGE_MASK);
1667 free_page((unsigned long)ptr);
1671 static void free_gcr3_tbl_level2(u64 *tbl)
1676 for (i = 0; i < 512; ++i) {
1677 if (!(tbl[i] & GCR3_VALID))
1680 ptr = __va(tbl[i] & PAGE_MASK);
1682 free_gcr3_tbl_level1(ptr);
1686 static void free_gcr3_table(struct protection_domain *domain)
1688 if (domain->glx == 2)
1689 free_gcr3_tbl_level2(domain->gcr3_tbl);
1690 else if (domain->glx == 1)
1691 free_gcr3_tbl_level1(domain->gcr3_tbl);
1692 else if (domain->glx != 0)
1695 free_page((unsigned long)domain->gcr3_tbl);
1699 * Free a domain, only used if something went wrong in the
1700 * allocation path and we need to free an already allocated page table
1702 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1709 del_domain_from_list(&dom->domain);
1711 free_pagetable(&dom->domain);
1713 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1714 if (!dom->aperture[i])
1716 free_page((unsigned long)dom->aperture[i]->bitmap);
1717 kfree(dom->aperture[i]);
1724 * Allocates a new protection domain usable for the dma_ops functions.
1725 * It also initializes the page table and the address allocator data
1726 * structures required for the dma_ops interface
1728 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1730 struct dma_ops_domain *dma_dom;
1732 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1736 spin_lock_init(&dma_dom->domain.lock);
1738 dma_dom->domain.id = domain_id_alloc();
1739 if (dma_dom->domain.id == 0)
1741 INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1742 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1743 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1744 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1745 dma_dom->domain.priv = dma_dom;
1746 if (!dma_dom->domain.pt_root)
1749 dma_dom->need_flush = false;
1750 dma_dom->target_dev = 0xffff;
1752 add_domain_to_list(&dma_dom->domain);
1754 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1758 * mark the first page as allocated so we never return 0 as
1759 * a valid dma-address. So we can use 0 as error value
1761 dma_dom->aperture[0]->bitmap[0] = 1;
1762 dma_dom->next_address = 0;
1768 dma_ops_domain_free(dma_dom);
1774 * little helper function to check whether a given protection domain is a
1777 static bool dma_ops_domain(struct protection_domain *domain)
1779 return domain->flags & PD_DMA_OPS_MASK;
1782 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1787 if (domain->mode != PAGE_MODE_NONE)
1788 pte_root = virt_to_phys(domain->pt_root);
1790 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1791 << DEV_ENTRY_MODE_SHIFT;
1792 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1794 flags = amd_iommu_dev_table[devid].data[1];
1797 flags |= DTE_FLAG_IOTLB;
1799 if (domain->flags & PD_IOMMUV2_MASK) {
1800 u64 gcr3 = __pa(domain->gcr3_tbl);
1801 u64 glx = domain->glx;
1804 pte_root |= DTE_FLAG_GV;
1805 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1807 /* First mask out possible old values for GCR3 table */
1808 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1811 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1814 /* Encode GCR3 table into DTE */
1815 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1818 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1821 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
1825 flags &= ~(0xffffUL);
1826 flags |= domain->id;
1828 amd_iommu_dev_table[devid].data[1] = flags;
1829 amd_iommu_dev_table[devid].data[0] = pte_root;
1832 static void clear_dte_entry(u16 devid)
1834 /* remove entry from the device table seen by the hardware */
1835 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1836 amd_iommu_dev_table[devid].data[1] = 0;
1838 amd_iommu_apply_erratum_63(devid);
1841 static void do_attach(struct iommu_dev_data *dev_data,
1842 struct protection_domain *domain)
1844 struct amd_iommu *iommu;
1847 iommu = amd_iommu_rlookup_table[dev_data->devid];
1848 ats = dev_data->ats.enabled;
1850 /* Update data structures */
1851 dev_data->domain = domain;
1852 list_add(&dev_data->list, &domain->dev_list);
1853 set_dte_entry(dev_data->devid, domain, ats);
1855 /* Do reference counting */
1856 domain->dev_iommu[iommu->index] += 1;
1857 domain->dev_cnt += 1;
1859 /* Flush the DTE entry */
1860 device_flush_dte(dev_data);
1863 static void do_detach(struct iommu_dev_data *dev_data)
1865 struct amd_iommu *iommu;
1867 iommu = amd_iommu_rlookup_table[dev_data->devid];
1869 /* decrease reference counters */
1870 dev_data->domain->dev_iommu[iommu->index] -= 1;
1871 dev_data->domain->dev_cnt -= 1;
1873 /* Update data structures */
1874 dev_data->domain = NULL;
1875 list_del(&dev_data->list);
1876 clear_dte_entry(dev_data->devid);
1878 /* Flush the DTE entry */
1879 device_flush_dte(dev_data);
1883 * If a device is not yet associated with a domain, this function does
1884 * assigns it visible for the hardware
1886 static int __attach_device(struct iommu_dev_data *dev_data,
1887 struct protection_domain *domain)
1892 spin_lock(&domain->lock);
1894 if (dev_data->alias_data != NULL) {
1895 struct iommu_dev_data *alias_data = dev_data->alias_data;
1897 /* Some sanity checks */
1899 if (alias_data->domain != NULL &&
1900 alias_data->domain != domain)
1903 if (dev_data->domain != NULL &&
1904 dev_data->domain != domain)
1907 /* Do real assignment */
1908 if (alias_data->domain == NULL)
1909 do_attach(alias_data, domain);
1911 atomic_inc(&alias_data->bind);
1914 if (dev_data->domain == NULL)
1915 do_attach(dev_data, domain);
1917 atomic_inc(&dev_data->bind);
1924 spin_unlock(&domain->lock);
1930 static void pdev_iommuv2_disable(struct pci_dev *pdev)
1932 pci_disable_ats(pdev);
1933 pci_disable_pri(pdev);
1934 pci_disable_pasid(pdev);
1937 static int pdev_iommuv2_enable(struct pci_dev *pdev)
1941 /* Only allow access to user-accessible pages */
1942 ret = pci_enable_pasid(pdev, 0);
1946 /* First reset the PRI state of the device */
1947 ret = pci_reset_pri(pdev);
1951 /* FIXME: Hardcode number of outstanding requests for now */
1952 ret = pci_enable_pri(pdev, 32);
1956 ret = pci_enable_ats(pdev, PAGE_SHIFT);
1963 pci_disable_pri(pdev);
1964 pci_disable_pasid(pdev);
1969 /* FIXME: Move this to PCI code */
1970 #define PCI_PRI_TLP_OFF (1 << 2)
1972 bool pci_pri_tlp_required(struct pci_dev *pdev)
1977 pos = pci_find_ext_capability(pdev, PCI_PRI_CAP);
1981 pci_read_config_word(pdev, pos + PCI_PRI_CONTROL_OFF, &control);
1983 return (control & PCI_PRI_TLP_OFF) ? true : false;
1987 * If a device is not yet associated with a domain, this function does
1988 * assigns it visible for the hardware
1990 static int attach_device(struct device *dev,
1991 struct protection_domain *domain)
1993 struct pci_dev *pdev = to_pci_dev(dev);
1994 struct iommu_dev_data *dev_data;
1995 unsigned long flags;
1998 dev_data = get_dev_data(dev);
2000 if (domain->flags & PD_IOMMUV2_MASK) {
2001 if (!dev_data->iommu_v2 || !dev_data->passthrough)
2004 if (pdev_iommuv2_enable(pdev) != 0)
2007 dev_data->ats.enabled = true;
2008 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2009 dev_data->pri_tlp = pci_pri_tlp_required(pdev);
2010 } else if (amd_iommu_iotlb_sup &&
2011 pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2012 dev_data->ats.enabled = true;
2013 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
2016 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2017 ret = __attach_device(dev_data, domain);
2018 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2021 * We might boot into a crash-kernel here. The crashed kernel
2022 * left the caches in the IOMMU dirty. So we have to flush
2023 * here to evict all dirty stuff.
2025 domain_flush_tlb_pde(domain);
2031 * Removes a device from a protection domain (unlocked)
2033 static void __detach_device(struct iommu_dev_data *dev_data)
2035 struct protection_domain *domain;
2036 unsigned long flags;
2038 BUG_ON(!dev_data->domain);
2040 domain = dev_data->domain;
2042 spin_lock_irqsave(&domain->lock, flags);
2044 if (dev_data->alias_data != NULL) {
2045 struct iommu_dev_data *alias_data = dev_data->alias_data;
2047 if (atomic_dec_and_test(&alias_data->bind))
2048 do_detach(alias_data);
2051 if (atomic_dec_and_test(&dev_data->bind))
2052 do_detach(dev_data);
2054 spin_unlock_irqrestore(&domain->lock, flags);
2057 * If we run in passthrough mode the device must be assigned to the
2058 * passthrough domain if it is detached from any other domain.
2059 * Make sure we can deassign from the pt_domain itself.
2061 if (dev_data->passthrough &&
2062 (dev_data->domain == NULL && domain != pt_domain))
2063 __attach_device(dev_data, pt_domain);
2067 * Removes a device from a protection domain (with devtable_lock held)
2069 static void detach_device(struct device *dev)
2071 struct protection_domain *domain;
2072 struct iommu_dev_data *dev_data;
2073 unsigned long flags;
2075 dev_data = get_dev_data(dev);
2076 domain = dev_data->domain;
2078 /* lock device table */
2079 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2080 __detach_device(dev_data);
2081 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2083 if (domain->flags & PD_IOMMUV2_MASK)
2084 pdev_iommuv2_disable(to_pci_dev(dev));
2085 else if (dev_data->ats.enabled)
2086 pci_disable_ats(to_pci_dev(dev));
2088 dev_data->ats.enabled = false;
2092 * Find out the protection domain structure for a given PCI device. This
2093 * will give us the pointer to the page table root for example.
2095 static struct protection_domain *domain_for_device(struct device *dev)
2097 struct iommu_dev_data *dev_data;
2098 struct protection_domain *dom = NULL;
2099 unsigned long flags;
2101 dev_data = get_dev_data(dev);
2103 if (dev_data->domain)
2104 return dev_data->domain;
2106 if (dev_data->alias_data != NULL) {
2107 struct iommu_dev_data *alias_data = dev_data->alias_data;
2109 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
2110 if (alias_data->domain != NULL) {
2111 __attach_device(dev_data, alias_data->domain);
2112 dom = alias_data->domain;
2114 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2120 static int device_change_notifier(struct notifier_block *nb,
2121 unsigned long action, void *data)
2123 struct dma_ops_domain *dma_domain;
2124 struct protection_domain *domain;
2125 struct iommu_dev_data *dev_data;
2126 struct device *dev = data;
2127 struct amd_iommu *iommu;
2128 unsigned long flags;
2131 if (!check_device(dev))
2134 devid = get_device_id(dev);
2135 iommu = amd_iommu_rlookup_table[devid];
2136 dev_data = get_dev_data(dev);
2139 case BUS_NOTIFY_UNBOUND_DRIVER:
2141 domain = domain_for_device(dev);
2145 if (dev_data->passthrough)
2149 case BUS_NOTIFY_ADD_DEVICE:
2151 iommu_init_device(dev);
2153 domain = domain_for_device(dev);
2155 /* allocate a protection domain if a device is added */
2156 dma_domain = find_protection_domain(devid);
2159 dma_domain = dma_ops_domain_alloc();
2162 dma_domain->target_dev = devid;
2164 spin_lock_irqsave(&iommu_pd_list_lock, flags);
2165 list_add_tail(&dma_domain->list, &iommu_pd_list);
2166 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
2169 case BUS_NOTIFY_DEL_DEVICE:
2171 iommu_uninit_device(dev);
2177 iommu_completion_wait(iommu);
2183 static struct notifier_block device_nb = {
2184 .notifier_call = device_change_notifier,
2187 void amd_iommu_init_notifier(void)
2189 bus_register_notifier(&pci_bus_type, &device_nb);
2192 /*****************************************************************************
2194 * The next functions belong to the dma_ops mapping/unmapping code.
2196 *****************************************************************************/
2199 * In the dma_ops path we only have the struct device. This function
2200 * finds the corresponding IOMMU, the protection domain and the
2201 * requestor id for a given device.
2202 * If the device is not yet associated with a domain this is also done
2205 static struct protection_domain *get_domain(struct device *dev)
2207 struct protection_domain *domain;
2208 struct dma_ops_domain *dma_dom;
2209 u16 devid = get_device_id(dev);
2211 if (!check_device(dev))
2212 return ERR_PTR(-EINVAL);
2214 domain = domain_for_device(dev);
2215 if (domain != NULL && !dma_ops_domain(domain))
2216 return ERR_PTR(-EBUSY);
2221 /* Device not bount yet - bind it */
2222 dma_dom = find_protection_domain(devid);
2224 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
2225 attach_device(dev, &dma_dom->domain);
2226 DUMP_printk("Using protection domain %d for device %s\n",
2227 dma_dom->domain.id, dev_name(dev));
2229 return &dma_dom->domain;
2232 static void update_device_table(struct protection_domain *domain)
2234 struct iommu_dev_data *dev_data;
2236 list_for_each_entry(dev_data, &domain->dev_list, list)
2237 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2240 static void update_domain(struct protection_domain *domain)
2242 if (!domain->updated)
2245 update_device_table(domain);
2247 domain_flush_devices(domain);
2248 domain_flush_tlb_pde(domain);
2250 domain->updated = false;
2254 * This function fetches the PTE for a given address in the aperture
2256 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2257 unsigned long address)
2259 struct aperture_range *aperture;
2260 u64 *pte, *pte_page;
2262 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2266 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2268 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2270 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2272 pte += PM_LEVEL_INDEX(0, address);
2274 update_domain(&dom->domain);
2280 * This is the generic map function. It maps one 4kb page at paddr to
2281 * the given address in the DMA address space for the domain.
2283 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2284 unsigned long address,
2290 WARN_ON(address > dom->aperture_size);
2294 pte = dma_ops_get_pte(dom, address);
2296 return DMA_ERROR_CODE;
2298 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2300 if (direction == DMA_TO_DEVICE)
2301 __pte |= IOMMU_PTE_IR;
2302 else if (direction == DMA_FROM_DEVICE)
2303 __pte |= IOMMU_PTE_IW;
2304 else if (direction == DMA_BIDIRECTIONAL)
2305 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2311 return (dma_addr_t)address;
2315 * The generic unmapping function for on page in the DMA address space.
2317 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2318 unsigned long address)
2320 struct aperture_range *aperture;
2323 if (address >= dom->aperture_size)
2326 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2330 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2334 pte += PM_LEVEL_INDEX(0, address);
2342 * This function contains common code for mapping of a physically
2343 * contiguous memory region into DMA address space. It is used by all
2344 * mapping functions provided with this IOMMU driver.
2345 * Must be called with the domain lock held.
2347 static dma_addr_t __map_single(struct device *dev,
2348 struct dma_ops_domain *dma_dom,
2355 dma_addr_t offset = paddr & ~PAGE_MASK;
2356 dma_addr_t address, start, ret;
2358 unsigned long align_mask = 0;
2361 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2364 INC_STATS_COUNTER(total_map_requests);
2367 INC_STATS_COUNTER(cross_page);
2370 align_mask = (1UL << get_order(size)) - 1;
2373 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2375 if (unlikely(address == DMA_ERROR_CODE)) {
2377 * setting next_address here will let the address
2378 * allocator only scan the new allocated range in the
2379 * first run. This is a small optimization.
2381 dma_dom->next_address = dma_dom->aperture_size;
2383 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2387 * aperture was successfully enlarged by 128 MB, try
2394 for (i = 0; i < pages; ++i) {
2395 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2396 if (ret == DMA_ERROR_CODE)
2404 ADD_STATS_COUNTER(alloced_io_mem, size);
2406 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2407 domain_flush_tlb(&dma_dom->domain);
2408 dma_dom->need_flush = false;
2409 } else if (unlikely(amd_iommu_np_cache))
2410 domain_flush_pages(&dma_dom->domain, address, size);
2417 for (--i; i >= 0; --i) {
2419 dma_ops_domain_unmap(dma_dom, start);
2422 dma_ops_free_addresses(dma_dom, address, pages);
2424 return DMA_ERROR_CODE;
2428 * Does the reverse of the __map_single function. Must be called with
2429 * the domain lock held too
2431 static void __unmap_single(struct dma_ops_domain *dma_dom,
2432 dma_addr_t dma_addr,
2436 dma_addr_t flush_addr;
2437 dma_addr_t i, start;
2440 if ((dma_addr == DMA_ERROR_CODE) ||
2441 (dma_addr + size > dma_dom->aperture_size))
2444 flush_addr = dma_addr;
2445 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2446 dma_addr &= PAGE_MASK;
2449 for (i = 0; i < pages; ++i) {
2450 dma_ops_domain_unmap(dma_dom, start);
2454 SUB_STATS_COUNTER(alloced_io_mem, size);
2456 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2458 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2459 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2460 dma_dom->need_flush = false;
2465 * The exported map_single function for dma_ops.
2467 static dma_addr_t map_page(struct device *dev, struct page *page,
2468 unsigned long offset, size_t size,
2469 enum dma_data_direction dir,
2470 struct dma_attrs *attrs)
2472 unsigned long flags;
2473 struct protection_domain *domain;
2476 phys_addr_t paddr = page_to_phys(page) + offset;
2478 INC_STATS_COUNTER(cnt_map_single);
2480 domain = get_domain(dev);
2481 if (PTR_ERR(domain) == -EINVAL)
2482 return (dma_addr_t)paddr;
2483 else if (IS_ERR(domain))
2484 return DMA_ERROR_CODE;
2486 dma_mask = *dev->dma_mask;
2488 spin_lock_irqsave(&domain->lock, flags);
2490 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2492 if (addr == DMA_ERROR_CODE)
2495 domain_flush_complete(domain);
2498 spin_unlock_irqrestore(&domain->lock, flags);
2504 * The exported unmap_single function for dma_ops.
2506 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2507 enum dma_data_direction dir, struct dma_attrs *attrs)
2509 unsigned long flags;
2510 struct protection_domain *domain;
2512 INC_STATS_COUNTER(cnt_unmap_single);
2514 domain = get_domain(dev);
2518 spin_lock_irqsave(&domain->lock, flags);
2520 __unmap_single(domain->priv, dma_addr, size, dir);
2522 domain_flush_complete(domain);
2524 spin_unlock_irqrestore(&domain->lock, flags);
2528 * This is a special map_sg function which is used if we should map a
2529 * device which is not handled by an AMD IOMMU in the system.
2531 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2532 int nelems, int dir)
2534 struct scatterlist *s;
2537 for_each_sg(sglist, s, nelems, i) {
2538 s->dma_address = (dma_addr_t)sg_phys(s);
2539 s->dma_length = s->length;
2546 * The exported map_sg function for dma_ops (handles scatter-gather
2549 static int map_sg(struct device *dev, struct scatterlist *sglist,
2550 int nelems, enum dma_data_direction dir,
2551 struct dma_attrs *attrs)
2553 unsigned long flags;
2554 struct protection_domain *domain;
2556 struct scatterlist *s;
2558 int mapped_elems = 0;
2561 INC_STATS_COUNTER(cnt_map_sg);
2563 domain = get_domain(dev);
2564 if (PTR_ERR(domain) == -EINVAL)
2565 return map_sg_no_iommu(dev, sglist, nelems, dir);
2566 else if (IS_ERR(domain))
2569 dma_mask = *dev->dma_mask;
2571 spin_lock_irqsave(&domain->lock, flags);
2573 for_each_sg(sglist, s, nelems, i) {
2576 s->dma_address = __map_single(dev, domain->priv,
2577 paddr, s->length, dir, false,
2580 if (s->dma_address) {
2581 s->dma_length = s->length;
2587 domain_flush_complete(domain);
2590 spin_unlock_irqrestore(&domain->lock, flags);
2592 return mapped_elems;
2594 for_each_sg(sglist, s, mapped_elems, i) {
2596 __unmap_single(domain->priv, s->dma_address,
2597 s->dma_length, dir);
2598 s->dma_address = s->dma_length = 0;
2607 * The exported map_sg function for dma_ops (handles scatter-gather
2610 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2611 int nelems, enum dma_data_direction dir,
2612 struct dma_attrs *attrs)
2614 unsigned long flags;
2615 struct protection_domain *domain;
2616 struct scatterlist *s;
2619 INC_STATS_COUNTER(cnt_unmap_sg);
2621 domain = get_domain(dev);
2625 spin_lock_irqsave(&domain->lock, flags);
2627 for_each_sg(sglist, s, nelems, i) {
2628 __unmap_single(domain->priv, s->dma_address,
2629 s->dma_length, dir);
2630 s->dma_address = s->dma_length = 0;
2633 domain_flush_complete(domain);
2635 spin_unlock_irqrestore(&domain->lock, flags);
2639 * The exported alloc_coherent function for dma_ops.
2641 static void *alloc_coherent(struct device *dev, size_t size,
2642 dma_addr_t *dma_addr, gfp_t flag)
2644 unsigned long flags;
2646 struct protection_domain *domain;
2648 u64 dma_mask = dev->coherent_dma_mask;
2650 INC_STATS_COUNTER(cnt_alloc_coherent);
2652 domain = get_domain(dev);
2653 if (PTR_ERR(domain) == -EINVAL) {
2654 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2655 *dma_addr = __pa(virt_addr);
2657 } else if (IS_ERR(domain))
2660 dma_mask = dev->coherent_dma_mask;
2661 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2664 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2668 paddr = virt_to_phys(virt_addr);
2671 dma_mask = *dev->dma_mask;
2673 spin_lock_irqsave(&domain->lock, flags);
2675 *dma_addr = __map_single(dev, domain->priv, paddr,
2676 size, DMA_BIDIRECTIONAL, true, dma_mask);
2678 if (*dma_addr == DMA_ERROR_CODE) {
2679 spin_unlock_irqrestore(&domain->lock, flags);
2683 domain_flush_complete(domain);
2685 spin_unlock_irqrestore(&domain->lock, flags);
2691 free_pages((unsigned long)virt_addr, get_order(size));
2697 * The exported free_coherent function for dma_ops.
2699 static void free_coherent(struct device *dev, size_t size,
2700 void *virt_addr, dma_addr_t dma_addr)
2702 unsigned long flags;
2703 struct protection_domain *domain;
2705 INC_STATS_COUNTER(cnt_free_coherent);
2707 domain = get_domain(dev);
2711 spin_lock_irqsave(&domain->lock, flags);
2713 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2715 domain_flush_complete(domain);
2717 spin_unlock_irqrestore(&domain->lock, flags);
2720 free_pages((unsigned long)virt_addr, get_order(size));
2724 * This function is called by the DMA layer to find out if we can handle a
2725 * particular device. It is part of the dma_ops.
2727 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2729 return check_device(dev);
2733 * The function for pre-allocating protection domains.
2735 * If the driver core informs the DMA layer if a driver grabs a device
2736 * we don't need to preallocate the protection domains anymore.
2737 * For now we have to.
2739 static void prealloc_protection_domains(void)
2741 struct iommu_dev_data *dev_data;
2742 struct dma_ops_domain *dma_dom;
2743 struct pci_dev *dev = NULL;
2746 for_each_pci_dev(dev) {
2748 /* Do we handle this device? */
2749 if (!check_device(&dev->dev))
2752 dev_data = get_dev_data(&dev->dev);
2753 if (!amd_iommu_force_isolation && dev_data->iommu_v2) {
2754 /* Make sure passthrough domain is allocated */
2755 alloc_passthrough_domain();
2756 dev_data->passthrough = true;
2757 attach_device(&dev->dev, pt_domain);
2758 pr_info("AMD-Vi: Using passthough domain for device %s\n",
2759 dev_name(&dev->dev));
2762 /* Is there already any domain for it? */
2763 if (domain_for_device(&dev->dev))
2766 devid = get_device_id(&dev->dev);
2768 dma_dom = dma_ops_domain_alloc();
2771 init_unity_mappings_for_device(dma_dom, devid);
2772 dma_dom->target_dev = devid;
2774 attach_device(&dev->dev, &dma_dom->domain);
2776 list_add_tail(&dma_dom->list, &iommu_pd_list);
2780 static struct dma_map_ops amd_iommu_dma_ops = {
2781 .alloc_coherent = alloc_coherent,
2782 .free_coherent = free_coherent,
2783 .map_page = map_page,
2784 .unmap_page = unmap_page,
2786 .unmap_sg = unmap_sg,
2787 .dma_supported = amd_iommu_dma_supported,
2790 static unsigned device_dma_ops_init(void)
2792 struct iommu_dev_data *dev_data;
2793 struct pci_dev *pdev = NULL;
2794 unsigned unhandled = 0;
2796 for_each_pci_dev(pdev) {
2797 if (!check_device(&pdev->dev)) {
2802 dev_data = get_dev_data(&pdev->dev);
2804 if (!dev_data->passthrough)
2805 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
2807 pdev->dev.archdata.dma_ops = &nommu_dma_ops;
2814 * The function which clues the AMD IOMMU driver into dma_ops.
2817 void __init amd_iommu_init_api(void)
2819 bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2822 int __init amd_iommu_init_dma_ops(void)
2824 struct amd_iommu *iommu;
2828 * first allocate a default protection domain for every IOMMU we
2829 * found in the system. Devices not assigned to any other
2830 * protection domain will be assigned to the default one.
2832 for_each_iommu(iommu) {
2833 iommu->default_dom = dma_ops_domain_alloc();
2834 if (iommu->default_dom == NULL)
2836 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
2837 ret = iommu_init_unity_mappings(iommu);
2843 * Pre-allocate the protection domains for each device.
2845 prealloc_protection_domains();
2850 /* Make the driver finally visible to the drivers */
2851 unhandled = device_dma_ops_init();
2852 if (unhandled && max_pfn > MAX_DMA32_PFN) {
2853 /* There are unhandled devices - initialize swiotlb for them */
2857 amd_iommu_stats_init();
2863 for_each_iommu(iommu) {
2864 if (iommu->default_dom)
2865 dma_ops_domain_free(iommu->default_dom);
2871 /*****************************************************************************
2873 * The following functions belong to the exported interface of AMD IOMMU
2875 * This interface allows access to lower level functions of the IOMMU
2876 * like protection domain handling and assignement of devices to domains
2877 * which is not possible with the dma_ops interface.
2879 *****************************************************************************/
2881 static void cleanup_domain(struct protection_domain *domain)
2883 struct iommu_dev_data *dev_data, *next;
2884 unsigned long flags;
2886 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2888 list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
2889 __detach_device(dev_data);
2890 atomic_set(&dev_data->bind, 0);
2893 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2896 static void protection_domain_free(struct protection_domain *domain)
2901 del_domain_from_list(domain);
2904 domain_id_free(domain->id);
2909 static struct protection_domain *protection_domain_alloc(void)
2911 struct protection_domain *domain;
2913 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2917 spin_lock_init(&domain->lock);
2918 mutex_init(&domain->api_lock);
2919 domain->id = domain_id_alloc();
2922 INIT_LIST_HEAD(&domain->dev_list);
2924 add_domain_to_list(domain);
2934 static int __init alloc_passthrough_domain(void)
2936 if (pt_domain != NULL)
2939 /* allocate passthrough domain */
2940 pt_domain = protection_domain_alloc();
2944 pt_domain->mode = PAGE_MODE_NONE;
2948 static int amd_iommu_domain_init(struct iommu_domain *dom)
2950 struct protection_domain *domain;
2952 domain = protection_domain_alloc();
2956 domain->mode = PAGE_MODE_3_LEVEL;
2957 domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2958 if (!domain->pt_root)
2961 domain->iommu_domain = dom;
2968 protection_domain_free(domain);
2973 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
2975 struct protection_domain *domain = dom->priv;
2980 if (domain->dev_cnt > 0)
2981 cleanup_domain(domain);
2983 BUG_ON(domain->dev_cnt != 0);
2985 if (domain->mode != PAGE_MODE_NONE)
2986 free_pagetable(domain);
2988 if (domain->flags & PD_IOMMUV2_MASK)
2989 free_gcr3_table(domain);
2991 protection_domain_free(domain);
2996 static void amd_iommu_detach_device(struct iommu_domain *dom,
2999 struct iommu_dev_data *dev_data = dev->archdata.iommu;
3000 struct amd_iommu *iommu;
3003 if (!check_device(dev))
3006 devid = get_device_id(dev);
3008 if (dev_data->domain != NULL)
3011 iommu = amd_iommu_rlookup_table[devid];
3015 iommu_completion_wait(iommu);
3018 static int amd_iommu_attach_device(struct iommu_domain *dom,
3021 struct protection_domain *domain = dom->priv;
3022 struct iommu_dev_data *dev_data;
3023 struct amd_iommu *iommu;
3026 if (!check_device(dev))
3029 dev_data = dev->archdata.iommu;
3031 iommu = amd_iommu_rlookup_table[dev_data->devid];
3035 if (dev_data->domain)
3038 ret = attach_device(dev, domain);
3040 iommu_completion_wait(iommu);
3045 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3046 phys_addr_t paddr, int gfp_order, int iommu_prot)
3048 unsigned long page_size = 0x1000UL << gfp_order;
3049 struct protection_domain *domain = dom->priv;
3053 if (domain->mode == PAGE_MODE_NONE)
3056 if (iommu_prot & IOMMU_READ)
3057 prot |= IOMMU_PROT_IR;
3058 if (iommu_prot & IOMMU_WRITE)
3059 prot |= IOMMU_PROT_IW;
3061 mutex_lock(&domain->api_lock);
3062 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3063 mutex_unlock(&domain->api_lock);
3068 static int amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3071 struct protection_domain *domain = dom->priv;
3072 unsigned long page_size, unmap_size;
3074 if (domain->mode == PAGE_MODE_NONE)
3077 page_size = 0x1000UL << gfp_order;
3079 mutex_lock(&domain->api_lock);
3080 unmap_size = iommu_unmap_page(domain, iova, page_size);
3081 mutex_unlock(&domain->api_lock);
3083 domain_flush_tlb_pde(domain);
3085 return get_order(unmap_size);
3088 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3091 struct protection_domain *domain = dom->priv;
3092 unsigned long offset_mask;
3096 if (domain->mode == PAGE_MODE_NONE)
3099 pte = fetch_pte(domain, iova);
3101 if (!pte || !IOMMU_PTE_PRESENT(*pte))
3104 if (PM_PTE_LEVEL(*pte) == 0)
3105 offset_mask = PAGE_SIZE - 1;
3107 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
3109 __pte = *pte & PM_ADDR_MASK;
3110 paddr = (__pte & ~offset_mask) | (iova & offset_mask);
3115 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
3119 case IOMMU_CAP_CACHE_COHERENCY:
3126 static struct iommu_ops amd_iommu_ops = {
3127 .domain_init = amd_iommu_domain_init,
3128 .domain_destroy = amd_iommu_domain_destroy,
3129 .attach_dev = amd_iommu_attach_device,
3130 .detach_dev = amd_iommu_detach_device,
3131 .map = amd_iommu_map,
3132 .unmap = amd_iommu_unmap,
3133 .iova_to_phys = amd_iommu_iova_to_phys,
3134 .domain_has_cap = amd_iommu_domain_has_cap,
3137 /*****************************************************************************
3139 * The next functions do a basic initialization of IOMMU for pass through
3142 * In passthrough mode the IOMMU is initialized and enabled but not used for
3143 * DMA-API translation.
3145 *****************************************************************************/
3147 int __init amd_iommu_init_passthrough(void)
3149 struct iommu_dev_data *dev_data;
3150 struct pci_dev *dev = NULL;
3151 struct amd_iommu *iommu;
3155 ret = alloc_passthrough_domain();
3159 for_each_pci_dev(dev) {
3160 if (!check_device(&dev->dev))
3163 dev_data = get_dev_data(&dev->dev);
3164 dev_data->passthrough = true;
3166 devid = get_device_id(&dev->dev);
3168 iommu = amd_iommu_rlookup_table[devid];
3172 attach_device(&dev->dev, pt_domain);
3175 pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
3180 /* IOMMUv2 specific functions */
3181 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3183 return atomic_notifier_chain_register(&ppr_notifier, nb);
3185 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3187 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3189 return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3191 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3193 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3195 struct protection_domain *domain = dom->priv;
3196 unsigned long flags;
3198 spin_lock_irqsave(&domain->lock, flags);
3200 /* Update data structure */
3201 domain->mode = PAGE_MODE_NONE;
3202 domain->updated = true;
3204 /* Make changes visible to IOMMUs */
3205 update_domain(domain);
3207 /* Page-table is not visible to IOMMU anymore, so free it */
3208 free_pagetable(domain);
3210 spin_unlock_irqrestore(&domain->lock, flags);
3212 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3214 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3216 struct protection_domain *domain = dom->priv;
3217 unsigned long flags;
3220 if (pasids <= 0 || pasids > (PASID_MASK + 1))
3223 /* Number of GCR3 table levels required */
3224 for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3227 if (levels > amd_iommu_max_glx_val)
3230 spin_lock_irqsave(&domain->lock, flags);
3233 * Save us all sanity checks whether devices already in the
3234 * domain support IOMMUv2. Just force that the domain has no
3235 * devices attached when it is switched into IOMMUv2 mode.
3238 if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3242 domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3243 if (domain->gcr3_tbl == NULL)
3246 domain->glx = levels;
3247 domain->flags |= PD_IOMMUV2_MASK;
3248 domain->updated = true;
3250 update_domain(domain);
3255 spin_unlock_irqrestore(&domain->lock, flags);
3259 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3261 static int __flush_pasid(struct protection_domain *domain, int pasid,
3262 u64 address, bool size)
3264 struct iommu_dev_data *dev_data;
3265 struct iommu_cmd cmd;
3268 if (!(domain->flags & PD_IOMMUV2_MASK))
3271 build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3274 * IOMMU TLB needs to be flushed before Device TLB to
3275 * prevent device TLB refill from IOMMU TLB
3277 for (i = 0; i < amd_iommus_present; ++i) {
3278 if (domain->dev_iommu[i] == 0)
3281 ret = iommu_queue_command(amd_iommus[i], &cmd);
3286 /* Wait until IOMMU TLB flushes are complete */
3287 domain_flush_complete(domain);
3289 /* Now flush device TLBs */
3290 list_for_each_entry(dev_data, &domain->dev_list, list) {
3291 struct amd_iommu *iommu;
3294 BUG_ON(!dev_data->ats.enabled);
3296 qdep = dev_data->ats.qdep;
3297 iommu = amd_iommu_rlookup_table[dev_data->devid];
3299 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3300 qdep, address, size);
3302 ret = iommu_queue_command(iommu, &cmd);
3307 /* Wait until all device TLBs are flushed */
3308 domain_flush_complete(domain);
3317 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3320 return __flush_pasid(domain, pasid, address, false);
3323 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3326 struct protection_domain *domain = dom->priv;
3327 unsigned long flags;
3330 spin_lock_irqsave(&domain->lock, flags);
3331 ret = __amd_iommu_flush_page(domain, pasid, address);
3332 spin_unlock_irqrestore(&domain->lock, flags);
3336 EXPORT_SYMBOL(amd_iommu_flush_page);
3338 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3340 return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3344 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3346 struct protection_domain *domain = dom->priv;
3347 unsigned long flags;
3350 spin_lock_irqsave(&domain->lock, flags);
3351 ret = __amd_iommu_flush_tlb(domain, pasid);
3352 spin_unlock_irqrestore(&domain->lock, flags);
3356 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3358 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3365 index = (pasid >> (9 * level)) & 0x1ff;
3371 if (!(*pte & GCR3_VALID)) {
3375 root = (void *)get_zeroed_page(GFP_ATOMIC);
3379 *pte = __pa(root) | GCR3_VALID;
3382 root = __va(*pte & PAGE_MASK);
3390 static int __set_gcr3(struct protection_domain *domain, int pasid,
3395 if (domain->mode != PAGE_MODE_NONE)
3398 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3402 *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3404 return __amd_iommu_flush_tlb(domain, pasid);
3407 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3411 if (domain->mode != PAGE_MODE_NONE)
3414 pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3420 return __amd_iommu_flush_tlb(domain, pasid);
3423 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3426 struct protection_domain *domain = dom->priv;
3427 unsigned long flags;
3430 spin_lock_irqsave(&domain->lock, flags);
3431 ret = __set_gcr3(domain, pasid, cr3);
3432 spin_unlock_irqrestore(&domain->lock, flags);
3436 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3438 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3440 struct protection_domain *domain = dom->priv;
3441 unsigned long flags;
3444 spin_lock_irqsave(&domain->lock, flags);
3445 ret = __clear_gcr3(domain, pasid);
3446 spin_unlock_irqrestore(&domain->lock, flags);
3450 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3452 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3453 int status, int tag)
3455 struct iommu_dev_data *dev_data;
3456 struct amd_iommu *iommu;
3457 struct iommu_cmd cmd;
3459 dev_data = get_dev_data(&pdev->dev);
3460 iommu = amd_iommu_rlookup_table[dev_data->devid];
3462 build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3463 tag, dev_data->pri_tlp);
3465 return iommu_queue_command(iommu, &cmd);
3467 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3469 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3471 struct protection_domain *domain;
3473 domain = get_domain(&pdev->dev);
3477 /* Only return IOMMUv2 domains */
3478 if (!(domain->flags & PD_IOMMUV2_MASK))
3481 return domain->iommu_domain;
3483 EXPORT_SYMBOL(amd_iommu_get_v2_domain);