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;
62 static struct dma_map_ops amd_iommu_dma_ops;
65 * general struct to manage commands send to an IOMMU
71 static void update_domain(struct protection_domain *domain);
73 /****************************************************************************
77 ****************************************************************************/
79 static struct iommu_dev_data *alloc_dev_data(u16 devid)
81 struct iommu_dev_data *dev_data;
84 dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
88 dev_data->devid = devid;
89 atomic_set(&dev_data->bind, 0);
91 spin_lock_irqsave(&dev_data_list_lock, flags);
92 list_add_tail(&dev_data->dev_data_list, &dev_data_list);
93 spin_unlock_irqrestore(&dev_data_list_lock, flags);
98 static void free_dev_data(struct iommu_dev_data *dev_data)
102 spin_lock_irqsave(&dev_data_list_lock, flags);
103 list_del(&dev_data->dev_data_list);
104 spin_unlock_irqrestore(&dev_data_list_lock, flags);
109 static struct iommu_dev_data *search_dev_data(u16 devid)
111 struct iommu_dev_data *dev_data;
114 spin_lock_irqsave(&dev_data_list_lock, flags);
115 list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
116 if (dev_data->devid == devid)
123 spin_unlock_irqrestore(&dev_data_list_lock, flags);
128 static struct iommu_dev_data *find_dev_data(u16 devid)
130 struct iommu_dev_data *dev_data;
132 dev_data = search_dev_data(devid);
134 if (dev_data == NULL)
135 dev_data = alloc_dev_data(devid);
140 static inline u16 get_device_id(struct device *dev)
142 struct pci_dev *pdev = to_pci_dev(dev);
144 return calc_devid(pdev->bus->number, pdev->devfn);
147 static struct iommu_dev_data *get_dev_data(struct device *dev)
149 return dev->archdata.iommu;
153 * In this function the list of preallocated protection domains is traversed to
154 * find the domain for a specific device
156 static struct dma_ops_domain *find_protection_domain(u16 devid)
158 struct dma_ops_domain *entry, *ret = NULL;
160 u16 alias = amd_iommu_alias_table[devid];
162 if (list_empty(&iommu_pd_list))
165 spin_lock_irqsave(&iommu_pd_list_lock, flags);
167 list_for_each_entry(entry, &iommu_pd_list, list) {
168 if (entry->target_dev == devid ||
169 entry->target_dev == alias) {
175 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
181 * This function checks if the driver got a valid device from the caller to
182 * avoid dereferencing invalid pointers.
184 static bool check_device(struct device *dev)
188 if (!dev || !dev->dma_mask)
191 /* No device or no PCI device */
192 if (dev->bus != &pci_bus_type)
195 devid = get_device_id(dev);
197 /* Out of our scope? */
198 if (devid > amd_iommu_last_bdf)
201 if (amd_iommu_rlookup_table[devid] == NULL)
207 static int iommu_init_device(struct device *dev)
209 struct iommu_dev_data *dev_data;
212 if (dev->archdata.iommu)
215 dev_data = find_dev_data(get_device_id(dev));
219 alias = amd_iommu_alias_table[dev_data->devid];
220 if (alias != dev_data->devid) {
221 struct iommu_dev_data *alias_data;
223 alias_data = find_dev_data(alias);
224 if (alias_data == NULL) {
225 pr_err("AMD-Vi: Warning: Unhandled device %s\n",
227 free_dev_data(dev_data);
230 dev_data->alias_data = alias_data;
233 dev->archdata.iommu = dev_data;
238 static void iommu_ignore_device(struct device *dev)
242 devid = get_device_id(dev);
243 alias = amd_iommu_alias_table[devid];
245 memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
246 memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
248 amd_iommu_rlookup_table[devid] = NULL;
249 amd_iommu_rlookup_table[alias] = NULL;
252 static void iommu_uninit_device(struct device *dev)
255 * Nothing to do here - we keep dev_data around for unplugged devices
256 * and reuse it when the device is re-plugged - not doing so would
257 * introduce a ton of races.
261 void __init amd_iommu_uninit_devices(void)
263 struct iommu_dev_data *dev_data, *n;
264 struct pci_dev *pdev = NULL;
266 for_each_pci_dev(pdev) {
268 if (!check_device(&pdev->dev))
271 iommu_uninit_device(&pdev->dev);
274 /* Free all of our dev_data structures */
275 list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
276 free_dev_data(dev_data);
279 int __init amd_iommu_init_devices(void)
281 struct pci_dev *pdev = NULL;
284 for_each_pci_dev(pdev) {
286 if (!check_device(&pdev->dev))
289 ret = iommu_init_device(&pdev->dev);
290 if (ret == -ENOTSUPP)
291 iommu_ignore_device(&pdev->dev);
300 amd_iommu_uninit_devices();
304 #ifdef CONFIG_AMD_IOMMU_STATS
307 * Initialization code for statistics collection
310 DECLARE_STATS_COUNTER(compl_wait);
311 DECLARE_STATS_COUNTER(cnt_map_single);
312 DECLARE_STATS_COUNTER(cnt_unmap_single);
313 DECLARE_STATS_COUNTER(cnt_map_sg);
314 DECLARE_STATS_COUNTER(cnt_unmap_sg);
315 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
316 DECLARE_STATS_COUNTER(cnt_free_coherent);
317 DECLARE_STATS_COUNTER(cross_page);
318 DECLARE_STATS_COUNTER(domain_flush_single);
319 DECLARE_STATS_COUNTER(domain_flush_all);
320 DECLARE_STATS_COUNTER(alloced_io_mem);
321 DECLARE_STATS_COUNTER(total_map_requests);
323 static struct dentry *stats_dir;
324 static struct dentry *de_fflush;
326 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
328 if (stats_dir == NULL)
331 cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
335 static void amd_iommu_stats_init(void)
337 stats_dir = debugfs_create_dir("amd-iommu", NULL);
338 if (stats_dir == NULL)
341 de_fflush = debugfs_create_bool("fullflush", 0444, stats_dir,
342 (u32 *)&amd_iommu_unmap_flush);
344 amd_iommu_stats_add(&compl_wait);
345 amd_iommu_stats_add(&cnt_map_single);
346 amd_iommu_stats_add(&cnt_unmap_single);
347 amd_iommu_stats_add(&cnt_map_sg);
348 amd_iommu_stats_add(&cnt_unmap_sg);
349 amd_iommu_stats_add(&cnt_alloc_coherent);
350 amd_iommu_stats_add(&cnt_free_coherent);
351 amd_iommu_stats_add(&cross_page);
352 amd_iommu_stats_add(&domain_flush_single);
353 amd_iommu_stats_add(&domain_flush_all);
354 amd_iommu_stats_add(&alloced_io_mem);
355 amd_iommu_stats_add(&total_map_requests);
360 /****************************************************************************
362 * Interrupt handling functions
364 ****************************************************************************/
366 static void dump_dte_entry(u16 devid)
370 for (i = 0; i < 8; ++i)
371 pr_err("AMD-Vi: DTE[%d]: %08x\n", i,
372 amd_iommu_dev_table[devid].data[i]);
375 static void dump_command(unsigned long phys_addr)
377 struct iommu_cmd *cmd = phys_to_virt(phys_addr);
380 for (i = 0; i < 4; ++i)
381 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
384 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
386 int type, devid, domid, flags;
387 volatile u32 *event = __evt;
392 type = (event[1] >> EVENT_TYPE_SHIFT) & EVENT_TYPE_MASK;
393 devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
394 domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
395 flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
396 address = (u64)(((u64)event[3]) << 32) | event[2];
399 /* Did we hit the erratum? */
400 if (++count == LOOP_TIMEOUT) {
401 pr_err("AMD-Vi: No event written to event log\n");
408 printk(KERN_ERR "AMD-Vi: Event logged [");
411 case EVENT_TYPE_ILL_DEV:
412 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
413 "address=0x%016llx flags=0x%04x]\n",
414 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
416 dump_dte_entry(devid);
418 case EVENT_TYPE_IO_FAULT:
419 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
420 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
421 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
422 domid, address, flags);
424 case EVENT_TYPE_DEV_TAB_ERR:
425 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
426 "address=0x%016llx flags=0x%04x]\n",
427 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
430 case EVENT_TYPE_PAGE_TAB_ERR:
431 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
432 "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
433 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
434 domid, address, flags);
436 case EVENT_TYPE_ILL_CMD:
437 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
438 dump_command(address);
440 case EVENT_TYPE_CMD_HARD_ERR:
441 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
442 "flags=0x%04x]\n", address, flags);
444 case EVENT_TYPE_IOTLB_INV_TO:
445 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
446 "address=0x%016llx]\n",
447 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
450 case EVENT_TYPE_INV_DEV_REQ:
451 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
452 "address=0x%016llx flags=0x%04x]\n",
453 PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
457 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
460 memset(__evt, 0, 4 * sizeof(u32));
463 static void iommu_poll_events(struct amd_iommu *iommu)
468 spin_lock_irqsave(&iommu->lock, flags);
470 head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
471 tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
473 while (head != tail) {
474 iommu_print_event(iommu, iommu->evt_buf + head);
475 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
478 writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
480 spin_unlock_irqrestore(&iommu->lock, flags);
483 irqreturn_t amd_iommu_int_thread(int irq, void *data)
485 struct amd_iommu *iommu;
487 for_each_iommu(iommu)
488 iommu_poll_events(iommu);
493 irqreturn_t amd_iommu_int_handler(int irq, void *data)
495 return IRQ_WAKE_THREAD;
498 /****************************************************************************
500 * IOMMU command queuing functions
502 ****************************************************************************/
504 static int wait_on_sem(volatile u64 *sem)
508 while (*sem == 0 && i < LOOP_TIMEOUT) {
513 if (i == LOOP_TIMEOUT) {
514 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
521 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
522 struct iommu_cmd *cmd,
527 target = iommu->cmd_buf + tail;
528 tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
530 /* Copy command to buffer */
531 memcpy(target, cmd, sizeof(*cmd));
533 /* Tell the IOMMU about it */
534 writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
537 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
539 WARN_ON(address & 0x7ULL);
541 memset(cmd, 0, sizeof(*cmd));
542 cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
543 cmd->data[1] = upper_32_bits(__pa(address));
545 CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
548 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
550 memset(cmd, 0, sizeof(*cmd));
551 cmd->data[0] = devid;
552 CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
555 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
556 size_t size, u16 domid, int pde)
561 pages = iommu_num_pages(address, size, PAGE_SIZE);
566 * If we have to flush more than one page, flush all
567 * TLB entries for this domain
569 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
573 address &= PAGE_MASK;
575 memset(cmd, 0, sizeof(*cmd));
576 cmd->data[1] |= domid;
577 cmd->data[2] = lower_32_bits(address);
578 cmd->data[3] = upper_32_bits(address);
579 CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
580 if (s) /* size bit - we flush more than one 4kb page */
581 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
582 if (pde) /* PDE bit - we wan't flush everything not only the PTEs */
583 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
586 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
587 u64 address, size_t size)
592 pages = iommu_num_pages(address, size, PAGE_SIZE);
597 * If we have to flush more than one page, flush all
598 * TLB entries for this domain
600 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
604 address &= PAGE_MASK;
606 memset(cmd, 0, sizeof(*cmd));
607 cmd->data[0] = devid;
608 cmd->data[0] |= (qdep & 0xff) << 24;
609 cmd->data[1] = devid;
610 cmd->data[2] = lower_32_bits(address);
611 cmd->data[3] = upper_32_bits(address);
612 CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
614 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
617 static void build_inv_all(struct iommu_cmd *cmd)
619 memset(cmd, 0, sizeof(*cmd));
620 CMD_SET_TYPE(cmd, CMD_INV_ALL);
624 * Writes the command to the IOMMUs command buffer and informs the
625 * hardware about the new command.
627 static int iommu_queue_command_sync(struct amd_iommu *iommu,
628 struct iommu_cmd *cmd,
631 u32 left, tail, head, next_tail;
634 WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
637 spin_lock_irqsave(&iommu->lock, flags);
639 head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
640 tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
641 next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
642 left = (head - next_tail) % iommu->cmd_buf_size;
645 struct iommu_cmd sync_cmd;
646 volatile u64 sem = 0;
649 build_completion_wait(&sync_cmd, (u64)&sem);
650 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
652 spin_unlock_irqrestore(&iommu->lock, flags);
654 if ((ret = wait_on_sem(&sem)) != 0)
660 copy_cmd_to_buffer(iommu, cmd, tail);
662 /* We need to sync now to make sure all commands are processed */
663 iommu->need_sync = sync;
665 spin_unlock_irqrestore(&iommu->lock, flags);
670 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
672 return iommu_queue_command_sync(iommu, cmd, true);
676 * This function queues a completion wait command into the command
679 static int iommu_completion_wait(struct amd_iommu *iommu)
681 struct iommu_cmd cmd;
682 volatile u64 sem = 0;
685 if (!iommu->need_sync)
688 build_completion_wait(&cmd, (u64)&sem);
690 ret = iommu_queue_command_sync(iommu, &cmd, false);
694 return wait_on_sem(&sem);
697 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
699 struct iommu_cmd cmd;
701 build_inv_dte(&cmd, devid);
703 return iommu_queue_command(iommu, &cmd);
706 static void iommu_flush_dte_all(struct amd_iommu *iommu)
710 for (devid = 0; devid <= 0xffff; ++devid)
711 iommu_flush_dte(iommu, devid);
713 iommu_completion_wait(iommu);
717 * This function uses heavy locking and may disable irqs for some time. But
718 * this is no issue because it is only called during resume.
720 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
724 for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
725 struct iommu_cmd cmd;
726 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
728 iommu_queue_command(iommu, &cmd);
731 iommu_completion_wait(iommu);
734 static void iommu_flush_all(struct amd_iommu *iommu)
736 struct iommu_cmd cmd;
740 iommu_queue_command(iommu, &cmd);
741 iommu_completion_wait(iommu);
744 void iommu_flush_all_caches(struct amd_iommu *iommu)
746 if (iommu_feature(iommu, FEATURE_IA)) {
747 iommu_flush_all(iommu);
749 iommu_flush_dte_all(iommu);
750 iommu_flush_tlb_all(iommu);
755 * Command send function for flushing on-device TLB
757 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
758 u64 address, size_t size)
760 struct amd_iommu *iommu;
761 struct iommu_cmd cmd;
764 qdep = dev_data->ats.qdep;
765 iommu = amd_iommu_rlookup_table[dev_data->devid];
767 build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
769 return iommu_queue_command(iommu, &cmd);
773 * Command send function for invalidating a device table entry
775 static int device_flush_dte(struct iommu_dev_data *dev_data)
777 struct amd_iommu *iommu;
780 iommu = amd_iommu_rlookup_table[dev_data->devid];
782 ret = iommu_flush_dte(iommu, dev_data->devid);
786 if (dev_data->ats.enabled)
787 ret = device_flush_iotlb(dev_data, 0, ~0UL);
793 * TLB invalidation function which is called from the mapping functions.
794 * It invalidates a single PTE if the range to flush is within a single
795 * page. Otherwise it flushes the whole TLB of the IOMMU.
797 static void __domain_flush_pages(struct protection_domain *domain,
798 u64 address, size_t size, int pde)
800 struct iommu_dev_data *dev_data;
801 struct iommu_cmd cmd;
804 build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
806 for (i = 0; i < amd_iommus_present; ++i) {
807 if (!domain->dev_iommu[i])
811 * Devices of this domain are behind this IOMMU
812 * We need a TLB flush
814 ret |= iommu_queue_command(amd_iommus[i], &cmd);
817 list_for_each_entry(dev_data, &domain->dev_list, list) {
819 if (!dev_data->ats.enabled)
822 ret |= device_flush_iotlb(dev_data, address, size);
828 static void domain_flush_pages(struct protection_domain *domain,
829 u64 address, size_t size)
831 __domain_flush_pages(domain, address, size, 0);
834 /* Flush the whole IO/TLB for a given protection domain */
835 static void domain_flush_tlb(struct protection_domain *domain)
837 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
840 /* Flush the whole IO/TLB for a given protection domain - including PDE */
841 static void domain_flush_tlb_pde(struct protection_domain *domain)
843 __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
846 static void domain_flush_complete(struct protection_domain *domain)
850 for (i = 0; i < amd_iommus_present; ++i) {
851 if (!domain->dev_iommu[i])
855 * Devices of this domain are behind this IOMMU
856 * We need to wait for completion of all commands.
858 iommu_completion_wait(amd_iommus[i]);
864 * This function flushes the DTEs for all devices in domain
866 static void domain_flush_devices(struct protection_domain *domain)
868 struct iommu_dev_data *dev_data;
870 list_for_each_entry(dev_data, &domain->dev_list, list)
871 device_flush_dte(dev_data);
874 /****************************************************************************
876 * The functions below are used the create the page table mappings for
877 * unity mapped regions.
879 ****************************************************************************/
882 * This function is used to add another level to an IO page table. Adding
883 * another level increases the size of the address space by 9 bits to a size up
886 static bool increase_address_space(struct protection_domain *domain,
891 if (domain->mode == PAGE_MODE_6_LEVEL)
892 /* address space already 64 bit large */
895 pte = (void *)get_zeroed_page(gfp);
899 *pte = PM_LEVEL_PDE(domain->mode,
900 virt_to_phys(domain->pt_root));
901 domain->pt_root = pte;
903 domain->updated = true;
908 static u64 *alloc_pte(struct protection_domain *domain,
909 unsigned long address,
910 unsigned long page_size,
917 BUG_ON(!is_power_of_2(page_size));
919 while (address > PM_LEVEL_SIZE(domain->mode))
920 increase_address_space(domain, gfp);
922 level = domain->mode - 1;
923 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
924 address = PAGE_SIZE_ALIGN(address, page_size);
925 end_lvl = PAGE_SIZE_LEVEL(page_size);
927 while (level > end_lvl) {
928 if (!IOMMU_PTE_PRESENT(*pte)) {
929 page = (u64 *)get_zeroed_page(gfp);
932 *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
935 /* No level skipping support yet */
936 if (PM_PTE_LEVEL(*pte) != level)
941 pte = IOMMU_PTE_PAGE(*pte);
943 if (pte_page && level == end_lvl)
946 pte = &pte[PM_LEVEL_INDEX(level, address)];
953 * This function checks if there is a PTE for a given dma address. If
954 * there is one, it returns the pointer to it.
956 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
961 if (address > PM_LEVEL_SIZE(domain->mode))
964 level = domain->mode - 1;
965 pte = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
970 if (!IOMMU_PTE_PRESENT(*pte))
974 if (PM_PTE_LEVEL(*pte) == 0x07) {
975 unsigned long pte_mask, __pte;
978 * If we have a series of large PTEs, make
979 * sure to return a pointer to the first one.
981 pte_mask = PTE_PAGE_SIZE(*pte);
982 pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
983 __pte = ((unsigned long)pte) & pte_mask;
988 /* No level skipping support yet */
989 if (PM_PTE_LEVEL(*pte) != level)
994 /* Walk to the next level */
995 pte = IOMMU_PTE_PAGE(*pte);
996 pte = &pte[PM_LEVEL_INDEX(level, address)];
1003 * Generic mapping functions. It maps a physical address into a DMA
1004 * address space. It allocates the page table pages if necessary.
1005 * In the future it can be extended to a generic mapping function
1006 * supporting all features of AMD IOMMU page tables like level skipping
1007 * and full 64 bit address spaces.
1009 static int iommu_map_page(struct protection_domain *dom,
1010 unsigned long bus_addr,
1011 unsigned long phys_addr,
1013 unsigned long page_size)
1018 if (!(prot & IOMMU_PROT_MASK))
1021 bus_addr = PAGE_ALIGN(bus_addr);
1022 phys_addr = PAGE_ALIGN(phys_addr);
1023 count = PAGE_SIZE_PTE_COUNT(page_size);
1024 pte = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1026 for (i = 0; i < count; ++i)
1027 if (IOMMU_PTE_PRESENT(pte[i]))
1030 if (page_size > PAGE_SIZE) {
1031 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1032 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1034 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1036 if (prot & IOMMU_PROT_IR)
1037 __pte |= IOMMU_PTE_IR;
1038 if (prot & IOMMU_PROT_IW)
1039 __pte |= IOMMU_PTE_IW;
1041 for (i = 0; i < count; ++i)
1049 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1050 unsigned long bus_addr,
1051 unsigned long page_size)
1053 unsigned long long unmap_size, unmapped;
1056 BUG_ON(!is_power_of_2(page_size));
1060 while (unmapped < page_size) {
1062 pte = fetch_pte(dom, bus_addr);
1066 * No PTE for this address
1067 * move forward in 4kb steps
1069 unmap_size = PAGE_SIZE;
1070 } else if (PM_PTE_LEVEL(*pte) == 0) {
1071 /* 4kb PTE found for this address */
1072 unmap_size = PAGE_SIZE;
1077 /* Large PTE found which maps this address */
1078 unmap_size = PTE_PAGE_SIZE(*pte);
1079 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1080 for (i = 0; i < count; i++)
1084 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1085 unmapped += unmap_size;
1088 BUG_ON(!is_power_of_2(unmapped));
1094 * This function checks if a specific unity mapping entry is needed for
1095 * this specific IOMMU.
1097 static int iommu_for_unity_map(struct amd_iommu *iommu,
1098 struct unity_map_entry *entry)
1102 for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1103 bdf = amd_iommu_alias_table[i];
1104 if (amd_iommu_rlookup_table[bdf] == iommu)
1112 * This function actually applies the mapping to the page table of the
1115 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1116 struct unity_map_entry *e)
1121 for (addr = e->address_start; addr < e->address_end;
1122 addr += PAGE_SIZE) {
1123 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1128 * if unity mapping is in aperture range mark the page
1129 * as allocated in the aperture
1131 if (addr < dma_dom->aperture_size)
1132 __set_bit(addr >> PAGE_SHIFT,
1133 dma_dom->aperture[0]->bitmap);
1140 * Init the unity mappings for a specific IOMMU in the system
1142 * Basically iterates over all unity mapping entries and applies them to
1143 * the default domain DMA of that IOMMU if necessary.
1145 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1147 struct unity_map_entry *entry;
1150 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1151 if (!iommu_for_unity_map(iommu, entry))
1153 ret = dma_ops_unity_map(iommu->default_dom, entry);
1162 * Inits the unity mappings required for a specific device
1164 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1167 struct unity_map_entry *e;
1170 list_for_each_entry(e, &amd_iommu_unity_map, list) {
1171 if (!(devid >= e->devid_start && devid <= e->devid_end))
1173 ret = dma_ops_unity_map(dma_dom, e);
1181 /****************************************************************************
1183 * The next functions belong to the address allocator for the dma_ops
1184 * interface functions. They work like the allocators in the other IOMMU
1185 * drivers. Its basically a bitmap which marks the allocated pages in
1186 * the aperture. Maybe it could be enhanced in the future to a more
1187 * efficient allocator.
1189 ****************************************************************************/
1192 * The address allocator core functions.
1194 * called with domain->lock held
1198 * Used to reserve address ranges in the aperture (e.g. for exclusion
1201 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1202 unsigned long start_page,
1205 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1207 if (start_page + pages > last_page)
1208 pages = last_page - start_page;
1210 for (i = start_page; i < start_page + pages; ++i) {
1211 int index = i / APERTURE_RANGE_PAGES;
1212 int page = i % APERTURE_RANGE_PAGES;
1213 __set_bit(page, dom->aperture[index]->bitmap);
1218 * This function is used to add a new aperture range to an existing
1219 * aperture in case of dma_ops domain allocation or address allocation
1222 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1223 bool populate, gfp_t gfp)
1225 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1226 struct amd_iommu *iommu;
1227 unsigned long i, old_size;
1229 #ifdef CONFIG_IOMMU_STRESS
1233 if (index >= APERTURE_MAX_RANGES)
1236 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1237 if (!dma_dom->aperture[index])
1240 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1241 if (!dma_dom->aperture[index]->bitmap)
1244 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1247 unsigned long address = dma_dom->aperture_size;
1248 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1249 u64 *pte, *pte_page;
1251 for (i = 0; i < num_ptes; ++i) {
1252 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1257 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1259 address += APERTURE_RANGE_SIZE / 64;
1263 old_size = dma_dom->aperture_size;
1264 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1266 /* Reserve address range used for MSI messages */
1267 if (old_size < MSI_ADDR_BASE_LO &&
1268 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1269 unsigned long spage;
1272 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1273 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1275 dma_ops_reserve_addresses(dma_dom, spage, pages);
1278 /* Initialize the exclusion range if necessary */
1279 for_each_iommu(iommu) {
1280 if (iommu->exclusion_start &&
1281 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1282 && iommu->exclusion_start < dma_dom->aperture_size) {
1283 unsigned long startpage;
1284 int pages = iommu_num_pages(iommu->exclusion_start,
1285 iommu->exclusion_length,
1287 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1288 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1293 * Check for areas already mapped as present in the new aperture
1294 * range and mark those pages as reserved in the allocator. Such
1295 * mappings may already exist as a result of requested unity
1296 * mappings for devices.
1298 for (i = dma_dom->aperture[index]->offset;
1299 i < dma_dom->aperture_size;
1301 u64 *pte = fetch_pte(&dma_dom->domain, i);
1302 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1305 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1308 update_domain(&dma_dom->domain);
1313 update_domain(&dma_dom->domain);
1315 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1317 kfree(dma_dom->aperture[index]);
1318 dma_dom->aperture[index] = NULL;
1323 static unsigned long dma_ops_area_alloc(struct device *dev,
1324 struct dma_ops_domain *dom,
1326 unsigned long align_mask,
1328 unsigned long start)
1330 unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1331 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1332 int i = start >> APERTURE_RANGE_SHIFT;
1333 unsigned long boundary_size;
1334 unsigned long address = -1;
1335 unsigned long limit;
1337 next_bit >>= PAGE_SHIFT;
1339 boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1340 PAGE_SIZE) >> PAGE_SHIFT;
1342 for (;i < max_index; ++i) {
1343 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1345 if (dom->aperture[i]->offset >= dma_mask)
1348 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1349 dma_mask >> PAGE_SHIFT);
1351 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1352 limit, next_bit, pages, 0,
1353 boundary_size, align_mask);
1354 if (address != -1) {
1355 address = dom->aperture[i]->offset +
1356 (address << PAGE_SHIFT);
1357 dom->next_address = address + (pages << PAGE_SHIFT);
1367 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1368 struct dma_ops_domain *dom,
1370 unsigned long align_mask,
1373 unsigned long address;
1375 #ifdef CONFIG_IOMMU_STRESS
1376 dom->next_address = 0;
1377 dom->need_flush = true;
1380 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1381 dma_mask, dom->next_address);
1383 if (address == -1) {
1384 dom->next_address = 0;
1385 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1387 dom->need_flush = true;
1390 if (unlikely(address == -1))
1391 address = DMA_ERROR_CODE;
1393 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1399 * The address free function.
1401 * called with domain->lock held
1403 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1404 unsigned long address,
1407 unsigned i = address >> APERTURE_RANGE_SHIFT;
1408 struct aperture_range *range = dom->aperture[i];
1410 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1412 #ifdef CONFIG_IOMMU_STRESS
1417 if (address >= dom->next_address)
1418 dom->need_flush = true;
1420 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1422 bitmap_clear(range->bitmap, address, pages);
1426 /****************************************************************************
1428 * The next functions belong to the domain allocation. A domain is
1429 * allocated for every IOMMU as the default domain. If device isolation
1430 * is enabled, every device get its own domain. The most important thing
1431 * about domains is the page table mapping the DMA address space they
1434 ****************************************************************************/
1437 * This function adds a protection domain to the global protection domain list
1439 static void add_domain_to_list(struct protection_domain *domain)
1441 unsigned long flags;
1443 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1444 list_add(&domain->list, &amd_iommu_pd_list);
1445 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1449 * This function removes a protection domain to the global
1450 * protection domain list
1452 static void del_domain_from_list(struct protection_domain *domain)
1454 unsigned long flags;
1456 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1457 list_del(&domain->list);
1458 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1461 static u16 domain_id_alloc(void)
1463 unsigned long flags;
1466 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1467 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1469 if (id > 0 && id < MAX_DOMAIN_ID)
1470 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1473 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1478 static void domain_id_free(int id)
1480 unsigned long flags;
1482 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1483 if (id > 0 && id < MAX_DOMAIN_ID)
1484 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1485 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1488 static void free_pagetable(struct protection_domain *domain)
1493 p1 = domain->pt_root;
1498 for (i = 0; i < 512; ++i) {
1499 if (!IOMMU_PTE_PRESENT(p1[i]))
1502 p2 = IOMMU_PTE_PAGE(p1[i]);
1503 for (j = 0; j < 512; ++j) {
1504 if (!IOMMU_PTE_PRESENT(p2[j]))
1506 p3 = IOMMU_PTE_PAGE(p2[j]);
1507 free_page((unsigned long)p3);
1510 free_page((unsigned long)p2);
1513 free_page((unsigned long)p1);
1515 domain->pt_root = NULL;
1519 * Free a domain, only used if something went wrong in the
1520 * allocation path and we need to free an already allocated page table
1522 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1529 del_domain_from_list(&dom->domain);
1531 free_pagetable(&dom->domain);
1533 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1534 if (!dom->aperture[i])
1536 free_page((unsigned long)dom->aperture[i]->bitmap);
1537 kfree(dom->aperture[i]);
1544 * Allocates a new protection domain usable for the dma_ops functions.
1545 * It also initializes the page table and the address allocator data
1546 * structures required for the dma_ops interface
1548 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1550 struct dma_ops_domain *dma_dom;
1552 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1556 spin_lock_init(&dma_dom->domain.lock);
1558 dma_dom->domain.id = domain_id_alloc();
1559 if (dma_dom->domain.id == 0)
1561 INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1562 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1563 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1564 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1565 dma_dom->domain.priv = dma_dom;
1566 if (!dma_dom->domain.pt_root)
1569 dma_dom->need_flush = false;
1570 dma_dom->target_dev = 0xffff;
1572 add_domain_to_list(&dma_dom->domain);
1574 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1578 * mark the first page as allocated so we never return 0 as
1579 * a valid dma-address. So we can use 0 as error value
1581 dma_dom->aperture[0]->bitmap[0] = 1;
1582 dma_dom->next_address = 0;
1588 dma_ops_domain_free(dma_dom);
1594 * little helper function to check whether a given protection domain is a
1597 static bool dma_ops_domain(struct protection_domain *domain)
1599 return domain->flags & PD_DMA_OPS_MASK;
1602 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1604 u64 pte_root = virt_to_phys(domain->pt_root);
1607 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1608 << DEV_ENTRY_MODE_SHIFT;
1609 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1612 flags |= DTE_FLAG_IOTLB;
1614 amd_iommu_dev_table[devid].data[3] |= flags;
1615 amd_iommu_dev_table[devid].data[2] = domain->id;
1616 amd_iommu_dev_table[devid].data[1] = upper_32_bits(pte_root);
1617 amd_iommu_dev_table[devid].data[0] = lower_32_bits(pte_root);
1620 static void clear_dte_entry(u16 devid)
1622 /* remove entry from the device table seen by the hardware */
1623 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1624 amd_iommu_dev_table[devid].data[1] = 0;
1625 amd_iommu_dev_table[devid].data[2] = 0;
1627 amd_iommu_apply_erratum_63(devid);
1630 static void do_attach(struct iommu_dev_data *dev_data,
1631 struct protection_domain *domain)
1633 struct amd_iommu *iommu;
1636 iommu = amd_iommu_rlookup_table[dev_data->devid];
1637 ats = dev_data->ats.enabled;
1639 /* Update data structures */
1640 dev_data->domain = domain;
1641 list_add(&dev_data->list, &domain->dev_list);
1642 set_dte_entry(dev_data->devid, domain, ats);
1644 /* Do reference counting */
1645 domain->dev_iommu[iommu->index] += 1;
1646 domain->dev_cnt += 1;
1648 /* Flush the DTE entry */
1649 device_flush_dte(dev_data);
1652 static void do_detach(struct iommu_dev_data *dev_data)
1654 struct amd_iommu *iommu;
1656 iommu = amd_iommu_rlookup_table[dev_data->devid];
1658 /* decrease reference counters */
1659 dev_data->domain->dev_iommu[iommu->index] -= 1;
1660 dev_data->domain->dev_cnt -= 1;
1662 /* Update data structures */
1663 dev_data->domain = NULL;
1664 list_del(&dev_data->list);
1665 clear_dte_entry(dev_data->devid);
1667 /* Flush the DTE entry */
1668 device_flush_dte(dev_data);
1672 * If a device is not yet associated with a domain, this function does
1673 * assigns it visible for the hardware
1675 static int __attach_device(struct iommu_dev_data *dev_data,
1676 struct protection_domain *domain)
1681 spin_lock(&domain->lock);
1683 if (dev_data->alias_data != NULL) {
1684 struct iommu_dev_data *alias_data = dev_data->alias_data;
1686 /* Some sanity checks */
1688 if (alias_data->domain != NULL &&
1689 alias_data->domain != domain)
1692 if (dev_data->domain != NULL &&
1693 dev_data->domain != domain)
1696 /* Do real assignment */
1697 if (alias_data->domain == NULL)
1698 do_attach(alias_data, domain);
1700 atomic_inc(&alias_data->bind);
1703 if (dev_data->domain == NULL)
1704 do_attach(dev_data, domain);
1706 atomic_inc(&dev_data->bind);
1713 spin_unlock(&domain->lock);
1719 * If a device is not yet associated with a domain, this function does
1720 * assigns it visible for the hardware
1722 static int attach_device(struct device *dev,
1723 struct protection_domain *domain)
1725 struct pci_dev *pdev = to_pci_dev(dev);
1726 struct iommu_dev_data *dev_data;
1727 unsigned long flags;
1730 dev_data = get_dev_data(dev);
1732 if (amd_iommu_iotlb_sup && pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
1733 dev_data->ats.enabled = true;
1734 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
1737 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1738 ret = __attach_device(dev_data, domain);
1739 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1742 * We might boot into a crash-kernel here. The crashed kernel
1743 * left the caches in the IOMMU dirty. So we have to flush
1744 * here to evict all dirty stuff.
1746 domain_flush_tlb_pde(domain);
1752 * Removes a device from a protection domain (unlocked)
1754 static void __detach_device(struct iommu_dev_data *dev_data)
1756 struct protection_domain *domain;
1757 unsigned long flags;
1759 BUG_ON(!dev_data->domain);
1761 domain = dev_data->domain;
1763 spin_lock_irqsave(&domain->lock, flags);
1765 if (dev_data->alias_data != NULL) {
1766 struct iommu_dev_data *alias_data = dev_data->alias_data;
1768 if (atomic_dec_and_test(&alias_data->bind))
1769 do_detach(alias_data);
1772 if (atomic_dec_and_test(&dev_data->bind))
1773 do_detach(dev_data);
1775 spin_unlock_irqrestore(&domain->lock, flags);
1778 * If we run in passthrough mode the device must be assigned to the
1779 * passthrough domain if it is detached from any other domain.
1780 * Make sure we can deassign from the pt_domain itself.
1782 if (iommu_pass_through &&
1783 (dev_data->domain == NULL && domain != pt_domain))
1784 __attach_device(dev_data, pt_domain);
1788 * Removes a device from a protection domain (with devtable_lock held)
1790 static void detach_device(struct device *dev)
1792 struct iommu_dev_data *dev_data;
1793 unsigned long flags;
1795 dev_data = get_dev_data(dev);
1797 /* lock device table */
1798 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1799 __detach_device(dev_data);
1800 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1802 if (dev_data->ats.enabled) {
1803 pci_disable_ats(to_pci_dev(dev));
1804 dev_data->ats.enabled = false;
1809 * Find out the protection domain structure for a given PCI device. This
1810 * will give us the pointer to the page table root for example.
1812 static struct protection_domain *domain_for_device(struct device *dev)
1814 struct iommu_dev_data *dev_data;
1815 struct protection_domain *dom = NULL;
1816 unsigned long flags;
1818 dev_data = get_dev_data(dev);
1820 if (dev_data->domain)
1821 return dev_data->domain;
1823 if (dev_data->alias_data != NULL) {
1824 struct iommu_dev_data *alias_data = dev_data->alias_data;
1826 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
1827 if (alias_data->domain != NULL) {
1828 __attach_device(dev_data, alias_data->domain);
1829 dom = alias_data->domain;
1831 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1837 static int device_change_notifier(struct notifier_block *nb,
1838 unsigned long action, void *data)
1840 struct device *dev = data;
1842 struct protection_domain *domain;
1843 struct dma_ops_domain *dma_domain;
1844 struct amd_iommu *iommu;
1845 unsigned long flags;
1847 if (!check_device(dev))
1850 devid = get_device_id(dev);
1851 iommu = amd_iommu_rlookup_table[devid];
1854 case BUS_NOTIFY_UNBOUND_DRIVER:
1856 domain = domain_for_device(dev);
1860 if (iommu_pass_through)
1864 case BUS_NOTIFY_ADD_DEVICE:
1866 iommu_init_device(dev);
1868 if (iommu_pass_through) {
1869 attach_device(dev, pt_domain);
1873 domain = domain_for_device(dev);
1875 /* allocate a protection domain if a device is added */
1876 dma_domain = find_protection_domain(devid);
1879 dma_domain = dma_ops_domain_alloc();
1882 dma_domain->target_dev = devid;
1884 spin_lock_irqsave(&iommu_pd_list_lock, flags);
1885 list_add_tail(&dma_domain->list, &iommu_pd_list);
1886 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
1888 dev->archdata.dma_ops = &amd_iommu_dma_ops;
1891 case BUS_NOTIFY_DEL_DEVICE:
1893 iommu_uninit_device(dev);
1899 iommu_completion_wait(iommu);
1905 static struct notifier_block device_nb = {
1906 .notifier_call = device_change_notifier,
1909 void amd_iommu_init_notifier(void)
1911 bus_register_notifier(&pci_bus_type, &device_nb);
1914 /*****************************************************************************
1916 * The next functions belong to the dma_ops mapping/unmapping code.
1918 *****************************************************************************/
1921 * In the dma_ops path we only have the struct device. This function
1922 * finds the corresponding IOMMU, the protection domain and the
1923 * requestor id for a given device.
1924 * If the device is not yet associated with a domain this is also done
1927 static struct protection_domain *get_domain(struct device *dev)
1929 struct protection_domain *domain;
1930 struct dma_ops_domain *dma_dom;
1931 u16 devid = get_device_id(dev);
1933 if (!check_device(dev))
1934 return ERR_PTR(-EINVAL);
1936 domain = domain_for_device(dev);
1937 if (domain != NULL && !dma_ops_domain(domain))
1938 return ERR_PTR(-EBUSY);
1943 /* Device not bount yet - bind it */
1944 dma_dom = find_protection_domain(devid);
1946 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
1947 attach_device(dev, &dma_dom->domain);
1948 DUMP_printk("Using protection domain %d for device %s\n",
1949 dma_dom->domain.id, dev_name(dev));
1951 return &dma_dom->domain;
1954 static void update_device_table(struct protection_domain *domain)
1956 struct iommu_dev_data *dev_data;
1958 list_for_each_entry(dev_data, &domain->dev_list, list)
1959 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
1962 static void update_domain(struct protection_domain *domain)
1964 if (!domain->updated)
1967 update_device_table(domain);
1969 domain_flush_devices(domain);
1970 domain_flush_tlb_pde(domain);
1972 domain->updated = false;
1976 * This function fetches the PTE for a given address in the aperture
1978 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
1979 unsigned long address)
1981 struct aperture_range *aperture;
1982 u64 *pte, *pte_page;
1984 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
1988 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
1990 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
1992 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
1994 pte += PM_LEVEL_INDEX(0, address);
1996 update_domain(&dom->domain);
2002 * This is the generic map function. It maps one 4kb page at paddr to
2003 * the given address in the DMA address space for the domain.
2005 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2006 unsigned long address,
2012 WARN_ON(address > dom->aperture_size);
2016 pte = dma_ops_get_pte(dom, address);
2018 return DMA_ERROR_CODE;
2020 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2022 if (direction == DMA_TO_DEVICE)
2023 __pte |= IOMMU_PTE_IR;
2024 else if (direction == DMA_FROM_DEVICE)
2025 __pte |= IOMMU_PTE_IW;
2026 else if (direction == DMA_BIDIRECTIONAL)
2027 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2033 return (dma_addr_t)address;
2037 * The generic unmapping function for on page in the DMA address space.
2039 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2040 unsigned long address)
2042 struct aperture_range *aperture;
2045 if (address >= dom->aperture_size)
2048 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2052 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2056 pte += PM_LEVEL_INDEX(0, address);
2064 * This function contains common code for mapping of a physically
2065 * contiguous memory region into DMA address space. It is used by all
2066 * mapping functions provided with this IOMMU driver.
2067 * Must be called with the domain lock held.
2069 static dma_addr_t __map_single(struct device *dev,
2070 struct dma_ops_domain *dma_dom,
2077 dma_addr_t offset = paddr & ~PAGE_MASK;
2078 dma_addr_t address, start, ret;
2080 unsigned long align_mask = 0;
2083 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2086 INC_STATS_COUNTER(total_map_requests);
2089 INC_STATS_COUNTER(cross_page);
2092 align_mask = (1UL << get_order(size)) - 1;
2095 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2097 if (unlikely(address == DMA_ERROR_CODE)) {
2099 * setting next_address here will let the address
2100 * allocator only scan the new allocated range in the
2101 * first run. This is a small optimization.
2103 dma_dom->next_address = dma_dom->aperture_size;
2105 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2109 * aperture was successfully enlarged by 128 MB, try
2116 for (i = 0; i < pages; ++i) {
2117 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2118 if (ret == DMA_ERROR_CODE)
2126 ADD_STATS_COUNTER(alloced_io_mem, size);
2128 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2129 domain_flush_tlb(&dma_dom->domain);
2130 dma_dom->need_flush = false;
2131 } else if (unlikely(amd_iommu_np_cache))
2132 domain_flush_pages(&dma_dom->domain, address, size);
2139 for (--i; i >= 0; --i) {
2141 dma_ops_domain_unmap(dma_dom, start);
2144 dma_ops_free_addresses(dma_dom, address, pages);
2146 return DMA_ERROR_CODE;
2150 * Does the reverse of the __map_single function. Must be called with
2151 * the domain lock held too
2153 static void __unmap_single(struct dma_ops_domain *dma_dom,
2154 dma_addr_t dma_addr,
2158 dma_addr_t flush_addr;
2159 dma_addr_t i, start;
2162 if ((dma_addr == DMA_ERROR_CODE) ||
2163 (dma_addr + size > dma_dom->aperture_size))
2166 flush_addr = dma_addr;
2167 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2168 dma_addr &= PAGE_MASK;
2171 for (i = 0; i < pages; ++i) {
2172 dma_ops_domain_unmap(dma_dom, start);
2176 SUB_STATS_COUNTER(alloced_io_mem, size);
2178 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2180 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2181 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2182 dma_dom->need_flush = false;
2187 * The exported map_single function for dma_ops.
2189 static dma_addr_t map_page(struct device *dev, struct page *page,
2190 unsigned long offset, size_t size,
2191 enum dma_data_direction dir,
2192 struct dma_attrs *attrs)
2194 unsigned long flags;
2195 struct protection_domain *domain;
2198 phys_addr_t paddr = page_to_phys(page) + offset;
2200 INC_STATS_COUNTER(cnt_map_single);
2202 domain = get_domain(dev);
2203 if (PTR_ERR(domain) == -EINVAL)
2204 return (dma_addr_t)paddr;
2205 else if (IS_ERR(domain))
2206 return DMA_ERROR_CODE;
2208 dma_mask = *dev->dma_mask;
2210 spin_lock_irqsave(&domain->lock, flags);
2212 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2214 if (addr == DMA_ERROR_CODE)
2217 domain_flush_complete(domain);
2220 spin_unlock_irqrestore(&domain->lock, flags);
2226 * The exported unmap_single function for dma_ops.
2228 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2229 enum dma_data_direction dir, struct dma_attrs *attrs)
2231 unsigned long flags;
2232 struct protection_domain *domain;
2234 INC_STATS_COUNTER(cnt_unmap_single);
2236 domain = get_domain(dev);
2240 spin_lock_irqsave(&domain->lock, flags);
2242 __unmap_single(domain->priv, dma_addr, size, dir);
2244 domain_flush_complete(domain);
2246 spin_unlock_irqrestore(&domain->lock, flags);
2250 * This is a special map_sg function which is used if we should map a
2251 * device which is not handled by an AMD IOMMU in the system.
2253 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2254 int nelems, int dir)
2256 struct scatterlist *s;
2259 for_each_sg(sglist, s, nelems, i) {
2260 s->dma_address = (dma_addr_t)sg_phys(s);
2261 s->dma_length = s->length;
2268 * The exported map_sg function for dma_ops (handles scatter-gather
2271 static int map_sg(struct device *dev, struct scatterlist *sglist,
2272 int nelems, enum dma_data_direction dir,
2273 struct dma_attrs *attrs)
2275 unsigned long flags;
2276 struct protection_domain *domain;
2278 struct scatterlist *s;
2280 int mapped_elems = 0;
2283 INC_STATS_COUNTER(cnt_map_sg);
2285 domain = get_domain(dev);
2286 if (PTR_ERR(domain) == -EINVAL)
2287 return map_sg_no_iommu(dev, sglist, nelems, dir);
2288 else if (IS_ERR(domain))
2291 dma_mask = *dev->dma_mask;
2293 spin_lock_irqsave(&domain->lock, flags);
2295 for_each_sg(sglist, s, nelems, i) {
2298 s->dma_address = __map_single(dev, domain->priv,
2299 paddr, s->length, dir, false,
2302 if (s->dma_address) {
2303 s->dma_length = s->length;
2309 domain_flush_complete(domain);
2312 spin_unlock_irqrestore(&domain->lock, flags);
2314 return mapped_elems;
2316 for_each_sg(sglist, s, mapped_elems, i) {
2318 __unmap_single(domain->priv, s->dma_address,
2319 s->dma_length, dir);
2320 s->dma_address = s->dma_length = 0;
2329 * The exported map_sg function for dma_ops (handles scatter-gather
2332 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2333 int nelems, enum dma_data_direction dir,
2334 struct dma_attrs *attrs)
2336 unsigned long flags;
2337 struct protection_domain *domain;
2338 struct scatterlist *s;
2341 INC_STATS_COUNTER(cnt_unmap_sg);
2343 domain = get_domain(dev);
2347 spin_lock_irqsave(&domain->lock, flags);
2349 for_each_sg(sglist, s, nelems, i) {
2350 __unmap_single(domain->priv, s->dma_address,
2351 s->dma_length, dir);
2352 s->dma_address = s->dma_length = 0;
2355 domain_flush_complete(domain);
2357 spin_unlock_irqrestore(&domain->lock, flags);
2361 * The exported alloc_coherent function for dma_ops.
2363 static void *alloc_coherent(struct device *dev, size_t size,
2364 dma_addr_t *dma_addr, gfp_t flag)
2366 unsigned long flags;
2368 struct protection_domain *domain;
2370 u64 dma_mask = dev->coherent_dma_mask;
2372 INC_STATS_COUNTER(cnt_alloc_coherent);
2374 domain = get_domain(dev);
2375 if (PTR_ERR(domain) == -EINVAL) {
2376 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2377 *dma_addr = __pa(virt_addr);
2379 } else if (IS_ERR(domain))
2382 dma_mask = dev->coherent_dma_mask;
2383 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2386 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2390 paddr = virt_to_phys(virt_addr);
2393 dma_mask = *dev->dma_mask;
2395 spin_lock_irqsave(&domain->lock, flags);
2397 *dma_addr = __map_single(dev, domain->priv, paddr,
2398 size, DMA_BIDIRECTIONAL, true, dma_mask);
2400 if (*dma_addr == DMA_ERROR_CODE) {
2401 spin_unlock_irqrestore(&domain->lock, flags);
2405 domain_flush_complete(domain);
2407 spin_unlock_irqrestore(&domain->lock, flags);
2413 free_pages((unsigned long)virt_addr, get_order(size));
2419 * The exported free_coherent function for dma_ops.
2421 static void free_coherent(struct device *dev, size_t size,
2422 void *virt_addr, dma_addr_t dma_addr)
2424 unsigned long flags;
2425 struct protection_domain *domain;
2427 INC_STATS_COUNTER(cnt_free_coherent);
2429 domain = get_domain(dev);
2433 spin_lock_irqsave(&domain->lock, flags);
2435 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2437 domain_flush_complete(domain);
2439 spin_unlock_irqrestore(&domain->lock, flags);
2442 free_pages((unsigned long)virt_addr, get_order(size));
2446 * This function is called by the DMA layer to find out if we can handle a
2447 * particular device. It is part of the dma_ops.
2449 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2451 return check_device(dev);
2455 * The function for pre-allocating protection domains.
2457 * If the driver core informs the DMA layer if a driver grabs a device
2458 * we don't need to preallocate the protection domains anymore.
2459 * For now we have to.
2461 static void __init prealloc_protection_domains(void)
2463 struct pci_dev *dev = NULL;
2464 struct dma_ops_domain *dma_dom;
2467 for_each_pci_dev(dev) {
2469 /* Do we handle this device? */
2470 if (!check_device(&dev->dev))
2473 /* Is there already any domain for it? */
2474 if (domain_for_device(&dev->dev))
2477 devid = get_device_id(&dev->dev);
2479 dma_dom = dma_ops_domain_alloc();
2482 init_unity_mappings_for_device(dma_dom, devid);
2483 dma_dom->target_dev = devid;
2485 attach_device(&dev->dev, &dma_dom->domain);
2487 list_add_tail(&dma_dom->list, &iommu_pd_list);
2491 static struct dma_map_ops amd_iommu_dma_ops = {
2492 .alloc_coherent = alloc_coherent,
2493 .free_coherent = free_coherent,
2494 .map_page = map_page,
2495 .unmap_page = unmap_page,
2497 .unmap_sg = unmap_sg,
2498 .dma_supported = amd_iommu_dma_supported,
2501 static unsigned device_dma_ops_init(void)
2503 struct pci_dev *pdev = NULL;
2504 unsigned unhandled = 0;
2506 for_each_pci_dev(pdev) {
2507 if (!check_device(&pdev->dev)) {
2509 iommu_ignore_device(&pdev->dev);
2515 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
2522 * The function which clues the AMD IOMMU driver into dma_ops.
2525 void __init amd_iommu_init_api(void)
2527 bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2530 int __init amd_iommu_init_dma_ops(void)
2532 struct amd_iommu *iommu;
2536 * first allocate a default protection domain for every IOMMU we
2537 * found in the system. Devices not assigned to any other
2538 * protection domain will be assigned to the default one.
2540 for_each_iommu(iommu) {
2541 iommu->default_dom = dma_ops_domain_alloc();
2542 if (iommu->default_dom == NULL)
2544 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
2545 ret = iommu_init_unity_mappings(iommu);
2551 * Pre-allocate the protection domains for each device.
2553 prealloc_protection_domains();
2558 /* Make the driver finally visible to the drivers */
2559 unhandled = device_dma_ops_init();
2560 if (unhandled && max_pfn > MAX_DMA32_PFN) {
2561 /* There are unhandled devices - initialize swiotlb for them */
2565 amd_iommu_stats_init();
2571 for_each_iommu(iommu) {
2572 if (iommu->default_dom)
2573 dma_ops_domain_free(iommu->default_dom);
2579 /*****************************************************************************
2581 * The following functions belong to the exported interface of AMD IOMMU
2583 * This interface allows access to lower level functions of the IOMMU
2584 * like protection domain handling and assignement of devices to domains
2585 * which is not possible with the dma_ops interface.
2587 *****************************************************************************/
2589 static void cleanup_domain(struct protection_domain *domain)
2591 struct iommu_dev_data *dev_data, *next;
2592 unsigned long flags;
2594 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2596 list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
2597 __detach_device(dev_data);
2598 atomic_set(&dev_data->bind, 0);
2601 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2604 static void protection_domain_free(struct protection_domain *domain)
2609 del_domain_from_list(domain);
2612 domain_id_free(domain->id);
2617 static struct protection_domain *protection_domain_alloc(void)
2619 struct protection_domain *domain;
2621 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2625 spin_lock_init(&domain->lock);
2626 mutex_init(&domain->api_lock);
2627 domain->id = domain_id_alloc();
2630 INIT_LIST_HEAD(&domain->dev_list);
2632 add_domain_to_list(domain);
2642 static int amd_iommu_domain_init(struct iommu_domain *dom)
2644 struct protection_domain *domain;
2646 domain = protection_domain_alloc();
2650 domain->mode = PAGE_MODE_3_LEVEL;
2651 domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2652 if (!domain->pt_root)
2660 protection_domain_free(domain);
2665 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
2667 struct protection_domain *domain = dom->priv;
2672 if (domain->dev_cnt > 0)
2673 cleanup_domain(domain);
2675 BUG_ON(domain->dev_cnt != 0);
2677 free_pagetable(domain);
2679 protection_domain_free(domain);
2684 static void amd_iommu_detach_device(struct iommu_domain *dom,
2687 struct iommu_dev_data *dev_data = dev->archdata.iommu;
2688 struct amd_iommu *iommu;
2691 if (!check_device(dev))
2694 devid = get_device_id(dev);
2696 if (dev_data->domain != NULL)
2699 iommu = amd_iommu_rlookup_table[devid];
2703 iommu_completion_wait(iommu);
2706 static int amd_iommu_attach_device(struct iommu_domain *dom,
2709 struct protection_domain *domain = dom->priv;
2710 struct iommu_dev_data *dev_data;
2711 struct amd_iommu *iommu;
2714 if (!check_device(dev))
2717 dev_data = dev->archdata.iommu;
2719 iommu = amd_iommu_rlookup_table[dev_data->devid];
2723 if (dev_data->domain)
2726 ret = attach_device(dev, domain);
2728 iommu_completion_wait(iommu);
2733 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
2734 phys_addr_t paddr, int gfp_order, int iommu_prot)
2736 unsigned long page_size = 0x1000UL << gfp_order;
2737 struct protection_domain *domain = dom->priv;
2741 if (iommu_prot & IOMMU_READ)
2742 prot |= IOMMU_PROT_IR;
2743 if (iommu_prot & IOMMU_WRITE)
2744 prot |= IOMMU_PROT_IW;
2746 mutex_lock(&domain->api_lock);
2747 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
2748 mutex_unlock(&domain->api_lock);
2753 static int amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
2756 struct protection_domain *domain = dom->priv;
2757 unsigned long page_size, unmap_size;
2759 page_size = 0x1000UL << gfp_order;
2761 mutex_lock(&domain->api_lock);
2762 unmap_size = iommu_unmap_page(domain, iova, page_size);
2763 mutex_unlock(&domain->api_lock);
2765 domain_flush_tlb_pde(domain);
2767 return get_order(unmap_size);
2770 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
2773 struct protection_domain *domain = dom->priv;
2774 unsigned long offset_mask;
2778 pte = fetch_pte(domain, iova);
2780 if (!pte || !IOMMU_PTE_PRESENT(*pte))
2783 if (PM_PTE_LEVEL(*pte) == 0)
2784 offset_mask = PAGE_SIZE - 1;
2786 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
2788 __pte = *pte & PM_ADDR_MASK;
2789 paddr = (__pte & ~offset_mask) | (iova & offset_mask);
2794 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
2798 case IOMMU_CAP_CACHE_COHERENCY:
2805 static struct iommu_ops amd_iommu_ops = {
2806 .domain_init = amd_iommu_domain_init,
2807 .domain_destroy = amd_iommu_domain_destroy,
2808 .attach_dev = amd_iommu_attach_device,
2809 .detach_dev = amd_iommu_detach_device,
2810 .map = amd_iommu_map,
2811 .unmap = amd_iommu_unmap,
2812 .iova_to_phys = amd_iommu_iova_to_phys,
2813 .domain_has_cap = amd_iommu_domain_has_cap,
2816 /*****************************************************************************
2818 * The next functions do a basic initialization of IOMMU for pass through
2821 * In passthrough mode the IOMMU is initialized and enabled but not used for
2822 * DMA-API translation.
2824 *****************************************************************************/
2826 int __init amd_iommu_init_passthrough(void)
2828 struct amd_iommu *iommu;
2829 struct pci_dev *dev = NULL;
2832 /* allocate passthrough domain */
2833 pt_domain = protection_domain_alloc();
2837 pt_domain->mode |= PAGE_MODE_NONE;
2839 for_each_pci_dev(dev) {
2840 if (!check_device(&dev->dev))
2843 devid = get_device_id(&dev->dev);
2845 iommu = amd_iommu_rlookup_table[devid];
2849 attach_device(&dev->dev, pt_domain);
2852 pr_info("AMD-Vi: Initialized for Passthrough Mode\n");