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/pci.h>
21 #include <linux/pci-ats.h>
22 #include <linux/bitmap.h>
23 #include <linux/slab.h>
24 #include <linux/debugfs.h>
25 #include <linux/scatterlist.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/iommu-helper.h>
28 #include <linux/iommu.h>
29 #include <linux/delay.h>
30 #include <linux/amd-iommu.h>
31 #include <asm/msidef.h>
32 #include <asm/proto.h>
33 #include <asm/iommu.h>
37 #include "amd_iommu_proto.h"
38 #include "amd_iommu_types.h"
40 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
42 #define LOOP_TIMEOUT 100000
44 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
46 /* A list of preallocated protection domains */
47 static LIST_HEAD(iommu_pd_list);
48 static DEFINE_SPINLOCK(iommu_pd_list_lock);
50 /* List of all available dev_data structures */
51 static LIST_HEAD(dev_data_list);
52 static DEFINE_SPINLOCK(dev_data_list_lock);
55 * Domain for untranslated devices - only allocated
56 * if iommu=pt passed on kernel cmd line.
58 static struct protection_domain *pt_domain;
60 static struct iommu_ops amd_iommu_ops;
63 * general struct to manage commands send to an IOMMU
69 static void update_domain(struct protection_domain *domain);
71 /****************************************************************************
75 ****************************************************************************/
77 static struct iommu_dev_data *alloc_dev_data(u16 devid)
79 struct iommu_dev_data *dev_data;
82 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
86 dev_data->devid = devid;
87 atomic_set(&dev_data->bind, 0);
89 spin_lock_irqsave(&dev_data_list_lock, flags);
90 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
91 spin_unlock_irqrestore(&dev_data_list_lock, flags);
96 static void free_dev_data(struct iommu_dev_data *dev_data)
100 spin_lock_irqsave(&dev_data_list_lock, flags);
101 list_del(&dev_data->dev_data_list);
102 spin_unlock_irqrestore(&dev_data_list_lock, flags);
107 static struct iommu_dev_data *search_dev_data(u16 devid)
109 struct iommu_dev_data *dev_data;
112 spin_lock_irqsave(&dev_data_list_lock, flags);
113 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
114 if (dev_data->devid == devid)
121 spin_unlock_irqrestore(&dev_data_list_lock, flags);
126 static struct iommu_dev_data *find_dev_data(u16 devid)
128 struct iommu_dev_data *dev_data;
130 dev_data = search_dev_data(devid);
132 if (dev_data == NULL)
133 dev_data = alloc_dev_data(devid);
138 static inline u16 get_device_id(struct device *dev)
140 struct pci_dev *pdev = to_pci_dev(dev);
142 return calc_devid(pdev->bus->number, pdev->devfn);
145 static struct iommu_dev_data *get_dev_data(struct device *dev)
147 return dev->archdata.iommu;
151 * In this function the list of preallocated protection domains is traversed to
152 * find the domain for a specific device
154 static struct dma_ops_domain *find_protection_domain(u16 devid)
156 struct dma_ops_domain *entry, *ret = NULL;
158 u16 alias = amd_iommu_alias_table[devid];
160 if (list_empty(&iommu_pd_list))
163 spin_lock_irqsave(&iommu_pd_list_lock, flags);
165 list_for_each_entry(entry, &iommu_pd_list, list) {
166 if (entry->target_dev == devid ||
167 entry->target_dev == alias) {
173 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
179 * This function checks if the driver got a valid device from the caller to
180 * avoid dereferencing invalid pointers.
182 static bool check_device(struct device *dev)
186 if (!dev || !dev->dma_mask)
189 /* No device or no PCI device */
190 if (dev->bus != &pci_bus_type)
193 devid = get_device_id(dev);
195 /* Out of our scope? */
196 if (devid > amd_iommu_last_bdf)
199 if (amd_iommu_rlookup_table[devid] == NULL)
205 static int iommu_init_device(struct device *dev)
207 struct iommu_dev_data *dev_data;
210 if (dev->archdata.iommu)
213 dev_data = find_dev_data(get_device_id(dev));
217 alias = amd_iommu_alias_table[dev_data->devid];
218 if (alias != dev_data->devid) {
219 struct iommu_dev_data *alias_data;
221 alias_data = find_dev_data(alias);
222 if (alias_data == NULL) {
223 pr_err("AMD-Vi: Warning: Unhandled device %s\n",
225 free_dev_data(dev_data);
228 dev_data->alias_data = alias_data;
231 dev->archdata.iommu = dev_data;
236 static void iommu_ignore_device(struct device *dev)
240 devid = get_device_id(dev);
241 alias = amd_iommu_alias_table[devid];
243 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
244 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
246 amd_iommu_rlookup_table[devid] = NULL;
247 amd_iommu_rlookup_table[alias] = NULL;
250 static void iommu_uninit_device(struct device *dev)
253 * Nothing to do here - we keep dev_data around for unplugged devices
254 * and reuse it when the device is re-plugged - not doing so would
255 * introduce a ton of races.
259 void __init amd_iommu_uninit_devices(void)
261 struct iommu_dev_data *dev_data, *n;
262 struct pci_dev *pdev = NULL;
264 for_each_pci_dev(pdev) {
266 if (!check_device(&pdev->dev))
269 iommu_uninit_device(&pdev->dev);
272 /* Free all of our dev_data structures */
273 list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
274 free_dev_data(dev_data);
277 int __init amd_iommu_init_devices(void)
279 struct pci_dev *pdev = NULL;
282 for_each_pci_dev(pdev) {
284 if (!check_device(&pdev->dev))
287 ret = iommu_init_device(&pdev->dev);
288 if (ret == -ENOTSUPP)
289 iommu_ignore_device(&pdev->dev);
298 amd_iommu_uninit_devices();
302 #ifdef CONFIG_AMD_IOMMU_STATS
305 * Initialization code for statistics collection
308 DECLARE_STATS_COUNTER(compl_wait);
309 DECLARE_STATS_COUNTER(cnt_map_single);
310 DECLARE_STATS_COUNTER(cnt_unmap_single);
311 DECLARE_STATS_COUNTER(cnt_map_sg);
312 DECLARE_STATS_COUNTER(cnt_unmap_sg);
313 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
314 DECLARE_STATS_COUNTER(cnt_free_coherent);
315 DECLARE_STATS_COUNTER(cross_page);
316 DECLARE_STATS_COUNTER(domain_flush_single);
317 DECLARE_STATS_COUNTER(domain_flush_all);
318 DECLARE_STATS_COUNTER(alloced_io_mem);
319 DECLARE_STATS_COUNTER(total_map_requests);
321 static struct dentry *stats_dir;
322 static struct dentry *de_fflush;
324 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
326 if (stats_dir == NULL)
329 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
333 static void amd_iommu_stats_init(void)
335 stats_dir = debugfs_create_dir("amd-iommu", NULL);
336 if (stats_dir == NULL)
339 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
340 (u32 *)&amd_iommu_unmap_flush);
342 amd_iommu_stats_add(&compl_wait);
343 amd_iommu_stats_add(&cnt_map_single);
344 amd_iommu_stats_add(&cnt_unmap_single);
345 amd_iommu_stats_add(&cnt_map_sg);
346 amd_iommu_stats_add(&cnt_unmap_sg);
347 amd_iommu_stats_add(&cnt_alloc_coherent);
348 amd_iommu_stats_add(&cnt_free_coherent);
349 amd_iommu_stats_add(&cross_page);
350 amd_iommu_stats_add(&domain_flush_single);
351 amd_iommu_stats_add(&domain_flush_all);
352 amd_iommu_stats_add(&alloced_io_mem);
353 amd_iommu_stats_add(&total_map_requests);
358 /****************************************************************************
360 * Interrupt handling functions
362 ****************************************************************************/
364 static void dump_dte_entry(u16 devid)
368 for (i = 0; i < 8; ++i)
369 pr_err("AMD-Vi: DTE[%d]: %08x\n", i,
370 amd_iommu_dev_table[devid].data[i]);
373 static void dump_command(unsigned long phys_addr)
375 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
378 for (i = 0; i < 4; ++i)
379 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
382 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
384 int type, devid, domid, flags;
385 volatile u32 *event = __evt;
390 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
391 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
392 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
393 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
394 address = (u64)(((u64)event[3]) << 32) | event[2];
397 /* Did we hit the erratum? */
398 if (++count == LOOP_TIMEOUT) {
399 pr_err("AMD-Vi: No event written to event log\n");
406 printk(KERN_ERR "AMD-Vi: Event logged [");
409 case EVENT_TYPE_ILL_DEV:
410 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
411 "address=0x%016llx flags=0x%04x]\n",
412 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
414 dump_dte_entry(devid);
416 case EVENT_TYPE_IO_FAULT:
417 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
418 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
419 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
420 domid, address, flags);
422 case EVENT_TYPE_DEV_TAB_ERR:
423 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
424 "address=0x%016llx flags=0x%04x]\n",
425 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
428 case EVENT_TYPE_PAGE_TAB_ERR:
429 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
430 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
431 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
432 domid, address, flags);
434 case EVENT_TYPE_ILL_CMD:
435 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
436 dump_command(address);
438 case EVENT_TYPE_CMD_HARD_ERR:
439 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
440 "flags=0x%04x]\n", address, flags);
442 case EVENT_TYPE_IOTLB_INV_TO:
443 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
444 "address=0x%016llx]\n",
445 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
448 case EVENT_TYPE_INV_DEV_REQ:
449 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
450 "address=0x%016llx flags=0x%04x]\n",
451 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
455 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
458 memset(__evt, 0, 4 * sizeof(u32));
461 static void iommu_poll_events(struct amd_iommu *iommu)
466 spin_lock_irqsave(&iommu->lock, flags);
468 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
469 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
471 while (head != tail) {
472 iommu_print_event(iommu, iommu->evt_buf + head);
473 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
476 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
478 spin_unlock_irqrestore(&iommu->lock, flags);
481 irqreturn_t amd_iommu_int_thread(int irq, void *data)
483 struct amd_iommu *iommu;
485 for_each_iommu(iommu)
486 iommu_poll_events(iommu);
491 irqreturn_t amd_iommu_int_handler(int irq, void *data)
493 return IRQ_WAKE_THREAD;
496 /****************************************************************************
498 * IOMMU command queuing functions
500 ****************************************************************************/
502 static int wait_on_sem(volatile u64 *sem)
506 while (*sem == 0 && i < LOOP_TIMEOUT) {
511 if (i == LOOP_TIMEOUT) {
512 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
519 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
520 struct iommu_cmd *cmd,
525 target = iommu->cmd_buf + tail;
526 tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
528 /* Copy command to buffer */
529 memcpy(target, cmd, sizeof(*cmd));
531 /* Tell the IOMMU about it */
532 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
535 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
537 WARN_ON(address & 0x7ULL);
539 memset(cmd, 0, sizeof(*cmd));
540 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
541 cmd->data[1] = upper_32_bits(__pa(address));
543 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
546 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
548 memset(cmd, 0, sizeof(*cmd));
549 cmd->data[0] = devid;
550 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
553 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
554 size_t size, u16 domid, int pde)
559 pages = iommu_num_pages(address, size, PAGE_SIZE);
564 * If we have to flush more than one page, flush all
565 * TLB entries for this domain
567 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
571 address &= PAGE_MASK;
573 memset(cmd, 0, sizeof(*cmd));
574 cmd->data[1] |= domid;
575 cmd->data[2] = lower_32_bits(address);
576 cmd->data[3] = upper_32_bits(address);
577 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
578 if (s) /* size bit - we flush more than one 4kb page */
579 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
580 if (pde) /* PDE bit - we wan't flush everything not only the PTEs */
581 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
584 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
585 u64 address, size_t size)
590 pages = iommu_num_pages(address, size, PAGE_SIZE);
595 * If we have to flush more than one page, flush all
596 * TLB entries for this domain
598 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
602 address &= PAGE_MASK;
604 memset(cmd, 0, sizeof(*cmd));
605 cmd->data[0] = devid;
606 cmd->data[0] |= (qdep & 0xff) << 24;
607 cmd->data[1] = devid;
608 cmd->data[2] = lower_32_bits(address);
609 cmd->data[3] = upper_32_bits(address);
610 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
612 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
615 static void build_inv_all(struct iommu_cmd *cmd)
617 memset(cmd, 0, sizeof(*cmd));
618 CMD_SET_TYPE(cmd, CMD_INV_ALL);
622 * Writes the command to the IOMMUs command buffer and informs the
623 * hardware about the new command.
625 static int iommu_queue_command_sync(struct amd_iommu *iommu,
626 struct iommu_cmd *cmd,
629 u32 left, tail, head, next_tail;
632 WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
635 spin_lock_irqsave(&iommu->lock, flags);
637 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
638 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
639 next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
640 left = (head - next_tail) % iommu->cmd_buf_size;
643 struct iommu_cmd sync_cmd;
644 volatile u64 sem = 0;
647 build_completion_wait(&sync_cmd, (u64)&sem);
648 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
650 spin_unlock_irqrestore(&iommu->lock, flags);
652 if ((ret = wait_on_sem(&sem)) != 0)
658 copy_cmd_to_buffer(iommu, cmd, tail);
660 /* We need to sync now to make sure all commands are processed */
661 iommu->need_sync = sync;
663 spin_unlock_irqrestore(&iommu->lock, flags);
668 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
670 return iommu_queue_command_sync(iommu, cmd, true);
674 * This function queues a completion wait command into the command
677 static int iommu_completion_wait(struct amd_iommu *iommu)
679 struct iommu_cmd cmd;
680 volatile u64 sem = 0;
683 if (!iommu->need_sync)
686 build_completion_wait(&cmd, (u64)&sem);
688 ret = iommu_queue_command_sync(iommu, &cmd, false);
692 return wait_on_sem(&sem);
695 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
697 struct iommu_cmd cmd;
699 build_inv_dte(&cmd, devid);
701 return iommu_queue_command(iommu, &cmd);
704 static void iommu_flush_dte_all(struct amd_iommu *iommu)
708 for (devid = 0; devid <= 0xffff; ++devid)
709 iommu_flush_dte(iommu, devid);
711 iommu_completion_wait(iommu);
715 * This function uses heavy locking and may disable irqs for some time. But
716 * this is no issue because it is only called during resume.
718 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
722 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
723 struct iommu_cmd cmd;
724 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
726 iommu_queue_command(iommu, &cmd);
729 iommu_completion_wait(iommu);
732 static void iommu_flush_all(struct amd_iommu *iommu)
734 struct iommu_cmd cmd;
738 iommu_queue_command(iommu, &cmd);
739 iommu_completion_wait(iommu);
742 void iommu_flush_all_caches(struct amd_iommu *iommu)
744 if (iommu_feature(iommu, FEATURE_IA)) {
745 iommu_flush_all(iommu);
747 iommu_flush_dte_all(iommu);
748 iommu_flush_tlb_all(iommu);
753 * Command send function for flushing on-device TLB
755 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
756 u64 address, size_t size)
758 struct amd_iommu *iommu;
759 struct iommu_cmd cmd;
762 qdep = dev_data->ats.qdep;
763 iommu = amd_iommu_rlookup_table[dev_data->devid];
765 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
767 return iommu_queue_command(iommu, &cmd);
771 * Command send function for invalidating a device table entry
773 static int device_flush_dte(struct iommu_dev_data *dev_data)
775 struct amd_iommu *iommu;
778 iommu = amd_iommu_rlookup_table[dev_data->devid];
780 ret = iommu_flush_dte(iommu, dev_data->devid);
784 if (dev_data->ats.enabled)
785 ret = device_flush_iotlb(dev_data, 0, ~0UL);
791 * TLB invalidation function which is called from the mapping functions.
792 * It invalidates a single PTE if the range to flush is within a single
793 * page. Otherwise it flushes the whole TLB of the IOMMU.
795 static void __domain_flush_pages(struct protection_domain *domain,
796 u64 address, size_t size, int pde)
798 struct iommu_dev_data *dev_data;
799 struct iommu_cmd cmd;
802 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
804 for (i = 0; i < amd_iommus_present; ++i) {
805 if (!domain->dev_iommu[i])
809 * Devices of this domain are behind this IOMMU
810 * We need a TLB flush
812 ret |= iommu_queue_command(amd_iommus[i], &cmd);
815 list_for_each_entry(dev_data, &domain->dev_list, list) {
817 if (!dev_data->ats.enabled)
820 ret |= device_flush_iotlb(dev_data, address, size);
826 static void domain_flush_pages(struct protection_domain *domain,
827 u64 address, size_t size)
829 __domain_flush_pages(domain, address, size, 0);
832 /* Flush the whole IO/TLB for a given protection domain */
833 static void domain_flush_tlb(struct protection_domain *domain)
835 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
838 /* Flush the whole IO/TLB for a given protection domain - including PDE */
839 static void domain_flush_tlb_pde(struct protection_domain *domain)
841 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
844 static void domain_flush_complete(struct protection_domain *domain)
848 for (i = 0; i < amd_iommus_present; ++i) {
849 if (!domain->dev_iommu[i])
853 * Devices of this domain are behind this IOMMU
854 * We need to wait for completion of all commands.
856 iommu_completion_wait(amd_iommus[i]);
862 * This function flushes the DTEs for all devices in domain
864 static void domain_flush_devices(struct protection_domain *domain)
866 struct iommu_dev_data *dev_data;
868 list_for_each_entry(dev_data, &domain->dev_list, list)
869 device_flush_dte(dev_data);
872 /****************************************************************************
874 * The functions below are used the create the page table mappings for
875 * unity mapped regions.
877 ****************************************************************************/
880 * This function is used to add another level to an IO page table. Adding
881 * another level increases the size of the address space by 9 bits to a size up
884 static bool increase_address_space(struct protection_domain *domain,
889 if (domain->mode == PAGE_MODE_6_LEVEL)
890 /* address space already 64 bit large */
893 pte = (void *)get_zeroed_page(gfp);
897 *pte = PM_LEVEL_PDE(domain->mode,
898 virt_to_phys(domain->pt_root));
899 domain->pt_root = pte;
901 domain->updated = true;
906 static u64 *alloc_pte(struct protection_domain *domain,
907 unsigned long address,
908 unsigned long page_size,
915 BUG_ON(!is_power_of_2(page_size));
917 while (address > PM_LEVEL_SIZE(domain->mode))
918 increase_address_space(domain, gfp);
920 level = domain->mode - 1;
921 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
922 address = PAGE_SIZE_ALIGN(address, page_size);
923 end_lvl = PAGE_SIZE_LEVEL(page_size);
925 while (level > end_lvl) {
926 if (!IOMMU_PTE_PRESENT(*pte)) {
927 page = (u64 *)get_zeroed_page(gfp);
930 *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
933 /* No level skipping support yet */
934 if (PM_PTE_LEVEL(*pte) != level)
939 pte = IOMMU_PTE_PAGE(*pte);
941 if (pte_page && level == end_lvl)
944 pte = &pte[PM_LEVEL_INDEX(level, address)];
951 * This function checks if there is a PTE for a given dma address. If
952 * there is one, it returns the pointer to it.
954 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
959 if (address > PM_LEVEL_SIZE(domain->mode))
962 level = domain->mode - 1;
963 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
968 if (!IOMMU_PTE_PRESENT(*pte))
972 if (PM_PTE_LEVEL(*pte) == 0x07) {
973 unsigned long pte_mask, __pte;
976 * If we have a series of large PTEs, make
977 * sure to return a pointer to the first one.
979 pte_mask = PTE_PAGE_SIZE(*pte);
980 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
981 __pte = ((unsigned long)pte) & pte_mask;
986 /* No level skipping support yet */
987 if (PM_PTE_LEVEL(*pte) != level)
992 /* Walk to the next level */
993 pte = IOMMU_PTE_PAGE(*pte);
994 pte = &pte[PM_LEVEL_INDEX(level, address)];
1001 * Generic mapping functions. It maps a physical address into a DMA
1002 * address space. It allocates the page table pages if necessary.
1003 * In the future it can be extended to a generic mapping function
1004 * supporting all features of AMD IOMMU page tables like level skipping
1005 * and full 64 bit address spaces.
1007 static int iommu_map_page(struct protection_domain *dom,
1008 unsigned long bus_addr,
1009 unsigned long phys_addr,
1011 unsigned long page_size)
1016 if (!(prot & IOMMU_PROT_MASK))
1019 bus_addr = PAGE_ALIGN(bus_addr);
1020 phys_addr = PAGE_ALIGN(phys_addr);
1021 count = PAGE_SIZE_PTE_COUNT(page_size);
1022 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1024 for (i = 0; i < count; ++i)
1025 if (IOMMU_PTE_PRESENT(pte[i]))
1028 if (page_size > PAGE_SIZE) {
1029 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1030 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1032 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1034 if (prot & IOMMU_PROT_IR)
1035 __pte |= IOMMU_PTE_IR;
1036 if (prot & IOMMU_PROT_IW)
1037 __pte |= IOMMU_PTE_IW;
1039 for (i = 0; i < count; ++i)
1047 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1048 unsigned long bus_addr,
1049 unsigned long page_size)
1051 unsigned long long unmap_size, unmapped;
1054 BUG_ON(!is_power_of_2(page_size));
1058 while (unmapped < page_size) {
1060 pte = fetch_pte(dom, bus_addr);
1064 * No PTE for this address
1065 * move forward in 4kb steps
1067 unmap_size = PAGE_SIZE;
1068 } else if (PM_PTE_LEVEL(*pte) == 0) {
1069 /* 4kb PTE found for this address */
1070 unmap_size = PAGE_SIZE;
1075 /* Large PTE found which maps this address */
1076 unmap_size = PTE_PAGE_SIZE(*pte);
1077 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1078 for (i = 0; i < count; i++)
1082 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1083 unmapped += unmap_size;
1086 BUG_ON(!is_power_of_2(unmapped));
1092 * This function checks if a specific unity mapping entry is needed for
1093 * this specific IOMMU.
1095 static int iommu_for_unity_map(struct amd_iommu *iommu,
1096 struct unity_map_entry *entry)
1100 for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1101 bdf = amd_iommu_alias_table[i];
1102 if (amd_iommu_rlookup_table[bdf] == iommu)
1110 * This function actually applies the mapping to the page table of the
1113 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1114 struct unity_map_entry *e)
1119 for (addr = e->address_start; addr < e->address_end;
1120 addr += PAGE_SIZE) {
1121 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1126 * if unity mapping is in aperture range mark the page
1127 * as allocated in the aperture
1129 if (addr < dma_dom->aperture_size)
1130 __set_bit(addr >> PAGE_SHIFT,
1131 dma_dom->aperture[0]->bitmap);
1138 * Init the unity mappings for a specific IOMMU in the system
1140 * Basically iterates over all unity mapping entries and applies them to
1141 * the default domain DMA of that IOMMU if necessary.
1143 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1145 struct unity_map_entry *entry;
1148 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1149 if (!iommu_for_unity_map(iommu, entry))
1151 ret = dma_ops_unity_map(iommu->default_dom, entry);
1160 * Inits the unity mappings required for a specific device
1162 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1165 struct unity_map_entry *e;
1168 list_for_each_entry(e, &amd_iommu_unity_map, list) {
1169 if (!(devid >= e->devid_start && devid <= e->devid_end))
1171 ret = dma_ops_unity_map(dma_dom, e);
1179 /****************************************************************************
1181 * The next functions belong to the address allocator for the dma_ops
1182 * interface functions. They work like the allocators in the other IOMMU
1183 * drivers. Its basically a bitmap which marks the allocated pages in
1184 * the aperture. Maybe it could be enhanced in the future to a more
1185 * efficient allocator.
1187 ****************************************************************************/
1190 * The address allocator core functions.
1192 * called with domain->lock held
1196 * Used to reserve address ranges in the aperture (e.g. for exclusion
1199 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1200 unsigned long start_page,
1203 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1205 if (start_page + pages > last_page)
1206 pages = last_page - start_page;
1208 for (i = start_page; i < start_page + pages; ++i) {
1209 int index = i / APERTURE_RANGE_PAGES;
1210 int page = i % APERTURE_RANGE_PAGES;
1211 __set_bit(page, dom->aperture[index]->bitmap);
1216 * This function is used to add a new aperture range to an existing
1217 * aperture in case of dma_ops domain allocation or address allocation
1220 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1221 bool populate, gfp_t gfp)
1223 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1224 struct amd_iommu *iommu;
1225 unsigned long i, old_size;
1227 #ifdef CONFIG_IOMMU_STRESS
1231 if (index >= APERTURE_MAX_RANGES)
1234 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1235 if (!dma_dom->aperture[index])
1238 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1239 if (!dma_dom->aperture[index]->bitmap)
1242 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1245 unsigned long address = dma_dom->aperture_size;
1246 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1247 u64 *pte, *pte_page;
1249 for (i = 0; i < num_ptes; ++i) {
1250 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1255 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1257 address += APERTURE_RANGE_SIZE / 64;
1261 old_size = dma_dom->aperture_size;
1262 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1264 /* Reserve address range used for MSI messages */
1265 if (old_size < MSI_ADDR_BASE_LO &&
1266 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1267 unsigned long spage;
1270 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1271 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1273 dma_ops_reserve_addresses(dma_dom, spage, pages);
1276 /* Initialize the exclusion range if necessary */
1277 for_each_iommu(iommu) {
1278 if (iommu->exclusion_start &&
1279 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1280 && iommu->exclusion_start < dma_dom->aperture_size) {
1281 unsigned long startpage;
1282 int pages = iommu_num_pages(iommu->exclusion_start,
1283 iommu->exclusion_length,
1285 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1286 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1291 * Check for areas already mapped as present in the new aperture
1292 * range and mark those pages as reserved in the allocator. Such
1293 * mappings may already exist as a result of requested unity
1294 * mappings for devices.
1296 for (i = dma_dom->aperture[index]->offset;
1297 i < dma_dom->aperture_size;
1299 u64 *pte = fetch_pte(&dma_dom->domain, i);
1300 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1303 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1306 update_domain(&dma_dom->domain);
1311 update_domain(&dma_dom->domain);
1313 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1315 kfree(dma_dom->aperture[index]);
1316 dma_dom->aperture[index] = NULL;
1321 static unsigned long dma_ops_area_alloc(struct device *dev,
1322 struct dma_ops_domain *dom,
1324 unsigned long align_mask,
1326 unsigned long start)
1328 unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1329 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1330 int i = start >> APERTURE_RANGE_SHIFT;
1331 unsigned long boundary_size;
1332 unsigned long address = -1;
1333 unsigned long limit;
1335 next_bit >>= PAGE_SHIFT;
1337 boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1338 PAGE_SIZE) >> PAGE_SHIFT;
1340 for (;i < max_index; ++i) {
1341 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1343 if (dom->aperture[i]->offset >= dma_mask)
1346 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1347 dma_mask >> PAGE_SHIFT);
1349 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1350 limit, next_bit, pages, 0,
1351 boundary_size, align_mask);
1352 if (address != -1) {
1353 address = dom->aperture[i]->offset +
1354 (address << PAGE_SHIFT);
1355 dom->next_address = address + (pages << PAGE_SHIFT);
1365 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1366 struct dma_ops_domain *dom,
1368 unsigned long align_mask,
1371 unsigned long address;
1373 #ifdef CONFIG_IOMMU_STRESS
1374 dom->next_address = 0;
1375 dom->need_flush = true;
1378 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1379 dma_mask, dom->next_address);
1381 if (address == -1) {
1382 dom->next_address = 0;
1383 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1385 dom->need_flush = true;
1388 if (unlikely(address == -1))
1389 address = DMA_ERROR_CODE;
1391 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1397 * The address free function.
1399 * called with domain->lock held
1401 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1402 unsigned long address,
1405 unsigned i = address >> APERTURE_RANGE_SHIFT;
1406 struct aperture_range *range = dom->aperture[i];
1408 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1410 #ifdef CONFIG_IOMMU_STRESS
1415 if (address >= dom->next_address)
1416 dom->need_flush = true;
1418 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1420 bitmap_clear(range->bitmap, address, pages);
1424 /****************************************************************************
1426 * The next functions belong to the domain allocation. A domain is
1427 * allocated for every IOMMU as the default domain. If device isolation
1428 * is enabled, every device get its own domain. The most important thing
1429 * about domains is the page table mapping the DMA address space they
1432 ****************************************************************************/
1435 * This function adds a protection domain to the global protection domain list
1437 static void add_domain_to_list(struct protection_domain *domain)
1439 unsigned long flags;
1441 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1442 list_add(&domain->list, &amd_iommu_pd_list);
1443 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1447 * This function removes a protection domain to the global
1448 * protection domain list
1450 static void del_domain_from_list(struct protection_domain *domain)
1452 unsigned long flags;
1454 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1455 list_del(&domain->list);
1456 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1459 static u16 domain_id_alloc(void)
1461 unsigned long flags;
1464 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1465 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1467 if (id > 0 && id < MAX_DOMAIN_ID)
1468 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1471 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1476 static void domain_id_free(int id)
1478 unsigned long flags;
1480 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1481 if (id > 0 && id < MAX_DOMAIN_ID)
1482 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1483 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1486 static void free_pagetable(struct protection_domain *domain)
1491 p1 = domain->pt_root;
1496 for (i = 0; i < 512; ++i) {
1497 if (!IOMMU_PTE_PRESENT(p1[i]))
1500 p2 = IOMMU_PTE_PAGE(p1[i]);
1501 for (j = 0; j < 512; ++j) {
1502 if (!IOMMU_PTE_PRESENT(p2[j]))
1504 p3 = IOMMU_PTE_PAGE(p2[j]);
1505 free_page((unsigned long)p3);
1508 free_page((unsigned long)p2);
1511 free_page((unsigned long)p1);
1513 domain->pt_root = NULL;
1517 * Free a domain, only used if something went wrong in the
1518 * allocation path and we need to free an already allocated page table
1520 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1527 del_domain_from_list(&dom->domain);
1529 free_pagetable(&dom->domain);
1531 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1532 if (!dom->aperture[i])
1534 free_page((unsigned long)dom->aperture[i]->bitmap);
1535 kfree(dom->aperture[i]);
1542 * Allocates a new protection domain usable for the dma_ops functions.
1543 * It also initializes the page table and the address allocator data
1544 * structures required for the dma_ops interface
1546 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1548 struct dma_ops_domain *dma_dom;
1550 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1554 spin_lock_init(&dma_dom->domain.lock);
1556 dma_dom->domain.id = domain_id_alloc();
1557 if (dma_dom->domain.id == 0)
1559 INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1560 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1561 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1562 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1563 dma_dom->domain.priv = dma_dom;
1564 if (!dma_dom->domain.pt_root)
1567 dma_dom->need_flush = false;
1568 dma_dom->target_dev = 0xffff;
1570 add_domain_to_list(&dma_dom->domain);
1572 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1576 * mark the first page as allocated so we never return 0 as
1577 * a valid dma-address. So we can use 0 as error value
1579 dma_dom->aperture[0]->bitmap[0] = 1;
1580 dma_dom->next_address = 0;
1586 dma_ops_domain_free(dma_dom);
1592 * little helper function to check whether a given protection domain is a
1595 static bool dma_ops_domain(struct protection_domain *domain)
1597 return domain->flags & PD_DMA_OPS_MASK;
1600 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1602 u64 pte_root = virt_to_phys(domain->pt_root);
1605 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1606 << DEV_ENTRY_MODE_SHIFT;
1607 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1610 flags |= DTE_FLAG_IOTLB;
1612 amd_iommu_dev_table[devid].data[3] |= flags;
1613 amd_iommu_dev_table[devid].data[2] = domain->id;
1614 amd_iommu_dev_table[devid].data[1] = upper_32_bits(pte_root);
1615 amd_iommu_dev_table[devid].data[0] = lower_32_bits(pte_root);
1618 static void clear_dte_entry(u16 devid)
1620 /* remove entry from the device table seen by the hardware */
1621 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1622 amd_iommu_dev_table[devid].data[1] = 0;
1623 amd_iommu_dev_table[devid].data[2] = 0;
1625 amd_iommu_apply_erratum_63(devid);
1628 static void do_attach(struct iommu_dev_data *dev_data,
1629 struct protection_domain *domain)
1631 struct amd_iommu *iommu;
1634 iommu = amd_iommu_rlookup_table[dev_data->devid];
1635 ats = dev_data->ats.enabled;
1637 /* Update data structures */
1638 dev_data->domain = domain;
1639 list_add(&dev_data->list, &domain->dev_list);
1640 set_dte_entry(dev_data->devid, domain, ats);
1642 /* Do reference counting */
1643 domain->dev_iommu[iommu->index] += 1;
1644 domain->dev_cnt += 1;
1646 /* Flush the DTE entry */
1647 device_flush_dte(dev_data);
1650 static void do_detach(struct iommu_dev_data *dev_data)
1652 struct amd_iommu *iommu;
1654 iommu = amd_iommu_rlookup_table[dev_data->devid];
1656 /* decrease reference counters */
1657 dev_data->domain->dev_iommu[iommu->index] -= 1;
1658 dev_data->domain->dev_cnt -= 1;
1660 /* Update data structures */
1661 dev_data->domain = NULL;
1662 list_del(&dev_data->list);
1663 clear_dte_entry(dev_data->devid);
1665 /* Flush the DTE entry */
1666 device_flush_dte(dev_data);
1670 * If a device is not yet associated with a domain, this function does
1671 * assigns it visible for the hardware
1673 static int __attach_device(struct iommu_dev_data *dev_data,
1674 struct protection_domain *domain)
1679 spin_lock(&domain->lock);
1681 if (dev_data->alias_data != NULL) {
1682 struct iommu_dev_data *alias_data = dev_data->alias_data;
1684 /* Some sanity checks */
1686 if (alias_data->domain != NULL &&
1687 alias_data->domain != domain)
1690 if (dev_data->domain != NULL &&
1691 dev_data->domain != domain)
1694 /* Do real assignment */
1695 if (alias_data->domain == NULL)
1696 do_attach(alias_data, domain);
1698 atomic_inc(&alias_data->bind);
1701 if (dev_data->domain == NULL)
1702 do_attach(dev_data, domain);
1704 atomic_inc(&dev_data->bind);
1711 spin_unlock(&domain->lock);
1717 * If a device is not yet associated with a domain, this function does
1718 * assigns it visible for the hardware
1720 static int attach_device(struct device *dev,
1721 struct protection_domain *domain)
1723 struct pci_dev *pdev = to_pci_dev(dev);
1724 struct iommu_dev_data *dev_data;
1725 unsigned long flags;
1728 dev_data = get_dev_data(dev);
1730 if (amd_iommu_iotlb_sup && pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
1731 dev_data->ats.enabled = true;
1732 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
1735 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1736 ret = __attach_device(dev_data, domain);
1737 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1740 * We might boot into a crash-kernel here. The crashed kernel
1741 * left the caches in the IOMMU dirty. So we have to flush
1742 * here to evict all dirty stuff.
1744 domain_flush_tlb_pde(domain);
1750 * Removes a device from a protection domain (unlocked)
1752 static void __detach_device(struct iommu_dev_data *dev_data)
1754 struct protection_domain *domain;
1755 unsigned long flags;
1757 BUG_ON(!dev_data->domain);
1759 domain = dev_data->domain;
1761 spin_lock_irqsave(&domain->lock, flags);
1763 if (dev_data->alias_data != NULL) {
1764 struct iommu_dev_data *alias_data = dev_data->alias_data;
1766 if (atomic_dec_and_test(&alias_data->bind))
1767 do_detach(alias_data);
1770 if (atomic_dec_and_test(&dev_data->bind))
1771 do_detach(dev_data);
1773 spin_unlock_irqrestore(&domain->lock, flags);
1776 * If we run in passthrough mode the device must be assigned to the
1777 * passthrough domain if it is detached from any other domain.
1778 * Make sure we can deassign from the pt_domain itself.
1780 if (iommu_pass_through &&
1781 (dev_data->domain == NULL && domain != pt_domain))
1782 __attach_device(dev_data, pt_domain);
1786 * Removes a device from a protection domain (with devtable_lock held)
1788 static void detach_device(struct device *dev)
1790 struct iommu_dev_data *dev_data;
1791 unsigned long flags;
1793 dev_data = get_dev_data(dev);
1795 /* lock device table */
1796 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1797 __detach_device(dev_data);
1798 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1800 if (dev_data->ats.enabled) {
1801 pci_disable_ats(to_pci_dev(dev));
1802 dev_data->ats.enabled = false;
1807 * Find out the protection domain structure for a given PCI device. This
1808 * will give us the pointer to the page table root for example.
1810 static struct protection_domain *domain_for_device(struct device *dev)
1812 struct iommu_dev_data *dev_data;
1813 struct protection_domain *dom = NULL;
1814 unsigned long flags;
1816 dev_data = get_dev_data(dev);
1818 if (dev_data->domain)
1819 return dev_data->domain;
1821 if (dev_data->alias_data != NULL) {
1822 struct iommu_dev_data *alias_data = dev_data->alias_data;
1824 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
1825 if (alias_data->domain != NULL) {
1826 __attach_device(dev_data, alias_data->domain);
1827 dom = alias_data->domain;
1829 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1835 static int device_change_notifier(struct notifier_block *nb,
1836 unsigned long action, void *data)
1838 struct device *dev = data;
1840 struct protection_domain *domain;
1841 struct dma_ops_domain *dma_domain;
1842 struct amd_iommu *iommu;
1843 unsigned long flags;
1845 if (!check_device(dev))
1848 devid = get_device_id(dev);
1849 iommu = amd_iommu_rlookup_table[devid];
1852 case BUS_NOTIFY_UNBOUND_DRIVER:
1854 domain = domain_for_device(dev);
1858 if (iommu_pass_through)
1862 case BUS_NOTIFY_ADD_DEVICE:
1864 iommu_init_device(dev);
1866 domain = domain_for_device(dev);
1868 /* allocate a protection domain if a device is added */
1869 dma_domain = find_protection_domain(devid);
1872 dma_domain = dma_ops_domain_alloc();
1875 dma_domain->target_dev = devid;
1877 spin_lock_irqsave(&iommu_pd_list_lock, flags);
1878 list_add_tail(&dma_domain->list, &iommu_pd_list);
1879 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
1882 case BUS_NOTIFY_DEL_DEVICE:
1884 iommu_uninit_device(dev);
1890 iommu_completion_wait(iommu);
1896 static struct notifier_block device_nb = {
1897 .notifier_call = device_change_notifier,
1900 void amd_iommu_init_notifier(void)
1902 bus_register_notifier(&pci_bus_type, &device_nb);
1905 /*****************************************************************************
1907 * The next functions belong to the dma_ops mapping/unmapping code.
1909 *****************************************************************************/
1912 * In the dma_ops path we only have the struct device. This function
1913 * finds the corresponding IOMMU, the protection domain and the
1914 * requestor id for a given device.
1915 * If the device is not yet associated with a domain this is also done
1918 static struct protection_domain *get_domain(struct device *dev)
1920 struct protection_domain *domain;
1921 struct dma_ops_domain *dma_dom;
1922 u16 devid = get_device_id(dev);
1924 if (!check_device(dev))
1925 return ERR_PTR(-EINVAL);
1927 domain = domain_for_device(dev);
1928 if (domain != NULL && !dma_ops_domain(domain))
1929 return ERR_PTR(-EBUSY);
1934 /* Device not bount yet - bind it */
1935 dma_dom = find_protection_domain(devid);
1937 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
1938 attach_device(dev, &dma_dom->domain);
1939 DUMP_printk("Using protection domain %d for device %s\n",
1940 dma_dom->domain.id, dev_name(dev));
1942 return &dma_dom->domain;
1945 static void update_device_table(struct protection_domain *domain)
1947 struct iommu_dev_data *dev_data;
1949 list_for_each_entry(dev_data, &domain->dev_list, list)
1950 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
1953 static void update_domain(struct protection_domain *domain)
1955 if (!domain->updated)
1958 update_device_table(domain);
1960 domain_flush_devices(domain);
1961 domain_flush_tlb_pde(domain);
1963 domain->updated = false;
1967 * This function fetches the PTE for a given address in the aperture
1969 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
1970 unsigned long address)
1972 struct aperture_range *aperture;
1973 u64 *pte, *pte_page;
1975 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
1979 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
1981 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
1983 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
1985 pte += PM_LEVEL_INDEX(0, address);
1987 update_domain(&dom->domain);
1993 * This is the generic map function. It maps one 4kb page at paddr to
1994 * the given address in the DMA address space for the domain.
1996 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
1997 unsigned long address,
2003 WARN_ON(address > dom->aperture_size);
2007 pte = dma_ops_get_pte(dom, address);
2009 return DMA_ERROR_CODE;
2011 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2013 if (direction == DMA_TO_DEVICE)
2014 __pte |= IOMMU_PTE_IR;
2015 else if (direction == DMA_FROM_DEVICE)
2016 __pte |= IOMMU_PTE_IW;
2017 else if (direction == DMA_BIDIRECTIONAL)
2018 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2024 return (dma_addr_t)address;
2028 * The generic unmapping function for on page in the DMA address space.
2030 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2031 unsigned long address)
2033 struct aperture_range *aperture;
2036 if (address >= dom->aperture_size)
2039 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2043 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2047 pte += PM_LEVEL_INDEX(0, address);
2055 * This function contains common code for mapping of a physically
2056 * contiguous memory region into DMA address space. It is used by all
2057 * mapping functions provided with this IOMMU driver.
2058 * Must be called with the domain lock held.
2060 static dma_addr_t __map_single(struct device *dev,
2061 struct dma_ops_domain *dma_dom,
2068 dma_addr_t offset = paddr & ~PAGE_MASK;
2069 dma_addr_t address, start, ret;
2071 unsigned long align_mask = 0;
2074 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2077 INC_STATS_COUNTER(total_map_requests);
2080 INC_STATS_COUNTER(cross_page);
2083 align_mask = (1UL << get_order(size)) - 1;
2086 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2088 if (unlikely(address == DMA_ERROR_CODE)) {
2090 * setting next_address here will let the address
2091 * allocator only scan the new allocated range in the
2092 * first run. This is a small optimization.
2094 dma_dom->next_address = dma_dom->aperture_size;
2096 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2100 * aperture was successfully enlarged by 128 MB, try
2107 for (i = 0; i < pages; ++i) {
2108 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2109 if (ret == DMA_ERROR_CODE)
2117 ADD_STATS_COUNTER(alloced_io_mem, size);
2119 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2120 domain_flush_tlb(&dma_dom->domain);
2121 dma_dom->need_flush = false;
2122 } else if (unlikely(amd_iommu_np_cache))
2123 domain_flush_pages(&dma_dom->domain, address, size);
2130 for (--i; i >= 0; --i) {
2132 dma_ops_domain_unmap(dma_dom, start);
2135 dma_ops_free_addresses(dma_dom, address, pages);
2137 return DMA_ERROR_CODE;
2141 * Does the reverse of the __map_single function. Must be called with
2142 * the domain lock held too
2144 static void __unmap_single(struct dma_ops_domain *dma_dom,
2145 dma_addr_t dma_addr,
2149 dma_addr_t flush_addr;
2150 dma_addr_t i, start;
2153 if ((dma_addr == DMA_ERROR_CODE) ||
2154 (dma_addr + size > dma_dom->aperture_size))
2157 flush_addr = dma_addr;
2158 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2159 dma_addr &= PAGE_MASK;
2162 for (i = 0; i < pages; ++i) {
2163 dma_ops_domain_unmap(dma_dom, start);
2167 SUB_STATS_COUNTER(alloced_io_mem, size);
2169 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2171 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2172 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2173 dma_dom->need_flush = false;
2178 * The exported map_single function for dma_ops.
2180 static dma_addr_t map_page(struct device *dev, struct page *page,
2181 unsigned long offset, size_t size,
2182 enum dma_data_direction dir,
2183 struct dma_attrs *attrs)
2185 unsigned long flags;
2186 struct protection_domain *domain;
2189 phys_addr_t paddr = page_to_phys(page) + offset;
2191 INC_STATS_COUNTER(cnt_map_single);
2193 domain = get_domain(dev);
2194 if (PTR_ERR(domain) == -EINVAL)
2195 return (dma_addr_t)paddr;
2196 else if (IS_ERR(domain))
2197 return DMA_ERROR_CODE;
2199 dma_mask = *dev->dma_mask;
2201 spin_lock_irqsave(&domain->lock, flags);
2203 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2205 if (addr == DMA_ERROR_CODE)
2208 domain_flush_complete(domain);
2211 spin_unlock_irqrestore(&domain->lock, flags);
2217 * The exported unmap_single function for dma_ops.
2219 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2220 enum dma_data_direction dir, struct dma_attrs *attrs)
2222 unsigned long flags;
2223 struct protection_domain *domain;
2225 INC_STATS_COUNTER(cnt_unmap_single);
2227 domain = get_domain(dev);
2231 spin_lock_irqsave(&domain->lock, flags);
2233 __unmap_single(domain->priv, dma_addr, size, dir);
2235 domain_flush_complete(domain);
2237 spin_unlock_irqrestore(&domain->lock, flags);
2241 * This is a special map_sg function which is used if we should map a
2242 * device which is not handled by an AMD IOMMU in the system.
2244 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2245 int nelems, int dir)
2247 struct scatterlist *s;
2250 for_each_sg(sglist, s, nelems, i) {
2251 s->dma_address = (dma_addr_t)sg_phys(s);
2252 s->dma_length = s->length;
2259 * The exported map_sg function for dma_ops (handles scatter-gather
2262 static int map_sg(struct device *dev, struct scatterlist *sglist,
2263 int nelems, enum dma_data_direction dir,
2264 struct dma_attrs *attrs)
2266 unsigned long flags;
2267 struct protection_domain *domain;
2269 struct scatterlist *s;
2271 int mapped_elems = 0;
2274 INC_STATS_COUNTER(cnt_map_sg);
2276 domain = get_domain(dev);
2277 if (PTR_ERR(domain) == -EINVAL)
2278 return map_sg_no_iommu(dev, sglist, nelems, dir);
2279 else if (IS_ERR(domain))
2282 dma_mask = *dev->dma_mask;
2284 spin_lock_irqsave(&domain->lock, flags);
2286 for_each_sg(sglist, s, nelems, i) {
2289 s->dma_address = __map_single(dev, domain->priv,
2290 paddr, s->length, dir, false,
2293 if (s->dma_address) {
2294 s->dma_length = s->length;
2300 domain_flush_complete(domain);
2303 spin_unlock_irqrestore(&domain->lock, flags);
2305 return mapped_elems;
2307 for_each_sg(sglist, s, mapped_elems, i) {
2309 __unmap_single(domain->priv, s->dma_address,
2310 s->dma_length, dir);
2311 s->dma_address = s->dma_length = 0;
2320 * The exported map_sg function for dma_ops (handles scatter-gather
2323 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2324 int nelems, enum dma_data_direction dir,
2325 struct dma_attrs *attrs)
2327 unsigned long flags;
2328 struct protection_domain *domain;
2329 struct scatterlist *s;
2332 INC_STATS_COUNTER(cnt_unmap_sg);
2334 domain = get_domain(dev);
2338 spin_lock_irqsave(&domain->lock, flags);
2340 for_each_sg(sglist, s, nelems, i) {
2341 __unmap_single(domain->priv, s->dma_address,
2342 s->dma_length, dir);
2343 s->dma_address = s->dma_length = 0;
2346 domain_flush_complete(domain);
2348 spin_unlock_irqrestore(&domain->lock, flags);
2352 * The exported alloc_coherent function for dma_ops.
2354 static void *alloc_coherent(struct device *dev, size_t size,
2355 dma_addr_t *dma_addr, gfp_t flag)
2357 unsigned long flags;
2359 struct protection_domain *domain;
2361 u64 dma_mask = dev->coherent_dma_mask;
2363 INC_STATS_COUNTER(cnt_alloc_coherent);
2365 domain = get_domain(dev);
2366 if (PTR_ERR(domain) == -EINVAL) {
2367 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2368 *dma_addr = __pa(virt_addr);
2370 } else if (IS_ERR(domain))
2373 dma_mask = dev->coherent_dma_mask;
2374 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2377 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2381 paddr = virt_to_phys(virt_addr);
2384 dma_mask = *dev->dma_mask;
2386 spin_lock_irqsave(&domain->lock, flags);
2388 *dma_addr = __map_single(dev, domain->priv, paddr,
2389 size, DMA_BIDIRECTIONAL, true, dma_mask);
2391 if (*dma_addr == DMA_ERROR_CODE) {
2392 spin_unlock_irqrestore(&domain->lock, flags);
2396 domain_flush_complete(domain);
2398 spin_unlock_irqrestore(&domain->lock, flags);
2404 free_pages((unsigned long)virt_addr, get_order(size));
2410 * The exported free_coherent function for dma_ops.
2412 static void free_coherent(struct device *dev, size_t size,
2413 void *virt_addr, dma_addr_t dma_addr)
2415 unsigned long flags;
2416 struct protection_domain *domain;
2418 INC_STATS_COUNTER(cnt_free_coherent);
2420 domain = get_domain(dev);
2424 spin_lock_irqsave(&domain->lock, flags);
2426 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2428 domain_flush_complete(domain);
2430 spin_unlock_irqrestore(&domain->lock, flags);
2433 free_pages((unsigned long)virt_addr, get_order(size));
2437 * This function is called by the DMA layer to find out if we can handle a
2438 * particular device. It is part of the dma_ops.
2440 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2442 return check_device(dev);
2446 * The function for pre-allocating protection domains.
2448 * If the driver core informs the DMA layer if a driver grabs a device
2449 * we don't need to preallocate the protection domains anymore.
2450 * For now we have to.
2452 static void __init prealloc_protection_domains(void)
2454 struct pci_dev *dev = NULL;
2455 struct dma_ops_domain *dma_dom;
2458 for_each_pci_dev(dev) {
2460 /* Do we handle this device? */
2461 if (!check_device(&dev->dev))
2464 /* Is there already any domain for it? */
2465 if (domain_for_device(&dev->dev))
2468 devid = get_device_id(&dev->dev);
2470 dma_dom = dma_ops_domain_alloc();
2473 init_unity_mappings_for_device(dma_dom, devid);
2474 dma_dom->target_dev = devid;
2476 attach_device(&dev->dev, &dma_dom->domain);
2478 list_add_tail(&dma_dom->list, &iommu_pd_list);
2482 static struct dma_map_ops amd_iommu_dma_ops = {
2483 .alloc_coherent = alloc_coherent,
2484 .free_coherent = free_coherent,
2485 .map_page = map_page,
2486 .unmap_page = unmap_page,
2488 .unmap_sg = unmap_sg,
2489 .dma_supported = amd_iommu_dma_supported,
2492 static unsigned device_dma_ops_init(void)
2494 struct pci_dev *pdev = NULL;
2495 unsigned unhandled = 0;
2497 for_each_pci_dev(pdev) {
2498 if (!check_device(&pdev->dev)) {
2500 iommu_ignore_device(&pdev->dev);
2506 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
2513 * The function which clues the AMD IOMMU driver into dma_ops.
2516 void __init amd_iommu_init_api(void)
2518 bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2521 int __init amd_iommu_init_dma_ops(void)
2523 struct amd_iommu *iommu;
2527 * first allocate a default protection domain for every IOMMU we
2528 * found in the system. Devices not assigned to any other
2529 * protection domain will be assigned to the default one.
2531 for_each_iommu(iommu) {
2532 iommu->default_dom = dma_ops_domain_alloc();
2533 if (iommu->default_dom == NULL)
2535 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
2536 ret = iommu_init_unity_mappings(iommu);
2542 * Pre-allocate the protection domains for each device.
2544 prealloc_protection_domains();
2549 /* Make the driver finally visible to the drivers */
2550 unhandled = device_dma_ops_init();
2551 if (unhandled && max_pfn > MAX_DMA32_PFN) {
2552 /* There are unhandled devices - initialize swiotlb for them */
2556 amd_iommu_stats_init();
2562 for_each_iommu(iommu) {
2563 if (iommu->default_dom)
2564 dma_ops_domain_free(iommu->default_dom);
2570 /*****************************************************************************
2572 * The following functions belong to the exported interface of AMD IOMMU
2574 * This interface allows access to lower level functions of the IOMMU
2575 * like protection domain handling and assignement of devices to domains
2576 * which is not possible with the dma_ops interface.
2578 *****************************************************************************/
2580 static void cleanup_domain(struct protection_domain *domain)
2582 struct iommu_dev_data *dev_data, *next;
2583 unsigned long flags;
2585 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2587 list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
2588 __detach_device(dev_data);
2589 atomic_set(&dev_data->bind, 0);
2592 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2595 static void protection_domain_free(struct protection_domain *domain)
2600 del_domain_from_list(domain);
2603 domain_id_free(domain->id);
2608 static struct protection_domain *protection_domain_alloc(void)
2610 struct protection_domain *domain;
2612 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2616 spin_lock_init(&domain->lock);
2617 mutex_init(&domain->api_lock);
2618 domain->id = domain_id_alloc();
2621 INIT_LIST_HEAD(&domain->dev_list);
2623 add_domain_to_list(domain);
2633 static int amd_iommu_domain_init(struct iommu_domain *dom)
2635 struct protection_domain *domain;
2637 domain = protection_domain_alloc();
2641 domain->mode = PAGE_MODE_3_LEVEL;
2642 domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2643 if (!domain->pt_root)
2651 protection_domain_free(domain);
2656 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
2658 struct protection_domain *domain = dom->priv;
2663 if (domain->dev_cnt > 0)
2664 cleanup_domain(domain);
2666 BUG_ON(domain->dev_cnt != 0);
2668 free_pagetable(domain);
2670 protection_domain_free(domain);
2675 static void amd_iommu_detach_device(struct iommu_domain *dom,
2678 struct iommu_dev_data *dev_data = dev->archdata.iommu;
2679 struct amd_iommu *iommu;
2682 if (!check_device(dev))
2685 devid = get_device_id(dev);
2687 if (dev_data->domain != NULL)
2690 iommu = amd_iommu_rlookup_table[devid];
2694 iommu_completion_wait(iommu);
2697 static int amd_iommu_attach_device(struct iommu_domain *dom,
2700 struct protection_domain *domain = dom->priv;
2701 struct iommu_dev_data *dev_data;
2702 struct amd_iommu *iommu;
2705 if (!check_device(dev))
2708 dev_data = dev->archdata.iommu;
2710 iommu = amd_iommu_rlookup_table[dev_data->devid];
2714 if (dev_data->domain)
2717 ret = attach_device(dev, domain);
2719 iommu_completion_wait(iommu);
2724 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
2725 phys_addr_t paddr, int gfp_order, int iommu_prot)
2727 unsigned long page_size = 0x1000UL << gfp_order;
2728 struct protection_domain *domain = dom->priv;
2732 if (iommu_prot & IOMMU_READ)
2733 prot |= IOMMU_PROT_IR;
2734 if (iommu_prot & IOMMU_WRITE)
2735 prot |= IOMMU_PROT_IW;
2737 mutex_lock(&domain->api_lock);
2738 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
2739 mutex_unlock(&domain->api_lock);
2744 static int amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
2747 struct protection_domain *domain = dom->priv;
2748 unsigned long page_size, unmap_size;
2750 page_size = 0x1000UL << gfp_order;
2752 mutex_lock(&domain->api_lock);
2753 unmap_size = iommu_unmap_page(domain, iova, page_size);
2754 mutex_unlock(&domain->api_lock);
2756 domain_flush_tlb_pde(domain);
2758 return get_order(unmap_size);
2761 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
2764 struct protection_domain *domain = dom->priv;
2765 unsigned long offset_mask;
2769 pte = fetch_pte(domain, iova);
2771 if (!pte || !IOMMU_PTE_PRESENT(*pte))
2774 if (PM_PTE_LEVEL(*pte) == 0)
2775 offset_mask = PAGE_SIZE - 1;
2777 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
2779 __pte = *pte & PM_ADDR_MASK;
2780 paddr = (__pte & ~offset_mask) | (iova & offset_mask);
2785 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
2789 case IOMMU_CAP_CACHE_COHERENCY:
2796 static struct iommu_ops amd_iommu_ops = {
2797 .domain_init = amd_iommu_domain_init,
2798 .domain_destroy = amd_iommu_domain_destroy,
2799 .attach_dev = amd_iommu_attach_device,
2800 .detach_dev = amd_iommu_detach_device,
2801 .map = amd_iommu_map,
2802 .unmap = amd_iommu_unmap,
2803 .iova_to_phys = amd_iommu_iova_to_phys,
2804 .domain_has_cap = amd_iommu_domain_has_cap,
2807 /*****************************************************************************
2809 * The next functions do a basic initialization of IOMMU for pass through
2812 * In passthrough mode the IOMMU is initialized and enabled but not used for
2813 * DMA-API translation.
2815 *****************************************************************************/
2817 int __init amd_iommu_init_passthrough(void)
2819 struct amd_iommu *iommu;
2820 struct pci_dev *dev = NULL;
2823 /* allocate passthrough domain */
2824 pt_domain = protection_domain_alloc();
2828 pt_domain->mode |= PAGE_MODE_NONE;
2830 for_each_pci_dev(dev) {
2831 if (!check_device(&dev->dev))
2834 devid = get_device_id(&dev->dev);
2836 iommu = amd_iommu_rlookup_table[devid];
2840 attach_device(&dev->dev, pt_domain);
2843 pr_info("AMD-Vi: Initialized for Passthrough Mode\n");